diff --git a/.flowconfig b/.flowconfig index 5b28e40e67..7ea4c96c9e 100644 --- a/.flowconfig +++ b/.flowconfig @@ -18,7 +18,6 @@ ; For RN Apps installed via npm, "Libraries" folder is inside ; "node_modules/react-native" but in the source repo it is in the root .*/Libraries/react-native/React.js -.*/Libraries/react-native/ReactNative.js [include] diff --git a/Libraries/Renderer/README.md b/Libraries/Renderer/README.md deleted file mode 100644 index 5136078bfa..0000000000 --- a/Libraries/Renderer/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# React Native Renderer - -This is a downstream copy of React's renderer code to render into React Native. -The source of truth is the React repo. Please submit any changes upstream to -the [React Core GitHub repository](https://github.com/facebook/react). diff --git a/Libraries/Renderer/ReactNativeFiber-dev.js b/Libraries/Renderer/ReactNativeFiber-dev.js new file mode 100644 index 0000000000..4e0d98ae96 --- /dev/null +++ b/Libraries/Renderer/ReactNativeFiber-dev.js @@ -0,0 +1,4624 @@ +/** + * Copyright 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @noflow + * @providesModule ReactNativeFiber-dev + */ +"use strict"; + +var invariant = require("fbjs/lib/invariant"), warning = require("fbjs/lib/warning"), ExceptionsManager = require("ExceptionsManager"); + +require("InitializeCore"); + +var RCTEventEmitter = require("RCTEventEmitter"), emptyFunction = require("fbjs/lib/emptyFunction"), UIManager = require("UIManager"), checkPropTypes = require("prop-types/checkPropTypes"), emptyObject = require("fbjs/lib/emptyObject"), react = require("react"), shallowEqual = require("fbjs/lib/shallowEqual"), deepDiffer = require("deepDiffer"), flattenStyle = require("flattenStyle"), TextInputState = require("TextInputState"), deepFreezeAndThrowOnMutationInDev = require("deepFreezeAndThrowOnMutationInDev"); + +require("ReactNativeFeatureFlags"); + +var ExecutionEnvironment = require("fbjs/lib/ExecutionEnvironment"), performanceNow = require("fbjs/lib/performanceNow"), defaultShowDialog = function() { + return !0; +}, showDialog = defaultShowDialog; + +function logCapturedError(capturedError) { + if (!1 !== showDialog(capturedError)) { + var componentName = capturedError.componentName, componentStack = capturedError.componentStack, error = capturedError.error, errorBoundaryName = capturedError.errorBoundaryName, errorBoundaryFound = capturedError.errorBoundaryFound, willRetry = capturedError.willRetry, message = error.message, name = error.name, stack = error.stack, errorSummary = message ? name + ": " + message : name, componentNameMessage = componentName ? "React caught an error thrown by " + componentName + "." : "React caught an error thrown by one of your components.", formattedCallStack = stack.slice(0, errorSummary.length) === errorSummary ? stack.slice(errorSummary.length) : stack; + formattedCallStack = formattedCallStack.trim().split("\n").map(function(line) { + return "\n " + line.trim(); + }).join(); + var errorBoundaryMessage = void 0; + errorBoundaryMessage = errorBoundaryFound && errorBoundaryName ? willRetry ? "React will try to recreate this component tree from scratch " + "using the error boundary you provided, " + errorBoundaryName + "." : "This error was initially handled by the error boundary " + errorBoundaryName + ". " + "Recreating the tree from scratch failed so React will unmount the tree." : "Consider adding an error boundary to your tree to customize error handling behavior.", + console.error(componentNameMessage + " You should fix this error in your code. " + errorBoundaryMessage + "\n\n" + errorSummary + "\n\n" + "The error is located at: " + componentStack + "\n\n" + "The error was thrown at: " + formattedCallStack); + } +} + +var injection = { + injectDialog: function(fn) { + invariant(showDialog === defaultShowDialog, "The custom dialog was already injected."), + invariant("function" == typeof fn, "Injected showDialog() must be a function."), + showDialog = fn; + } +}, logCapturedError_1 = logCapturedError, ReactFiberErrorLogger = { + injection: injection, + logCapturedError: logCapturedError_1 +}, caughtError = null, invokeGuardedCallback = 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) { + return error; + } + return null; +}; + +if ("undefined" != typeof window && "function" == typeof window.dispatchEvent && "undefined" != typeof document && "function" == typeof document.createEvent) { + var fakeNode = document.createElement("react"), depth = 0; + invokeGuardedCallback = function(name, func, context, a, b, c, d, e, f) { + depth++; + var thisDepth = depth, funcArgs = Array.prototype.slice.call(arguments, 3), boundFunc = function() { + func.apply(context, funcArgs); + }, fakeEventError = null, onFakeEventError = function(event) { + depth === thisDepth && (fakeEventError = event.error); + }, evtType = "react-" + (name || "invokeguardedcallback") + "-" + depth; + window.addEventListener("error", onFakeEventError), fakeNode.addEventListener(evtType, boundFunc, !1); + var evt = document.createEvent("Event"); + return evt.initEvent(evtType, !1, !1), fakeNode.dispatchEvent(evt), fakeNode.removeEventListener(evtType, boundFunc, !1), + window.removeEventListener("error", onFakeEventError), depth--, fakeEventError; + }; +} + +var rethrowCaughtError = function() { + if (caughtError) { + var error = caughtError; + throw caughtError = null, error; + } +}, ReactErrorUtils = { + injection: { + injectErrorUtils: function(injectedErrorUtils) { + invariant("function" == typeof injectedErrorUtils.invokeGuardedCallback, "Injected invokeGuardedCallback() must be a function."), + invokeGuardedCallback = injectedErrorUtils.invokeGuardedCallback; + } + }, + invokeGuardedCallback: function(name, func, context, a, b, c, d, e, f) { + return invokeGuardedCallback.apply(this, arguments); + }, + invokeGuardedCallbackAndCatchFirstError: function(name, func, context, a, b, c, d, e, f) { + var error = ReactErrorUtils.invokeGuardedCallback.apply(this, arguments); + null !== error && null === caughtError && (caughtError = error); + }, + rethrowCaughtError: function() { + return rethrowCaughtError.apply(this, arguments); + } +}, ReactErrorUtils_1 = ReactErrorUtils, ComponentTree, injection$1 = { + injectComponentTree: function(Injected) { + ComponentTree = Injected, warning(Injected && Injected.getNodeFromInstance && Injected.getInstanceFromNode, "EventPluginUtils.injection.injectComponentTree(...): Injected " + "module is missing getNodeFromInstance or getInstanceFromNode."); + } +}; + +function isEndish(topLevelType) { + return "topMouseUp" === topLevelType || "topTouchEnd" === topLevelType || "topTouchCancel" === topLevelType; +} + +function isMoveish(topLevelType) { + return "topMouseMove" === topLevelType || "topTouchMove" === topLevelType; +} + +function isStartish(topLevelType) { + return "topMouseDown" === topLevelType || "topTouchStart" === topLevelType; +} + +var validateEventDispatches; + +validateEventDispatches = function(event) { + var dispatchListeners = event._dispatchListeners, dispatchInstances = event._dispatchInstances, listenersIsArr = Array.isArray(dispatchListeners), listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0, instancesIsArr = Array.isArray(dispatchInstances), instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0; + warning(instancesIsArr === listenersIsArr && instancesLen === listenersLen, "EventPluginUtils: Invalid `event`."); +}; + +function executeDispatch(event, simulated, listener, inst) { + var type = event.type || "unknown-event"; + event.currentTarget = EventPluginUtils.getNodeFromInstance(inst), ReactErrorUtils_1.invokeGuardedCallbackAndCatchFirstError(type, listener, void 0, event), + event.currentTarget = null; +} + +function executeDispatchesInOrder(event, simulated) { + var dispatchListeners = event._dispatchListeners, dispatchInstances = event._dispatchInstances; + if (validateEventDispatches(event), Array.isArray(dispatchListeners)) for (var i = 0; i < dispatchListeners.length && !event.isPropagationStopped(); i++) executeDispatch(event, simulated, dispatchListeners[i], dispatchInstances[i]); else dispatchListeners && executeDispatch(event, simulated, dispatchListeners, dispatchInstances); + event._dispatchListeners = null, event._dispatchInstances = null; +} + +function executeDispatchesInOrderStopAtTrueImpl(event) { + var dispatchListeners = event._dispatchListeners, dispatchInstances = event._dispatchInstances; + if (validateEventDispatches(event), Array.isArray(dispatchListeners)) { + for (var i = 0; i < dispatchListeners.length && !event.isPropagationStopped(); i++) if (dispatchListeners[i](event, dispatchInstances[i])) return dispatchInstances[i]; + } else if (dispatchListeners && dispatchListeners(event, dispatchInstances)) return dispatchInstances; + return null; +} + +function executeDispatchesInOrderStopAtTrue(event) { + var ret = executeDispatchesInOrderStopAtTrueImpl(event); + return event._dispatchInstances = null, event._dispatchListeners = null, ret; +} + +function executeDirectDispatch(event) { + validateEventDispatches(event); + var dispatchListener = event._dispatchListeners, dispatchInstance = event._dispatchInstances; + invariant(!Array.isArray(dispatchListener), "executeDirectDispatch(...): Invalid `event`."), + event.currentTarget = dispatchListener ? EventPluginUtils.getNodeFromInstance(dispatchInstance) : null; + var res = dispatchListener ? dispatchListener(event) : null; + return event.currentTarget = null, event._dispatchListeners = null, event._dispatchInstances = null, + res; +} + +function hasDispatches(event) { + return !!event._dispatchListeners; +} + +var EventPluginUtils = { + isEndish: isEndish, + isMoveish: isMoveish, + isStartish: isStartish, + executeDirectDispatch: executeDirectDispatch, + executeDispatchesInOrder: executeDispatchesInOrder, + executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue, + hasDispatches: hasDispatches, + getFiberCurrentPropsFromNode: function(node) { + return ComponentTree.getFiberCurrentPropsFromNode(node); + }, + getInstanceFromNode: function(node) { + return ComponentTree.getInstanceFromNode(node); + }, + getNodeFromInstance: function(node) { + return ComponentTree.getNodeFromInstance(node); + }, + injection: injection$1 +}, EventPluginUtils_1 = EventPluginUtils, fiberHostComponent = null, ReactControlledComponentInjection = { + injectFiberControlledHostComponent: function(hostComponentImpl) { + fiberHostComponent = hostComponentImpl; + } +}, restoreTarget = null, restoreQueue = null; + +function restoreStateOfTarget(target) { + var internalInstance = EventPluginUtils_1.getInstanceFromNode(target); + if (internalInstance) { + if ("number" == typeof internalInstance.tag) { + invariant(fiberHostComponent && "function" == typeof fiberHostComponent.restoreControlledState, "Fiber needs to be injected to handle a fiber target for controlled " + "events."); + var props = EventPluginUtils_1.getFiberCurrentPropsFromNode(internalInstance.stateNode); + return void fiberHostComponent.restoreControlledState(internalInstance.stateNode, internalInstance.type, props); + } + invariant("function" == typeof internalInstance.restoreControlledState, "The internal instance must be a React host component."), + internalInstance.restoreControlledState(); + } +} + +var ReactControlledComponent = { + injection: ReactControlledComponentInjection, + enqueueStateRestore: function(target) { + restoreTarget ? restoreQueue ? restoreQueue.push(target) : restoreQueue = [ target ] : restoreTarget = target; + }, + restoreStateIfNeeded: function() { + if (restoreTarget) { + var target = restoreTarget, queuedTargets = restoreQueue; + if (restoreTarget = null, restoreQueue = null, restoreStateOfTarget(target), queuedTargets) for (var i = 0; i < queuedTargets.length; i++) restoreStateOfTarget(queuedTargets[i]); + } + } +}, ReactControlledComponent_1 = ReactControlledComponent, stackBatchedUpdates = function(fn, a, b, c, d, e) { + return fn(a, b, c, d, e); +}, fiberBatchedUpdates = function(fn, bookkeeping) { + return fn(bookkeeping); +}; + +function performFiberBatchedUpdates(fn, bookkeeping) { + return fiberBatchedUpdates(fn, bookkeeping); +} + +function batchedUpdates(fn, bookkeeping) { + return stackBatchedUpdates(performFiberBatchedUpdates, fn, bookkeeping); +} + +var isNestingBatched = !1; + +function batchedUpdatesWithControlledComponents(fn, bookkeeping) { + if (isNestingBatched) return batchedUpdates(fn, bookkeeping); + isNestingBatched = !0; + try { + return batchedUpdates(fn, bookkeeping); + } finally { + isNestingBatched = !1, ReactControlledComponent_1.restoreStateIfNeeded(); + } +} + +var ReactGenericBatchingInjection = { + injectStackBatchedUpdates: function(_batchedUpdates) { + stackBatchedUpdates = _batchedUpdates; + }, + injectFiberBatchedUpdates: function(_batchedUpdates) { + fiberBatchedUpdates = _batchedUpdates; + } +}, ReactGenericBatching = { + batchedUpdates: batchedUpdatesWithControlledComponents, + injection: ReactGenericBatchingInjection +}, ReactGenericBatching_1 = ReactGenericBatching; + +function ReactNativeFiberErrorDialog(capturedError) { + var componentStack = capturedError.componentStack, error = capturedError.error, errorMessage = void 0, errorStack = void 0, errorType = void 0; + if (error && "object" == typeof error) { + var message = error.message, name = error.name; + errorMessage = (message ? name + ": " + message : name) + "\n\nThis error is located at:" + componentStack, + errorStack = error.stack, errorType = error.constructor; + } else errorMessage = "Unspecified error at:" + componentStack, errorStack = "", + errorType = Error; + var newError = new errorType(errorMessage); + return newError.stack = errorStack, ExceptionsManager.handleException(newError, !1), + !1; +} + +var showDialog$1 = ReactNativeFiberErrorDialog, ReactNativeFiberErrorDialog_1 = { + showDialog: showDialog$1 +}, eventPluginOrder = null, namesToPlugins = {}; + +function recomputePluginOrdering() { + if (eventPluginOrder) for (var pluginName in namesToPlugins) { + var pluginModule = namesToPlugins[pluginName], pluginIndex = eventPluginOrder.indexOf(pluginName); + if (invariant(pluginIndex > -1, "EventPluginRegistry: Cannot inject event plugins that do not exist in " + "the plugin ordering, `%s`.", pluginName), + !EventPluginRegistry.plugins[pluginIndex]) { + invariant(pluginModule.extractEvents, "EventPluginRegistry: Event plugins must implement an `extractEvents` " + "method, but `%s` does not.", pluginName), + EventPluginRegistry.plugins[pluginIndex] = pluginModule; + var publishedEvents = pluginModule.eventTypes; + for (var eventName in publishedEvents) invariant(publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName), "EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.", eventName, pluginName); + } + } +} + +function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { + invariant(!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName), "EventPluginHub: More than one plugin attempted to publish the same " + "event name, `%s`.", eventName), + EventPluginRegistry.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 !0; + } + return !!dispatchConfig.registrationName && (publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName), + !0); +} + +function publishRegistrationName(registrationName, pluginModule, eventName) { + invariant(!EventPluginRegistry.registrationNameModules[registrationName], "EventPluginHub: More than one plugin attempted to publish the same " + "registration name, `%s`.", registrationName), + EventPluginRegistry.registrationNameModules[registrationName] = pluginModule, EventPluginRegistry.registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies; + var lowerCasedName = registrationName.toLowerCase(); + EventPluginRegistry.possibleRegistrationNames[lowerCasedName] = registrationName, + "onDoubleClick" === registrationName && (EventPluginRegistry.possibleRegistrationNames.ondblclick = registrationName); +} + +var EventPluginRegistry = { + plugins: [], + eventNameDispatchConfigs: {}, + registrationNameModules: {}, + registrationNameDependencies: {}, + possibleRegistrationNames: {}, + injectEventPluginOrder: function(injectedEventPluginOrder) { + invariant(!eventPluginOrder, "EventPluginRegistry: Cannot inject event plugin ordering more than " + "once. You are likely trying to load more than one copy of React."), + eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder), recomputePluginOrdering(); + }, + injectEventPluginsByName: function(injectedNamesToPlugins) { + var isOrderingDirty = !1; + for (var pluginName in injectedNamesToPlugins) if (injectedNamesToPlugins.hasOwnProperty(pluginName)) { + var pluginModule = injectedNamesToPlugins[pluginName]; + namesToPlugins.hasOwnProperty(pluginName) && namesToPlugins[pluginName] === pluginModule || (invariant(!namesToPlugins[pluginName], "EventPluginRegistry: Cannot inject two different event plugins " + "using the same name, `%s`.", pluginName), + namesToPlugins[pluginName] = pluginModule, isOrderingDirty = !0); + } + isOrderingDirty && recomputePluginOrdering(); + } +}, EventPluginRegistry_1 = EventPluginRegistry; + +function accumulateInto(current, next) { + return invariant(null != next, "accumulateInto(...): Accumulated items must not be null or undefined."), + null == current ? next : Array.isArray(current) ? Array.isArray(next) ? (current.push.apply(current, next), + current) : (current.push(next), current) : Array.isArray(next) ? [ current ].concat(next) : [ current, next ]; +} + +var accumulateInto_1 = accumulateInto; + +function forEachAccumulated(arr, cb, scope) { + Array.isArray(arr) ? arr.forEach(cb, scope) : arr && cb.call(scope, arr); +} + +var forEachAccumulated_1 = forEachAccumulated, eventQueue = null, executeDispatchesAndRelease = function(event, simulated) { + event && (EventPluginUtils_1.executeDispatchesInOrder(event, simulated), event.isPersistent() || event.constructor.release(event)); +}, executeDispatchesAndReleaseSimulated = function(e) { + return executeDispatchesAndRelease(e, !0); +}, executeDispatchesAndReleaseTopLevel = function(e) { + return executeDispatchesAndRelease(e, !1); +}; + +function isInteractive(tag) { + return "button" === tag || "input" === tag || "select" === tag || "textarea" === tag; +} + +function shouldPreventMouseEvent(name, type, props) { + switch (name) { + case "onClick": + case "onClickCapture": + case "onDoubleClick": + case "onDoubleClickCapture": + case "onMouseDown": + case "onMouseDownCapture": + case "onMouseMove": + case "onMouseMoveCapture": + case "onMouseUp": + case "onMouseUpCapture": + return !(!props.disabled || !isInteractive(type)); + + default: + return !1; + } +} + +var EventPluginHub = { + injection: { + injectEventPluginOrder: EventPluginRegistry_1.injectEventPluginOrder, + injectEventPluginsByName: EventPluginRegistry_1.injectEventPluginsByName + }, + getListener: function(inst, registrationName) { + var listener; + if ("number" == typeof inst.tag) { + var stateNode = inst.stateNode; + if (!stateNode) return null; + var props = EventPluginUtils_1.getFiberCurrentPropsFromNode(stateNode); + if (!props) return null; + if (listener = props[registrationName], shouldPreventMouseEvent(registrationName, inst.type, props)) return null; + } else { + var currentElement = inst._currentElement; + if ("string" == typeof currentElement || "number" == typeof currentElement) return null; + if (!inst._rootNodeID) return null; + var _props = currentElement.props; + if (listener = _props[registrationName], shouldPreventMouseEvent(registrationName, currentElement.type, _props)) return null; + } + return invariant(!listener || "function" == typeof listener, "Expected %s listener to be a function, instead got type %s", registrationName, typeof listener), + listener; + }, + extractEvents: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) { + for (var events, plugins = EventPluginRegistry_1.plugins, i = 0; i < plugins.length; i++) { + var possiblePlugin = plugins[i]; + if (possiblePlugin) { + var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); + extractedEvents && (events = accumulateInto_1(events, extractedEvents)); + } + } + return events; + }, + enqueueEvents: function(events) { + events && (eventQueue = accumulateInto_1(eventQueue, events)); + }, + processEventQueue: function(simulated) { + var processingEventQueue = eventQueue; + eventQueue = null, simulated ? forEachAccumulated_1(processingEventQueue, executeDispatchesAndReleaseSimulated) : forEachAccumulated_1(processingEventQueue, executeDispatchesAndReleaseTopLevel), + invariant(!eventQueue, "processEventQueue(): Additional events were enqueued while processing " + "an event queue. Support for this has not yet been implemented."), + ReactErrorUtils_1.rethrowCaughtError(); + } +}, EventPluginHub_1 = EventPluginHub, ReactTypeOfWork = { + IndeterminateComponent: 0, + FunctionalComponent: 1, + ClassComponent: 2, + HostRoot: 3, + HostPortal: 4, + HostComponent: 5, + HostText: 6, + CoroutineComponent: 7, + CoroutineHandlerPhase: 8, + YieldComponent: 9, + Fragment: 10 +}, HostComponent = ReactTypeOfWork.HostComponent; + +function getParent(inst) { + if (void 0 !== inst._hostParent) return inst._hostParent; + if ("number" == typeof inst.tag) { + do { + inst = inst.return; + } while (inst && inst.tag !== HostComponent); + if (inst) return inst; + } + return null; +} + +function getLowestCommonAncestor(instA, instB) { + for (var depthA = 0, tempA = instA; tempA; tempA = getParent(tempA)) depthA++; + for (var depthB = 0, tempB = instB; tempB; tempB = getParent(tempB)) depthB++; + for (;depthA - depthB > 0; ) instA = getParent(instA), depthA--; + for (;depthB - depthA > 0; ) instB = getParent(instB), depthB--; + for (var depth = depthA; depth--; ) { + if (instA === instB || instA === instB.alternate) return instA; + instA = getParent(instA), instB = getParent(instB); + } + return null; +} + +function isAncestor(instA, instB) { + for (;instB; ) { + if (instA === instB || instA === instB.alternate) return !0; + instB = getParent(instB); + } + return !1; +} + +function getParentInstance(inst) { + return getParent(inst); +} + +function traverseTwoPhase(inst, fn, arg) { + for (var path = []; inst; ) path.push(inst), inst = getParent(inst); + var i; + for (i = path.length; i-- > 0; ) fn(path[i], "captured", arg); + for (i = 0; i < path.length; i++) fn(path[i], "bubbled", arg); +} + +function traverseEnterLeave(from, to, fn, argFrom, argTo) { + for (var common = from && to ? getLowestCommonAncestor(from, to) : null, pathFrom = []; from && from !== common; ) pathFrom.push(from), + from = getParent(from); + for (var pathTo = []; to && to !== common; ) pathTo.push(to), to = getParent(to); + var i; + for (i = 0; i < pathFrom.length; i++) fn(pathFrom[i], "bubbled", argFrom); + for (i = pathTo.length; i-- > 0; ) fn(pathTo[i], "captured", argTo); +} + +var ReactTreeTraversal = { + isAncestor: isAncestor, + getLowestCommonAncestor: getLowestCommonAncestor, + getParentInstance: getParentInstance, + traverseTwoPhase: traverseTwoPhase, + traverseEnterLeave: traverseEnterLeave +}, getListener = EventPluginHub_1.getListener; + +function listenerAtPhase(inst, event, propagationPhase) { + var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; + return getListener(inst, registrationName); +} + +function accumulateDirectionalDispatches(inst, phase, event) { + warning(inst, "Dispatching inst must not be null"); + var listener = listenerAtPhase(inst, event, phase); + listener && (event._dispatchListeners = accumulateInto_1(event._dispatchListeners, listener), + event._dispatchInstances = accumulateInto_1(event._dispatchInstances, inst)); +} + +function accumulateTwoPhaseDispatchesSingle(event) { + event && event.dispatchConfig.phasedRegistrationNames && ReactTreeTraversal.traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event); +} + +function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { + if (event && event.dispatchConfig.phasedRegistrationNames) { + var targetInst = event._targetInst, parentInst = targetInst ? ReactTreeTraversal.getParentInstance(targetInst) : null; + ReactTreeTraversal.traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event); + } +} + +function accumulateDispatches(inst, ignoredDirection, event) { + if (inst && event && event.dispatchConfig.registrationName) { + var registrationName = event.dispatchConfig.registrationName, listener = getListener(inst, registrationName); + listener && (event._dispatchListeners = accumulateInto_1(event._dispatchListeners, listener), + event._dispatchInstances = accumulateInto_1(event._dispatchInstances, inst)); + } +} + +function accumulateDirectDispatchesSingle(event) { + event && event.dispatchConfig.registrationName && accumulateDispatches(event._targetInst, null, event); +} + +function accumulateTwoPhaseDispatches(events) { + forEachAccumulated_1(events, accumulateTwoPhaseDispatchesSingle); +} + +function accumulateTwoPhaseDispatchesSkipTarget(events) { + forEachAccumulated_1(events, accumulateTwoPhaseDispatchesSingleSkipTarget); +} + +function accumulateEnterLeaveDispatches(leave, enter, from, to) { + ReactTreeTraversal.traverseEnterLeave(from, to, accumulateDispatches, leave, enter); +} + +function accumulateDirectDispatches(events) { + forEachAccumulated_1(events, accumulateDirectDispatchesSingle); +} + +var EventPropagators = { + accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches, + accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget, + accumulateDirectDispatches: accumulateDirectDispatches, + accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches +}, EventPropagators_1 = EventPropagators, oneArgumentPooler = function(copyFieldsFrom) { + var Klass = this; + if (Klass.instancePool.length) { + var instance = Klass.instancePool.pop(); + return Klass.call(instance, copyFieldsFrom), instance; + } + return new Klass(copyFieldsFrom); +}, twoArgumentPooler = function(a1, a2) { + var Klass = this; + if (Klass.instancePool.length) { + var instance = Klass.instancePool.pop(); + return Klass.call(instance, a1, a2), instance; + } + return new Klass(a1, a2); +}, threeArgumentPooler = function(a1, a2, a3) { + var Klass = this; + if (Klass.instancePool.length) { + var instance = Klass.instancePool.pop(); + return Klass.call(instance, a1, a2, a3), instance; + } + return new Klass(a1, a2, a3); +}, fourArgumentPooler = function(a1, a2, a3, a4) { + var Klass = this; + if (Klass.instancePool.length) { + var instance = Klass.instancePool.pop(); + return Klass.call(instance, a1, a2, a3, a4), instance; + } + return new Klass(a1, a2, a3, a4); +}, standardReleaser = function(instance) { + var Klass = this; + invariant(instance instanceof Klass, "Trying to release an instance into a pool of a different type."), + instance.destructor(), Klass.instancePool.length < Klass.poolSize && Klass.instancePool.push(instance); +}, DEFAULT_POOL_SIZE = 10, DEFAULT_POOLER = oneArgumentPooler, addPoolingTo = function(CopyConstructor, pooler) { + var NewKlass = CopyConstructor; + return NewKlass.instancePool = [], NewKlass.getPooled = pooler || DEFAULT_POOLER, + NewKlass.poolSize || (NewKlass.poolSize = DEFAULT_POOL_SIZE), NewKlass.release = standardReleaser, + NewKlass; +}, PooledClass = { + addPoolingTo: addPoolingTo, + oneArgumentPooler: oneArgumentPooler, + twoArgumentPooler: twoArgumentPooler, + threeArgumentPooler: threeArgumentPooler, + fourArgumentPooler: fourArgumentPooler +}, PooledClass_1 = PooledClass, didWarnForAddedNewProperty = !1, isProxySupported = "function" == typeof Proxy, shouldBeReleasedProperties = [ "dispatchConfig", "_targetInst", "nativeEvent", "isDefaultPrevented", "isPropagationStopped", "_dispatchListeners", "_dispatchInstances" ], EventInterface = { + type: null, + target: null, + currentTarget: emptyFunction.thatReturnsNull, + eventPhase: null, + bubbles: null, + cancelable: null, + timeStamp: function(event) { + return event.timeStamp || Date.now(); + }, + defaultPrevented: null, + isTrusted: null +}; + +function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) { + delete this.nativeEvent, delete this.preventDefault, delete this.stopPropagation, + this.dispatchConfig = dispatchConfig, this._targetInst = targetInst, this.nativeEvent = nativeEvent; + var Interface = this.constructor.Interface; + for (var propName in Interface) if (Interface.hasOwnProperty(propName)) { + delete this[propName]; + var normalize = Interface[propName]; + normalize ? this[propName] = normalize(nativeEvent) : "target" === propName ? this.target = nativeEventTarget : this[propName] = nativeEvent[propName]; + } + var defaultPrevented = null != nativeEvent.defaultPrevented ? nativeEvent.defaultPrevented : !1 === nativeEvent.returnValue; + return this.isDefaultPrevented = defaultPrevented ? emptyFunction.thatReturnsTrue : emptyFunction.thatReturnsFalse, + this.isPropagationStopped = emptyFunction.thatReturnsFalse, this; +} + +Object.assign(SyntheticEvent.prototype, { + preventDefault: function() { + this.defaultPrevented = !0; + var event = this.nativeEvent; + event && (event.preventDefault ? event.preventDefault() : "unknown" != typeof event.returnValue && (event.returnValue = !1), + this.isDefaultPrevented = emptyFunction.thatReturnsTrue); + }, + stopPropagation: function() { + var event = this.nativeEvent; + event && (event.stopPropagation ? event.stopPropagation() : "unknown" != typeof event.cancelBubble && (event.cancelBubble = !0), + this.isPropagationStopped = emptyFunction.thatReturnsTrue); + }, + persist: function() { + this.isPersistent = emptyFunction.thatReturnsTrue; + }, + isPersistent: emptyFunction.thatReturnsFalse, + destructor: function() { + var Interface = this.constructor.Interface; + for (var propName in Interface) Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName])); + for (var i = 0; i < shouldBeReleasedProperties.length; i++) this[shouldBeReleasedProperties[i]] = null; + Object.defineProperty(this, "nativeEvent", getPooledWarningPropertyDefinition("nativeEvent", null)), + Object.defineProperty(this, "preventDefault", getPooledWarningPropertyDefinition("preventDefault", emptyFunction)), + Object.defineProperty(this, "stopPropagation", getPooledWarningPropertyDefinition("stopPropagation", emptyFunction)); + } +}), SyntheticEvent.Interface = EventInterface, isProxySupported && (SyntheticEvent = new Proxy(SyntheticEvent, { + construct: function(target, args) { + return this.apply(target, Object.create(target.prototype), args); + }, + apply: function(constructor, that, args) { + return new Proxy(constructor.apply(that, args), { + set: function(target, prop, value) { + return "isPersistent" === prop || target.constructor.Interface.hasOwnProperty(prop) || -1 !== shouldBeReleasedProperties.indexOf(prop) || (warning(didWarnForAddedNewProperty || target.isPersistent(), "This synthetic event is reused for performance reasons. If you're " + "seeing this, you're adding a new property in the synthetic event object. " + "The property is never released. See " + "https://fb.me/react-event-pooling for more information."), + didWarnForAddedNewProperty = !0), target[prop] = value, !0; + } + }); + } +})), SyntheticEvent.augmentClass = function(Class, Interface) { + var Super = this, E = function() {}; + E.prototype = Super.prototype; + var prototype = new E(); + Object.assign(prototype, Class.prototype), Class.prototype = prototype, Class.prototype.constructor = Class, + Class.Interface = Object.assign({}, Super.Interface, Interface), Class.augmentClass = Super.augmentClass, + PooledClass_1.addPoolingTo(Class, PooledClass_1.fourArgumentPooler); +}, PooledClass_1.addPoolingTo(SyntheticEvent, PooledClass_1.fourArgumentPooler); + +var SyntheticEvent_1 = SyntheticEvent; + +function getPooledWarningPropertyDefinition(propName, getVal) { + var isFunction = "function" == typeof getVal; + return { + configurable: !0, + set: set, + get: get + }; + function set(val) { + return warn(isFunction ? "setting the method" : "setting the property", "This is effectively a no-op"), + val; + } + function get() { + return warn(isFunction ? "accessing the method" : "accessing the property", isFunction ? "This is a no-op function" : "This is set to null"), + getVal; + } + function warn(action, result) { + warning(!1, "This synthetic event is reused for performance reasons. If you're seeing this, " + "you're %s `%s` on a released/nullified synthetic event. %s. " + "If you must keep the original synthetic event around, use event.persist(). " + "See https://fb.me/react-event-pooling for more information.", action, propName, result); + } +} + +var _extends = Object.assign || function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]); + } + return target; +}, customBubblingEventTypes = UIManager.customBubblingEventTypes, customDirectEventTypes = UIManager.customDirectEventTypes, allTypesByEventName = {}; + +for (var bubblingTypeName in customBubblingEventTypes) allTypesByEventName[bubblingTypeName] = customBubblingEventTypes[bubblingTypeName]; + +for (var directTypeName in customDirectEventTypes) warning(!customBubblingEventTypes[directTypeName], "Event cannot be both direct and bubbling: %s", directTypeName), +allTypesByEventName[directTypeName] = customDirectEventTypes[directTypeName]; + +var ReactNativeBridgeEventPlugin = { + eventTypes: _extends({}, customBubblingEventTypes, customDirectEventTypes), + extractEvents: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) { + var bubbleDispatchConfig = customBubblingEventTypes[topLevelType], directDispatchConfig = customDirectEventTypes[topLevelType], event = SyntheticEvent_1.getPooled(bubbleDispatchConfig || directDispatchConfig, targetInst, nativeEvent, nativeEventTarget); + if (bubbleDispatchConfig) EventPropagators_1.accumulateTwoPhaseDispatches(event); else { + if (!directDispatchConfig) return null; + EventPropagators_1.accumulateDirectDispatches(event); + } + return event; + } +}, ReactNativeBridgeEventPlugin_1 = ReactNativeBridgeEventPlugin, instanceCache = {}, instanceProps = {}; + +function getRenderedHostOrTextFromComponent(component) { + for (var rendered; rendered = component._renderedComponent; ) component = rendered; + return component; +} + +function precacheNode(inst, tag) { + var nativeInst = getRenderedHostOrTextFromComponent(inst); + instanceCache[tag] = nativeInst; +} + +function precacheFiberNode(hostInst, tag) { + instanceCache[tag] = hostInst; +} + +function uncacheNode(inst) { + var tag = inst._rootNodeID; + tag && delete instanceCache[tag]; +} + +function uncacheFiberNode(tag) { + delete instanceCache[tag], delete instanceProps[tag]; +} + +function getInstanceFromTag(tag) { + return instanceCache[tag] || null; +} + +function getTagFromInstance(inst) { + var tag = "number" != typeof inst.tag ? inst._rootNodeID : inst.stateNode._nativeTag; + return invariant(tag, "All native instances should have a tag."), tag; +} + +function getFiberCurrentPropsFromNode(stateNode) { + return instanceProps[stateNode._nativeTag] || null; +} + +function updateFiberProps(tag, props) { + instanceProps[tag] = props; +} + +var ReactNativeComponentTree = { + getClosestInstanceFromNode: getInstanceFromTag, + getInstanceFromNode: getInstanceFromTag, + getNodeFromInstance: getTagFromInstance, + precacheFiberNode: precacheFiberNode, + precacheNode: precacheNode, + uncacheFiberNode: uncacheFiberNode, + uncacheNode: uncacheNode, + getFiberCurrentPropsFromNode: getFiberCurrentPropsFromNode, + updateFiberProps: updateFiberProps +}, ReactNativeComponentTree_1 = ReactNativeComponentTree; + +function runEventQueueInBatch(events) { + EventPluginHub_1.enqueueEvents(events), EventPluginHub_1.processEventQueue(!1); +} + +var ReactEventEmitterMixin = { + handleTopLevel: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) { + runEventQueueInBatch(EventPluginHub_1.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget)); + } +}, ReactEventEmitterMixin_1 = ReactEventEmitterMixin, INITIAL_TAG_COUNT = 1, ReactNativeTagHandles = { + tagsStartAt: INITIAL_TAG_COUNT, + tagCount: INITIAL_TAG_COUNT, + allocateTag: function() { + for (;this.reactTagIsNativeTopRootID(ReactNativeTagHandles.tagCount); ) ReactNativeTagHandles.tagCount++; + var tag = ReactNativeTagHandles.tagCount; + return ReactNativeTagHandles.tagCount++, tag; + }, + assertRootTag: function(tag) { + invariant(this.reactTagIsNativeTopRootID(tag), "Expect a native root tag, instead got %s", tag); + }, + reactTagIsNativeTopRootID: function(reactTag) { + return reactTag % 10 == 1; + } +}, ReactNativeTagHandles_1 = ReactNativeTagHandles, _extends$1 = Object.assign || function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]); + } + return target; +}, EMPTY_NATIVE_EVENT = {}, touchSubsequence = function(touches, indices) { + for (var ret = [], i = 0; i < indices.length; i++) ret.push(touches[indices[i]]); + return ret; +}, removeTouchesAtIndices = function(touches, indices) { + for (var rippedOut = [], temp = touches, i = 0; i < indices.length; i++) { + var index = indices[i]; + rippedOut.push(touches[index]), temp[index] = null; + } + for (var fillAt = 0, j = 0; j < temp.length; j++) { + var cur = temp[j]; + null !== cur && (temp[fillAt++] = cur); + } + return temp.length = fillAt, rippedOut; +}, ReactNativeEventEmitter = _extends$1({}, ReactEventEmitterMixin_1, { + registrationNames: EventPluginRegistry_1.registrationNameModules, + getListener: EventPluginHub_1.getListener, + _receiveRootNodeIDEvent: function(rootNodeID, topLevelType, nativeEventParam) { + var nativeEvent = nativeEventParam || EMPTY_NATIVE_EVENT, inst = ReactNativeComponentTree_1.getInstanceFromNode(rootNodeID); + ReactGenericBatching_1.batchedUpdates(function() { + ReactNativeEventEmitter.handleTopLevel(topLevelType, inst, nativeEvent, nativeEvent.target); + }); + }, + receiveEvent: function(tag, topLevelType, nativeEventParam) { + var rootNodeID = tag; + ReactNativeEventEmitter._receiveRootNodeIDEvent(rootNodeID, topLevelType, nativeEventParam); + }, + receiveTouches: function(eventTopLevelType, touches, changedIndices) { + for (var changedTouches = "topTouchEnd" === eventTopLevelType || "topTouchCancel" === eventTopLevelType ? removeTouchesAtIndices(touches, changedIndices) : touchSubsequence(touches, changedIndices), jj = 0; jj < changedTouches.length; jj++) { + var touch = changedTouches[jj]; + touch.changedTouches = changedTouches, touch.touches = touches; + var nativeEvent = touch, rootNodeID = null, target = nativeEvent.target; + null !== target && void 0 !== target && (target < ReactNativeTagHandles_1.tagsStartAt ? warning(!1, "A view is reporting that a touch occurred on tag zero.") : rootNodeID = target), + ReactNativeEventEmitter._receiveRootNodeIDEvent(rootNodeID, eventTopLevelType, nativeEvent); + } + } +}), ReactNativeEventEmitter_1 = ReactNativeEventEmitter, ReactNativeEventPluginOrder = [ "ResponderEventPlugin", "ReactNativeBridgeEventPlugin" ], ReactNativeEventPluginOrder_1 = ReactNativeEventPluginOrder, ReactNativeGlobalResponderHandler = { + onChange: function(from, to, blockNativeResponder) { + if (null !== to) { + var tag = "number" != typeof to.tag ? to._rootNodeID : to.stateNode._nativeTag; + UIManager.setJSResponder(tag, blockNativeResponder); + } else UIManager.clearJSResponder(); + } +}, ReactNativeGlobalResponderHandler_1 = ReactNativeGlobalResponderHandler, ResponderEventInterface = { + touchHistory: function(nativeEvent) { + return null; + } +}; + +function ResponderSyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { + return SyntheticEvent_1.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); +} + +SyntheticEvent_1.augmentClass(ResponderSyntheticEvent, ResponderEventInterface); + +var ResponderSyntheticEvent_1 = ResponderSyntheticEvent, isEndish$2 = EventPluginUtils_1.isEndish, isMoveish$2 = EventPluginUtils_1.isMoveish, isStartish$2 = EventPluginUtils_1.isStartish, MAX_TOUCH_BANK = 20, touchBank = [], touchHistory = { + touchBank: touchBank, + numberActiveTouches: 0, + indexOfSingleActiveTouch: -1, + mostRecentTimeStamp: 0 +}; + +function timestampForTouch(touch) { + return touch.timeStamp || touch.timestamp; +} + +function createTouchRecord(touch) { + return { + touchActive: !0, + startPageX: touch.pageX, + startPageY: touch.pageY, + startTimeStamp: timestampForTouch(touch), + currentPageX: touch.pageX, + currentPageY: touch.pageY, + currentTimeStamp: timestampForTouch(touch), + previousPageX: touch.pageX, + previousPageY: touch.pageY, + previousTimeStamp: timestampForTouch(touch) + }; +} + +function resetTouchRecord(touchRecord, touch) { + touchRecord.touchActive = !0, touchRecord.startPageX = touch.pageX, touchRecord.startPageY = touch.pageY, + touchRecord.startTimeStamp = timestampForTouch(touch), touchRecord.currentPageX = touch.pageX, + touchRecord.currentPageY = touch.pageY, touchRecord.currentTimeStamp = timestampForTouch(touch), + touchRecord.previousPageX = touch.pageX, touchRecord.previousPageY = touch.pageY, + touchRecord.previousTimeStamp = timestampForTouch(touch); +} + +function getTouchIdentifier(_ref) { + var identifier = _ref.identifier; + return invariant(null != identifier, "Touch object is missing identifier."), warning(identifier <= MAX_TOUCH_BANK, "Touch identifier %s is greater than maximum supported %s which causes " + "performance issues backfilling array locations for all of the indices.", identifier, MAX_TOUCH_BANK), + identifier; +} + +function recordTouchStart(touch) { + var identifier = getTouchIdentifier(touch), touchRecord = touchBank[identifier]; + touchRecord ? resetTouchRecord(touchRecord, touch) : touchBank[identifier] = createTouchRecord(touch), + touchHistory.mostRecentTimeStamp = timestampForTouch(touch); +} + +function recordTouchMove(touch) { + var touchRecord = touchBank[getTouchIdentifier(touch)]; + touchRecord ? (touchRecord.touchActive = !0, touchRecord.previousPageX = touchRecord.currentPageX, + touchRecord.previousPageY = touchRecord.currentPageY, touchRecord.previousTimeStamp = touchRecord.currentTimeStamp, + touchRecord.currentPageX = touch.pageX, touchRecord.currentPageY = touch.pageY, + touchRecord.currentTimeStamp = timestampForTouch(touch), touchHistory.mostRecentTimeStamp = timestampForTouch(touch)) : console.error("Cannot record touch move without a touch start.\n" + "Touch Move: %s\n", "Touch Bank: %s", printTouch(touch), printTouchBank()); +} + +function recordTouchEnd(touch) { + var touchRecord = touchBank[getTouchIdentifier(touch)]; + touchRecord ? (touchRecord.touchActive = !1, touchRecord.previousPageX = touchRecord.currentPageX, + touchRecord.previousPageY = touchRecord.currentPageY, touchRecord.previousTimeStamp = touchRecord.currentTimeStamp, + touchRecord.currentPageX = touch.pageX, touchRecord.currentPageY = touch.pageY, + touchRecord.currentTimeStamp = timestampForTouch(touch), touchHistory.mostRecentTimeStamp = timestampForTouch(touch)) : console.error("Cannot record touch end without a touch start.\n" + "Touch End: %s\n", "Touch Bank: %s", printTouch(touch), printTouchBank()); +} + +function printTouch(touch) { + return JSON.stringify({ + identifier: touch.identifier, + pageX: touch.pageX, + pageY: touch.pageY, + timestamp: timestampForTouch(touch) + }); +} + +function printTouchBank() { + var printed = JSON.stringify(touchBank.slice(0, MAX_TOUCH_BANK)); + return touchBank.length > MAX_TOUCH_BANK && (printed += " (original size: " + touchBank.length + ")"), + printed; +} + +var ResponderTouchHistoryStore = { + recordTouchTrack: function(topLevelType, nativeEvent) { + if (isMoveish$2(topLevelType)) nativeEvent.changedTouches.forEach(recordTouchMove); else if (isStartish$2(topLevelType)) nativeEvent.changedTouches.forEach(recordTouchStart), + touchHistory.numberActiveTouches = nativeEvent.touches.length, 1 === touchHistory.numberActiveTouches && (touchHistory.indexOfSingleActiveTouch = nativeEvent.touches[0].identifier); else if (isEndish$2(topLevelType) && (nativeEvent.changedTouches.forEach(recordTouchEnd), + touchHistory.numberActiveTouches = nativeEvent.touches.length, 1 === touchHistory.numberActiveTouches)) { + for (var i = 0; i < touchBank.length; i++) { + var touchTrackToCheck = touchBank[i]; + if (null != touchTrackToCheck && touchTrackToCheck.touchActive) { + touchHistory.indexOfSingleActiveTouch = i; + break; + } + } + var activeRecord = touchBank[touchHistory.indexOfSingleActiveTouch]; + warning(null != activeRecord && activeRecord.touchActive, "Cannot find single active touch."); + } + }, + touchHistory: touchHistory +}, ResponderTouchHistoryStore_1 = ResponderTouchHistoryStore; + +function accumulate(current, next) { + return invariant(null != next, "accumulate(...): Accumulated items must be not be null or undefined."), + null == current ? next : Array.isArray(current) ? current.concat(next) : Array.isArray(next) ? [ current ].concat(next) : [ current, next ]; +} + +var accumulate_1 = accumulate, isStartish$1 = EventPluginUtils_1.isStartish, isMoveish$1 = EventPluginUtils_1.isMoveish, isEndish$1 = EventPluginUtils_1.isEndish, executeDirectDispatch$1 = EventPluginUtils_1.executeDirectDispatch, hasDispatches$1 = EventPluginUtils_1.hasDispatches, executeDispatchesInOrderStopAtTrue$1 = EventPluginUtils_1.executeDispatchesInOrderStopAtTrue, responderInst = null, trackedTouchCount = 0, previousActiveTouches = 0, changeResponder = function(nextResponderInst, blockHostResponder) { + var oldResponderInst = responderInst; + responderInst = nextResponderInst, null !== ResponderEventPlugin.GlobalResponderHandler && ResponderEventPlugin.GlobalResponderHandler.onChange(oldResponderInst, nextResponderInst, blockHostResponder); +}, eventTypes = { + startShouldSetResponder: { + phasedRegistrationNames: { + bubbled: "onStartShouldSetResponder", + captured: "onStartShouldSetResponderCapture" + } + }, + scrollShouldSetResponder: { + phasedRegistrationNames: { + bubbled: "onScrollShouldSetResponder", + captured: "onScrollShouldSetResponderCapture" + } + }, + selectionChangeShouldSetResponder: { + phasedRegistrationNames: { + bubbled: "onSelectionChangeShouldSetResponder", + captured: "onSelectionChangeShouldSetResponderCapture" + } + }, + moveShouldSetResponder: { + phasedRegistrationNames: { + bubbled: "onMoveShouldSetResponder", + captured: "onMoveShouldSetResponderCapture" + } + }, + responderStart: { + registrationName: "onResponderStart" + }, + responderMove: { + registrationName: "onResponderMove" + }, + responderEnd: { + registrationName: "onResponderEnd" + }, + responderRelease: { + registrationName: "onResponderRelease" + }, + responderTerminationRequest: { + registrationName: "onResponderTerminationRequest" + }, + responderGrant: { + registrationName: "onResponderGrant" + }, + responderReject: { + registrationName: "onResponderReject" + }, + responderTerminate: { + registrationName: "onResponderTerminate" + } +}; + +function setResponderAndExtractTransfer(topLevelType, targetInst, nativeEvent, nativeEventTarget) { + var shouldSetEventType = isStartish$1(topLevelType) ? eventTypes.startShouldSetResponder : isMoveish$1(topLevelType) ? eventTypes.moveShouldSetResponder : "topSelectionChange" === topLevelType ? eventTypes.selectionChangeShouldSetResponder : eventTypes.scrollShouldSetResponder, bubbleShouldSetFrom = responderInst ? ReactTreeTraversal.getLowestCommonAncestor(responderInst, targetInst) : targetInst, skipOverBubbleShouldSetFrom = bubbleShouldSetFrom === responderInst, shouldSetEvent = ResponderSyntheticEvent_1.getPooled(shouldSetEventType, bubbleShouldSetFrom, nativeEvent, nativeEventTarget); + shouldSetEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, skipOverBubbleShouldSetFrom ? EventPropagators_1.accumulateTwoPhaseDispatchesSkipTarget(shouldSetEvent) : EventPropagators_1.accumulateTwoPhaseDispatches(shouldSetEvent); + var wantsResponderInst = executeDispatchesInOrderStopAtTrue$1(shouldSetEvent); + if (shouldSetEvent.isPersistent() || shouldSetEvent.constructor.release(shouldSetEvent), + !wantsResponderInst || wantsResponderInst === responderInst) return null; + var extracted, grantEvent = ResponderSyntheticEvent_1.getPooled(eventTypes.responderGrant, wantsResponderInst, nativeEvent, nativeEventTarget); + grantEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, EventPropagators_1.accumulateDirectDispatches(grantEvent); + var blockHostResponder = !0 === executeDirectDispatch$1(grantEvent); + if (responderInst) { + var terminationRequestEvent = ResponderSyntheticEvent_1.getPooled(eventTypes.responderTerminationRequest, responderInst, nativeEvent, nativeEventTarget); + terminationRequestEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, + EventPropagators_1.accumulateDirectDispatches(terminationRequestEvent); + var shouldSwitch = !hasDispatches$1(terminationRequestEvent) || executeDirectDispatch$1(terminationRequestEvent); + if (terminationRequestEvent.isPersistent() || terminationRequestEvent.constructor.release(terminationRequestEvent), + shouldSwitch) { + var terminateEvent = ResponderSyntheticEvent_1.getPooled(eventTypes.responderTerminate, responderInst, nativeEvent, nativeEventTarget); + terminateEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, EventPropagators_1.accumulateDirectDispatches(terminateEvent), + extracted = accumulate_1(extracted, [ grantEvent, terminateEvent ]), changeResponder(wantsResponderInst, blockHostResponder); + } else { + var rejectEvent = ResponderSyntheticEvent_1.getPooled(eventTypes.responderReject, wantsResponderInst, nativeEvent, nativeEventTarget); + rejectEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, EventPropagators_1.accumulateDirectDispatches(rejectEvent), + extracted = accumulate_1(extracted, rejectEvent); + } + } else extracted = accumulate_1(extracted, grantEvent), changeResponder(wantsResponderInst, blockHostResponder); + return extracted; +} + +function canTriggerTransfer(topLevelType, topLevelInst, nativeEvent) { + return topLevelInst && ("topScroll" === topLevelType && !nativeEvent.responderIgnoreScroll || trackedTouchCount > 0 && "topSelectionChange" === topLevelType || isStartish$1(topLevelType) || isMoveish$1(topLevelType)); +} + +function noResponderTouches(nativeEvent) { + var touches = nativeEvent.touches; + if (!touches || 0 === touches.length) return !0; + for (var i = 0; i < touches.length; i++) { + var activeTouch = touches[i], target = activeTouch.target; + if (null !== target && void 0 !== target && 0 !== target) { + var targetInst = EventPluginUtils_1.getInstanceFromNode(target); + if (ReactTreeTraversal.isAncestor(responderInst, targetInst)) return !1; + } + } + return !0; +} + +var ResponderEventPlugin = { + _getResponder: function() { + return responderInst; + }, + eventTypes: eventTypes, + extractEvents: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) { + if (isStartish$1(topLevelType)) trackedTouchCount += 1; else if (isEndish$1(topLevelType)) { + if (!(trackedTouchCount >= 0)) return console.error("Ended a touch event which was not counted in `trackedTouchCount`."), + null; + trackedTouchCount -= 1; + } + ResponderTouchHistoryStore_1.recordTouchTrack(topLevelType, nativeEvent); + var extracted = canTriggerTransfer(topLevelType, targetInst, nativeEvent) ? setResponderAndExtractTransfer(topLevelType, targetInst, nativeEvent, nativeEventTarget) : null, isResponderTouchStart = responderInst && isStartish$1(topLevelType), isResponderTouchMove = responderInst && isMoveish$1(topLevelType), isResponderTouchEnd = responderInst && isEndish$1(topLevelType), incrementalTouch = isResponderTouchStart ? eventTypes.responderStart : isResponderTouchMove ? eventTypes.responderMove : isResponderTouchEnd ? eventTypes.responderEnd : null; + if (incrementalTouch) { + var gesture = ResponderSyntheticEvent_1.getPooled(incrementalTouch, responderInst, nativeEvent, nativeEventTarget); + gesture.touchHistory = ResponderTouchHistoryStore_1.touchHistory, EventPropagators_1.accumulateDirectDispatches(gesture), + extracted = accumulate_1(extracted, gesture); + } + var isResponderTerminate = responderInst && "topTouchCancel" === topLevelType, isResponderRelease = responderInst && !isResponderTerminate && isEndish$1(topLevelType) && noResponderTouches(nativeEvent), finalTouch = isResponderTerminate ? eventTypes.responderTerminate : isResponderRelease ? eventTypes.responderRelease : null; + if (finalTouch) { + var finalEvent = ResponderSyntheticEvent_1.getPooled(finalTouch, responderInst, nativeEvent, nativeEventTarget); + finalEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, EventPropagators_1.accumulateDirectDispatches(finalEvent), + extracted = accumulate_1(extracted, finalEvent), changeResponder(null); + } + var numberActiveTouches = ResponderTouchHistoryStore_1.touchHistory.numberActiveTouches; + return ResponderEventPlugin.GlobalInteractionHandler && numberActiveTouches !== previousActiveTouches && ResponderEventPlugin.GlobalInteractionHandler.onChange(numberActiveTouches), + previousActiveTouches = numberActiveTouches, extracted; + }, + GlobalResponderHandler: null, + GlobalInteractionHandler: null, + injection: { + injectGlobalResponderHandler: function(GlobalResponderHandler) { + ResponderEventPlugin.GlobalResponderHandler = GlobalResponderHandler; + }, + injectGlobalInteractionHandler: function(GlobalInteractionHandler) { + ResponderEventPlugin.GlobalInteractionHandler = GlobalInteractionHandler; + } + } +}, ResponderEventPlugin_1 = ResponderEventPlugin; + +function inject() { + RCTEventEmitter.register(ReactNativeEventEmitter_1), EventPluginHub_1.injection.injectEventPluginOrder(ReactNativeEventPluginOrder_1), + EventPluginUtils_1.injection.injectComponentTree(ReactNativeComponentTree_1), ResponderEventPlugin_1.injection.injectGlobalResponderHandler(ReactNativeGlobalResponderHandler_1), + EventPluginHub_1.injection.injectEventPluginsByName({ + ResponderEventPlugin: ResponderEventPlugin_1, + ReactNativeBridgeEventPlugin: ReactNativeBridgeEventPlugin_1 + }); +} + +var ReactNativeInjection = { + inject: inject +}, REACT_PORTAL_TYPE = "function" == typeof Symbol && Symbol.for && Symbol.for("react.portal") || 60106, createPortal = function(children, containerInfo, implementation) { + var key = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : null; + return { + $$typeof: REACT_PORTAL_TYPE, + key: null == key ? null : "" + key, + children: children, + containerInfo: containerInfo, + implementation: implementation + }; +}, isPortal = function(object) { + return "object" == typeof object && null !== object && object.$$typeof === REACT_PORTAL_TYPE; +}, REACT_PORTAL_TYPE_1 = REACT_PORTAL_TYPE, ReactPortal = { + createPortal: createPortal, + isPortal: isPortal, + REACT_PORTAL_TYPE: REACT_PORTAL_TYPE_1 +}, commonjsGlobal = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof self ? self : {}, ReactFeatureFlags = { + logTopLevelRenders: !1, + prepareNewChildrenBeforeUnmountInStack: !0, + disableNewFiberFeatures: !1, + enableAsyncSubtreeAPI: !1 +}, ReactFeatureFlags_1 = ReactFeatureFlags, ReactTypeOfSideEffect = { + NoEffect: 0, + Placement: 1, + Update: 2, + PlacementAndUpdate: 3, + Deletion: 4, + ContentReset: 8, + Callback: 16, + Err: 32, + Ref: 64 +}, ReactPriorityLevel = { + NoWork: 0, + SynchronousPriority: 1, + TaskPriority: 2, + AnimationPriority: 3, + HighPriority: 4, + LowPriority: 5, + OffscreenPriority: 6 +}, CallbackEffect = ReactTypeOfSideEffect.Callback, NoWork = ReactPriorityLevel.NoWork, SynchronousPriority = ReactPriorityLevel.SynchronousPriority, TaskPriority = ReactPriorityLevel.TaskPriority, warning$3 = warning; + +function comparePriority(a, b) { + return a !== TaskPriority && a !== SynchronousPriority || b !== TaskPriority && b !== SynchronousPriority ? a === NoWork && b !== NoWork ? -255 : a !== NoWork && b === NoWork ? 255 : a - b : 0; +} + +function ensureUpdateQueue(fiber) { + if (null !== fiber.updateQueue) return fiber.updateQueue; + var queue = void 0; + return queue = { + first: null, + last: null, + hasForceUpdate: !1, + callbackList: null, + isProcessing: !1 + }, fiber.updateQueue = queue, queue; +} + +function cloneUpdateQueue(current, workInProgress) { + var currentQueue = current.updateQueue; + if (null === currentQueue) return workInProgress.updateQueue = null, null; + var altQueue = null !== workInProgress.updateQueue ? workInProgress.updateQueue : {}; + return altQueue.first = currentQueue.first, altQueue.last = currentQueue.last, altQueue.hasForceUpdate = !1, + altQueue.callbackList = null, altQueue.isProcessing = !1, workInProgress.updateQueue = altQueue, + altQueue; +} + +var cloneUpdateQueue_1 = cloneUpdateQueue; + +function cloneUpdate(update) { + return { + priorityLevel: update.priorityLevel, + partialState: update.partialState, + callback: update.callback, + isReplace: update.isReplace, + isForced: update.isForced, + isTopLevelUnmount: update.isTopLevelUnmount, + next: null + }; +} + +function insertUpdateIntoQueue(queue, update, insertAfter, insertBefore) { + null !== insertAfter ? insertAfter.next = update : (update.next = queue.first, queue.first = update), + null !== insertBefore ? update.next = insertBefore : queue.last = update; +} + +function findInsertionPosition(queue, update) { + var priorityLevel = update.priorityLevel, insertAfter = null, insertBefore = null; + if (null !== queue.last && comparePriority(queue.last.priorityLevel, priorityLevel) <= 0) insertAfter = queue.last; else for (insertBefore = queue.first; null !== insertBefore && comparePriority(insertBefore.priorityLevel, priorityLevel) <= 0; ) insertAfter = insertBefore, + insertBefore = insertBefore.next; + return insertAfter; +} + +function insertUpdate(fiber, update) { + var queue1 = ensureUpdateQueue(fiber), queue2 = null !== fiber.alternate ? ensureUpdateQueue(fiber.alternate) : null; + (queue1.isProcessing || null !== queue2 && queue2.isProcessing) && warning$3(!1, "An update (setState, replaceState, or forceUpdate) was scheduled " + "from inside an update function. Update functions should be pure, " + "with zero side-effects. Consider using componentDidUpdate or a " + "callback."); + var insertAfter1 = findInsertionPosition(queue1, update), insertBefore1 = null !== insertAfter1 ? insertAfter1.next : queue1.first; + if (null === queue2) return insertUpdateIntoQueue(queue1, update, insertAfter1, insertBefore1), + null; + var insertAfter2 = findInsertionPosition(queue2, update), insertBefore2 = null !== insertAfter2 ? insertAfter2.next : queue2.first; + if (insertUpdateIntoQueue(queue1, update, insertAfter1, insertBefore1), insertBefore1 !== insertBefore2) { + var update2 = cloneUpdate(update); + return insertUpdateIntoQueue(queue2, update2, insertAfter2, insertBefore2), update2; + } + return null === insertAfter2 && (queue2.first = update), null === insertBefore2 && (queue2.last = null), + null; +} + +function addUpdate(fiber, partialState, callback, priorityLevel) { + insertUpdate(fiber, { + priorityLevel: priorityLevel, + partialState: partialState, + callback: callback, + isReplace: !1, + isForced: !1, + isTopLevelUnmount: !1, + next: null + }); +} + +var addUpdate_1 = addUpdate; + +function addReplaceUpdate(fiber, state, callback, priorityLevel) { + insertUpdate(fiber, { + priorityLevel: priorityLevel, + partialState: state, + callback: callback, + isReplace: !0, + isForced: !1, + isTopLevelUnmount: !1, + next: null + }); +} + +var addReplaceUpdate_1 = addReplaceUpdate; + +function addForceUpdate(fiber, callback, priorityLevel) { + insertUpdate(fiber, { + priorityLevel: priorityLevel, + partialState: null, + callback: callback, + isReplace: !1, + isForced: !0, + isTopLevelUnmount: !1, + next: null + }); +} + +var addForceUpdate_1 = addForceUpdate; + +function getPendingPriority(queue) { + return null !== queue.first ? queue.first.priorityLevel : NoWork; +} + +var getPendingPriority_1 = getPendingPriority; + +function addTopLevelUpdate$1(fiber, partialState, callback, priorityLevel) { + var isTopLevelUnmount = null === partialState.element, update = { + priorityLevel: priorityLevel, + partialState: partialState, + callback: callback, + isReplace: !1, + isForced: !1, + isTopLevelUnmount: isTopLevelUnmount, + next: null + }, update2 = insertUpdate(fiber, update); + if (isTopLevelUnmount) { + var queue1 = fiber.updateQueue, queue2 = null !== fiber.alternate ? fiber.alternate.updateQueue : null; + null !== queue1 && null !== update.next && (update.next = null, queue1.last = update), + null !== queue2 && null !== update2 && null !== update2.next && (update2.next = null, + queue2.last = update); + } +} + +var addTopLevelUpdate_1 = addTopLevelUpdate$1; + +function getStateFromUpdate(update, instance, prevState, props) { + var partialState = update.partialState; + if ("function" == typeof partialState) { + return partialState.call(instance, prevState, props); + } + return partialState; +} + +function beginUpdateQueue(workInProgress, queue, instance, prevState, props, priorityLevel) { + queue.isProcessing = !0, queue.hasForceUpdate = !1; + for (var state = prevState, dontMutatePrevState = !0, callbackList = queue.callbackList, update = queue.first; null !== update && comparePriority(update.priorityLevel, priorityLevel) <= 0; ) { + queue.first = update.next, null === queue.first && (queue.last = null); + var _partialState = void 0; + update.isReplace ? (state = getStateFromUpdate(update, instance, state, props), + dontMutatePrevState = !0) : (_partialState = getStateFromUpdate(update, instance, state, props)) && (state = dontMutatePrevState ? Object.assign({}, state, _partialState) : Object.assign(state, _partialState), + dontMutatePrevState = !1), update.isForced && (queue.hasForceUpdate = !0), null === update.callback || update.isTopLevelUnmount && null !== update.next || (callbackList = callbackList || [], + callbackList.push(update.callback), workInProgress.effectTag |= CallbackEffect), + update = update.next; + } + return queue.callbackList = callbackList, null !== queue.first || null !== callbackList || queue.hasForceUpdate || (workInProgress.updateQueue = null), + queue.isProcessing = !1, state; +} + +var beginUpdateQueue_1 = beginUpdateQueue; + +function commitCallbacks(finishedWork, queue, context) { + var callbackList = queue.callbackList; + if (null !== callbackList) for (var i = 0; i < callbackList.length; i++) { + var _callback = callbackList[i]; + invariant("function" == typeof _callback, "Invalid argument passed as callback. Expected a function. Instead " + "received: %s", _callback), + _callback.call(context); + } +} + +var commitCallbacks_1 = commitCallbacks, ReactFiberUpdateQueue = { + cloneUpdateQueue: cloneUpdateQueue_1, + addUpdate: addUpdate_1, + addReplaceUpdate: addReplaceUpdate_1, + addForceUpdate: addForceUpdate_1, + getPendingPriority: getPendingPriority_1, + addTopLevelUpdate: addTopLevelUpdate_1, + beginUpdateQueue: beginUpdateQueue_1, + commitCallbacks: commitCallbacks_1 +}; + +function getComponentName$1(instanceOrFiber) { + if ("function" == typeof instanceOrFiber.getName) { + return instanceOrFiber.getName(); + } + if ("number" == typeof instanceOrFiber.tag) { + var fiber = instanceOrFiber, type = fiber.type; + if ("string" == typeof type) return type; + if ("function" == typeof type) return type.displayName || type.name; + } + return null; +} + +var getComponentName_1 = getComponentName$1, ReactInstanceMap = { + remove: function(key) { + key._reactInternalInstance = void 0; + }, + get: function(key) { + return key._reactInternalInstance; + }, + has: function(key) { + return void 0 !== key._reactInternalInstance; + }, + set: function(key, value) { + key._reactInternalInstance = value; + } +}, ReactInstanceMap_1 = ReactInstanceMap, ReactInternals = react.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, ReactGlobalSharedState = { + ReactCurrentOwner: ReactInternals.ReactCurrentOwner +}; + +Object.assign(ReactGlobalSharedState, { + ReactComponentTreeHook: ReactInternals.ReactComponentTreeHook, + ReactDebugCurrentFrame: ReactInternals.ReactDebugCurrentFrame +}); + +var ReactGlobalSharedState_1 = ReactGlobalSharedState, ReactCurrentOwner = ReactGlobalSharedState_1.ReactCurrentOwner, warning$4 = warning, HostRoot$1 = ReactTypeOfWork.HostRoot, HostComponent$1 = ReactTypeOfWork.HostComponent, HostText = ReactTypeOfWork.HostText, ClassComponent$1 = ReactTypeOfWork.ClassComponent, NoEffect = ReactTypeOfSideEffect.NoEffect, Placement = ReactTypeOfSideEffect.Placement, MOUNTING = 1, MOUNTED = 2, UNMOUNTED = 3; + +function isFiberMountedImpl(fiber) { + var node = fiber; + if (fiber.alternate) for (;node.return; ) node = node.return; else { + if ((node.effectTag & Placement) !== NoEffect) return MOUNTING; + for (;node.return; ) if (node = node.return, (node.effectTag & Placement) !== NoEffect) return MOUNTING; + } + return node.tag === HostRoot$1 ? MOUNTED : UNMOUNTED; +} + +var isFiberMounted$1 = function(fiber) { + return isFiberMountedImpl(fiber) === MOUNTED; +}, isMounted = function(component) { + var owner = ReactCurrentOwner.current; + if (null !== owner && owner.tag === ClassComponent$1) { + var ownerFiber = owner, instance = ownerFiber.stateNode; + warning$4(instance._warnedAboutRefsInRender, "%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_1(ownerFiber) || "A component"), + instance._warnedAboutRefsInRender = !0; + } + var fiber = ReactInstanceMap_1.get(component); + return !!fiber && isFiberMountedImpl(fiber) === MOUNTED; +}; + +function assertIsMounted(fiber) { + invariant(isFiberMountedImpl(fiber) === MOUNTED, "Unable to find node on an unmounted component."); +} + +function findCurrentFiberUsingSlowPath(fiber) { + var alternate = fiber.alternate; + if (!alternate) { + var state = isFiberMountedImpl(fiber); + return invariant(state !== UNMOUNTED, "Unable to find node on an unmounted component."), + state === MOUNTING ? null : fiber; + } + for (var a = fiber, b = alternate; !0; ) { + var parentA = a.return, parentB = parentA ? parentA.alternate : null; + if (!parentA || !parentB) break; + if (parentA.child === parentB.child) { + for (var child = parentA.child; child; ) { + if (child === a) return assertIsMounted(parentA), fiber; + if (child === b) return assertIsMounted(parentA), alternate; + child = child.sibling; + } + invariant(!1, "Unable to find node on an unmounted component."); + } + if (a.return !== b.return) a = parentA, b = parentB; else { + for (var didFindChild = !1, _child = parentA.child; _child; ) { + if (_child === a) { + didFindChild = !0, a = parentA, b = parentB; + break; + } + if (_child === b) { + didFindChild = !0, b = parentA, a = parentB; + break; + } + _child = _child.sibling; + } + if (!didFindChild) { + for (_child = parentB.child; _child; ) { + if (_child === a) { + didFindChild = !0, a = parentB, b = parentA; + break; + } + if (_child === b) { + didFindChild = !0, b = parentB, a = parentA; + break; + } + _child = _child.sibling; + } + invariant(didFindChild, "Child was not found in either parent set. This indicates a bug " + "related to the return pointer."); + } + } + invariant(a.alternate === b, "Return fibers should always be each others' alternates."); + } + return invariant(a.tag === HostRoot$1, "Unable to find node on an unmounted component."), + a.stateNode.current === a ? fiber : alternate; +} + +var findCurrentFiberUsingSlowPath_1 = findCurrentFiberUsingSlowPath, findCurrentHostFiber$1 = function(parent) { + var currentParent = findCurrentFiberUsingSlowPath(parent); + if (!currentParent) return null; + for (var node = currentParent; !0; ) { + if (node.tag === HostComponent$1 || node.tag === HostText) return node; + if (node.child) node.child.return = node, node = node.child; else { + if (node === currentParent) return null; + for (;!node.sibling; ) { + if (!node.return || node.return === currentParent) return null; + node = node.return; + } + node.sibling.return = node.return, node = node.sibling; + } + } + return null; +}, ReactFiberTreeReflection = { + isFiberMounted: isFiberMounted$1, + isMounted: isMounted, + findCurrentFiberUsingSlowPath: findCurrentFiberUsingSlowPath_1, + findCurrentHostFiber: findCurrentHostFiber$1 +}, valueStack = [], fiberStack = [], index = -1, createCursor$1 = function(defaultValue) { + return { + current: defaultValue + }; +}, isEmpty = function() { + return -1 === index; +}, pop$1 = function(cursor, fiber) { + if (index < 0) return void warning(!1, "Unexpected pop."); + fiber !== fiberStack[index] && warning(!1, "Unexpected Fiber popped."), cursor.current = valueStack[index], + valueStack[index] = null, fiberStack[index] = null, index--; +}, push$1 = function(cursor, value, fiber) { + index++, valueStack[index] = cursor.current, fiberStack[index] = fiber, cursor.current = value; +}, reset = function() { + for (;index > -1; ) valueStack[index] = null, fiberStack[index] = null, index--; +}, ReactFiberStack = { + createCursor: createCursor$1, + isEmpty: isEmpty, + pop: pop$1, + push: push$1, + reset: reset +}, IndeterminateComponent = ReactTypeOfWork.IndeterminateComponent, FunctionalComponent = ReactTypeOfWork.FunctionalComponent, ClassComponent$2 = ReactTypeOfWork.ClassComponent, HostComponent$2 = ReactTypeOfWork.HostComponent; + +function describeComponentFrame(name, source, ownerName) { + return "\n in " + (name || "Unknown") + (source ? " (at " + source.fileName.replace(/^.*[\\\/]/, "") + ":" + source.lineNumber + ")" : ownerName ? " (created by " + ownerName + ")" : ""); +} + +function describeFiber(fiber) { + switch (fiber.tag) { + case IndeterminateComponent: + case FunctionalComponent: + case ClassComponent$2: + case HostComponent$2: + var owner = fiber._debugOwner, source = fiber._debugSource, name = getComponentName_1(fiber), ownerName = null; + return owner && (ownerName = getComponentName_1(owner)), describeComponentFrame(name, source, ownerName); + + default: + return ""; + } +} + +function getStackAddendumByWorkInProgressFiber$1(workInProgress) { + var info = "", node = workInProgress; + do { + info += describeFiber(node), node = node.return; + } while (node); + return info; +} + +var ReactFiberComponentTreeHook = { + getStackAddendumByWorkInProgressFiber: getStackAddendumByWorkInProgressFiber$1, + describeComponentFrame: describeComponentFrame +}, getComponentName$3 = getComponentName_1, _require$1 = ReactFiberComponentTreeHook, getStackAddendumByWorkInProgressFiber = _require$1.getStackAddendumByWorkInProgressFiber; + +function getCurrentFiberOwnerName() { + var fiber = ReactDebugCurrentFiber$2.current; + return null === fiber ? null : null != fiber._debugOwner ? getComponentName$3(fiber._debugOwner) : null; +} + +function getCurrentFiberStackAddendum() { + var fiber = ReactDebugCurrentFiber$2.current; + return null === fiber ? null : getStackAddendumByWorkInProgressFiber(fiber); +} + +var ReactDebugCurrentFiber$2 = { + current: null, + phase: null, + getCurrentFiberOwnerName: getCurrentFiberOwnerName, + getCurrentFiberStackAddendum: getCurrentFiberStackAddendum +}, ReactDebugCurrentFiber_1 = ReactDebugCurrentFiber$2, ReactDebugFiberPerf = null, _require$2 = ReactTypeOfWork, HostRoot$2 = _require$2.HostRoot, HostComponent$3 = _require$2.HostComponent, HostText$1 = _require$2.HostText, HostPortal = _require$2.HostPortal, YieldComponent = _require$2.YieldComponent, Fragment = _require$2.Fragment, getComponentName$4 = getComponentName_1, reactEmoji = "⚛", warningEmoji = "⛔", supportsUserTiming = "undefined" != typeof performance && "function" == typeof performance.mark && "function" == typeof performance.clearMarks && "function" == typeof performance.measure && "function" == typeof performance.clearMeasures, currentFiber = null, currentPhase = null, currentPhaseFiber = null, isCommitting = !1, hasScheduledUpdateInCurrentCommit = !1, hasScheduledUpdateInCurrentPhase = !1, commitCountInCurrentWorkLoop = 0, effectCountInCurrentCommit = 0, labelsInCurrentCommit = new Set(), formatMarkName = function(markName) { + return reactEmoji + " " + markName; +}, formatLabel = function(label, warning$$1) { + return (warning$$1 ? warningEmoji + " " : reactEmoji + " ") + label + (warning$$1 ? " Warning: " + warning$$1 : ""); +}, beginMark = function(markName) { + performance.mark(formatMarkName(markName)); +}, clearMark = function(markName) { + performance.clearMarks(formatMarkName(markName)); +}, endMark = function(label, markName, warning$$1) { + var formattedMarkName = formatMarkName(markName), formattedLabel = formatLabel(label, warning$$1); + try { + performance.measure(formattedLabel, formattedMarkName); + } catch (err) {} + performance.clearMarks(formattedMarkName), performance.clearMeasures(formattedLabel); +}, getFiberMarkName = function(label, debugID) { + return label + " (#" + debugID + ")"; +}, getFiberLabel = function(componentName, isMounted, phase) { + return null === phase ? componentName + " [" + (isMounted ? "update" : "mount") + "]" : componentName + "." + phase; +}, beginFiberMark = function(fiber, phase) { + var componentName = getComponentName$4(fiber) || "Unknown", debugID = fiber._debugID, isMounted = null !== fiber.alternate, label = getFiberLabel(componentName, isMounted, phase); + if (isCommitting && labelsInCurrentCommit.has(label)) return !1; + labelsInCurrentCommit.add(label); + var markName = getFiberMarkName(label, debugID); + return beginMark(markName), !0; +}, clearFiberMark = function(fiber, phase) { + var componentName = getComponentName$4(fiber) || "Unknown", debugID = fiber._debugID, isMounted = null !== fiber.alternate, label = getFiberLabel(componentName, isMounted, phase), markName = getFiberMarkName(label, debugID); + clearMark(markName); +}, endFiberMark = function(fiber, phase, warning$$1) { + var componentName = getComponentName$4(fiber) || "Unknown", debugID = fiber._debugID, isMounted = null !== fiber.alternate, label = getFiberLabel(componentName, isMounted, phase), markName = getFiberMarkName(label, debugID); + endMark(label, markName, warning$$1); +}, shouldIgnoreFiber = function(fiber) { + switch (fiber.tag) { + case HostRoot$2: + case HostComponent$3: + case HostText$1: + case HostPortal: + case YieldComponent: + case Fragment: + return !0; + + default: + return !1; + } +}, clearPendingPhaseMeasurement = function() { + null !== currentPhase && null !== currentPhaseFiber && clearFiberMark(currentPhaseFiber, currentPhase), + currentPhaseFiber = null, currentPhase = null, hasScheduledUpdateInCurrentPhase = !1; +}, pauseTimers = function() { + for (var fiber = currentFiber; fiber; ) fiber._debugIsCurrentlyTiming && endFiberMark(fiber, null, null), + fiber = fiber.return; +}, resumeTimersRecursively = function(fiber) { + null !== fiber.return && resumeTimersRecursively(fiber.return), fiber._debugIsCurrentlyTiming && beginFiberMark(fiber, null); +}, resumeTimers = function() { + null !== currentFiber && resumeTimersRecursively(currentFiber); +}; + +ReactDebugFiberPerf = { + recordEffect: function() { + effectCountInCurrentCommit++; + }, + recordScheduleUpdate: function() { + isCommitting && (hasScheduledUpdateInCurrentCommit = !0), null !== currentPhase && "componentWillMount" !== currentPhase && "componentWillReceiveProps" !== currentPhase && (hasScheduledUpdateInCurrentPhase = !0); + }, + startWorkTimer: function(fiber) { + supportsUserTiming && !shouldIgnoreFiber(fiber) && (currentFiber = fiber, beginFiberMark(fiber, null) && (fiber._debugIsCurrentlyTiming = !0)); + }, + cancelWorkTimer: function(fiber) { + supportsUserTiming && !shouldIgnoreFiber(fiber) && (fiber._debugIsCurrentlyTiming = !1, + clearFiberMark(fiber, null)); + }, + stopWorkTimer: function(fiber) { + supportsUserTiming && !shouldIgnoreFiber(fiber) && (currentFiber = fiber.return, + fiber._debugIsCurrentlyTiming && (fiber._debugIsCurrentlyTiming = !1, endFiberMark(fiber, null, null))); + }, + startPhaseTimer: function(fiber, phase) { + supportsUserTiming && (clearPendingPhaseMeasurement(), beginFiberMark(fiber, phase) && (currentPhaseFiber = fiber, + currentPhase = phase)); + }, + stopPhaseTimer: function() { + if (supportsUserTiming) { + if (null !== currentPhase && null !== currentPhaseFiber) { + endFiberMark(currentPhaseFiber, currentPhase, hasScheduledUpdateInCurrentPhase ? "Scheduled a cascading update" : null); + } + currentPhase = null, currentPhaseFiber = null; + } + }, + startWorkLoopTimer: function() { + supportsUserTiming && (commitCountInCurrentWorkLoop = 0, beginMark("(React Tree Reconciliation)"), + resumeTimers()); + }, + stopWorkLoopTimer: function() { + if (supportsUserTiming) { + var warning$$1 = commitCountInCurrentWorkLoop > 1 ? "There were cascading updates" : null; + commitCountInCurrentWorkLoop = 0, pauseTimers(), endMark("(React Tree Reconciliation)", "(React Tree Reconciliation)", warning$$1); + } + }, + startCommitTimer: function() { + supportsUserTiming && (isCommitting = !0, hasScheduledUpdateInCurrentCommit = !1, + labelsInCurrentCommit.clear(), beginMark("(Committing Changes)")); + }, + stopCommitTimer: function() { + if (supportsUserTiming) { + var warning$$1 = null; + hasScheduledUpdateInCurrentCommit ? warning$$1 = "Lifecycle hook scheduled a cascading update" : commitCountInCurrentWorkLoop > 0 && (warning$$1 = "Caused by a cascading update in earlier commit"), + hasScheduledUpdateInCurrentCommit = !1, commitCountInCurrentWorkLoop++, isCommitting = !1, + labelsInCurrentCommit.clear(), endMark("(Committing Changes)", "(Committing Changes)", warning$$1); + } + }, + startCommitHostEffectsTimer: function() { + supportsUserTiming && (effectCountInCurrentCommit = 0, beginMark("(Committing Host Effects)")); + }, + stopCommitHostEffectsTimer: function() { + if (supportsUserTiming) { + var count = effectCountInCurrentCommit; + effectCountInCurrentCommit = 0, endMark("(Committing Host Effects: " + count + " Total)", "(Committing Host Effects)", null); + } + }, + startCommitLifeCyclesTimer: function() { + supportsUserTiming && (effectCountInCurrentCommit = 0, beginMark("(Calling Lifecycle Methods)")); + }, + stopCommitLifeCyclesTimer: function() { + if (supportsUserTiming) { + var count = effectCountInCurrentCommit; + effectCountInCurrentCommit = 0, endMark("(Calling Lifecycle Methods: " + count + " Total)", "(Calling Lifecycle Methods)", null); + } + } +}; + +var ReactDebugFiberPerf_1 = ReactDebugFiberPerf, _extends$2 = Object.assign || function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]); + } + return target; +}, isFiberMounted = ReactFiberTreeReflection.isFiberMounted, ClassComponent = ReactTypeOfWork.ClassComponent, HostRoot = ReactTypeOfWork.HostRoot, createCursor = ReactFiberStack.createCursor, pop = ReactFiberStack.pop, push = ReactFiberStack.push, ReactDebugCurrentFiber$1 = ReactDebugCurrentFiber_1, _require4$1 = ReactGlobalSharedState_1, ReactDebugCurrentFrame = _require4$1.ReactDebugCurrentFrame, _require5 = ReactDebugFiberPerf_1, startPhaseTimer = _require5.startPhaseTimer, stopPhaseTimer = _require5.stopPhaseTimer, warnedAboutMissingGetChildContext = {}, contextStackCursor = createCursor(emptyObject), didPerformWorkStackCursor = createCursor(!1), previousContext = emptyObject; + +function getUnmaskedContext(workInProgress) { + return isContextProvider$1(workInProgress) ? previousContext : contextStackCursor.current; +} + +var getUnmaskedContext_1 = getUnmaskedContext; + +function cacheContext(workInProgress, unmaskedContext, maskedContext) { + var instance = workInProgress.stateNode; + instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext, instance.__reactInternalMemoizedMaskedChildContext = maskedContext; +} + +var cacheContext_1 = cacheContext, getMaskedContext = function(workInProgress, unmaskedContext) { + var type = workInProgress.type, contextTypes = type.contextTypes; + if (!contextTypes) return emptyObject; + var instance = workInProgress.stateNode; + if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) return instance.__reactInternalMemoizedMaskedChildContext; + var context = {}; + for (var key in contextTypes) context[key] = unmaskedContext[key]; + var name = getComponentName_1(workInProgress) || "Unknown"; + return ReactDebugCurrentFrame.current = workInProgress, checkPropTypes(contextTypes, context, "context", name, ReactDebugCurrentFrame.getStackAddendum), + ReactDebugCurrentFrame.current = null, instance && cacheContext(workInProgress, unmaskedContext, context), + context; +}, hasContextChanged = function() { + return didPerformWorkStackCursor.current; +}; + +function isContextConsumer(fiber) { + return fiber.tag === ClassComponent && null != fiber.type.contextTypes; +} + +var isContextConsumer_1 = isContextConsumer; + +function isContextProvider$1(fiber) { + return fiber.tag === ClassComponent && null != fiber.type.childContextTypes; +} + +var isContextProvider_1 = isContextProvider$1; + +function popContextProvider(fiber) { + isContextProvider$1(fiber) && (pop(didPerformWorkStackCursor, fiber), pop(contextStackCursor, fiber)); +} + +var popContextProvider_1 = popContextProvider, pushTopLevelContextObject = function(fiber, context, didChange) { + invariant(null == contextStackCursor.cursor, "Unexpected context found on stack"), + push(contextStackCursor, context, fiber), push(didPerformWorkStackCursor, didChange, fiber); +}; + +function processChildContext$1(fiber, parentContext, isReconciling) { + var instance = fiber.stateNode, childContextTypes = fiber.type.childContextTypes; + if ("function" != typeof instance.getChildContext) { + var componentName = getComponentName_1(fiber) || "Unknown"; + return warnedAboutMissingGetChildContext[componentName] || (warnedAboutMissingGetChildContext[componentName] = !0, + warning(!1, "%s.childContextTypes is specified but there is no getChildContext() method " + "on the instance. You can either define getChildContext() on %s or remove " + "childContextTypes from it.", componentName, componentName)), + parentContext; + } + var childContext = void 0; + ReactDebugCurrentFiber$1.phase = "getChildContext", startPhaseTimer(fiber, "getChildContext"), + childContext = instance.getChildContext(), stopPhaseTimer(), ReactDebugCurrentFiber$1.phase = null; + for (var contextKey in childContext) invariant(contextKey in childContextTypes, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', getComponentName_1(fiber) || "Unknown", contextKey); + var name = getComponentName_1(fiber) || "Unknown", workInProgress = isReconciling ? fiber : null; + return ReactDebugCurrentFrame.current = workInProgress, checkPropTypes(childContextTypes, childContext, "child context", name, ReactDebugCurrentFrame.getStackAddendum), + ReactDebugCurrentFrame.current = null, _extends$2({}, parentContext, childContext); +} + +var processChildContext_1 = processChildContext$1, pushContextProvider = function(workInProgress) { + if (!isContextProvider$1(workInProgress)) return !1; + var instance = workInProgress.stateNode, memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyObject; + return previousContext = contextStackCursor.current, push(contextStackCursor, memoizedMergedChildContext, workInProgress), + push(didPerformWorkStackCursor, !1, workInProgress), !0; +}, invalidateContextProvider = function(workInProgress) { + var instance = workInProgress.stateNode; + invariant(instance, "Expected to have an instance by this point."); + var mergedContext = processChildContext$1(workInProgress, previousContext, !0); + instance.__reactInternalMemoizedMergedChildContext = mergedContext, pop(didPerformWorkStackCursor, workInProgress), + pop(contextStackCursor, workInProgress), push(contextStackCursor, mergedContext, workInProgress), + push(didPerformWorkStackCursor, !0, workInProgress); +}, resetContext = function() { + previousContext = emptyObject, contextStackCursor.current = emptyObject, didPerformWorkStackCursor.current = !1; +}, findCurrentUnmaskedContext$1 = function(fiber) { + invariant(isFiberMounted(fiber) && fiber.tag === ClassComponent, "Expected subtree parent to be a mounted class component"); + for (var node = fiber; node.tag !== HostRoot; ) { + if (isContextProvider$1(node)) return node.stateNode.__reactInternalMemoizedMergedChildContext; + var parent = node.return; + invariant(parent, "Found unexpected detached subtree parent"), node = parent; + } + return node.stateNode.context; +}, ReactFiberContext = { + getUnmaskedContext: getUnmaskedContext_1, + cacheContext: cacheContext_1, + getMaskedContext: getMaskedContext, + hasContextChanged: hasContextChanged, + isContextConsumer: isContextConsumer_1, + isContextProvider: isContextProvider_1, + popContextProvider: popContextProvider_1, + pushTopLevelContextObject: pushTopLevelContextObject, + processChildContext: processChildContext_1, + pushContextProvider: pushContextProvider, + invalidateContextProvider: invalidateContextProvider, + resetContext: resetContext, + findCurrentUnmaskedContext: findCurrentUnmaskedContext$1 +}, ReactTypeOfInternalContext = { + NoContext: 0, + AsyncUpdates: 1 +}, IndeterminateComponent$1 = ReactTypeOfWork.IndeterminateComponent, ClassComponent$3 = ReactTypeOfWork.ClassComponent, HostRoot$3 = ReactTypeOfWork.HostRoot, HostComponent$4 = ReactTypeOfWork.HostComponent, HostText$2 = ReactTypeOfWork.HostText, HostPortal$1 = ReactTypeOfWork.HostPortal, CoroutineComponent = ReactTypeOfWork.CoroutineComponent, YieldComponent$1 = ReactTypeOfWork.YieldComponent, Fragment$1 = ReactTypeOfWork.Fragment, NoWork$1 = ReactPriorityLevel.NoWork, NoContext = ReactTypeOfInternalContext.NoContext, NoEffect$1 = ReactTypeOfSideEffect.NoEffect, cloneUpdateQueue$1 = ReactFiberUpdateQueue.cloneUpdateQueue, getComponentName$5 = getComponentName_1, hasBadMapPolyfill = !1; + +try { + var nonExtensibleObject = Object.preventExtensions({}); + new Map([ [ nonExtensibleObject, null ] ]), new Set([ nonExtensibleObject ]); +} catch (e) { + hasBadMapPolyfill = !0; +} + +var debugCounter = 1, createFiber = function(tag, key, internalContextTag) { + var fiber = { + tag: tag, + key: key, + type: null, + stateNode: null, + return: null, + child: null, + sibling: null, + index: 0, + ref: null, + pendingProps: null, + memoizedProps: null, + updateQueue: null, + memoizedState: null, + internalContextTag: internalContextTag, + effectTag: NoEffect$1, + nextEffect: null, + firstEffect: null, + lastEffect: null, + pendingWorkPriority: NoWork$1, + progressedPriority: NoWork$1, + progressedChild: null, + progressedFirstDeletion: null, + progressedLastDeletion: null, + alternate: null + }; + return fiber._debugID = debugCounter++, fiber._debugSource = null, fiber._debugOwner = null, + fiber._debugIsCurrentlyTiming = !1, hasBadMapPolyfill || "function" != typeof Object.preventExtensions || Object.preventExtensions(fiber), + fiber; +}; + +function shouldConstruct(Component) { + return !(!Component.prototype || !Component.prototype.isReactComponent); +} + +var cloneFiber = function(fiber, priorityLevel) { + var alt = fiber.alternate; + return null !== alt ? (alt.effectTag = NoEffect$1, alt.nextEffect = null, alt.firstEffect = null, + alt.lastEffect = null) : (alt = createFiber(fiber.tag, fiber.key, fiber.internalContextTag), + alt.type = fiber.type, alt.progressedChild = fiber.progressedChild, alt.progressedPriority = fiber.progressedPriority, + alt.alternate = fiber, fiber.alternate = alt), alt.stateNode = fiber.stateNode, + alt.child = fiber.child, alt.sibling = fiber.sibling, alt.index = fiber.index, alt.ref = fiber.ref, + alt.pendingProps = fiber.pendingProps, cloneUpdateQueue$1(fiber, alt), alt.pendingWorkPriority = priorityLevel, + alt.memoizedProps = fiber.memoizedProps, alt.memoizedState = fiber.memoizedState, + alt._debugID = fiber._debugID, alt._debugSource = fiber._debugSource, alt._debugOwner = fiber._debugOwner, + alt; +}, createHostRootFiber$1 = function() { + return createFiber(HostRoot$3, null, NoContext); +}, createFiberFromElement = function(element, internalContextTag, priorityLevel) { + var owner = null; + owner = element._owner; + var fiber = createFiberFromElementType(element.type, element.key, internalContextTag, owner); + return fiber.pendingProps = element.props, fiber.pendingWorkPriority = priorityLevel, + fiber._debugSource = element._source, fiber._debugOwner = element._owner, fiber; +}, createFiberFromFragment = function(elements, internalContextTag, priorityLevel) { + var fiber = createFiber(Fragment$1, null, internalContextTag); + return fiber.pendingProps = elements, fiber.pendingWorkPriority = priorityLevel, + fiber; +}, createFiberFromText = function(content, internalContextTag, priorityLevel) { + var fiber = createFiber(HostText$2, null, internalContextTag); + return fiber.pendingProps = content, fiber.pendingWorkPriority = priorityLevel, + fiber; +}; + +function createFiberFromElementType(type, key, internalContextTag, debugOwner) { + var fiber = void 0; + if ("function" == typeof type) fiber = shouldConstruct(type) ? createFiber(ClassComponent$3, key, internalContextTag) : createFiber(IndeterminateComponent$1, key, internalContextTag), + fiber.type = type; else if ("string" == typeof type) fiber = createFiber(HostComponent$4, key, internalContextTag), + fiber.type = type; else if ("object" == typeof type && null !== type && "number" == typeof type.tag) fiber = type; else { + var info = ""; + (void 0 === type || "object" == typeof type && null !== type && 0 === Object.keys(type).length) && (info += " You likely forgot to export your component from the file " + "it's defined in."); + var ownerName = debugOwner ? getComponentName$5(debugOwner) : null; + ownerName && (info += "\n\nCheck the render method of `" + ownerName + "`."), invariant(!1, "Element type is invalid: expected a string (for built-in components) " + "or a class/function (for composite components) but got: %s.%s", null == type ? type : typeof type, info); + } + return fiber; +} + +var createFiberFromElementType_1 = createFiberFromElementType, createFiberFromHostInstanceForDeletion = function() { + var fiber = createFiber(HostComponent$4, null, NoContext); + return fiber.type = "DELETED", fiber; +}, createFiberFromCoroutine = function(coroutine, internalContextTag, priorityLevel) { + var fiber = createFiber(CoroutineComponent, coroutine.key, internalContextTag); + return fiber.type = coroutine.handler, fiber.pendingProps = coroutine, fiber.pendingWorkPriority = priorityLevel, + fiber; +}, createFiberFromYield = function(yieldNode, internalContextTag, priorityLevel) { + return createFiber(YieldComponent$1, null, internalContextTag); +}, createFiberFromPortal = function(portal, internalContextTag, priorityLevel) { + var fiber = createFiber(HostPortal$1, portal.key, internalContextTag); + return fiber.pendingProps = portal.children || [], fiber.pendingWorkPriority = priorityLevel, + fiber.stateNode = { + containerInfo: portal.containerInfo, + implementation: portal.implementation + }, fiber; +}, ReactFiber = { + cloneFiber: cloneFiber, + createHostRootFiber: createHostRootFiber$1, + createFiberFromElement: createFiberFromElement, + createFiberFromFragment: createFiberFromFragment, + createFiberFromText: createFiberFromText, + createFiberFromElementType: createFiberFromElementType_1, + createFiberFromHostInstanceForDeletion: createFiberFromHostInstanceForDeletion, + createFiberFromCoroutine: createFiberFromCoroutine, + createFiberFromYield: createFiberFromYield, + createFiberFromPortal: createFiberFromPortal +}, createHostRootFiber = ReactFiber.createHostRootFiber, createFiberRoot$1 = function(containerInfo) { + var uninitializedFiber = createHostRootFiber(), root = { + current: uninitializedFiber, + containerInfo: containerInfo, + isScheduled: !1, + nextScheduledRoot: null, + context: null, + pendingContext: null + }; + return uninitializedFiber.stateNode = root, root; +}, ReactFiberRoot = { + createFiberRoot: createFiberRoot$1 +}, REACT_ELEMENT_TYPE = "function" == typeof Symbol && Symbol.for && Symbol.for("react.element") || 60103, ReactElementSymbol = REACT_ELEMENT_TYPE, REACT_COROUTINE_TYPE$1, REACT_YIELD_TYPE$1; + +"function" == typeof Symbol && Symbol.for ? (REACT_COROUTINE_TYPE$1 = Symbol.for("react.coroutine"), +REACT_YIELD_TYPE$1 = Symbol.for("react.yield")) : (REACT_COROUTINE_TYPE$1 = 60104, +REACT_YIELD_TYPE$1 = 60105); + +var createCoroutine = function(children, handler, props) { + var key = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : null, coroutine = { + $$typeof: REACT_COROUTINE_TYPE$1, + key: null == key ? null : "" + key, + children: children, + handler: handler, + props: props + }; + return Object.freeze && (Object.freeze(coroutine.props), Object.freeze(coroutine)), + coroutine; +}, createYield = function(value) { + var yieldNode = { + $$typeof: REACT_YIELD_TYPE$1, + value: value + }; + return Object.freeze && Object.freeze(yieldNode), yieldNode; +}, isCoroutine = function(object) { + return "object" == typeof object && null !== object && object.$$typeof === REACT_COROUTINE_TYPE$1; +}, isYield = function(object) { + return "object" == typeof object && null !== object && object.$$typeof === REACT_YIELD_TYPE$1; +}, REACT_YIELD_TYPE_1 = REACT_YIELD_TYPE$1, REACT_COROUTINE_TYPE_1 = REACT_COROUTINE_TYPE$1, ReactCoroutine = { + createCoroutine: createCoroutine, + createYield: createYield, + isCoroutine: isCoroutine, + isYield: isYield, + REACT_YIELD_TYPE: REACT_YIELD_TYPE_1, + REACT_COROUTINE_TYPE: REACT_COROUTINE_TYPE_1 +}, ITERATOR_SYMBOL = "function" == typeof Symbol && Symbol.iterator, FAUX_ITERATOR_SYMBOL = "@@iterator"; + +function getIteratorFn(maybeIterable) { + var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); + if ("function" == typeof iteratorFn) return iteratorFn; +} + +var getIteratorFn_1 = getIteratorFn, REACT_COROUTINE_TYPE = ReactCoroutine.REACT_COROUTINE_TYPE, REACT_YIELD_TYPE = ReactCoroutine.REACT_YIELD_TYPE, REACT_PORTAL_TYPE$1 = ReactPortal.REACT_PORTAL_TYPE, _require3$3 = ReactDebugCurrentFiber_1, getCurrentFiberStackAddendum$1 = _require3$3.getCurrentFiberStackAddendum, warning$7 = warning, didWarnAboutMaps = !1, ownerHasKeyUseWarning = {}, warnForMissingKey = function(child) { + if (null !== child && "object" == typeof child && child._store && !child._store.validated && null == child.key) { + invariant("object" == typeof child._store, "React Component in warnForMissingKey should have a _store"), + child._store.validated = !0; + var currentComponentErrorInfo = "Each child in an array or iterator should have a unique " + '"key" prop. See https://fb.me/react-warning-keys for ' + "more information." + (getCurrentFiberStackAddendum$1(child) || ""); + ownerHasKeyUseWarning[currentComponentErrorInfo] || (ownerHasKeyUseWarning[currentComponentErrorInfo] = !0, + warning$7(!1, "Each child in an array or iterator should have a unique " + '"key" prop. See https://fb.me/react-warning-keys for ' + "more information.%s", getCurrentFiberStackAddendum$1(child))); + } +}, cloneFiber$2 = ReactFiber.cloneFiber, createFiberFromElement$1 = ReactFiber.createFiberFromElement, createFiberFromFragment$1 = ReactFiber.createFiberFromFragment, createFiberFromText$1 = ReactFiber.createFiberFromText, createFiberFromCoroutine$1 = ReactFiber.createFiberFromCoroutine, createFiberFromYield$1 = ReactFiber.createFiberFromYield, createFiberFromPortal$1 = ReactFiber.createFiberFromPortal, isArray = Array.isArray, FunctionalComponent$2 = ReactTypeOfWork.FunctionalComponent, ClassComponent$6 = ReactTypeOfWork.ClassComponent, HostText$4 = ReactTypeOfWork.HostText, HostPortal$4 = ReactTypeOfWork.HostPortal, CoroutineComponent$2 = ReactTypeOfWork.CoroutineComponent, YieldComponent$3 = ReactTypeOfWork.YieldComponent, Fragment$3 = ReactTypeOfWork.Fragment, NoEffect$3 = ReactTypeOfSideEffect.NoEffect, Placement$3 = ReactTypeOfSideEffect.Placement, Deletion$1 = ReactTypeOfSideEffect.Deletion; + +function coerceRef(current, element) { + var mixedRef = element.ref; + if (null !== mixedRef && "function" != typeof mixedRef && element._owner) { + var owner = element._owner, inst = void 0; + if (owner) if ("number" == typeof owner.tag) { + var ownerFiber = owner; + invariant(ownerFiber.tag === ClassComponent$6, "Stateless function components cannot have refs."), + inst = ownerFiber.stateNode; + } else inst = owner.getPublicInstance(); + invariant(inst, "Missing owner for string ref %s. This error is likely caused by a " + "bug in React. Please file an issue.", mixedRef); + var stringRef = "" + mixedRef; + if (null !== current && null !== current.ref && current.ref._stringRef === stringRef) return current.ref; + var ref = function(value) { + var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs; + null === value ? delete refs[stringRef] : refs[stringRef] = value; + }; + return ref._stringRef = stringRef, ref; + } + return mixedRef; +} + +function throwOnInvalidObjectType(returnFiber, newChild) { + if ("textarea" !== returnFiber.type) { + var addendum = ""; + addendum = " If you meant to render a collection of children, use an array " + "instead." + (getCurrentFiberStackAddendum$1() || ""), + invariant(!1, "Objects are not valid as a React child (found: %s).%s", "[object Object]" === Object.prototype.toString.call(newChild) ? "object with keys {" + Object.keys(newChild).join(", ") + "}" : newChild, addendum); + } +} + +function ChildReconciler(shouldClone, shouldTrackSideEffects) { + function deleteChild(returnFiber, childToDelete) { + if (shouldTrackSideEffects) { + if (!shouldClone) { + if (null === childToDelete.alternate) return; + childToDelete = childToDelete.alternate; + } + var last = returnFiber.progressedLastDeletion; + null !== last ? (last.nextEffect = childToDelete, returnFiber.progressedLastDeletion = childToDelete) : returnFiber.progressedFirstDeletion = returnFiber.progressedLastDeletion = childToDelete, + childToDelete.nextEffect = null, childToDelete.effectTag = Deletion$1; + } + } + function deleteRemainingChildren(returnFiber, currentFirstChild) { + if (!shouldTrackSideEffects) return null; + for (var childToDelete = currentFirstChild; null !== childToDelete; ) deleteChild(returnFiber, childToDelete), + childToDelete = childToDelete.sibling; + return null; + } + function mapRemainingChildren(returnFiber, currentFirstChild) { + for (var existingChildren = new Map(), existingChild = currentFirstChild; null !== existingChild; ) null !== existingChild.key ? existingChildren.set(existingChild.key, existingChild) : existingChildren.set(existingChild.index, existingChild), + existingChild = existingChild.sibling; + return existingChildren; + } + function useFiber(fiber, priority) { + if (shouldClone) { + var clone = cloneFiber$2(fiber, priority); + return clone.index = 0, clone.sibling = null, clone; + } + return fiber.pendingWorkPriority = priority, fiber.effectTag = NoEffect$3, fiber.index = 0, + fiber.sibling = null, fiber; + } + function placeChild(newFiber, lastPlacedIndex, newIndex) { + if (newFiber.index = newIndex, !shouldTrackSideEffects) return lastPlacedIndex; + var current = newFiber.alternate; + if (null !== current) { + var oldIndex = current.index; + return oldIndex < lastPlacedIndex ? (newFiber.effectTag = Placement$3, lastPlacedIndex) : oldIndex; + } + return newFiber.effectTag = Placement$3, lastPlacedIndex; + } + function placeSingleChild(newFiber) { + return shouldTrackSideEffects && null === newFiber.alternate && (newFiber.effectTag = Placement$3), + newFiber; + } + function updateTextNode(returnFiber, current, textContent, priority) { + if (null === current || current.tag !== HostText$4) { + var created = createFiberFromText$1(textContent, returnFiber.internalContextTag, priority); + return created.return = returnFiber, created; + } + var existing = useFiber(current, priority); + return existing.pendingProps = textContent, existing.return = returnFiber, existing; + } + function updateElement(returnFiber, current, element, priority) { + if (null === current || current.type !== element.type) { + var created = createFiberFromElement$1(element, returnFiber.internalContextTag, priority); + return created.ref = coerceRef(current, element), created.return = returnFiber, + created; + } + var existing = useFiber(current, priority); + return existing.ref = coerceRef(current, element), existing.pendingProps = element.props, + existing.return = returnFiber, existing._debugSource = element._source, existing._debugOwner = element._owner, + existing; + } + function updateCoroutine(returnFiber, current, coroutine, priority) { + if (null === current || current.tag !== CoroutineComponent$2) { + var created = createFiberFromCoroutine$1(coroutine, returnFiber.internalContextTag, priority); + return created.return = returnFiber, created; + } + var existing = useFiber(current, priority); + return existing.pendingProps = coroutine, existing.return = returnFiber, existing; + } + function updateYield(returnFiber, current, yieldNode, priority) { + if (null === current || current.tag !== YieldComponent$3) { + var created = createFiberFromYield$1(yieldNode, returnFiber.internalContextTag, priority); + return created.type = yieldNode.value, created.return = returnFiber, created; + } + var existing = useFiber(current, priority); + return existing.type = yieldNode.value, existing.return = returnFiber, existing; + } + function updatePortal(returnFiber, current, portal, priority) { + if (null === current || current.tag !== HostPortal$4 || current.stateNode.containerInfo !== portal.containerInfo || current.stateNode.implementation !== portal.implementation) { + var created = createFiberFromPortal$1(portal, returnFiber.internalContextTag, priority); + return created.return = returnFiber, created; + } + var existing = useFiber(current, priority); + return existing.pendingProps = portal.children || [], existing.return = returnFiber, + existing; + } + function updateFragment(returnFiber, current, fragment, priority) { + if (null === current || current.tag !== Fragment$3) { + var created = createFiberFromFragment$1(fragment, returnFiber.internalContextTag, priority); + return created.return = returnFiber, created; + } + var existing = useFiber(current, priority); + return existing.pendingProps = fragment, existing.return = returnFiber, existing; + } + function createChild(returnFiber, newChild, priority) { + if ("string" == typeof newChild || "number" == typeof newChild) { + var created = createFiberFromText$1("" + newChild, returnFiber.internalContextTag, priority); + return created.return = returnFiber, created; + } + if ("object" == typeof newChild && null !== newChild) { + switch (newChild.$$typeof) { + case ReactElementSymbol: + var _created = createFiberFromElement$1(newChild, returnFiber.internalContextTag, priority); + return _created.ref = coerceRef(null, newChild), _created.return = returnFiber, + _created; + + case REACT_COROUTINE_TYPE: + var _created2 = createFiberFromCoroutine$1(newChild, returnFiber.internalContextTag, priority); + return _created2.return = returnFiber, _created2; + + case REACT_YIELD_TYPE: + var _created3 = createFiberFromYield$1(newChild, returnFiber.internalContextTag, priority); + return _created3.type = newChild.value, _created3.return = returnFiber, _created3; + + case REACT_PORTAL_TYPE$1: + var _created4 = createFiberFromPortal$1(newChild, returnFiber.internalContextTag, priority); + return _created4.return = returnFiber, _created4; + } + if (isArray(newChild) || getIteratorFn_1(newChild)) { + var _created5 = createFiberFromFragment$1(newChild, returnFiber.internalContextTag, priority); + return _created5.return = returnFiber, _created5; + } + throwOnInvalidObjectType(returnFiber, newChild); + } + return null; + } + function updateSlot(returnFiber, oldFiber, newChild, priority) { + var key = null !== oldFiber ? oldFiber.key : null; + if ("string" == typeof newChild || "number" == typeof newChild) return null !== key ? null : updateTextNode(returnFiber, oldFiber, "" + newChild, priority); + if ("object" == typeof newChild && null !== newChild) { + switch (newChild.$$typeof) { + case ReactElementSymbol: + return newChild.key === key ? updateElement(returnFiber, oldFiber, newChild, priority) : null; + + case REACT_COROUTINE_TYPE: + return newChild.key === key ? updateCoroutine(returnFiber, oldFiber, newChild, priority) : null; + + case REACT_YIELD_TYPE: + return null === key ? updateYield(returnFiber, oldFiber, newChild, priority) : null; + + case REACT_PORTAL_TYPE$1: + return newChild.key === key ? updatePortal(returnFiber, oldFiber, newChild, priority) : null; + } + if (isArray(newChild) || getIteratorFn_1(newChild)) return null !== key ? null : updateFragment(returnFiber, oldFiber, newChild, priority); + throwOnInvalidObjectType(returnFiber, newChild); + } + return null; + } + function updateFromMap(existingChildren, returnFiber, newIdx, newChild, priority) { + if ("string" == typeof newChild || "number" == typeof newChild) { + return updateTextNode(returnFiber, existingChildren.get(newIdx) || null, "" + newChild, priority); + } + if ("object" == typeof newChild && null !== newChild) { + switch (newChild.$$typeof) { + case ReactElementSymbol: + return updateElement(returnFiber, existingChildren.get(null === newChild.key ? newIdx : newChild.key) || null, newChild, priority); + + case REACT_COROUTINE_TYPE: + return updateCoroutine(returnFiber, existingChildren.get(null === newChild.key ? newIdx : newChild.key) || null, newChild, priority); + + case REACT_YIELD_TYPE: + return updateYield(returnFiber, existingChildren.get(newIdx) || null, newChild, priority); + + case REACT_PORTAL_TYPE$1: + return updatePortal(returnFiber, existingChildren.get(null === newChild.key ? newIdx : newChild.key) || null, newChild, priority); + } + if (isArray(newChild) || getIteratorFn_1(newChild)) { + return updateFragment(returnFiber, existingChildren.get(newIdx) || null, newChild, priority); + } + throwOnInvalidObjectType(returnFiber, newChild); + } + return null; + } + function warnOnInvalidKey(child, knownKeys) { + if ("object" != typeof child || null === child) return knownKeys; + switch (child.$$typeof) { + case ReactElementSymbol: + case REACT_COROUTINE_TYPE: + case REACT_PORTAL_TYPE$1: + warnForMissingKey(child); + var key = child.key; + if ("string" != typeof key) break; + if (null === knownKeys) { + knownKeys = new Set(), knownKeys.add(key); + break; + } + if (!knownKeys.has(key)) { + knownKeys.add(key); + break; + } + warning$7(!1, "Encountered two children with the same key, " + "`%s`. Child keys must be unique; when two children share a key, " + "only the first child will be used.%s", key, getCurrentFiberStackAddendum$1()); + } + return knownKeys; + } + function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, priority) { + for (var knownKeys = null, i = 0; i < newChildren.length; i++) { + knownKeys = warnOnInvalidKey(newChildren[i], knownKeys); + } + for (var resultingFirstChild = null, previousNewFiber = null, oldFiber = currentFirstChild, lastPlacedIndex = 0, newIdx = 0, nextOldFiber = null; null !== oldFiber && newIdx < newChildren.length; newIdx++) { + oldFiber.index > newIdx ? (nextOldFiber = oldFiber, oldFiber = null) : nextOldFiber = oldFiber.sibling; + var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], priority); + if (null === newFiber) { + null === oldFiber && (oldFiber = nextOldFiber); + break; + } + shouldTrackSideEffects && oldFiber && null === newFiber.alternate && deleteChild(returnFiber, oldFiber), + lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx), null === previousNewFiber ? resultingFirstChild = newFiber : previousNewFiber.sibling = newFiber, + previousNewFiber = newFiber, oldFiber = nextOldFiber; + } + if (newIdx === newChildren.length) return deleteRemainingChildren(returnFiber, oldFiber), + resultingFirstChild; + if (null === oldFiber) { + for (;newIdx < newChildren.length; newIdx++) { + var _newFiber = createChild(returnFiber, newChildren[newIdx], priority); + _newFiber && (lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx), + null === previousNewFiber ? resultingFirstChild = _newFiber : previousNewFiber.sibling = _newFiber, + previousNewFiber = _newFiber); + } + return resultingFirstChild; + } + for (var existingChildren = mapRemainingChildren(returnFiber, oldFiber); newIdx < newChildren.length; newIdx++) { + var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], priority); + _newFiber2 && (shouldTrackSideEffects && null !== _newFiber2.alternate && existingChildren.delete(null === _newFiber2.key ? newIdx : _newFiber2.key), + lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx), null === previousNewFiber ? resultingFirstChild = _newFiber2 : previousNewFiber.sibling = _newFiber2, + previousNewFiber = _newFiber2); + } + return shouldTrackSideEffects && existingChildren.forEach(function(child) { + return deleteChild(returnFiber, child); + }), resultingFirstChild; + } + function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, priority) { + var iteratorFn = getIteratorFn_1(newChildrenIterable); + if (invariant("function" == typeof iteratorFn, "An object is not an iterable. This error is likely caused by a bug in " + "React. Please file an issue."), + "function" == typeof newChildrenIterable.entries) { + newChildrenIterable.entries === iteratorFn && (warning$7(didWarnAboutMaps, "Using Maps as children is unsupported and will likely yield " + "unexpected results. Convert it to a sequence/iterable of keyed " + "ReactElements instead.%s", getCurrentFiberStackAddendum$1()), + didWarnAboutMaps = !0); + } + var _newChildren = iteratorFn.call(newChildrenIterable); + if (_newChildren) for (var knownKeys = null, _step = _newChildren.next(); !_step.done; _step = _newChildren.next()) { + var child = _step.value; + knownKeys = warnOnInvalidKey(child, knownKeys); + } + var newChildren = iteratorFn.call(newChildrenIterable); + invariant(null != newChildren, "An iterable object provided no iterator."); + for (var resultingFirstChild = null, previousNewFiber = null, oldFiber = currentFirstChild, lastPlacedIndex = 0, newIdx = 0, nextOldFiber = null, step = newChildren.next(); null !== oldFiber && !step.done; newIdx++, + step = newChildren.next()) { + oldFiber.index > newIdx ? (nextOldFiber = oldFiber, oldFiber = null) : nextOldFiber = oldFiber.sibling; + var newFiber = updateSlot(returnFiber, oldFiber, step.value, priority); + if (null === newFiber) { + oldFiber || (oldFiber = nextOldFiber); + break; + } + shouldTrackSideEffects && oldFiber && null === newFiber.alternate && deleteChild(returnFiber, oldFiber), + lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx), null === previousNewFiber ? resultingFirstChild = newFiber : previousNewFiber.sibling = newFiber, + previousNewFiber = newFiber, oldFiber = nextOldFiber; + } + if (step.done) return deleteRemainingChildren(returnFiber, oldFiber), resultingFirstChild; + if (null === oldFiber) { + for (;!step.done; newIdx++, step = newChildren.next()) { + var _newFiber3 = createChild(returnFiber, step.value, priority); + null !== _newFiber3 && (lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx), + null === previousNewFiber ? resultingFirstChild = _newFiber3 : previousNewFiber.sibling = _newFiber3, + previousNewFiber = _newFiber3); + } + return resultingFirstChild; + } + for (var existingChildren = mapRemainingChildren(returnFiber, oldFiber); !step.done; newIdx++, + step = newChildren.next()) { + var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, priority); + null !== _newFiber4 && (shouldTrackSideEffects && null !== _newFiber4.alternate && existingChildren.delete(null === _newFiber4.key ? newIdx : _newFiber4.key), + lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx), null === previousNewFiber ? resultingFirstChild = _newFiber4 : previousNewFiber.sibling = _newFiber4, + previousNewFiber = _newFiber4); + } + return shouldTrackSideEffects && existingChildren.forEach(function(child) { + return deleteChild(returnFiber, child); + }), resultingFirstChild; + } + function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, priority) { + if (null !== currentFirstChild && currentFirstChild.tag === HostText$4) { + deleteRemainingChildren(returnFiber, currentFirstChild.sibling); + var existing = useFiber(currentFirstChild, priority); + return existing.pendingProps = textContent, existing.return = returnFiber, existing; + } + deleteRemainingChildren(returnFiber, currentFirstChild); + var created = createFiberFromText$1(textContent, returnFiber.internalContextTag, priority); + return created.return = returnFiber, created; + } + function reconcileSingleElement(returnFiber, currentFirstChild, element, priority) { + for (var key = element.key, child = currentFirstChild; null !== child; ) { + if (child.key === key) { + if (child.type === element.type) { + deleteRemainingChildren(returnFiber, child.sibling); + var existing = useFiber(child, priority); + return existing.ref = coerceRef(child, element), existing.pendingProps = element.props, + existing.return = returnFiber, existing._debugSource = element._source, existing._debugOwner = element._owner, + existing; + } + deleteRemainingChildren(returnFiber, child); + break; + } + deleteChild(returnFiber, child), child = child.sibling; + } + var created = createFiberFromElement$1(element, returnFiber.internalContextTag, priority); + return created.ref = coerceRef(currentFirstChild, element), created.return = returnFiber, + created; + } + function reconcileSingleCoroutine(returnFiber, currentFirstChild, coroutine, priority) { + for (var key = coroutine.key, child = currentFirstChild; null !== child; ) { + if (child.key === key) { + if (child.tag === CoroutineComponent$2) { + deleteRemainingChildren(returnFiber, child.sibling); + var existing = useFiber(child, priority); + return existing.pendingProps = coroutine, existing.return = returnFiber, existing; + } + deleteRemainingChildren(returnFiber, child); + break; + } + deleteChild(returnFiber, child), child = child.sibling; + } + var created = createFiberFromCoroutine$1(coroutine, returnFiber.internalContextTag, priority); + return created.return = returnFiber, created; + } + function reconcileSingleYield(returnFiber, currentFirstChild, yieldNode, priority) { + var child = currentFirstChild; + if (null !== child) { + if (child.tag === YieldComponent$3) { + deleteRemainingChildren(returnFiber, child.sibling); + var existing = useFiber(child, priority); + return existing.type = yieldNode.value, existing.return = returnFiber, existing; + } + deleteRemainingChildren(returnFiber, child); + } + var created = createFiberFromYield$1(yieldNode, returnFiber.internalContextTag, priority); + return created.type = yieldNode.value, created.return = returnFiber, created; + } + function reconcileSinglePortal(returnFiber, currentFirstChild, portal, priority) { + for (var key = portal.key, child = currentFirstChild; null !== child; ) { + if (child.key === key) { + if (child.tag === HostPortal$4 && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) { + deleteRemainingChildren(returnFiber, child.sibling); + var existing = useFiber(child, priority); + return existing.pendingProps = portal.children || [], existing.return = returnFiber, + existing; + } + deleteRemainingChildren(returnFiber, child); + break; + } + deleteChild(returnFiber, child), child = child.sibling; + } + var created = createFiberFromPortal$1(portal, returnFiber.internalContextTag, priority); + return created.return = returnFiber, created; + } + function reconcileChildFibers(returnFiber, currentFirstChild, newChild, priority) { + var disableNewFiberFeatures = ReactFeatureFlags_1.disableNewFiberFeatures, isObject = "object" == typeof newChild && null !== newChild; + if (isObject) if (disableNewFiberFeatures) switch (newChild.$$typeof) { + case ReactElementSymbol: + return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, priority)); + + case REACT_PORTAL_TYPE$1: + return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, priority)); + } else switch (newChild.$$typeof) { + case ReactElementSymbol: + return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, priority)); + + case REACT_COROUTINE_TYPE: + return placeSingleChild(reconcileSingleCoroutine(returnFiber, currentFirstChild, newChild, priority)); + + case REACT_YIELD_TYPE: + return placeSingleChild(reconcileSingleYield(returnFiber, currentFirstChild, newChild, priority)); + + case REACT_PORTAL_TYPE$1: + return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, priority)); + } + if (disableNewFiberFeatures) switch (returnFiber.tag) { + case ClassComponent$6: + if (returnFiber.stateNode.render._isMockFunction && void 0 === newChild) break; + var Component = returnFiber.type; + invariant(null === newChild || !1 === newChild, "%s.render(): A valid React element (or null) must be returned. " + "You may have returned undefined, an array or some other " + "invalid object.", Component.displayName || Component.name || "Component"); + break; + + case FunctionalComponent$2: + var _Component = returnFiber.type; + invariant(null === newChild || !1 === newChild, "%s(...): A valid React element (or null) must be returned. " + "You may have returned undefined, an array or some other " + "invalid object.", _Component.displayName || _Component.name || "Component"); + } + if ("string" == typeof newChild || "number" == typeof newChild) return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, "" + newChild, priority)); + if (isArray(newChild)) return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, priority); + if (getIteratorFn_1(newChild)) return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, priority); + if (isObject && throwOnInvalidObjectType(returnFiber, newChild), !disableNewFiberFeatures && void 0 === newChild) switch (returnFiber.tag) { + case ClassComponent$6: + if (returnFiber.stateNode.render._isMockFunction) break; + + case FunctionalComponent$2: + var _Component2 = returnFiber.type; + invariant(!1, "%s(...): Nothing was returned from render. This usually means a " + "return statement is missing. Or, to render nothing, " + "return null.", _Component2.displayName || _Component2.name || "Component"); + } + return deleteRemainingChildren(returnFiber, currentFirstChild); + } + return reconcileChildFibers; +} + +var reconcileChildFibers$1 = ChildReconciler(!0, !0), reconcileChildFibersInPlace$1 = ChildReconciler(!1, !0), mountChildFibersInPlace$1 = ChildReconciler(!1, !1), cloneChildFibers$1 = function(current, workInProgress) { + if (workInProgress.child) if (null !== current && workInProgress.child === current.child) { + var currentChild = workInProgress.child, newChild = cloneFiber$2(currentChild, currentChild.pendingWorkPriority); + for (workInProgress.child = newChild, newChild.return = workInProgress; null !== currentChild.sibling; ) currentChild = currentChild.sibling, + newChild = newChild.sibling = cloneFiber$2(currentChild, currentChild.pendingWorkPriority), + newChild.return = workInProgress; + newChild.sibling = null; + } else for (var child = workInProgress.child; null !== child; ) child.return = workInProgress, + child = child.sibling; +}, ReactChildFiber = { + reconcileChildFibers: reconcileChildFibers$1, + reconcileChildFibersInPlace: reconcileChildFibersInPlace$1, + mountChildFibersInPlace: mountChildFibersInPlace$1, + cloneChildFibers: cloneChildFibers$1 +}, Update$1 = ReactTypeOfSideEffect.Update, AsyncUpdates$1 = ReactTypeOfInternalContext.AsyncUpdates, cacheContext$1 = ReactFiberContext.cacheContext, getMaskedContext$2 = ReactFiberContext.getMaskedContext, getUnmaskedContext$2 = ReactFiberContext.getUnmaskedContext, isContextConsumer$1 = ReactFiberContext.isContextConsumer, addUpdate$1 = ReactFiberUpdateQueue.addUpdate, addReplaceUpdate$1 = ReactFiberUpdateQueue.addReplaceUpdate, addForceUpdate$1 = ReactFiberUpdateQueue.addForceUpdate, beginUpdateQueue$2 = ReactFiberUpdateQueue.beginUpdateQueue, _require5$1 = ReactFiberContext, hasContextChanged$2 = _require5$1.hasContextChanged, isMounted$1 = ReactFiberTreeReflection.isMounted, isArray$1 = Array.isArray, _require7$1 = ReactDebugFiberPerf_1, startPhaseTimer$1 = _require7$1.startPhaseTimer, stopPhaseTimer$1 = _require7$1.stopPhaseTimer, warning$8 = warning, warnOnInvalidCallback = function(callback, callerName) { + warning$8(null === callback || "function" == typeof callback, "%s(...): Expected the last optional `callback` argument to be a " + "function. Instead received: %s.", callerName, callback); +}, ReactFiberClassComponent = function(scheduleUpdate, getPriorityContext, memoizeProps, memoizeState) { + var updater = { + isMounted: isMounted$1, + enqueueSetState: function(instance, partialState, callback) { + var fiber = ReactInstanceMap_1.get(instance), priorityLevel = getPriorityContext(fiber, !1); + callback = void 0 === callback ? null : callback, warnOnInvalidCallback(callback, "setState"), + addUpdate$1(fiber, partialState, callback, priorityLevel), scheduleUpdate(fiber, priorityLevel); + }, + enqueueReplaceState: function(instance, state, callback) { + var fiber = ReactInstanceMap_1.get(instance), priorityLevel = getPriorityContext(fiber, !1); + callback = void 0 === callback ? null : callback, warnOnInvalidCallback(callback, "replaceState"), + addReplaceUpdate$1(fiber, state, callback, priorityLevel), scheduleUpdate(fiber, priorityLevel); + }, + enqueueForceUpdate: function(instance, callback) { + var fiber = ReactInstanceMap_1.get(instance), priorityLevel = getPriorityContext(fiber, !1); + callback = void 0 === callback ? null : callback, warnOnInvalidCallback(callback, "forceUpdate"), + addForceUpdate$1(fiber, callback, priorityLevel), scheduleUpdate(fiber, priorityLevel); + } + }; + function checkShouldComponentUpdate(workInProgress, oldProps, newProps, oldState, newState, newContext) { + if (null === oldProps || null !== workInProgress.updateQueue && workInProgress.updateQueue.hasForceUpdate) return !0; + var instance = workInProgress.stateNode, type = workInProgress.type; + if ("function" == typeof instance.shouldComponentUpdate) { + startPhaseTimer$1(workInProgress, "shouldComponentUpdate"); + var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, newContext); + return stopPhaseTimer$1(), warning$8(void 0 !== shouldUpdate, "%s.shouldComponentUpdate(): Returned undefined instead of a " + "boolean value. Make sure to return true or false.", getComponentName_1(workInProgress) || "Unknown"), + shouldUpdate; + } + return !type.prototype || !type.prototype.isPureReactComponent || (!shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState)); + } + function checkClassInstance(workInProgress) { + var instance = workInProgress.stateNode, type = workInProgress.type, name = getComponentName_1(workInProgress), renderPresent = instance.render; + warning$8(renderPresent, "%s(...): No `render` method found on the returned component " + "instance: you may have forgotten to define `render`.", name); + var noGetInitialStateOnES6 = !instance.getInitialState || instance.getInitialState.isReactClassApproved || instance.state; + warning$8(noGetInitialStateOnES6, "getInitialState was defined on %s, a plain JavaScript class. " + "This is only supported for classes created using React.createClass. " + "Did you mean to define a state property instead?", name); + var noGetDefaultPropsOnES6 = !instance.getDefaultProps || instance.getDefaultProps.isReactClassApproved; + warning$8(noGetDefaultPropsOnES6, "getDefaultProps was defined on %s, a plain JavaScript class. " + "This is only supported for classes created using React.createClass. " + "Use a static property to define defaultProps instead.", name); + var noInstancePropTypes = !instance.propTypes; + warning$8(noInstancePropTypes, "propTypes was defined as an instance property on %s. Use a static " + "property to define propTypes instead.", name); + var noInstanceContextTypes = !instance.contextTypes; + warning$8(noInstanceContextTypes, "contextTypes was defined as an instance property on %s. Use a static " + "property to define contextTypes instead.", name); + var noComponentShouldUpdate = "function" != typeof instance.componentShouldUpdate; + warning$8(noComponentShouldUpdate, "%s has a method called " + "componentShouldUpdate(). Did you mean shouldComponentUpdate()? " + "The name is phrased as a question because the function is " + "expected to return a value.", name), + type.prototype && type.prototype.isPureReactComponent && void 0 !== instance.shouldComponentUpdate && warning$8(!1, "%s has a method called shouldComponentUpdate(). " + "shouldComponentUpdate should not be used when extending React.PureComponent. " + "Please extend React.Component if shouldComponentUpdate is used.", getComponentName_1(workInProgress) || "A pure component"); + var noComponentDidUnmount = "function" != typeof instance.componentDidUnmount; + warning$8(noComponentDidUnmount, "%s has a method called " + "componentDidUnmount(). But there is no such lifecycle method. " + "Did you mean componentWillUnmount()?", name); + var noComponentWillRecieveProps = "function" != typeof instance.componentWillRecieveProps; + warning$8(noComponentWillRecieveProps, "%s has a method called " + "componentWillRecieveProps(). Did you mean componentWillReceiveProps()?", name); + var hasMutatedProps = instance.props !== workInProgress.pendingProps; + warning$8(void 0 === instance.props || !hasMutatedProps, "%s(...): When calling super() in `%s`, make sure to pass " + "up the same props that your component's constructor was passed.", name, name); + var noInstanceDefaultProps = !instance.defaultProps; + warning$8(noInstanceDefaultProps, "Setting defaultProps as an instance property on %s is not supported and will be ignored." + " Instead, define defaultProps as a static property on %s.", name, name); + var state = instance.state; + state && ("object" != typeof state || isArray$1(state)) && invariant(!1, "%s.state: must be set to an object or null", getComponentName_1(workInProgress)), + "function" == typeof instance.getChildContext && invariant("object" == typeof workInProgress.type.childContextTypes, "%s.getChildContext(): childContextTypes must be defined in order to " + "use getChildContext().", getComponentName_1(workInProgress)); + } + function resetInputPointers(workInProgress, instance) { + instance.props = workInProgress.memoizedProps, instance.state = workInProgress.memoizedState; + } + function adoptClassInstance(workInProgress, instance) { + instance.updater = updater, workInProgress.stateNode = instance, ReactInstanceMap_1.set(instance, workInProgress); + } + function constructClassInstance(workInProgress, props) { + var ctor = workInProgress.type, unmaskedContext = getUnmaskedContext$2(workInProgress), needsContext = isContextConsumer$1(workInProgress), context = needsContext ? getMaskedContext$2(workInProgress, unmaskedContext) : emptyObject, instance = new ctor(props, context); + return adoptClassInstance(workInProgress, instance), needsContext && cacheContext$1(workInProgress, unmaskedContext, context), + instance; + } + function callComponentWillMount(workInProgress, instance) { + startPhaseTimer$1(workInProgress, "componentWillMount"); + var oldState = instance.state; + instance.componentWillMount(), stopPhaseTimer$1(), oldState !== instance.state && (warning$8(!1, "%s.componentWillMount(): Assigning directly to this.state is " + "deprecated (except inside a component's " + "constructor). Use setState instead.", getComponentName_1(workInProgress)), + updater.enqueueReplaceState(instance, instance.state, null)); + } + function callComponentWillReceiveProps(workInProgress, instance, newProps, newContext) { + startPhaseTimer$1(workInProgress, "componentWillReceiveProps"); + var oldState = instance.state; + instance.componentWillReceiveProps(newProps, newContext), stopPhaseTimer$1(), instance.state !== oldState && (warning$8(!1, "%s.componentWillReceiveProps(): Assigning directly to " + "this.state is deprecated (except inside a component's " + "constructor). Use setState instead.", getComponentName_1(workInProgress)), + updater.enqueueReplaceState(instance, instance.state, null)); + } + function mountClassInstance(workInProgress, priorityLevel) { + checkClassInstance(workInProgress); + var instance = workInProgress.stateNode, state = instance.state || null, props = workInProgress.pendingProps; + invariant(props, "There must be pending props for an initial mount. This error is " + "likely caused by a bug in React. Please file an issue."); + var unmaskedContext = getUnmaskedContext$2(workInProgress); + if (instance.props = props, instance.state = state, instance.refs = emptyObject, + instance.context = getMaskedContext$2(workInProgress, unmaskedContext), ReactFeatureFlags_1.enableAsyncSubtreeAPI && null != workInProgress.type && !0 === workInProgress.type.unstable_asyncUpdates && (workInProgress.internalContextTag |= AsyncUpdates$1), + "function" == typeof instance.componentWillMount) { + callComponentWillMount(workInProgress, instance); + var updateQueue = workInProgress.updateQueue; + null !== updateQueue && (instance.state = beginUpdateQueue$2(workInProgress, updateQueue, instance, state, props, priorityLevel)); + } + "function" == typeof instance.componentDidMount && (workInProgress.effectTag |= Update$1); + } + function resumeMountClassInstance(workInProgress, priorityLevel) { + var instance = workInProgress.stateNode; + resetInputPointers(workInProgress, instance); + var newState = workInProgress.memoizedState, newProps = workInProgress.pendingProps; + newProps || (newProps = workInProgress.memoizedProps, invariant(null != newProps, "There should always be pending or memoized props. This error is " + "likely caused by a bug in React. Please file an issue.")); + var newUnmaskedContext = getUnmaskedContext$2(workInProgress), newContext = getMaskedContext$2(workInProgress, newUnmaskedContext), oldContext = instance.context, oldProps = workInProgress.memoizedProps; + "function" != typeof instance.componentWillReceiveProps || oldProps === newProps && oldContext === newContext || callComponentWillReceiveProps(workInProgress, instance, newProps, newContext); + var updateQueue = workInProgress.updateQueue; + if (null !== updateQueue && (newState = beginUpdateQueue$2(workInProgress, updateQueue, instance, newState, newProps, priorityLevel)), + !checkShouldComponentUpdate(workInProgress, workInProgress.memoizedProps, newProps, workInProgress.memoizedState, newState, newContext)) return instance.props = newProps, + instance.state = newState, instance.context = newContext, !1; + if (instance.props = newProps, instance.state = newState, instance.context = newContext, + "function" == typeof instance.componentWillMount) { + callComponentWillMount(workInProgress, instance); + var newUpdateQueue = workInProgress.updateQueue; + null !== newUpdateQueue && (newState = beginUpdateQueue$2(workInProgress, newUpdateQueue, instance, newState, newProps, priorityLevel)); + } + return "function" == typeof instance.componentDidMount && (workInProgress.effectTag |= Update$1), + instance.state = newState, !0; + } + function updateClassInstance(current, workInProgress, priorityLevel) { + var instance = workInProgress.stateNode; + resetInputPointers(workInProgress, instance); + var oldProps = workInProgress.memoizedProps, newProps = workInProgress.pendingProps; + newProps || (newProps = oldProps, invariant(null != newProps, "There should always be pending or memoized props. This error is " + "likely caused by a bug in React. Please file an issue.")); + var oldContext = instance.context, newUnmaskedContext = getUnmaskedContext$2(workInProgress), newContext = getMaskedContext$2(workInProgress, newUnmaskedContext); + "function" != typeof instance.componentWillReceiveProps || oldProps === newProps && oldContext === newContext || callComponentWillReceiveProps(workInProgress, instance, newProps, newContext); + var updateQueue = workInProgress.updateQueue, oldState = workInProgress.memoizedState, newState = void 0; + if (newState = null !== updateQueue ? beginUpdateQueue$2(workInProgress, updateQueue, instance, oldState, newProps, priorityLevel) : oldState, + !(oldProps !== newProps || oldState !== newState || hasContextChanged$2() || null !== updateQueue && updateQueue.hasForceUpdate)) return "function" == typeof instance.componentDidUpdate && (oldProps === current.memoizedProps && oldState === current.memoizedState || (workInProgress.effectTag |= Update$1)), + !1; + var shouldUpdate = checkShouldComponentUpdate(workInProgress, oldProps, newProps, oldState, newState, newContext); + return shouldUpdate ? ("function" == typeof instance.componentWillUpdate && (startPhaseTimer$1(workInProgress, "componentWillUpdate"), + instance.componentWillUpdate(newProps, newState, newContext), stopPhaseTimer$1()), + "function" == typeof instance.componentDidUpdate && (workInProgress.effectTag |= Update$1)) : ("function" == typeof instance.componentDidUpdate && (oldProps === current.memoizedProps && oldState === current.memoizedState || (workInProgress.effectTag |= Update$1)), + memoizeProps(workInProgress, newProps), memoizeState(workInProgress, newState)), + instance.props = newProps, instance.state = newState, instance.context = newContext, + shouldUpdate; + } + return { + adoptClassInstance: adoptClassInstance, + constructClassInstance: constructClassInstance, + mountClassInstance: mountClassInstance, + resumeMountClassInstance: resumeMountClassInstance, + updateClassInstance: updateClassInstance + }; +}, mountChildFibersInPlace = ReactChildFiber.mountChildFibersInPlace, reconcileChildFibers = ReactChildFiber.reconcileChildFibers, reconcileChildFibersInPlace = ReactChildFiber.reconcileChildFibersInPlace, cloneChildFibers = ReactChildFiber.cloneChildFibers, beginUpdateQueue$1 = ReactFiberUpdateQueue.beginUpdateQueue, getMaskedContext$1 = ReactFiberContext.getMaskedContext, getUnmaskedContext$1 = ReactFiberContext.getUnmaskedContext, hasContextChanged$1 = ReactFiberContext.hasContextChanged, pushContextProvider$1 = ReactFiberContext.pushContextProvider, pushTopLevelContextObject$1 = ReactFiberContext.pushTopLevelContextObject, invalidateContextProvider$1 = ReactFiberContext.invalidateContextProvider, IndeterminateComponent$2 = ReactTypeOfWork.IndeterminateComponent, FunctionalComponent$1 = ReactTypeOfWork.FunctionalComponent, ClassComponent$5 = ReactTypeOfWork.ClassComponent, HostRoot$5 = ReactTypeOfWork.HostRoot, HostComponent$6 = ReactTypeOfWork.HostComponent, HostText$3 = ReactTypeOfWork.HostText, HostPortal$3 = ReactTypeOfWork.HostPortal, CoroutineComponent$1 = ReactTypeOfWork.CoroutineComponent, CoroutineHandlerPhase = ReactTypeOfWork.CoroutineHandlerPhase, YieldComponent$2 = ReactTypeOfWork.YieldComponent, Fragment$2 = ReactTypeOfWork.Fragment, NoWork$3 = ReactPriorityLevel.NoWork, OffscreenPriority$1 = ReactPriorityLevel.OffscreenPriority, Placement$2 = ReactTypeOfSideEffect.Placement, ContentReset$1 = ReactTypeOfSideEffect.ContentReset, Err$1 = ReactTypeOfSideEffect.Err, Ref$1 = ReactTypeOfSideEffect.Ref, ReactCurrentOwner$2 = ReactGlobalSharedState_1.ReactCurrentOwner, ReactDebugCurrentFiber$4 = ReactDebugCurrentFiber_1, _require7 = ReactDebugFiberPerf_1, cancelWorkTimer = _require7.cancelWorkTimer, warning$6 = warning, warnedAboutStatelessRefs = {}, ReactFiberBeginWork = function(config, hostContext, hydrationContext, scheduleUpdate, getPriorityContext) { + var shouldSetTextContent = config.shouldSetTextContent, useSyncScheduling = config.useSyncScheduling, shouldDeprioritizeSubtree = config.shouldDeprioritizeSubtree, pushHostContext = hostContext.pushHostContext, pushHostContainer = hostContext.pushHostContainer, enterHydrationState = hydrationContext.enterHydrationState, resetHydrationState = hydrationContext.resetHydrationState, tryToClaimNextHydratableInstance = hydrationContext.tryToClaimNextHydratableInstance, _ReactFiberClassCompo = ReactFiberClassComponent(scheduleUpdate, getPriorityContext, memoizeProps, memoizeState), adoptClassInstance = _ReactFiberClassCompo.adoptClassInstance, constructClassInstance = _ReactFiberClassCompo.constructClassInstance, mountClassInstance = _ReactFiberClassCompo.mountClassInstance, resumeMountClassInstance = _ReactFiberClassCompo.resumeMountClassInstance, updateClassInstance = _ReactFiberClassCompo.updateClassInstance; + function markChildAsProgressed(current, workInProgress, priorityLevel) { + workInProgress.progressedChild = workInProgress.child, workInProgress.progressedPriority = priorityLevel, + null !== current && (current.progressedChild = workInProgress.progressedChild, current.progressedPriority = workInProgress.progressedPriority); + } + function clearDeletions(workInProgress) { + workInProgress.progressedFirstDeletion = workInProgress.progressedLastDeletion = null; + } + function transferDeletions(workInProgress) { + workInProgress.firstEffect = workInProgress.progressedFirstDeletion, workInProgress.lastEffect = workInProgress.progressedLastDeletion; + } + function reconcileChildren(current, workInProgress, nextChildren) { + reconcileChildrenAtPriority(current, workInProgress, nextChildren, workInProgress.pendingWorkPriority); + } + function reconcileChildrenAtPriority(current, workInProgress, nextChildren, priorityLevel) { + workInProgress.memoizedProps = null, null === current ? workInProgress.child = mountChildFibersInPlace(workInProgress, workInProgress.child, nextChildren, priorityLevel) : current.child === workInProgress.child ? (clearDeletions(workInProgress), + workInProgress.child = reconcileChildFibers(workInProgress, workInProgress.child, nextChildren, priorityLevel), + transferDeletions(workInProgress)) : (workInProgress.child = reconcileChildFibersInPlace(workInProgress, workInProgress.child, nextChildren, priorityLevel), + transferDeletions(workInProgress)), markChildAsProgressed(current, workInProgress, priorityLevel); + } + function updateFragment(current, workInProgress) { + var nextChildren = workInProgress.pendingProps; + if (hasContextChanged$1()) null === nextChildren && (nextChildren = workInProgress.memoizedProps); else if (null === nextChildren || workInProgress.memoizedProps === nextChildren) return bailoutOnAlreadyFinishedWork(current, workInProgress); + return reconcileChildren(current, workInProgress, nextChildren), memoizeProps(workInProgress, nextChildren), + workInProgress.child; + } + function markRef(current, workInProgress) { + var ref = workInProgress.ref; + null === ref || current && current.ref === ref || (workInProgress.effectTag |= Ref$1); + } + function updateFunctionalComponent(current, workInProgress) { + var fn = workInProgress.type, nextProps = workInProgress.pendingProps, memoizedProps = workInProgress.memoizedProps; + if (hasContextChanged$1()) null === nextProps && (nextProps = memoizedProps); else { + if (null === nextProps || memoizedProps === nextProps) return bailoutOnAlreadyFinishedWork(current, workInProgress); + if ("function" == typeof fn.shouldComponentUpdate && !fn.shouldComponentUpdate(memoizedProps, nextProps)) return memoizeProps(workInProgress, nextProps), + bailoutOnAlreadyFinishedWork(current, workInProgress); + } + var nextChildren, unmaskedContext = getUnmaskedContext$1(workInProgress), context = getMaskedContext$1(workInProgress, unmaskedContext); + return ReactCurrentOwner$2.current = workInProgress, ReactDebugCurrentFiber$4.phase = "render", + nextChildren = fn(nextProps, context), ReactDebugCurrentFiber$4.phase = null, reconcileChildren(current, workInProgress, nextChildren), + memoizeProps(workInProgress, nextProps), workInProgress.child; + } + function updateClassComponent(current, workInProgress, priorityLevel) { + var hasContext = pushContextProvider$1(workInProgress), shouldUpdate = void 0; + return null === current ? workInProgress.stateNode ? shouldUpdate = resumeMountClassInstance(workInProgress, priorityLevel) : (constructClassInstance(workInProgress, workInProgress.pendingProps), + mountClassInstance(workInProgress, priorityLevel), shouldUpdate = !0) : shouldUpdate = updateClassInstance(current, workInProgress, priorityLevel), + finishClassComponent(current, workInProgress, shouldUpdate, hasContext); + } + function finishClassComponent(current, workInProgress, shouldUpdate, hasContext) { + if (markRef(current, workInProgress), !shouldUpdate) return bailoutOnAlreadyFinishedWork(current, workInProgress); + var instance = workInProgress.stateNode; + ReactCurrentOwner$2.current = workInProgress; + var nextChildren = void 0; + return ReactDebugCurrentFiber$4.phase = "render", nextChildren = instance.render(), + ReactDebugCurrentFiber$4.phase = null, reconcileChildren(current, workInProgress, nextChildren), + memoizeState(workInProgress, instance.state), memoizeProps(workInProgress, instance.props), + hasContext && invalidateContextProvider$1(workInProgress), workInProgress.child; + } + function updateHostRoot(current, workInProgress, priorityLevel) { + var root = workInProgress.stateNode; + root.pendingContext ? pushTopLevelContextObject$1(workInProgress, root.pendingContext, root.pendingContext !== root.context) : root.context && pushTopLevelContextObject$1(workInProgress, root.context, !1), + pushHostContainer(workInProgress, root.containerInfo); + var updateQueue = workInProgress.updateQueue; + if (null !== updateQueue) { + var prevState = workInProgress.memoizedState, state = beginUpdateQueue$1(workInProgress, updateQueue, null, prevState, null, priorityLevel); + if (prevState === state) return resetHydrationState(), bailoutOnAlreadyFinishedWork(current, workInProgress); + var element = state.element; + return null !== current && null !== current.child || !enterHydrationState(workInProgress) ? (resetHydrationState(), + reconcileChildren(current, workInProgress, element), memoizeState(workInProgress, state), + workInProgress.child) : (workInProgress.effectTag |= Placement$2, workInProgress.child = mountChildFibersInPlace(workInProgress, workInProgress.child, element, priorityLevel), + markChildAsProgressed(current, workInProgress, priorityLevel), workInProgress.child); + } + return resetHydrationState(), bailoutOnAlreadyFinishedWork(current, workInProgress); + } + function updateHostComponent(current, workInProgress) { + pushHostContext(workInProgress), null === current && tryToClaimNextHydratableInstance(workInProgress); + var nextProps = workInProgress.pendingProps, prevProps = null !== current ? current.memoizedProps : null, memoizedProps = workInProgress.memoizedProps; + if (hasContextChanged$1()) null === nextProps && (nextProps = memoizedProps, invariant(null !== nextProps, "We should always have pending or current props. This error is " + "likely caused by a bug in React. Please file an issue.")); else if (null === nextProps || memoizedProps === nextProps) { + if (!useSyncScheduling && shouldDeprioritizeSubtree(workInProgress.type, memoizedProps) && workInProgress.pendingWorkPriority !== OffscreenPriority$1) { + for (var child = workInProgress.progressedChild; null !== child; ) child.pendingWorkPriority = OffscreenPriority$1, + child = child.sibling; + return null; + } + return bailoutOnAlreadyFinishedWork(current, workInProgress); + } + var nextChildren = nextProps.children; + if (shouldSetTextContent(nextProps) ? nextChildren = null : prevProps && shouldSetTextContent(prevProps) && (workInProgress.effectTag |= ContentReset$1), + markRef(current, workInProgress), !useSyncScheduling && shouldDeprioritizeSubtree(workInProgress.type, nextProps) && workInProgress.pendingWorkPriority !== OffscreenPriority$1) { + if (workInProgress.progressedPriority === OffscreenPriority$1 && (workInProgress.child = workInProgress.progressedChild), + reconcileChildrenAtPriority(current, workInProgress, nextChildren, OffscreenPriority$1), + memoizeProps(workInProgress, nextProps), workInProgress.child = null !== current ? current.child : null, + null === current) for (var _child = workInProgress.progressedChild; null !== _child; ) _child.effectTag = Placement$2, + _child = _child.sibling; + return null; + } + return reconcileChildren(current, workInProgress, nextChildren), memoizeProps(workInProgress, nextProps), + workInProgress.child; + } + function updateHostText(current, workInProgress) { + null === current && tryToClaimNextHydratableInstance(workInProgress); + var nextProps = workInProgress.pendingProps; + return null === nextProps && (nextProps = workInProgress.memoizedProps), memoizeProps(workInProgress, nextProps), + null; + } + function mountIndeterminateComponent(current, workInProgress, priorityLevel) { + invariant(null === current, "An indeterminate component should never have mounted. This error is " + "likely caused by a bug in React. Please file an issue."); + var value, fn = workInProgress.type, props = workInProgress.pendingProps, unmaskedContext = getUnmaskedContext$1(workInProgress), context = getMaskedContext$1(workInProgress, unmaskedContext); + if (ReactCurrentOwner$2.current = workInProgress, "object" == typeof (value = fn(props, context)) && null !== value && "function" == typeof value.render) { + workInProgress.tag = ClassComponent$5; + var hasContext = pushContextProvider$1(workInProgress); + return adoptClassInstance(workInProgress, value), mountClassInstance(workInProgress, priorityLevel), + finishClassComponent(current, workInProgress, !0, hasContext); + } + workInProgress.tag = FunctionalComponent$1; + var Component = workInProgress.type; + if (Component && warning$6(!Component.childContextTypes, "%s(...): childContextTypes cannot be defined on a functional component.", Component.displayName || Component.name || "Component"), + null !== workInProgress.ref) { + var info = "", ownerName = ReactDebugCurrentFiber$4.getCurrentFiberOwnerName(); + ownerName && (info += "\n\nCheck the render method of `" + ownerName + "`."); + var warningKey = ownerName || workInProgress._debugID || "", debugSource = workInProgress._debugSource; + debugSource && (warningKey = debugSource.fileName + ":" + debugSource.lineNumber), + warnedAboutStatelessRefs[warningKey] || (warnedAboutStatelessRefs[warningKey] = !0, + warning$6(!1, "Stateless function components cannot be given refs. " + "Attempts to access this ref will fail.%s%s", info, ReactDebugCurrentFiber$4.getCurrentFiberStackAddendum())); + } + return reconcileChildren(current, workInProgress, value), memoizeProps(workInProgress, props), + workInProgress.child; + } + function updateCoroutineComponent(current, workInProgress) { + var nextCoroutine = workInProgress.pendingProps; + hasContextChanged$1() ? null === nextCoroutine && (nextCoroutine = current && current.memoizedProps, + invariant(null !== nextCoroutine, "We should always have pending or current props. This error is " + "likely caused by a bug in React. Please file an issue.")) : null !== nextCoroutine && workInProgress.memoizedProps !== nextCoroutine || (nextCoroutine = workInProgress.memoizedProps); + var nextChildren = nextCoroutine.children, priorityLevel = workInProgress.pendingWorkPriority; + return workInProgress.memoizedProps = null, null === current ? workInProgress.stateNode = mountChildFibersInPlace(workInProgress, workInProgress.stateNode, nextChildren, priorityLevel) : current.child === workInProgress.child ? (clearDeletions(workInProgress), + workInProgress.stateNode = reconcileChildFibers(workInProgress, workInProgress.stateNode, nextChildren, priorityLevel), + transferDeletions(workInProgress)) : (workInProgress.stateNode = reconcileChildFibersInPlace(workInProgress, workInProgress.stateNode, nextChildren, priorityLevel), + transferDeletions(workInProgress)), memoizeProps(workInProgress, nextCoroutine), + workInProgress.stateNode; + } + function updatePortalComponent(current, workInProgress) { + pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); + var priorityLevel = workInProgress.pendingWorkPriority, nextChildren = workInProgress.pendingProps; + if (hasContextChanged$1()) null === nextChildren && (nextChildren = current && current.memoizedProps, + invariant(null != nextChildren, "We should always have pending or current props. This error is " + "likely caused by a bug in React. Please file an issue.")); else if (null === nextChildren || workInProgress.memoizedProps === nextChildren) return bailoutOnAlreadyFinishedWork(current, workInProgress); + return null === current ? (workInProgress.child = reconcileChildFibersInPlace(workInProgress, workInProgress.child, nextChildren, priorityLevel), + memoizeProps(workInProgress, nextChildren), markChildAsProgressed(current, workInProgress, priorityLevel)) : (reconcileChildren(current, workInProgress, nextChildren), + memoizeProps(workInProgress, nextChildren)), workInProgress.child; + } + function bailoutOnAlreadyFinishedWork(current, workInProgress) { + cancelWorkTimer(workInProgress); + var priorityLevel = workInProgress.pendingWorkPriority; + return current && workInProgress.child === current.child && clearDeletions(workInProgress), + cloneChildFibers(current, workInProgress), markChildAsProgressed(current, workInProgress, priorityLevel), + workInProgress.child; + } + function bailoutOnLowPriority(current, workInProgress) { + switch (cancelWorkTimer(workInProgress), workInProgress.tag) { + case ClassComponent$5: + pushContextProvider$1(workInProgress); + break; + + case HostPortal$3: + pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); + } + return null; + } + function memoizeProps(workInProgress, nextProps) { + workInProgress.memoizedProps = nextProps, workInProgress.pendingProps = null; + } + function memoizeState(workInProgress, nextState) { + workInProgress.memoizedState = nextState; + } + function beginWork(current, workInProgress, priorityLevel) { + if (workInProgress.pendingWorkPriority === NoWork$3 || workInProgress.pendingWorkPriority > priorityLevel) return bailoutOnLowPriority(current, workInProgress); + switch (ReactDebugCurrentFiber$4.current = workInProgress, workInProgress.firstEffect = null, + workInProgress.lastEffect = null, workInProgress.progressedPriority === priorityLevel && (workInProgress.child = workInProgress.progressedChild), + workInProgress.tag) { + case IndeterminateComponent$2: + return mountIndeterminateComponent(current, workInProgress, priorityLevel); + + case FunctionalComponent$1: + return updateFunctionalComponent(current, workInProgress); + + case ClassComponent$5: + return updateClassComponent(current, workInProgress, priorityLevel); + + case HostRoot$5: + return updateHostRoot(current, workInProgress, priorityLevel); + + case HostComponent$6: + return updateHostComponent(current, workInProgress); + + case HostText$3: + return updateHostText(current, workInProgress); + + case CoroutineHandlerPhase: + workInProgress.tag = CoroutineComponent$1; + + case CoroutineComponent$1: + return updateCoroutineComponent(current, workInProgress); + + case YieldComponent$2: + return null; + + case HostPortal$3: + return updatePortalComponent(current, workInProgress); + + case Fragment$2: + return updateFragment(current, workInProgress); + + default: + invariant(!1, "Unknown unit of work tag. This error is likely caused by a bug in " + "React. Please file an issue."); + } + } + function beginFailedWork(current, workInProgress, priorityLevel) { + if (invariant(workInProgress.tag === ClassComponent$5 || workInProgress.tag === HostRoot$5, "Invalid type of work. This error is likely caused by a bug in React. " + "Please file an issue."), + workInProgress.effectTag |= Err$1, workInProgress.pendingWorkPriority === NoWork$3 || workInProgress.pendingWorkPriority > priorityLevel) return bailoutOnLowPriority(current, workInProgress); + if (workInProgress.firstEffect = null, workInProgress.lastEffect = null, reconcileChildren(current, workInProgress, null), + workInProgress.tag === ClassComponent$5) { + var instance = workInProgress.stateNode; + workInProgress.memoizedProps = instance.props, workInProgress.memoizedState = instance.state, + workInProgress.pendingProps = null; + } + return workInProgress.child; + } + return { + beginWork: beginWork, + beginFailedWork: beginFailedWork + }; +}, reconcileChildFibers$2 = ReactChildFiber.reconcileChildFibers, popContextProvider$2 = ReactFiberContext.popContextProvider, IndeterminateComponent$3 = ReactTypeOfWork.IndeterminateComponent, FunctionalComponent$3 = ReactTypeOfWork.FunctionalComponent, ClassComponent$7 = ReactTypeOfWork.ClassComponent, HostRoot$6 = ReactTypeOfWork.HostRoot, HostComponent$7 = ReactTypeOfWork.HostComponent, HostText$5 = ReactTypeOfWork.HostText, HostPortal$5 = ReactTypeOfWork.HostPortal, CoroutineComponent$3 = ReactTypeOfWork.CoroutineComponent, CoroutineHandlerPhase$1 = ReactTypeOfWork.CoroutineHandlerPhase, YieldComponent$4 = ReactTypeOfWork.YieldComponent, Fragment$4 = ReactTypeOfWork.Fragment, Placement$4 = ReactTypeOfSideEffect.Placement, Ref$2 = ReactTypeOfSideEffect.Ref, Update$2 = ReactTypeOfSideEffect.Update, ReactDebugCurrentFiber$5 = ReactDebugCurrentFiber_1, ReactFiberCompleteWork = function(config, hostContext, hydrationContext) { + var createInstance = config.createInstance, createTextInstance = config.createTextInstance, appendInitialChild = config.appendInitialChild, finalizeInitialChildren = config.finalizeInitialChildren, prepareUpdate = config.prepareUpdate, getRootHostContainer = hostContext.getRootHostContainer, popHostContext = hostContext.popHostContext, getHostContext = hostContext.getHostContext, popHostContainer = hostContext.popHostContainer, hydrateHostInstance = hydrationContext.hydrateHostInstance, hydrateHostTextInstance = hydrationContext.hydrateHostTextInstance, popHydrationState = hydrationContext.popHydrationState; + function markChildAsProgressed(current, workInProgress, priorityLevel) { + workInProgress.progressedChild = workInProgress.child, workInProgress.progressedPriority = priorityLevel, + null !== current && (current.progressedChild = workInProgress.progressedChild, current.progressedPriority = workInProgress.progressedPriority); + } + function markUpdate(workInProgress) { + workInProgress.effectTag |= Update$2; + } + function markRef(workInProgress) { + workInProgress.effectTag |= Ref$2; + } + function appendAllYields(yields, workInProgress) { + var node = workInProgress.stateNode; + for (node && (node.return = workInProgress); null !== node; ) { + if (node.tag === HostComponent$7 || node.tag === HostText$5 || node.tag === HostPortal$5) invariant(!1, "A coroutine cannot have host component children."); else if (node.tag === YieldComponent$4) yields.push(node.type); else if (null !== node.child) { + node.child.return = node, node = node.child; + continue; + } + for (;null === node.sibling; ) { + if (null === node.return || node.return === workInProgress) return; + node = node.return; + } + node.sibling.return = node.return, node = node.sibling; + } + } + function moveCoroutineToHandlerPhase(current, workInProgress) { + var coroutine = workInProgress.memoizedProps; + invariant(coroutine, "Should be resolved by now. This error is likely caused by a bug in " + "React. Please file an issue."), + workInProgress.tag = CoroutineHandlerPhase$1; + var yields = []; + appendAllYields(yields, workInProgress); + var fn = coroutine.handler, props = coroutine.props, nextChildren = fn(props, yields), currentFirstChild = null !== current ? current.child : null, priority = workInProgress.pendingWorkPriority; + return workInProgress.child = reconcileChildFibers$2(workInProgress, currentFirstChild, nextChildren, priority), + markChildAsProgressed(current, workInProgress, priority), workInProgress.child; + } + function appendAllChildren(parent, workInProgress) { + for (var node = workInProgress.child; null !== node; ) { + if (node.tag === HostComponent$7 || node.tag === HostText$5) appendInitialChild(parent, node.stateNode); else if (node.tag === HostPortal$5) ; else if (null !== node.child) { + node = node.child; + continue; + } + if (node === workInProgress) return; + for (;null === node.sibling; ) { + if (null === node.return || node.return === workInProgress) return; + node = node.return; + } + node = node.sibling; + } + } + function completeWork(current, workInProgress) { + switch (ReactDebugCurrentFiber$5.current = workInProgress, workInProgress.tag) { + case FunctionalComponent$3: + return null; + + case ClassComponent$7: + return popContextProvider$2(workInProgress), null; + + case HostRoot$6: + var fiberRoot = workInProgress.stateNode; + return fiberRoot.pendingContext && (fiberRoot.context = fiberRoot.pendingContext, + fiberRoot.pendingContext = null), null !== current && null !== current.child || (popHydrationState(workInProgress), + workInProgress.effectTag &= ~Placement$4), null; + + case HostComponent$7: + popHostContext(workInProgress); + var rootContainerInstance = getRootHostContainer(), type = workInProgress.type, newProps = workInProgress.memoizedProps; + if (null !== current && null != workInProgress.stateNode) { + var oldProps = current.memoizedProps, instance = workInProgress.stateNode, currentHostContext = getHostContext(), updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext); + workInProgress.updateQueue = updatePayload, updatePayload && markUpdate(workInProgress), + current.ref !== workInProgress.ref && markRef(workInProgress); + } else { + if (!newProps) return invariant(null !== workInProgress.stateNode, "We must have new props for new mounts. This error is likely " + "caused by a bug in React. Please file an issue."), + null; + var _currentHostContext = getHostContext(), _instance = void 0; + popHydrationState(workInProgress) ? _instance = hydrateHostInstance(workInProgress, rootContainerInstance) : (_instance = createInstance(type, newProps, rootContainerInstance, _currentHostContext, workInProgress), + appendAllChildren(_instance, workInProgress), finalizeInitialChildren(_instance, type, newProps, rootContainerInstance) && markUpdate(workInProgress)), + workInProgress.stateNode = _instance, null !== workInProgress.ref && markRef(workInProgress); + } + return null; + + case HostText$5: + var newText = workInProgress.memoizedProps; + if (current && null != workInProgress.stateNode) { + current.memoizedProps !== newText && markUpdate(workInProgress); + } else { + if ("string" != typeof newText) return invariant(null !== workInProgress.stateNode, "We must have new props for new mounts. This error is likely " + "caused by a bug in React. Please file an issue."), + null; + var _rootContainerInstance = getRootHostContainer(), _currentHostContext2 = getHostContext(), textInstance = void 0; + textInstance = popHydrationState(workInProgress) ? hydrateHostTextInstance(workInProgress, _rootContainerInstance) : createTextInstance(newText, _rootContainerInstance, _currentHostContext2, workInProgress), + workInProgress.stateNode = textInstance; + } + return null; + + case CoroutineComponent$3: + return moveCoroutineToHandlerPhase(current, workInProgress); + + case CoroutineHandlerPhase$1: + return workInProgress.tag = CoroutineComponent$3, null; + + case YieldComponent$4: + case Fragment$4: + return null; + + case HostPortal$5: + return markUpdate(workInProgress), popHostContainer(workInProgress), null; + + case IndeterminateComponent$3: + invariant(!1, "An indeterminate component should have become determinate before " + "completing. This error is likely caused by a bug in React. Please " + "file an issue."); + + default: + invariant(!1, "Unknown unit of work tag. This error is likely caused by a bug in " + "React. Please file an issue."); + } + } + return { + completeWork: completeWork + }; +}, rendererID = null, injectInternals$1 = null, onCommitRoot$1 = null, onCommitUnmount$1 = null; + +if ("undefined" != typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && __REACT_DEVTOOLS_GLOBAL_HOOK__.supportsFiber) { + var inject$1 = __REACT_DEVTOOLS_GLOBAL_HOOK__.inject, onCommitFiberRoot = __REACT_DEVTOOLS_GLOBAL_HOOK__.onCommitFiberRoot, onCommitFiberUnmount = __REACT_DEVTOOLS_GLOBAL_HOOK__.onCommitFiberUnmount; + injectInternals$1 = function(internals) { + warning(null == rendererID, "Cannot inject into DevTools twice."), rendererID = inject$1(internals); + }, onCommitRoot$1 = function(root) { + if (null != rendererID) try { + onCommitFiberRoot(rendererID, root); + } catch (err) { + warning(!1, "React DevTools encountered an error: %s", err); + } + }, onCommitUnmount$1 = function(fiber) { + if (null != rendererID) try { + onCommitFiberUnmount(rendererID, fiber); + } catch (err) { + warning(!1, "React DevTools encountered an error: %s", err); + } + }; +} + +var injectInternals_1 = injectInternals$1, onCommitRoot_1 = onCommitRoot$1, onCommitUnmount_1 = onCommitUnmount$1, ReactFiberDevToolsHook = { + injectInternals: injectInternals_1, + onCommitRoot: onCommitRoot_1, + onCommitUnmount: onCommitUnmount_1 +}, ClassComponent$8 = ReactTypeOfWork.ClassComponent, HostRoot$7 = ReactTypeOfWork.HostRoot, HostComponent$8 = ReactTypeOfWork.HostComponent, HostText$6 = ReactTypeOfWork.HostText, HostPortal$6 = ReactTypeOfWork.HostPortal, CoroutineComponent$4 = ReactTypeOfWork.CoroutineComponent, commitCallbacks$1 = ReactFiberUpdateQueue.commitCallbacks, onCommitUnmount = ReactFiberDevToolsHook.onCommitUnmount, invokeGuardedCallback$2 = ReactErrorUtils_1.invokeGuardedCallback, Placement$5 = ReactTypeOfSideEffect.Placement, Update$3 = ReactTypeOfSideEffect.Update, Callback$1 = ReactTypeOfSideEffect.Callback, ContentReset$2 = ReactTypeOfSideEffect.ContentReset, _require5$2 = ReactDebugFiberPerf_1, startPhaseTimer$2 = _require5$2.startPhaseTimer, stopPhaseTimer$2 = _require5$2.stopPhaseTimer, ReactFiberCommitWork = function(config, captureError) { + var commitMount = config.commitMount, commitUpdate = config.commitUpdate, resetTextContent = config.resetTextContent, commitTextUpdate = config.commitTextUpdate, appendChild = config.appendChild, insertBefore = config.insertBefore, removeChild = config.removeChild, getPublicInstance = config.getPublicInstance, callComponentWillUnmountWithTimerInDev = function(current, instance) { + startPhaseTimer$2(current, "componentWillUnmount"), instance.componentWillUnmount(), + stopPhaseTimer$2(); + }; + function safelyCallComponentWillUnmount(current, instance) { + var unmountError = invokeGuardedCallback$2(null, callComponentWillUnmountWithTimerInDev, null, current, instance); + unmountError && captureError(current, unmountError); + } + function safelyDetachRef(current) { + var ref = current.ref; + if (null !== ref) { + var refError = invokeGuardedCallback$2(null, ref, null, null); + null !== refError && captureError(current, refError); + } + } + function getHostParent(fiber) { + for (var parent = fiber.return; null !== parent; ) { + switch (parent.tag) { + case HostComponent$8: + return parent.stateNode; + + case HostRoot$7: + case HostPortal$6: + return parent.stateNode.containerInfo; + } + parent = parent.return; + } + invariant(!1, "Expected to find a host parent. This error is likely caused by a bug " + "in React. Please file an issue."); + } + function getHostParentFiber(fiber) { + for (var parent = fiber.return; null !== parent; ) { + if (isHostParent(parent)) return parent; + parent = parent.return; + } + invariant(!1, "Expected to find a host parent. This error is likely caused by a bug " + "in React. Please file an issue."); + } + function isHostParent(fiber) { + return fiber.tag === HostComponent$8 || fiber.tag === HostRoot$7 || fiber.tag === HostPortal$6; + } + function getHostSibling(fiber) { + var node = fiber; + siblings: for (;!0; ) { + for (;null === node.sibling; ) { + if (null === node.return || isHostParent(node.return)) return null; + node = node.return; + } + for (node.sibling.return = node.return, node = node.sibling; node.tag !== HostComponent$8 && node.tag !== HostText$6; ) { + if (node.effectTag & Placement$5) continue siblings; + if (null === node.child || node.tag === HostPortal$6) continue siblings; + node.child.return = node, node = node.child; + } + if (!(node.effectTag & Placement$5)) return node.stateNode; + } + } + function commitPlacement(finishedWork) { + var parentFiber = getHostParentFiber(finishedWork), parent = void 0; + switch (parentFiber.tag) { + case HostComponent$8: + parent = parentFiber.stateNode; + break; + + case HostRoot$7: + case HostPortal$6: + parent = parentFiber.stateNode.containerInfo; + break; + + default: + invariant(!1, "Invalid host parent fiber. This error is likely caused by a bug " + "in React. Please file an issue."); + } + parentFiber.effectTag & ContentReset$2 && (resetTextContent(parent), parentFiber.effectTag &= ~ContentReset$2); + for (var before = getHostSibling(finishedWork), node = finishedWork; !0; ) { + if (node.tag === HostComponent$8 || node.tag === HostText$6) before ? insertBefore(parent, node.stateNode, before) : appendChild(parent, node.stateNode); else if (node.tag === HostPortal$6) ; else if (null !== node.child) { + node.child.return = node, node = node.child; + continue; + } + if (node === finishedWork) return; + for (;null === node.sibling; ) { + if (null === node.return || node.return === finishedWork) return; + node = node.return; + } + node.sibling.return = node.return, node = node.sibling; + } + } + function commitNestedUnmounts(root) { + for (var node = root; !0; ) if (commitUnmount(node), null === node.child || node.tag === HostPortal$6) { + if (node === root) return; + for (;null === node.sibling; ) { + if (null === node.return || node.return === root) return; + node = node.return; + } + node.sibling.return = node.return, node = node.sibling; + } else node.child.return = node, node = node.child; + } + function unmountHostComponents(parent, current) { + for (var node = current; !0; ) { + if (node.tag === HostComponent$8 || node.tag === HostText$6) commitNestedUnmounts(node), + removeChild(parent, node.stateNode); else if (node.tag === HostPortal$6) { + if (parent = node.stateNode.containerInfo, null !== node.child) { + node.child.return = node, node = node.child; + continue; + } + } else if (commitUnmount(node), null !== node.child) { + node.child.return = node, node = node.child; + continue; + } + if (node === current) return; + for (;null === node.sibling; ) { + if (null === node.return || node.return === current) return; + node = node.return, node.tag === HostPortal$6 && (parent = getHostParent(node)); + } + node.sibling.return = node.return, node = node.sibling; + } + } + function commitDeletion(current) { + unmountHostComponents(getHostParent(current), current), current.return = null, current.child = null, + current.alternate && (current.alternate.child = null, current.alternate.return = null); + } + function commitUnmount(current) { + switch ("function" == typeof onCommitUnmount && onCommitUnmount(current), current.tag) { + case ClassComponent$8: + safelyDetachRef(current); + var instance = current.stateNode; + return void ("function" == typeof instance.componentWillUnmount && safelyCallComponentWillUnmount(current, instance)); + + case HostComponent$8: + return void safelyDetachRef(current); + + case CoroutineComponent$4: + return void commitNestedUnmounts(current.stateNode); + + case HostPortal$6: + return void unmountHostComponents(getHostParent(current), current); + } + } + function commitWork(current, finishedWork) { + switch (finishedWork.tag) { + case ClassComponent$8: + return; + + case HostComponent$8: + var instance = finishedWork.stateNode; + if (null != instance && null !== current) { + var newProps = finishedWork.memoizedProps, oldProps = current.memoizedProps, type = finishedWork.type, updatePayload = finishedWork.updateQueue; + finishedWork.updateQueue = null, null !== updatePayload && commitUpdate(instance, updatePayload, type, oldProps, newProps, finishedWork); + } + return; + + case HostText$6: + invariant(null !== finishedWork.stateNode && null !== current, "This should only be done during updates. This error is likely " + "caused by a bug in React. Please file an issue."); + var textInstance = finishedWork.stateNode, newText = finishedWork.memoizedProps, oldText = current.memoizedProps; + return void commitTextUpdate(textInstance, oldText, newText); + + case HostRoot$7: + case HostPortal$6: + return; + + default: + invariant(!1, "This unit of work tag should not have side-effects. This error is " + "likely caused by a bug in React. Please file an issue."); + } + } + function commitLifeCycles(current, finishedWork) { + switch (finishedWork.tag) { + case ClassComponent$8: + var instance = finishedWork.stateNode; + if (finishedWork.effectTag & Update$3) if (null === current) startPhaseTimer$2(finishedWork, "componentDidMount"), + instance.componentDidMount(), stopPhaseTimer$2(); else { + var prevProps = current.memoizedProps, prevState = current.memoizedState; + startPhaseTimer$2(finishedWork, "componentDidUpdate"), instance.componentDidUpdate(prevProps, prevState), + stopPhaseTimer$2(); + } + return void (finishedWork.effectTag & Callback$1 && null !== finishedWork.updateQueue && commitCallbacks$1(finishedWork, finishedWork.updateQueue, instance)); + + case HostRoot$7: + var updateQueue = finishedWork.updateQueue; + if (null !== updateQueue) { + var _instance = finishedWork.child && finishedWork.child.stateNode; + commitCallbacks$1(finishedWork, updateQueue, _instance); + } + return; + + case HostComponent$8: + var _instance2 = finishedWork.stateNode; + if (null === current && finishedWork.effectTag & Update$3) { + var type = finishedWork.type, props = finishedWork.memoizedProps; + commitMount(_instance2, type, props, finishedWork); + } + return; + + case HostText$6: + case HostPortal$6: + return; + + default: + invariant(!1, "This unit of work tag should not have side-effects. This error is " + "likely caused by a bug in React. Please file an issue."); + } + } + function commitAttachRef(finishedWork) { + var ref = finishedWork.ref; + if (null !== ref) { + ref(getPublicInstance(finishedWork.stateNode)); + } + } + function commitDetachRef(current) { + var currentRef = current.ref; + null !== currentRef && currentRef(null); + } + return { + commitPlacement: commitPlacement, + commitDeletion: commitDeletion, + commitWork: commitWork, + commitLifeCycles: commitLifeCycles, + commitAttachRef: commitAttachRef, + commitDetachRef: commitDetachRef + }; +}, createCursor$2 = ReactFiberStack.createCursor, pop$2 = ReactFiberStack.pop, push$2 = ReactFiberStack.push, NO_CONTEXT = {}, ReactFiberHostContext = function(config) { + var getChildHostContext = config.getChildHostContext, getRootHostContext = config.getRootHostContext, contextStackCursor = createCursor$2(NO_CONTEXT), contextFiberStackCursor = createCursor$2(NO_CONTEXT), rootInstanceStackCursor = createCursor$2(NO_CONTEXT); + function requiredContext(c) { + return invariant(c !== NO_CONTEXT, "Expected host context to exist. This error is likely caused by a bug " + "in React. Please file an issue."), + c; + } + function getRootHostContainer() { + return requiredContext(rootInstanceStackCursor.current); + } + function pushHostContainer(fiber, nextRootInstance) { + push$2(rootInstanceStackCursor, nextRootInstance, fiber); + var nextRootContext = getRootHostContext(nextRootInstance); + push$2(contextFiberStackCursor, fiber, fiber), push$2(contextStackCursor, nextRootContext, fiber); + } + function popHostContainer(fiber) { + pop$2(contextStackCursor, fiber), pop$2(contextFiberStackCursor, fiber), pop$2(rootInstanceStackCursor, fiber); + } + function getHostContext() { + return requiredContext(contextStackCursor.current); + } + function pushHostContext(fiber) { + var rootInstance = requiredContext(rootInstanceStackCursor.current), context = requiredContext(contextStackCursor.current), nextContext = getChildHostContext(context, fiber.type, rootInstance); + context !== nextContext && (push$2(contextFiberStackCursor, fiber, fiber), push$2(contextStackCursor, nextContext, fiber)); + } + function popHostContext(fiber) { + contextFiberStackCursor.current === fiber && (pop$2(contextStackCursor, fiber), + pop$2(contextFiberStackCursor, fiber)); + } + function resetHostContainer() { + contextStackCursor.current = NO_CONTEXT, rootInstanceStackCursor.current = NO_CONTEXT; + } + return { + getHostContext: getHostContext, + getRootHostContainer: getRootHostContainer, + popHostContainer: popHostContainer, + popHostContext: popHostContext, + pushHostContainer: pushHostContainer, + pushHostContext: pushHostContext, + resetHostContainer: resetHostContainer + }; +}, HostComponent$9 = ReactTypeOfWork.HostComponent, HostRoot$8 = ReactTypeOfWork.HostRoot, Deletion$2 = ReactTypeOfSideEffect.Deletion, Placement$6 = ReactTypeOfSideEffect.Placement, createFiberFromHostInstanceForDeletion$1 = ReactFiber.createFiberFromHostInstanceForDeletion, ReactFiberHydrationContext = function(config) { + var shouldSetTextContent = config.shouldSetTextContent, canHydrateInstance = config.canHydrateInstance, canHydrateTextInstance = config.canHydrateTextInstance, getNextHydratableSibling = config.getNextHydratableSibling, getFirstHydratableChild = config.getFirstHydratableChild, hydrateInstance = config.hydrateInstance, hydrateTextInstance = config.hydrateTextInstance; + if (!(canHydrateInstance && canHydrateTextInstance && getNextHydratableSibling && getFirstHydratableChild && hydrateInstance && hydrateTextInstance)) return { + enterHydrationState: function() { + return !1; + }, + resetHydrationState: function() {}, + tryToClaimNextHydratableInstance: function() {}, + hydrateHostInstance: function() { + invariant(!1, "React bug."); + }, + hydrateHostTextInstance: function() { + invariant(!1, "React bug."); + }, + popHydrationState: function(fiber) { + return !1; + } + }; + var hydrationParentFiber = null, nextHydratableInstance = null, isHydrating = !1; + function enterHydrationState(fiber) { + var parentInstance = fiber.stateNode.containerInfo; + return nextHydratableInstance = getFirstHydratableChild(parentInstance), hydrationParentFiber = fiber, + isHydrating = !0, !0; + } + function deleteHydratableInstance(returnFiber, instance) { + var childToDelete = createFiberFromHostInstanceForDeletion$1(); + childToDelete.stateNode = instance, childToDelete.return = returnFiber; + var last = returnFiber.progressedLastDeletion; + null !== last ? (last.nextEffect = childToDelete, returnFiber.progressedLastDeletion = childToDelete) : returnFiber.progressedFirstDeletion = returnFiber.progressedLastDeletion = childToDelete, + childToDelete.effectTag = Deletion$2, null !== returnFiber.lastEffect ? (returnFiber.lastEffect.nextEffect = childToDelete, + returnFiber.lastEffect = childToDelete) : returnFiber.firstEffect = returnFiber.lastEffect = childToDelete; + } + function tryToClaimNextHydratableInstance(fiber) { + if (isHydrating) { + var nextInstance = nextHydratableInstance; + if (!nextInstance) return fiber.effectTag |= Placement$6, isHydrating = !1, void (hydrationParentFiber = fiber); + var type = fiber.type, props = fiber.memoizedProps; + if (!canHydrateInstance(nextInstance, type, props)) { + if (!(nextInstance = getNextHydratableSibling(nextInstance)) || !canHydrateInstance(nextInstance, type, props)) return fiber.effectTag |= Placement$6, + isHydrating = !1, void (hydrationParentFiber = fiber); + deleteHydratableInstance(hydrationParentFiber, nextHydratableInstance); + } + fiber.stateNode = nextInstance, hydrationParentFiber = fiber, nextHydratableInstance = getFirstHydratableChild(nextInstance); + } + } + function hydrateHostInstance(fiber, rootContainerInstance) { + var instance = fiber.stateNode; + return hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, fiber), + instance; + } + function hydrateHostTextInstance(fiber) { + var textInstance = fiber.stateNode; + return hydrateTextInstance(textInstance, fiber), textInstance; + } + function popToNextHostParent(fiber) { + for (var parent = fiber.return; null !== parent && parent.tag !== HostComponent$9 && parent.tag !== HostRoot$8; ) parent = parent.return; + hydrationParentFiber = parent; + } + function popHydrationState(fiber) { + if (fiber !== hydrationParentFiber) return !1; + if (!isHydrating) return popToNextHostParent(fiber), isHydrating = !0, !1; + if (fiber.tag !== HostComponent$9 || "head" !== fiber.type && "body" !== fiber.type && !shouldSetTextContent(fiber.memoizedProps)) for (var nextInstance = nextHydratableInstance; nextInstance; ) deleteHydratableInstance(fiber, nextInstance), + nextInstance = getNextHydratableSibling(nextInstance); + return popToNextHostParent(fiber), nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null, + !0; + } + function resetHydrationState() { + hydrationParentFiber = null, nextHydratableInstance = null, isHydrating = !1; + } + return { + enterHydrationState: enterHydrationState, + resetHydrationState: resetHydrationState, + tryToClaimNextHydratableInstance: tryToClaimNextHydratableInstance, + hydrateHostInstance: hydrateHostInstance, + hydrateHostTextInstance: hydrateHostTextInstance, + popHydrationState: popHydrationState + }; +}, ReactFiberInstrumentation$2 = { + debugTool: null +}, ReactFiberInstrumentation_1 = ReactFiberInstrumentation$2, popContextProvider$1 = ReactFiberContext.popContextProvider, reset$1 = ReactFiberStack.reset, getStackAddendumByWorkInProgressFiber$2 = ReactFiberComponentTreeHook.getStackAddendumByWorkInProgressFiber, logCapturedError$1 = ReactFiberErrorLogger.logCapturedError, invokeGuardedCallback$1 = ReactErrorUtils_1.invokeGuardedCallback, ReactCurrentOwner$1 = ReactGlobalSharedState_1.ReactCurrentOwner, cloneFiber$1 = ReactFiber.cloneFiber, onCommitRoot = ReactFiberDevToolsHook.onCommitRoot, NoWork$2 = ReactPriorityLevel.NoWork, SynchronousPriority$1 = ReactPriorityLevel.SynchronousPriority, TaskPriority$1 = ReactPriorityLevel.TaskPriority, AnimationPriority = ReactPriorityLevel.AnimationPriority, HighPriority = ReactPriorityLevel.HighPriority, LowPriority = ReactPriorityLevel.LowPriority, OffscreenPriority = ReactPriorityLevel.OffscreenPriority, AsyncUpdates = ReactTypeOfInternalContext.AsyncUpdates, NoEffect$2 = ReactTypeOfSideEffect.NoEffect, Placement$1 = ReactTypeOfSideEffect.Placement, Update = ReactTypeOfSideEffect.Update, PlacementAndUpdate = ReactTypeOfSideEffect.PlacementAndUpdate, Deletion = ReactTypeOfSideEffect.Deletion, ContentReset = ReactTypeOfSideEffect.ContentReset, Callback = ReactTypeOfSideEffect.Callback, Err = ReactTypeOfSideEffect.Err, Ref = ReactTypeOfSideEffect.Ref, HostRoot$4 = ReactTypeOfWork.HostRoot, HostComponent$5 = ReactTypeOfWork.HostComponent, HostPortal$2 = ReactTypeOfWork.HostPortal, ClassComponent$4 = ReactTypeOfWork.ClassComponent, getPendingPriority$1 = ReactFiberUpdateQueue.getPendingPriority, _require14 = ReactFiberContext, resetContext$1 = _require14.resetContext, warning$5 = warning, ReactFiberInstrumentation$1 = ReactFiberInstrumentation_1, ReactDebugCurrentFiber$3 = ReactDebugCurrentFiber_1, _require15 = ReactDebugFiberPerf_1, recordEffect = _require15.recordEffect, recordScheduleUpdate = _require15.recordScheduleUpdate, startWorkTimer = _require15.startWorkTimer, stopWorkTimer = _require15.stopWorkTimer, startWorkLoopTimer = _require15.startWorkLoopTimer, stopWorkLoopTimer = _require15.stopWorkLoopTimer, startCommitTimer = _require15.startCommitTimer, stopCommitTimer = _require15.stopCommitTimer, startCommitHostEffectsTimer = _require15.startCommitHostEffectsTimer, stopCommitHostEffectsTimer = _require15.stopCommitHostEffectsTimer, startCommitLifeCyclesTimer = _require15.startCommitLifeCyclesTimer, stopCommitLifeCyclesTimer = _require15.stopCommitLifeCyclesTimer, warnAboutUpdateOnUnmounted = function(instance) { + var ctor = instance.constructor; + warning$5(!1, "Can only update a mounted or mounting component. This usually means " + "you called setState, replaceState, or forceUpdate on an unmounted " + "component. This is a no-op.\n\nPlease check the code for the " + "%s component.", ctor && (ctor.displayName || ctor.name) || "ReactClass"); +}, warnAboutInvalidUpdates = function(instance) { + switch (ReactDebugCurrentFiber$3.phase) { + case "getChildContext": + warning$5(!1, "setState(...): Cannot call setState() inside getChildContext()"); + break; + + case "render": + warning$5(!1, "Cannot update during an existing state transition (such as within " + "`render` or another component's constructor). Render methods should " + "be a pure function of props and state; constructor side-effects are " + "an anti-pattern, but can be moved to `componentWillMount`."); + } +}, timeHeuristicForUnitOfWork = 1, ReactFiberScheduler = function(config) { + var hostContext = ReactFiberHostContext(config), hydrationContext = ReactFiberHydrationContext(config), popHostContainer = hostContext.popHostContainer, popHostContext = hostContext.popHostContext, resetHostContainer = hostContext.resetHostContainer, _ReactFiberBeginWork = ReactFiberBeginWork(config, hostContext, hydrationContext, scheduleUpdate, getPriorityContext), beginWork = _ReactFiberBeginWork.beginWork, beginFailedWork = _ReactFiberBeginWork.beginFailedWork, _ReactFiberCompleteWo = ReactFiberCompleteWork(config, hostContext, hydrationContext), completeWork = _ReactFiberCompleteWo.completeWork, _ReactFiberCommitWork = ReactFiberCommitWork(config, captureError), commitPlacement = _ReactFiberCommitWork.commitPlacement, commitDeletion = _ReactFiberCommitWork.commitDeletion, commitWork = _ReactFiberCommitWork.commitWork, commitLifeCycles = _ReactFiberCommitWork.commitLifeCycles, commitAttachRef = _ReactFiberCommitWork.commitAttachRef, commitDetachRef = _ReactFiberCommitWork.commitDetachRef, hostScheduleAnimationCallback = config.scheduleAnimationCallback, hostScheduleDeferredCallback = config.scheduleDeferredCallback, useSyncScheduling = config.useSyncScheduling, prepareForCommit = config.prepareForCommit, resetAfterCommit = config.resetAfterCommit, priorityContext = NoWork$2, priorityContextBeforeReconciliation = NoWork$2, isPerformingWork = !1, deadlineHasExpired = !1, isBatchingUpdates = !1, nextUnitOfWork = null, nextPriorityLevel = NoWork$2, nextEffect = null, pendingCommit = null, nextScheduledRoot = null, lastScheduledRoot = null, isAnimationCallbackScheduled = !1, isDeferredCallbackScheduled = !1, capturedErrors = null, failedBoundaries = null, commitPhaseBoundaries = null, firstUncaughtError = null, fatalError = null, isCommitting = !1, isUnmounting = !1; + function scheduleAnimationCallback(callback) { + isAnimationCallbackScheduled || (isAnimationCallbackScheduled = !0, hostScheduleAnimationCallback(callback)); + } + function scheduleDeferredCallback(callback) { + isDeferredCallbackScheduled || (isDeferredCallbackScheduled = !0, hostScheduleDeferredCallback(callback)); + } + function resetContextStack() { + reset$1(), resetContext$1(), resetHostContainer(); + } + function findNextUnitOfWork() { + for (;null !== nextScheduledRoot && nextScheduledRoot.current.pendingWorkPriority === NoWork$2; ) { + nextScheduledRoot.isScheduled = !1; + var next = nextScheduledRoot.nextScheduledRoot; + if (nextScheduledRoot.nextScheduledRoot = null, nextScheduledRoot === lastScheduledRoot) return nextScheduledRoot = null, + lastScheduledRoot = null, nextPriorityLevel = NoWork$2, null; + nextScheduledRoot = next; + } + for (var root = nextScheduledRoot, highestPriorityRoot = null, highestPriorityLevel = NoWork$2; null !== root; ) root.current.pendingWorkPriority !== NoWork$2 && (highestPriorityLevel === NoWork$2 || highestPriorityLevel > root.current.pendingWorkPriority) && (highestPriorityLevel = root.current.pendingWorkPriority, + highestPriorityRoot = root), root = root.nextScheduledRoot; + return null !== highestPriorityRoot ? (nextPriorityLevel = highestPriorityLevel, + priorityContext = nextPriorityLevel, resetContextStack(), cloneFiber$1(highestPriorityRoot.current, highestPriorityLevel)) : (nextPriorityLevel = NoWork$2, + null); + } + function commitAllHostEffects() { + for (;null !== nextEffect; ) { + ReactDebugCurrentFiber$3.current = nextEffect, recordEffect(); + var effectTag = nextEffect.effectTag; + if (effectTag & ContentReset && config.resetTextContent(nextEffect.stateNode), effectTag & Ref) { + var current = nextEffect.alternate; + null !== current && commitDetachRef(current); + } + switch (effectTag & ~(Callback | Err | ContentReset | Ref)) { + case Placement$1: + commitPlacement(nextEffect), nextEffect.effectTag &= ~Placement$1; + break; + + case PlacementAndUpdate: + commitPlacement(nextEffect), nextEffect.effectTag &= ~Placement$1; + var _current = nextEffect.alternate; + commitWork(_current, nextEffect); + break; + + case Update: + var _current2 = nextEffect.alternate; + commitWork(_current2, nextEffect); + break; + + case Deletion: + isUnmounting = !0, commitDeletion(nextEffect), isUnmounting = !1; + } + nextEffect = nextEffect.nextEffect; + } + ReactDebugCurrentFiber$3.current = null; + } + function commitAllLifeCycles() { + for (;null !== nextEffect; ) { + var effectTag = nextEffect.effectTag; + if (effectTag & (Update | Callback)) { + recordEffect(); + var current = nextEffect.alternate; + commitLifeCycles(current, nextEffect); + } + effectTag & Ref && (recordEffect(), commitAttachRef(nextEffect)), effectTag & Err && (recordEffect(), + commitErrorHandling(nextEffect)); + var next = nextEffect.nextEffect; + nextEffect.nextEffect = null, nextEffect = next; + } + } + function commitAllWork(finishedWork) { + isCommitting = !0, startCommitTimer(), pendingCommit = null; + var root = finishedWork.stateNode; + invariant(root.current !== finishedWork, "Cannot commit the same tree as before. This is probably a bug " + "related to the return field. This error is likely caused by a bug " + "in React. Please file an issue."), + ReactCurrentOwner$1.current = null; + var previousPriorityContext = priorityContext; + priorityContext = TaskPriority$1; + var firstEffect = void 0; + finishedWork.effectTag !== NoEffect$2 ? null !== finishedWork.lastEffect ? (finishedWork.lastEffect.nextEffect = finishedWork, + firstEffect = finishedWork.firstEffect) : firstEffect = finishedWork : firstEffect = finishedWork.firstEffect; + var commitInfo = prepareForCommit(); + for (nextEffect = firstEffect, startCommitHostEffectsTimer(); null !== nextEffect; ) { + var _error = null; + _error = invokeGuardedCallback$1(null, commitAllHostEffects, null, finishedWork), + null !== _error && (invariant(null !== nextEffect, "Should have next effect. This error is likely caused by a bug " + "in React. Please file an issue."), + captureError(nextEffect, _error), null !== nextEffect && (nextEffect = nextEffect.nextEffect)); + } + for (stopCommitHostEffectsTimer(), resetAfterCommit(commitInfo), root.current = finishedWork, + nextEffect = firstEffect, startCommitLifeCyclesTimer(); null !== nextEffect; ) { + var _error2 = null; + _error2 = invokeGuardedCallback$1(null, commitAllLifeCycles, null, finishedWork), + null !== _error2 && (invariant(null !== nextEffect, "Should have next effect. This error is likely caused by a bug " + "in React. Please file an issue."), + captureError(nextEffect, _error2), null !== nextEffect && (nextEffect = nextEffect.nextEffect)); + } + isCommitting = !1, stopCommitLifeCyclesTimer(), stopCommitTimer(), "function" == typeof onCommitRoot && onCommitRoot(finishedWork.stateNode), + !0 && ReactFiberInstrumentation$1.debugTool && ReactFiberInstrumentation$1.debugTool.onCommitWork(finishedWork), + commitPhaseBoundaries && (commitPhaseBoundaries.forEach(scheduleErrorRecovery), + commitPhaseBoundaries = null), priorityContext = previousPriorityContext; + } + function resetWorkPriority(workInProgress) { + var newPriority = NoWork$2, queue = workInProgress.updateQueue, tag = workInProgress.tag; + null === queue || tag !== ClassComponent$4 && tag !== HostRoot$4 || (newPriority = getPendingPriority$1(queue)); + for (var child = workInProgress.progressedChild; null !== child; ) child.pendingWorkPriority !== NoWork$2 && (newPriority === NoWork$2 || newPriority > child.pendingWorkPriority) && (newPriority = child.pendingWorkPriority), + child = child.sibling; + workInProgress.pendingWorkPriority = newPriority; + } + function completeUnitOfWork(workInProgress) { + for (;!0; ) { + var current = workInProgress.alternate, next = completeWork(current, workInProgress), returnFiber = workInProgress.return, siblingFiber = workInProgress.sibling; + if (resetWorkPriority(workInProgress), null !== next) return stopWorkTimer(workInProgress), + !0 && ReactFiberInstrumentation$1.debugTool && ReactFiberInstrumentation$1.debugTool.onCompleteWork(workInProgress), + next; + if (null !== returnFiber && (null === returnFiber.firstEffect && (returnFiber.firstEffect = workInProgress.firstEffect), + null !== workInProgress.lastEffect && (null !== returnFiber.lastEffect && (returnFiber.lastEffect.nextEffect = workInProgress.firstEffect), + returnFiber.lastEffect = workInProgress.lastEffect), workInProgress.effectTag !== NoEffect$2 && (null !== returnFiber.lastEffect ? returnFiber.lastEffect.nextEffect = workInProgress : returnFiber.firstEffect = workInProgress, + returnFiber.lastEffect = workInProgress)), stopWorkTimer(workInProgress), !0 && ReactFiberInstrumentation$1.debugTool && ReactFiberInstrumentation$1.debugTool.onCompleteWork(workInProgress), + null !== siblingFiber) return siblingFiber; + if (null === returnFiber) return nextPriorityLevel < HighPriority ? commitAllWork(workInProgress) : pendingCommit = workInProgress, + null; + workInProgress = returnFiber; + } + return null; + } + function performUnitOfWork(workInProgress) { + var current = workInProgress.alternate; + startWorkTimer(workInProgress); + var next = beginWork(current, workInProgress, nextPriorityLevel); + return !0 && ReactFiberInstrumentation$1.debugTool && ReactFiberInstrumentation$1.debugTool.onBeginWork(workInProgress), + null === next && (next = completeUnitOfWork(workInProgress)), ReactCurrentOwner$1.current = null, + ReactDebugCurrentFiber$3.current = null, next; + } + function performFailedUnitOfWork(workInProgress) { + var current = workInProgress.alternate; + startWorkTimer(workInProgress); + var next = beginFailedWork(current, workInProgress, nextPriorityLevel); + return !0 && ReactFiberInstrumentation$1.debugTool && ReactFiberInstrumentation$1.debugTool.onBeginWork(workInProgress), + null === next && (next = completeUnitOfWork(workInProgress)), ReactCurrentOwner$1.current = null, + ReactDebugCurrentFiber$3.current = null, next; + } + function performDeferredWork(deadline) { + isDeferredCallbackScheduled = !1, performWork(OffscreenPriority, deadline); + } + function performAnimationWork() { + isAnimationCallbackScheduled = !1, performWork(AnimationPriority, null); + } + function clearErrors() { + for (null === nextUnitOfWork && (nextUnitOfWork = findNextUnitOfWork()); null !== capturedErrors && capturedErrors.size && null !== nextUnitOfWork && nextPriorityLevel !== NoWork$2 && nextPriorityLevel <= TaskPriority$1; ) null === (nextUnitOfWork = hasCapturedError(nextUnitOfWork) ? performFailedUnitOfWork(nextUnitOfWork) : performUnitOfWork(nextUnitOfWork)) && (nextUnitOfWork = findNextUnitOfWork()); + } + function workLoop(priorityLevel, deadline) { + clearErrors(), null === nextUnitOfWork && (nextUnitOfWork = findNextUnitOfWork()); + var hostRootTimeMarker = void 0; + if (ReactFeatureFlags_1.logTopLevelRenders && null !== nextUnitOfWork && nextUnitOfWork.tag === HostRoot$4 && null !== nextUnitOfWork.child) { + hostRootTimeMarker = "React update: " + (getComponentName_1(nextUnitOfWork.child) || ""), + console.time(hostRootTimeMarker); + } + if (null !== deadline && priorityLevel > TaskPriority$1) for (;null !== nextUnitOfWork && !deadlineHasExpired; ) deadline.timeRemaining() > timeHeuristicForUnitOfWork ? null === (nextUnitOfWork = performUnitOfWork(nextUnitOfWork)) && null !== pendingCommit && (deadline.timeRemaining() > timeHeuristicForUnitOfWork ? (commitAllWork(pendingCommit), + nextUnitOfWork = findNextUnitOfWork(), clearErrors()) : deadlineHasExpired = !0) : deadlineHasExpired = !0; else for (;null !== nextUnitOfWork && nextPriorityLevel !== NoWork$2 && nextPriorityLevel <= priorityLevel; ) null === (nextUnitOfWork = performUnitOfWork(nextUnitOfWork)) && (nextUnitOfWork = findNextUnitOfWork(), + clearErrors()); + hostRootTimeMarker && console.timeEnd(hostRootTimeMarker); + } + function performWork(priorityLevel, deadline) { + startWorkLoopTimer(), invariant(!isPerformingWork, "performWork was called recursively. This error is likely caused " + "by a bug in React. Please file an issue."), + isPerformingWork = !0; + for (var isPerformingDeferredWork = !!deadline; priorityLevel !== NoWork$2 && !fatalError; ) { + invariant(null !== deadline || priorityLevel < HighPriority, "Cannot perform deferred work without a deadline. This error is " + "likely caused by a bug in React. Please file an issue."), + null === pendingCommit || deadlineHasExpired || commitAllWork(pendingCommit), priorityContextBeforeReconciliation = priorityContext; + var _error3 = null; + if (_error3 = invokeGuardedCallback$1(null, workLoop, null, priorityLevel, deadline), + priorityContext = priorityContextBeforeReconciliation, null !== _error3) { + var failedWork = nextUnitOfWork; + if (null !== failedWork) { + var maybeBoundary = captureError(failedWork, _error3); + if (null !== maybeBoundary) { + var boundary = maybeBoundary; + beginFailedWork(boundary.alternate, boundary, priorityLevel), unwindContexts(failedWork, boundary), + nextUnitOfWork = completeUnitOfWork(boundary); + } + continue; + } + null === fatalError && (fatalError = _error3); + } + if (priorityLevel = NoWork$2, nextPriorityLevel === NoWork$2 || !isPerformingDeferredWork || deadlineHasExpired) switch (nextPriorityLevel) { + case SynchronousPriority$1: + case TaskPriority$1: + priorityLevel = nextPriorityLevel; + break; + + case AnimationPriority: + scheduleAnimationCallback(performAnimationWork), scheduleDeferredCallback(performDeferredWork); + break; + + case HighPriority: + case LowPriority: + case OffscreenPriority: + scheduleDeferredCallback(performDeferredWork); + } else priorityLevel = nextPriorityLevel; + } + var errorToThrow = fatalError || firstUncaughtError; + if (isPerformingWork = !1, deadlineHasExpired = !1, fatalError = null, firstUncaughtError = null, + capturedErrors = null, failedBoundaries = null, stopWorkLoopTimer(), null !== errorToThrow) throw errorToThrow; + } + function captureError(failedWork, error) { + ReactCurrentOwner$1.current = null, ReactDebugCurrentFiber$3.current = null, ReactDebugCurrentFiber$3.phase = null, + nextUnitOfWork = null; + var boundary = null, errorBoundaryFound = !1, willRetry = !1, errorBoundaryName = null; + if (failedWork.tag === HostRoot$4) boundary = failedWork, isFailedBoundary(failedWork) && (fatalError = error); else for (var node = failedWork.return; null !== node && null === boundary; ) { + if (node.tag === ClassComponent$4) { + var instance = node.stateNode; + "function" == typeof instance.unstable_handleError && (errorBoundaryFound = !0, + errorBoundaryName = getComponentName_1(node), boundary = node, willRetry = !0); + } else node.tag === HostRoot$4 && (boundary = node); + if (isFailedBoundary(node)) { + if (isUnmounting) return null; + if (null !== commitPhaseBoundaries && (commitPhaseBoundaries.has(node) || null !== node.alternate && commitPhaseBoundaries.has(node.alternate))) return null; + boundary = null, willRetry = !1; + } + node = node.return; + } + if (null !== boundary) { + null === failedBoundaries && (failedBoundaries = new Set()), failedBoundaries.add(boundary); + var _componentStack = getStackAddendumByWorkInProgressFiber$2(failedWork), _componentName2 = getComponentName_1(failedWork); + return null === capturedErrors && (capturedErrors = new Map()), capturedErrors.set(boundary, { + componentName: _componentName2, + componentStack: _componentStack, + error: error, + errorBoundary: errorBoundaryFound ? boundary.stateNode : null, + errorBoundaryFound: errorBoundaryFound, + errorBoundaryName: errorBoundaryName, + willRetry: willRetry + }), isCommitting ? (null === commitPhaseBoundaries && (commitPhaseBoundaries = new Set()), + commitPhaseBoundaries.add(boundary)) : scheduleErrorRecovery(boundary), boundary; + } + return null === firstUncaughtError && (firstUncaughtError = error), null; + } + function hasCapturedError(fiber) { + return null !== capturedErrors && (capturedErrors.has(fiber) || null !== fiber.alternate && capturedErrors.has(fiber.alternate)); + } + function isFailedBoundary(fiber) { + return null !== failedBoundaries && (failedBoundaries.has(fiber) || null !== fiber.alternate && failedBoundaries.has(fiber.alternate)); + } + function commitErrorHandling(effectfulFiber) { + var capturedError = void 0; + null !== capturedErrors && (capturedError = capturedErrors.get(effectfulFiber), + capturedErrors.delete(effectfulFiber), null == capturedError && null !== effectfulFiber.alternate && (effectfulFiber = effectfulFiber.alternate, + capturedError = capturedErrors.get(effectfulFiber), capturedErrors.delete(effectfulFiber))), + invariant(null != capturedError, "No error for given unit of work. This error is likely caused by a " + "bug in React. Please file an issue."); + var error = capturedError.error; + try { + logCapturedError$1(capturedError); + } catch (e) { + console.error(e); + } + switch (effectfulFiber.tag) { + case ClassComponent$4: + var instance = effectfulFiber.stateNode, info = { + componentStack: capturedError.componentStack + }; + return void instance.unstable_handleError(error, info); + + case HostRoot$4: + return void (null === firstUncaughtError && (firstUncaughtError = error)); + + default: + invariant(!1, "Invalid type of work. This error is likely caused by a bug in " + "React. Please file an issue."); + } + } + function unwindContexts(from, to) { + for (var node = from; null !== node && node !== to && node.alternate !== to; ) { + switch (node.tag) { + case ClassComponent$4: + popContextProvider$1(node); + break; + + case HostComponent$5: + popHostContext(node); + break; + + case HostRoot$4: + case HostPortal$2: + popHostContainer(node); + } + stopWorkTimer(node), node = node.return; + } + } + function scheduleRoot(root, priorityLevel) { + priorityLevel !== NoWork$2 && (root.isScheduled || (root.isScheduled = !0, lastScheduledRoot ? (lastScheduledRoot.nextScheduledRoot = root, + lastScheduledRoot = root) : (nextScheduledRoot = root, lastScheduledRoot = root))); + } + function scheduleUpdate(fiber, priorityLevel) { + if (recordScheduleUpdate(), priorityLevel <= nextPriorityLevel && (nextUnitOfWork = null), + fiber.tag === ClassComponent$4) { + var instance = fiber.stateNode; + warnAboutInvalidUpdates(instance); + } + for (var node = fiber, shouldContinue = !0; null !== node && shouldContinue; ) { + if (shouldContinue = !1, (node.pendingWorkPriority === NoWork$2 || node.pendingWorkPriority > priorityLevel) && (shouldContinue = !0, + node.pendingWorkPriority = priorityLevel), null !== node.alternate && (node.alternate.pendingWorkPriority === NoWork$2 || node.alternate.pendingWorkPriority > priorityLevel) && (shouldContinue = !0, + node.alternate.pendingWorkPriority = priorityLevel), null === node.return) { + if (node.tag !== HostRoot$4) return void (fiber.tag === ClassComponent$4 && warnAboutUpdateOnUnmounted(fiber.stateNode)); + switch (scheduleRoot(node.stateNode, priorityLevel), priorityLevel) { + case SynchronousPriority$1: + return void performWork(SynchronousPriority$1, null); + + case TaskPriority$1: + return; + + case AnimationPriority: + return void scheduleAnimationCallback(performAnimationWork); + + case HighPriority: + case LowPriority: + case OffscreenPriority: + return void scheduleDeferredCallback(performDeferredWork); + } + } + node = node.return; + } + } + function getPriorityContext(fiber, forceAsync) { + var priorityLevel = priorityContext; + return priorityLevel === NoWork$2 && (priorityLevel = !useSyncScheduling || fiber.internalContextTag & AsyncUpdates || forceAsync ? LowPriority : SynchronousPriority$1), + priorityLevel === SynchronousPriority$1 && (isPerformingWork || isBatchingUpdates) ? TaskPriority$1 : priorityLevel; + } + function scheduleErrorRecovery(fiber) { + scheduleUpdate(fiber, TaskPriority$1); + } + function performWithPriority(priorityLevel, fn) { + var previousPriorityContext = priorityContext; + priorityContext = priorityLevel; + try { + fn(); + } finally { + priorityContext = previousPriorityContext; + } + } + function batchedUpdates(fn, a) { + var previousIsBatchingUpdates = isBatchingUpdates; + isBatchingUpdates = !0; + try { + return fn(a); + } finally { + isBatchingUpdates = previousIsBatchingUpdates, isPerformingWork || isBatchingUpdates || performWork(TaskPriority$1, null); + } + } + function unbatchedUpdates(fn) { + var previousIsBatchingUpdates = isBatchingUpdates; + isBatchingUpdates = !1; + try { + return fn(); + } finally { + isBatchingUpdates = previousIsBatchingUpdates; + } + } + function syncUpdates(fn) { + var previousPriorityContext = priorityContext; + priorityContext = SynchronousPriority$1; + try { + return fn(); + } finally { + priorityContext = previousPriorityContext; + } + } + function deferredUpdates(fn) { + var previousPriorityContext = priorityContext; + priorityContext = LowPriority; + try { + return fn(); + } finally { + priorityContext = previousPriorityContext; + } + } + return { + scheduleUpdate: scheduleUpdate, + getPriorityContext: getPriorityContext, + performWithPriority: performWithPriority, + batchedUpdates: batchedUpdates, + unbatchedUpdates: unbatchedUpdates, + syncUpdates: syncUpdates, + deferredUpdates: deferredUpdates + }; +}, getContextFiber = function(arg) { + invariant(!1, "Missing injection for fiber getContextForSubtree"); +}; + +function getContextForSubtree(parentComponent) { + if (!parentComponent) return emptyObject; + var instance = ReactInstanceMap_1.get(parentComponent); + return "number" == typeof instance.tag ? getContextFiber(instance) : instance._processChildContext(instance._context); +} + +getContextForSubtree._injectFiber = function(fn) { + getContextFiber = fn; +}; + +var getContextForSubtree_1 = getContextForSubtree, addTopLevelUpdate = ReactFiberUpdateQueue.addTopLevelUpdate, findCurrentUnmaskedContext = ReactFiberContext.findCurrentUnmaskedContext, isContextProvider = ReactFiberContext.isContextProvider, processChildContext = ReactFiberContext.processChildContext, createFiberRoot = ReactFiberRoot.createFiberRoot, warning$2 = warning, ReactFiberInstrumentation = ReactFiberInstrumentation_1, ReactDebugCurrentFiber = ReactDebugCurrentFiber_1, getComponentName = getComponentName_1, findCurrentHostFiber = ReactFiberTreeReflection.findCurrentHostFiber; + +getContextForSubtree_1._injectFiber(function(fiber) { + var parentContext = findCurrentUnmaskedContext(fiber); + return isContextProvider(fiber) ? processChildContext(fiber, parentContext, !1) : parentContext; +}); + +var ReactFiberReconciler = function(config) { + var _ReactFiberScheduler = ReactFiberScheduler(config), scheduleUpdate = _ReactFiberScheduler.scheduleUpdate, getPriorityContext = _ReactFiberScheduler.getPriorityContext, performWithPriority = _ReactFiberScheduler.performWithPriority, batchedUpdates = _ReactFiberScheduler.batchedUpdates, unbatchedUpdates = _ReactFiberScheduler.unbatchedUpdates, syncUpdates = _ReactFiberScheduler.syncUpdates, deferredUpdates = _ReactFiberScheduler.deferredUpdates; + function scheduleTopLevelUpdate(current, element, callback) { + "render" === ReactDebugCurrentFiber.phase && null !== ReactDebugCurrentFiber.current && warning$2(!1, "Render methods should be a pure function of props and state; " + "triggering nested component updates from render is not allowed. " + "If necessary, trigger nested updates in componentDidUpdate.\n\n" + "Check the render method of %s.", getComponentName(ReactDebugCurrentFiber.current) || "Unknown"); + var forceAsync = ReactFeatureFlags_1.enableAsyncSubtreeAPI && null != element && null != element.type && !0 === element.type.unstable_asyncUpdates, priorityLevel = getPriorityContext(current, forceAsync), nextState = { + element: element + }; + callback = void 0 === callback ? null : callback, warning$2(null === callback || "function" == typeof callback, "render(...): Expected the last optional `callback` argument to be a " + "function. Instead received: %s.", callback), + addTopLevelUpdate(current, nextState, callback, priorityLevel), scheduleUpdate(current, priorityLevel); + } + return { + createContainer: function(containerInfo) { + return createFiberRoot(containerInfo); + }, + updateContainer: function(element, container, parentComponent, callback) { + var current = container.current; + ReactFiberInstrumentation.debugTool && (null === current.alternate ? ReactFiberInstrumentation.debugTool.onMountContainer(container) : null === element ? ReactFiberInstrumentation.debugTool.onUnmountContainer(container) : ReactFiberInstrumentation.debugTool.onUpdateContainer(container)); + var context = getContextForSubtree_1(parentComponent); + null === container.context ? container.context = context : container.pendingContext = context, + scheduleTopLevelUpdate(current, element, callback); + }, + performWithPriority: performWithPriority, + batchedUpdates: batchedUpdates, + unbatchedUpdates: unbatchedUpdates, + syncUpdates: syncUpdates, + deferredUpdates: deferredUpdates, + getPublicRootInstance: function(container) { + var containerFiber = container.current; + return containerFiber.child ? containerFiber.child.stateNode : null; + }, + findHostInstance: function(fiber) { + var hostFiber = findCurrentHostFiber(fiber); + return null === hostFiber ? null : hostFiber.stateNode; + } + }; +}; + +function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); +} + +var objects = {}, uniqueID = 1, emptyObject$3 = {}, ReactNativePropRegistry = function() { + function ReactNativePropRegistry() { + _classCallCheck(this, ReactNativePropRegistry); + } + return ReactNativePropRegistry.register = function(object) { + var id = ++uniqueID; + return Object.freeze(object), objects[id] = object, id; + }, ReactNativePropRegistry.getByID = function(id) { + if (!id) return emptyObject$3; + var object = objects[id]; + return object || (console.warn("Invalid style with id `" + id + "`. Skipping ..."), + emptyObject$3); + }, ReactNativePropRegistry; +}(), ReactNativePropRegistry_1 = ReactNativePropRegistry, emptyObject$2 = {}, removedKeys = null, removedKeyCount = 0; + +function defaultDiffer(prevProp, nextProp) { + return "object" != typeof nextProp || null === nextProp || deepDiffer(prevProp, nextProp); +} + +function resolveObject(idOrObject) { + return "number" == typeof idOrObject ? ReactNativePropRegistry_1.getByID(idOrObject) : idOrObject; +} + +function restoreDeletedValuesInNestedArray(updatePayload, node, validAttributes) { + if (Array.isArray(node)) for (var i = node.length; i-- && removedKeyCount > 0; ) restoreDeletedValuesInNestedArray(updatePayload, node[i], validAttributes); else if (node && removedKeyCount > 0) { + var obj = resolveObject(node); + for (var propKey in removedKeys) if (removedKeys[propKey]) { + var nextProp = obj[propKey]; + if (void 0 !== nextProp) { + var attributeConfig = validAttributes[propKey]; + if (attributeConfig) { + if ("function" == typeof nextProp && (nextProp = !0), void 0 === nextProp && (nextProp = null), + "object" != typeof attributeConfig) updatePayload[propKey] = nextProp; else if ("function" == typeof attributeConfig.diff || "function" == typeof attributeConfig.process) { + var nextValue = "function" == typeof attributeConfig.process ? attributeConfig.process(nextProp) : nextProp; + updatePayload[propKey] = nextValue; + } + removedKeys[propKey] = !1, removedKeyCount--; + } + } + } + } +} + +function diffNestedArrayProperty(updatePayload, prevArray, nextArray, validAttributes) { + var i, minLength = prevArray.length < nextArray.length ? prevArray.length : nextArray.length; + for (i = 0; i < minLength; i++) updatePayload = diffNestedProperty(updatePayload, prevArray[i], nextArray[i], validAttributes); + for (;i < prevArray.length; i++) updatePayload = clearNestedProperty(updatePayload, prevArray[i], validAttributes); + for (;i < nextArray.length; i++) updatePayload = addNestedProperty(updatePayload, nextArray[i], validAttributes); + return updatePayload; +} + +function diffNestedProperty(updatePayload, prevProp, nextProp, validAttributes) { + return updatePayload || prevProp !== nextProp ? prevProp && nextProp ? Array.isArray(prevProp) || Array.isArray(nextProp) ? Array.isArray(prevProp) && Array.isArray(nextProp) ? diffNestedArrayProperty(updatePayload, prevProp, nextProp, validAttributes) : Array.isArray(prevProp) ? diffProperties(updatePayload, flattenStyle(prevProp), resolveObject(nextProp), validAttributes) : diffProperties(updatePayload, resolveObject(prevProp), flattenStyle(nextProp), validAttributes) : diffProperties(updatePayload, resolveObject(prevProp), resolveObject(nextProp), validAttributes) : nextProp ? addNestedProperty(updatePayload, nextProp, validAttributes) : prevProp ? clearNestedProperty(updatePayload, prevProp, validAttributes) : updatePayload : updatePayload; +} + +function addNestedProperty(updatePayload, nextProp, validAttributes) { + if (!nextProp) return updatePayload; + if (!Array.isArray(nextProp)) return addProperties(updatePayload, resolveObject(nextProp), validAttributes); + for (var i = 0; i < nextProp.length; i++) updatePayload = addNestedProperty(updatePayload, nextProp[i], validAttributes); + return updatePayload; +} + +function clearNestedProperty(updatePayload, prevProp, validAttributes) { + if (!prevProp) return updatePayload; + if (!Array.isArray(prevProp)) return clearProperties(updatePayload, resolveObject(prevProp), validAttributes); + for (var i = 0; i < prevProp.length; i++) updatePayload = clearNestedProperty(updatePayload, prevProp[i], validAttributes); + return updatePayload; +} + +function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { + var attributeConfig, nextProp, prevProp; + for (var propKey in nextProps) if (attributeConfig = validAttributes[propKey]) if (prevProp = prevProps[propKey], + nextProp = nextProps[propKey], "function" == typeof nextProp && (nextProp = !0, + "function" == typeof prevProp && (prevProp = !0)), void 0 === nextProp && (nextProp = null, + void 0 === prevProp && (prevProp = null)), removedKeys && (removedKeys[propKey] = !1), + updatePayload && void 0 !== updatePayload[propKey]) { + if ("object" != typeof attributeConfig) updatePayload[propKey] = nextProp; else if ("function" == typeof attributeConfig.diff || "function" == typeof attributeConfig.process) { + var nextValue = "function" == typeof attributeConfig.process ? attributeConfig.process(nextProp) : nextProp; + updatePayload[propKey] = nextValue; + } + } else if (prevProp !== nextProp) if ("object" != typeof attributeConfig) defaultDiffer(prevProp, nextProp) && ((updatePayload || (updatePayload = {}))[propKey] = nextProp); else if ("function" == typeof attributeConfig.diff || "function" == typeof attributeConfig.process) { + var shouldUpdate = void 0 === prevProp || ("function" == typeof attributeConfig.diff ? attributeConfig.diff(prevProp, nextProp) : defaultDiffer(prevProp, nextProp)); + shouldUpdate && (nextValue = "function" == typeof attributeConfig.process ? attributeConfig.process(nextProp) : nextProp, + (updatePayload || (updatePayload = {}))[propKey] = nextValue); + } else removedKeys = null, removedKeyCount = 0, updatePayload = diffNestedProperty(updatePayload, prevProp, nextProp, attributeConfig), + removedKeyCount > 0 && updatePayload && (restoreDeletedValuesInNestedArray(updatePayload, nextProp, attributeConfig), + removedKeys = null); + for (propKey in prevProps) void 0 === nextProps[propKey] && (attributeConfig = validAttributes[propKey]) && (updatePayload && void 0 !== updatePayload[propKey] || void 0 !== (prevProp = prevProps[propKey]) && ("object" != typeof attributeConfig || "function" == typeof attributeConfig.diff || "function" == typeof attributeConfig.process ? ((updatePayload || (updatePayload = {}))[propKey] = null, + removedKeys || (removedKeys = {}), removedKeys[propKey] || (removedKeys[propKey] = !0, + removedKeyCount++)) : updatePayload = clearNestedProperty(updatePayload, prevProp, attributeConfig))); + return updatePayload; +} + +function addProperties(updatePayload, props, validAttributes) { + return diffProperties(updatePayload, emptyObject$2, props, validAttributes); +} + +function clearProperties(updatePayload, prevProps, validAttributes) { + return diffProperties(updatePayload, prevProps, emptyObject$2, validAttributes); +} + +var ReactNativeAttributePayload = { + create: function(props, validAttributes) { + return addProperties(null, props, validAttributes); + }, + diff: function(prevProps, nextProps, validAttributes) { + return diffProperties(null, prevProps, nextProps, validAttributes); + } +}, ReactNativeAttributePayload_1 = ReactNativeAttributePayload; + +function mountSafeCallback$1(context, callback) { + return function() { + if (callback) { + if ("boolean" == typeof context.__isMounted) { + if (!context.__isMounted) return; + } else if ("function" == typeof context.isMounted && !context.isMounted()) return; + return callback.apply(context, arguments); + } + }; +} + +function throwOnStylesProp(component, props) { + if (void 0 !== props.styles) { + var owner = component._owner || null, name = component.constructor.displayName, msg = "`styles` is not a supported property of `" + name + "`, did " + "you mean `style` (singular)?"; + throw owner && owner.constructor && owner.constructor.displayName && (msg += "\n\nCheck the `" + owner.constructor.displayName + "` parent " + " component."), + new Error(msg); + } +} + +function warnForStyleProps$1(props, validAttributes) { + for (var key in validAttributes.style) validAttributes[key] || void 0 === props[key] || console.error("You are setting the style `{ " + key + ": ... }` as a prop. You " + "should nest it in a style object. " + "E.g. `{ style: { " + key + ": ... } }`"); +} + +var NativeMethodsMixinUtils = { + mountSafeCallback: mountSafeCallback$1, + throwOnStylesProp: throwOnStylesProp, + warnForStyleProps: warnForStyleProps$1 +}; + +function _classCallCheck$1(instance, Constructor) { + if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); +} + +var mountSafeCallback = NativeMethodsMixinUtils.mountSafeCallback, warnForStyleProps = NativeMethodsMixinUtils.warnForStyleProps, ReactNativeFiberHostComponent = function() { + function ReactNativeFiberHostComponent(tag, viewConfig) { + _classCallCheck$1(this, ReactNativeFiberHostComponent), this._nativeTag = tag, this._children = [], + this.viewConfig = viewConfig; + } + return ReactNativeFiberHostComponent.prototype.blur = function() { + TextInputState.blurTextInput(this._nativeTag); + }, ReactNativeFiberHostComponent.prototype.focus = function() { + TextInputState.focusTextInput(this._nativeTag); + }, ReactNativeFiberHostComponent.prototype.measure = function(callback) { + UIManager.measure(this._nativeTag, mountSafeCallback(this, callback)); + }, ReactNativeFiberHostComponent.prototype.measureInWindow = function(callback) { + UIManager.measureInWindow(this._nativeTag, mountSafeCallback(this, callback)); + }, ReactNativeFiberHostComponent.prototype.measureLayout = function(relativeToNativeNode, onSuccess, onFail) { + UIManager.measureLayout(this._nativeTag, relativeToNativeNode, mountSafeCallback(this, onFail), mountSafeCallback(this, onSuccess)); + }, ReactNativeFiberHostComponent.prototype.setNativeProps = function(nativeProps) { + warnForStyleProps(nativeProps, this.viewConfig.validAttributes); + var updatePayload = ReactNativeAttributePayload_1.create(nativeProps, this.viewConfig.validAttributes); + UIManager.updateView(this._nativeTag, this.viewConfig.uiViewClassName, updatePayload); + }, ReactNativeFiberHostComponent; +}(), ReactNativeFiberHostComponent_1 = ReactNativeFiberHostComponent, viewConfigs = new Map(), prefix = "topsecret-", ReactNativeViewConfigRegistry = { + register: function(viewConfig) { + var name = viewConfig.uiViewClassName; + invariant(!viewConfigs.has(name), "Tried to register two views with the same name %s", name); + var secretName = prefix + name; + return viewConfigs.set(secretName, viewConfig), secretName; + }, + get: function(secretName) { + var config = viewConfigs.get(secretName); + return invariant(config, "View config not found for name %s", secretName), config; + } +}, ReactNativeViewConfigRegistry_1 = ReactNativeViewConfigRegistry, precacheFiberNode$1 = ReactNativeComponentTree_1.precacheFiberNode, uncacheFiberNode$1 = ReactNativeComponentTree_1.uncacheFiberNode, updateFiberProps$1 = ReactNativeComponentTree_1.updateFiberProps; + +function recursivelyUncacheFiberNode(node) { + "number" == typeof node ? uncacheFiberNode$1(node) : (uncacheFiberNode$1(node._nativeTag), + node._children.forEach(recursivelyUncacheFiberNode)); +} + +var NativeRenderer = ReactFiberReconciler({ + appendChild: function(parentInstance, child) { + var childTag = "number" == typeof child ? child : child._nativeTag; + if ("number" == typeof parentInstance) UIManager.setChildren(parentInstance, [ childTag ]); else { + var children = parentInstance._children, index = children.indexOf(child); + index >= 0 ? (children.splice(index, 1), children.push(child), UIManager.manageChildren(parentInstance._nativeTag, [ index ], [ children.length - 1 ], [], [], [])) : (children.push(child), + UIManager.manageChildren(parentInstance._nativeTag, [], [], [ childTag ], [ children.length - 1 ], [])); + } + }, + appendInitialChild: function(parentInstance, child) { + parentInstance._children.push(child); + }, + commitTextUpdate: function(textInstance, oldText, newText) { + UIManager.updateView(textInstance, "RCTRawText", { + text: newText + }); + }, + commitMount: function(instance, type, newProps, internalInstanceHandle) {}, + commitUpdate: function(instance, updatePayloadTODO, type, oldProps, newProps, internalInstanceHandle) { + var viewConfig = instance.viewConfig; + updateFiberProps$1(instance._nativeTag, newProps); + var updatePayload = ReactNativeAttributePayload_1.diff(oldProps, newProps, viewConfig.validAttributes); + UIManager.updateView(instance._nativeTag, viewConfig.uiViewClassName, updatePayload); + }, + createInstance: function(type, props, rootContainerInstance, hostContext, internalInstanceHandle) { + var tag = ReactNativeTagHandles_1.allocateTag(), viewConfig = ReactNativeViewConfigRegistry_1.get(type); + for (var key in viewConfig.validAttributes) props.hasOwnProperty(key) && deepFreezeAndThrowOnMutationInDev(props[key]); + var updatePayload = ReactNativeAttributePayload_1.create(props, viewConfig.validAttributes); + UIManager.createView(tag, viewConfig.uiViewClassName, rootContainerInstance, updatePayload); + var component = new ReactNativeFiberHostComponent_1(tag, viewConfig); + return precacheFiberNode$1(internalInstanceHandle, tag), updateFiberProps$1(tag, props), + component; + }, + createTextInstance: function(text, rootContainerInstance, hostContext, internalInstanceHandle) { + var tag = ReactNativeTagHandles_1.allocateTag(); + return UIManager.createView(tag, "RCTRawText", rootContainerInstance, { + text: text + }), precacheFiberNode$1(internalInstanceHandle, tag), tag; + }, + finalizeInitialChildren: function(parentInstance, type, props, rootContainerInstance) { + if (0 === parentInstance._children.length) return !1; + var nativeTags = parentInstance._children.map(function(child) { + return "number" == typeof child ? child : child._nativeTag; + }); + return UIManager.setChildren(parentInstance._nativeTag, nativeTags), !1; + }, + getRootHostContext: function() { + return emptyObject; + }, + getChildHostContext: function() { + return emptyObject; + }, + getPublicInstance: function(instance) { + return instance; + }, + insertBefore: function(parentInstance, child, beforeChild) { + invariant("number" != typeof parentInstance, "Container does not support insertBefore operation"); + var children = parentInstance._children, index = children.indexOf(child); + if (index >= 0) { + children.splice(index, 1); + var beforeChildIndex = children.indexOf(beforeChild); + children.splice(beforeChildIndex, 0, child), UIManager.manageChildren(parentInstance._nativeTag, [ index ], [ beforeChildIndex ], [], [], []); + } else { + var _beforeChildIndex = children.indexOf(beforeChild); + children.splice(_beforeChildIndex, 0, child); + var childTag = "number" == typeof child ? child : child._nativeTag; + UIManager.manageChildren(parentInstance._nativeTag, [], [], [ childTag ], [ _beforeChildIndex ], []); + } + }, + prepareForCommit: function() {}, + prepareUpdate: function(instance, type, oldProps, newProps, rootContainerInstance, hostContext) { + return emptyObject; + }, + removeChild: function(parentInstance, child) { + if (recursivelyUncacheFiberNode(child), "number" == typeof parentInstance) UIManager.manageChildren(parentInstance, [], [], [], [], [ 0 ]); else { + var children = parentInstance._children, index = children.indexOf(child); + children.splice(index, 1), UIManager.manageChildren(parentInstance._nativeTag, [], [], [], [], [ index ]); + } + }, + resetAfterCommit: function() {}, + resetTextContent: function(instance) {}, + shouldDeprioritizeSubtree: function(type, props) { + return !1; + }, + scheduleAnimationCallback: commonjsGlobal.requestAnimationFrame, + scheduleDeferredCallback: commonjsGlobal.requestIdleCallback, + shouldSetTextContent: function(props) { + return !1; + }, + useSyncScheduling: !0 +}), ReactNativeFiberRenderer = NativeRenderer, getClosestInstanceFromNode = ReactNativeComponentTree_1.getClosestInstanceFromNode, findCurrentFiberUsingSlowPath$1 = ReactFiberTreeReflection.findCurrentFiberUsingSlowPath, HostComponent$10 = ReactTypeOfWork.HostComponent, getInspectorDataForViewTag = void 0, traverseOwnerTreeUp = function(hierarchy, instance) { + instance && (hierarchy.unshift(instance), traverseOwnerTreeUp(hierarchy, instance._debugOwner)); +}, getOwnerHierarchy = function(instance) { + var hierarchy = []; + return traverseOwnerTreeUp(hierarchy, instance), hierarchy; +}, lastNonHostInstance = function(hierarchy) { + for (var i = hierarchy.length - 1; i > 1; i--) { + var instance = hierarchy[i]; + if (instance.tag !== HostComponent$10) return instance; + } + return hierarchy[0]; +}, getHostProps = function(fiber) { + var host = ReactFiberTreeReflection.findCurrentHostFiber(fiber); + return host ? host.memoizedProps || emptyObject : emptyObject; +}, getHostNode = function(fiber, findNodeHandle) { + for (var hostNode = void 0; fiber; ) { + if (null !== fiber.stateNode && fiber.tag === HostComponent$10 && (hostNode = findNodeHandle(fiber.stateNode)), + hostNode) return hostNode; + fiber = fiber.child; + } + return null; +}, stripTopSecret = function(str) { + return "string" == typeof str && str.replace("topsecret-", ""); +}, createHierarchy = function(fiberHierarchy) { + return fiberHierarchy.map(function(fiber) { + return { + name: stripTopSecret(getComponentName_1(fiber)), + getInspectorData: function(findNodeHandle) { + return { + measure: function(callback) { + return UIManager.measure(getHostNode(fiber, findNodeHandle), callback); + }, + props: getHostProps(fiber), + source: fiber._debugSource + }; + } + }; + }); +}; + +getInspectorDataForViewTag = function(viewTag) { + var fiber = findCurrentFiberUsingSlowPath$1(getClosestInstanceFromNode(viewTag)), fiberHierarchy = getOwnerHierarchy(fiber), instance = lastNonHostInstance(fiberHierarchy), hierarchy = createHierarchy(fiberHierarchy), props = getHostProps(instance), source = instance._debugSource; + return { + hierarchy: hierarchy, + instance: instance, + props: props, + selection: fiberHierarchy.indexOf(instance), + source: source + }; +}; + +var ReactNativeFiberInspector = { + getInspectorDataForViewTag: getInspectorDataForViewTag +}, ReactVersion = "16.0.0-alpha.12", ReactNativeFeatureFlags$2 = { + useFiber: !0 +}, ReactNativeFeatureFlags_1 = ReactNativeFeatureFlags$2, ReactNativeFeatureFlags$3 = Object.freeze({ + default: ReactNativeFeatureFlags_1, + __moduleExports: ReactNativeFeatureFlags_1 +}), ReactNativeFeatureFlags$1 = ReactNativeFeatureFlags$3 && ReactNativeFeatureFlags_1 || ReactNativeFeatureFlags$3, ReactCurrentOwner$3 = ReactGlobalSharedState_1.ReactCurrentOwner, injectedFindNode = ReactNativeFeatureFlags$1.useFiber ? function(fiber) { + return ReactNativeFiberRenderer.findHostInstance(fiber); +} : function(instance) { + return instance; +}; + +function findNodeHandle(componentOrHandle) { + var owner = ReactCurrentOwner$3.current; + if (null !== owner && (warning(owner._warnedAboutRefsInRender, "%s is accessing findNodeHandle inside its render(). " + "render() should be a pure function of props and state. It should " + "never access something that requires stale data from the previous " + "render, such as refs. Move this logic to componentDidMount and " + "componentDidUpdate instead.", owner.getName() || "A component"), + owner._warnedAboutRefsInRender = !0), null == componentOrHandle) return null; + if ("number" == typeof componentOrHandle) return componentOrHandle; + var component = componentOrHandle, internalInstance = ReactInstanceMap_1.get(component); + return internalInstance ? injectedFindNode(internalInstance) : component || (invariant("object" == typeof component && ("_rootNodeID" in component || "_nativeTag" in component) || null != component.render && "function" == typeof component.render, "findNodeHandle(...): Argument is not a component " + "(type: %s, keys: %s)", typeof component, Object.keys(component)), + void invariant(!1, "findNodeHandle(...): Unable to find node handle for unmounted " + "component.")); +} + +var findNodeHandle_1 = findNodeHandle, findNumericNodeHandleFiber = function(componentOrHandle) { + var instance = findNodeHandle_1(componentOrHandle); + return null == instance || "number" == typeof instance ? instance : instance._nativeTag; +}, DevOnlyStubShim = null, mountSafeCallback$2 = NativeMethodsMixinUtils.mountSafeCallback, throwOnStylesProp$1 = NativeMethodsMixinUtils.throwOnStylesProp, warnForStyleProps$2 = NativeMethodsMixinUtils.warnForStyleProps, findNumericNodeHandle = ReactNativeFeatureFlags$1.useFiber ? findNumericNodeHandleFiber : DevOnlyStubShim, NativeMethodsMixin = { + measure: function(callback) { + UIManager.measure(findNumericNodeHandle(this), mountSafeCallback$2(this, callback)); + }, + measureInWindow: function(callback) { + UIManager.measureInWindow(findNumericNodeHandle(this), mountSafeCallback$2(this, callback)); + }, + measureLayout: function(relativeToNativeNode, onSuccess, onFail) { + UIManager.measureLayout(findNumericNodeHandle(this), relativeToNativeNode, mountSafeCallback$2(this, onFail), mountSafeCallback$2(this, onSuccess)); + }, + setNativeProps: function(nativeProps) { + injectedSetNativeProps(this, nativeProps); + }, + focus: function() { + TextInputState.focusTextInput(findNumericNodeHandle(this)); + }, + blur: function() { + TextInputState.blurTextInput(findNumericNodeHandle(this)); + } +}; + +function setNativePropsFiber(componentOrHandle, nativeProps) { + var maybeInstance = void 0; + try { + maybeInstance = findNodeHandle_1(componentOrHandle); + } catch (error) {} + if (null != maybeInstance) { + var viewConfig = maybeInstance.viewConfig; + warnForStyleProps$2(nativeProps, viewConfig.validAttributes); + var updatePayload = ReactNativeAttributePayload_1.create(nativeProps, viewConfig.validAttributes); + UIManager.updateView(maybeInstance._nativeTag, viewConfig.uiViewClassName, updatePayload); + } +} + +function setNativePropsStack(componentOrHandle, nativeProps) { + var maybeInstance = findNodeHandle_1(componentOrHandle); + if (null != maybeInstance) { + var viewConfig = void 0; + if (void 0 !== maybeInstance.viewConfig) viewConfig = maybeInstance.viewConfig; else if (void 0 !== maybeInstance._instance && void 0 !== maybeInstance._instance.viewConfig) viewConfig = maybeInstance._instance.viewConfig; else { + for (;void 0 !== maybeInstance._renderedComponent; ) maybeInstance = maybeInstance._renderedComponent; + viewConfig = maybeInstance.viewConfig; + } + var tag = "function" == typeof maybeInstance.getHostNode ? maybeInstance.getHostNode() : maybeInstance._rootNodeID; + warnForStyleProps$2(nativeProps, viewConfig.validAttributes); + var updatePayload = ReactNativeAttributePayload_1.create(nativeProps, viewConfig.validAttributes); + UIManager.updateView(tag, viewConfig.uiViewClassName, updatePayload); + } +} + +var injectedSetNativeProps = void 0; + +injectedSetNativeProps = ReactNativeFeatureFlags$1.useFiber ? setNativePropsFiber : setNativePropsStack; + +var NativeMethodsMixin_DEV = NativeMethodsMixin; + +invariant(!NativeMethodsMixin_DEV.componentWillMount && !NativeMethodsMixin_DEV.componentWillReceiveProps, "Do not override existing functions."), +NativeMethodsMixin_DEV.componentWillMount = function() { + throwOnStylesProp$1(this, this.props); +}, NativeMethodsMixin_DEV.componentWillReceiveProps = function(newProps) { + throwOnStylesProp$1(this, newProps); +}; + +var NativeMethodsMixin_1 = NativeMethodsMixin, TouchHistoryMath = { + centroidDimension: function(touchHistory, touchesChangedAfter, isXAxis, ofCurrent) { + var touchBank = touchHistory.touchBank, total = 0, count = 0, oneTouchData = 1 === touchHistory.numberActiveTouches ? touchHistory.touchBank[touchHistory.indexOfSingleActiveTouch] : null; + if (null !== oneTouchData) oneTouchData.touchActive && oneTouchData.currentTimeStamp > touchesChangedAfter && (total += ofCurrent && isXAxis ? oneTouchData.currentPageX : ofCurrent && !isXAxis ? oneTouchData.currentPageY : !ofCurrent && isXAxis ? oneTouchData.previousPageX : oneTouchData.previousPageY, + count = 1); else for (var i = 0; i < touchBank.length; i++) { + var touchTrack = touchBank[i]; + if (null !== touchTrack && void 0 !== touchTrack && touchTrack.touchActive && touchTrack.currentTimeStamp >= touchesChangedAfter) { + var toAdd; + toAdd = ofCurrent && isXAxis ? touchTrack.currentPageX : ofCurrent && !isXAxis ? touchTrack.currentPageY : !ofCurrent && isXAxis ? touchTrack.previousPageX : touchTrack.previousPageY, + total += toAdd, count++; + } + } + return count > 0 ? total / count : TouchHistoryMath.noCentroid; + }, + currentCentroidXOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) { + return TouchHistoryMath.centroidDimension(touchHistory, touchesChangedAfter, !0, !0); + }, + currentCentroidYOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) { + return TouchHistoryMath.centroidDimension(touchHistory, touchesChangedAfter, !1, !0); + }, + previousCentroidXOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) { + return TouchHistoryMath.centroidDimension(touchHistory, touchesChangedAfter, !0, !1); + }, + previousCentroidYOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) { + return TouchHistoryMath.centroidDimension(touchHistory, touchesChangedAfter, !1, !1); + }, + currentCentroidX: function(touchHistory) { + return TouchHistoryMath.centroidDimension(touchHistory, 0, !0, !0); + }, + currentCentroidY: function(touchHistory) { + return TouchHistoryMath.centroidDimension(touchHistory, 0, !1, !0); + }, + noCentroid: -1 +}, TouchHistoryMath_1 = TouchHistoryMath, createReactNativeComponentClassFiber = function(viewConfig) { + return ReactNativeViewConfigRegistry_1.register(viewConfig); +}, createReactNativeComponentClassFiber_1 = createReactNativeComponentClassFiber, createReactNativeComponentClass = ReactNativeFeatureFlags$1.useFiber ? createReactNativeComponentClassFiber_1 : DevOnlyStubShim, findNumericNodeHandle$1 = ReactNativeFeatureFlags$1.useFiber ? findNumericNodeHandleFiber : DevOnlyStubShim; + +function takeSnapshot(view, options) { + return "number" != typeof view && "window" !== view && (view = findNumericNodeHandle$1(view) || "window"), + UIManager.__takeSnapshot(view, options); +} + +var takeSnapshot_1 = takeSnapshot, ReactInvalidSetStateWarningHook = {}, processingChildContext = !1, warnInvalidSetState = function() { + warning(!processingChildContext, "setState(...): Cannot call setState() inside getChildContext()"); +}; + +ReactInvalidSetStateWarningHook = { + onBeginProcessingChildContext: function() { + processingChildContext = !0; + }, + onEndProcessingChildContext: function() { + processingChildContext = !1; + }, + onSetState: function() { + warnInvalidSetState(); + } +}; + +var ReactInvalidSetStateWarningHook_1 = ReactInvalidSetStateWarningHook, ReactHostOperationHistoryHook = null, history = []; + +ReactHostOperationHistoryHook = { + onHostOperation: function(operation) { + history.push(operation); + }, + clearHistory: function() { + ReactHostOperationHistoryHook._preventClearing || (history = []); + }, + getHistory: function() { + return history; + } +}; + +var ReactHostOperationHistoryHook_1 = ReactHostOperationHistoryHook, ReactComponentTreeHook = ReactGlobalSharedState_1.ReactComponentTreeHook, ReactDebugTool = null, hooks = [], didHookThrowForEvent = {}, callHook = function(event, fn, context, arg1, arg2, arg3, arg4, arg5) { + try { + fn.call(context, arg1, arg2, arg3, arg4, arg5); + } catch (e) { + warning(didHookThrowForEvent[event], "Exception thrown by hook while handling %s: %s", event, e + "\n" + e.stack), + didHookThrowForEvent[event] = !0; + } +}, emitEvent = function(event, arg1, arg2, arg3, arg4, arg5) { + for (var i = 0; i < hooks.length; i++) { + var hook = hooks[i], fn = hook[event]; + fn && callHook(event, fn, hook, arg1, arg2, arg3, arg4, arg5); + } +}, isProfiling = !1, flushHistory = [], lifeCycleTimerStack = [], currentFlushNesting = 0, currentFlushMeasurements = [], currentFlushStartTime = 0, currentTimerDebugID = null, currentTimerStartTime = 0, currentTimerNestedFlushDuration = 0, currentTimerType = null, lifeCycleTimerHasWarned = !1, clearHistory = function() { + ReactComponentTreeHook.purgeUnmountedComponents(), ReactHostOperationHistoryHook_1.clearHistory(); +}, getTreeSnapshot = function(registeredIDs) { + return registeredIDs.reduce(function(tree, id) { + var ownerID = ReactComponentTreeHook.getOwnerID(id), parentID = ReactComponentTreeHook.getParentID(id); + return tree[id] = { + displayName: ReactComponentTreeHook.getDisplayName(id), + text: ReactComponentTreeHook.getText(id), + updateCount: ReactComponentTreeHook.getUpdateCount(id), + childIDs: ReactComponentTreeHook.getChildIDs(id), + ownerID: ownerID || parentID && ReactComponentTreeHook.getOwnerID(parentID) || 0, + parentID: parentID + }, tree; + }, {}); +}, resetMeasurements = function() { + var previousStartTime = currentFlushStartTime, previousMeasurements = currentFlushMeasurements, previousOperations = ReactHostOperationHistoryHook_1.getHistory(); + if (0 === currentFlushNesting) return currentFlushStartTime = 0, currentFlushMeasurements = [], + void clearHistory(); + if (previousMeasurements.length || previousOperations.length) { + var registeredIDs = ReactComponentTreeHook.getRegisteredIDs(); + flushHistory.push({ + duration: performanceNow() - previousStartTime, + measurements: previousMeasurements || [], + operations: previousOperations || [], + treeSnapshot: getTreeSnapshot(registeredIDs) + }); + } + clearHistory(), currentFlushStartTime = performanceNow(), currentFlushMeasurements = []; +}, checkDebugID = function(debugID) { + arguments.length > 1 && void 0 !== arguments[1] && arguments[1] && 0 === debugID || debugID || warning(!1, "ReactDebugTool: debugID may not be empty."); +}, beginLifeCycleTimer = function(debugID, timerType) { + 0 !== currentFlushNesting && (currentTimerType && !lifeCycleTimerHasWarned && (warning(!1, "There is an internal error in the React performance measurement code." + "\n\nDid not expect %s timer to start while %s timer is still in " + "progress for %s instance.", timerType, currentTimerType || "no", debugID === currentTimerDebugID ? "the same" : "another"), + lifeCycleTimerHasWarned = !0), currentTimerStartTime = performanceNow(), currentTimerNestedFlushDuration = 0, + currentTimerDebugID = debugID, currentTimerType = timerType); +}, endLifeCycleTimer = function(debugID, timerType) { + 0 !== currentFlushNesting && (currentTimerType === timerType || lifeCycleTimerHasWarned || (warning(!1, "There is an internal error in the React performance measurement code. " + "We did not expect %s timer to stop while %s timer is still in " + "progress for %s instance. Please report this as a bug in React.", timerType, currentTimerType || "no", debugID === currentTimerDebugID ? "the same" : "another"), + lifeCycleTimerHasWarned = !0), isProfiling && currentFlushMeasurements.push({ + timerType: timerType, + instanceID: debugID, + duration: performanceNow() - currentTimerStartTime - currentTimerNestedFlushDuration + }), currentTimerStartTime = 0, currentTimerNestedFlushDuration = 0, currentTimerDebugID = null, + currentTimerType = null); +}, pauseCurrentLifeCycleTimer = function() { + var currentTimer = { + startTime: currentTimerStartTime, + nestedFlushStartTime: performanceNow(), + debugID: currentTimerDebugID, + timerType: currentTimerType + }; + lifeCycleTimerStack.push(currentTimer), currentTimerStartTime = 0, currentTimerNestedFlushDuration = 0, + currentTimerDebugID = null, currentTimerType = null; +}, resumeCurrentLifeCycleTimer = function() { + var _lifeCycleTimerStack$ = lifeCycleTimerStack.pop(), startTime = _lifeCycleTimerStack$.startTime, nestedFlushStartTime = _lifeCycleTimerStack$.nestedFlushStartTime, debugID = _lifeCycleTimerStack$.debugID, timerType = _lifeCycleTimerStack$.timerType, nestedFlushDuration = performanceNow() - nestedFlushStartTime; + currentTimerStartTime = startTime, currentTimerNestedFlushDuration += nestedFlushDuration, + currentTimerDebugID = debugID, currentTimerType = timerType; +}, lastMarkTimeStamp = 0, canUsePerformanceMeasure = "undefined" != typeof performance && "function" == typeof performance.mark && "function" == typeof performance.clearMarks && "function" == typeof performance.measure && "function" == typeof performance.clearMeasures, shouldMark = function(debugID) { + if (!isProfiling || !canUsePerformanceMeasure) return !1; + var element = ReactComponentTreeHook.getElement(debugID); + return null != element && "object" == typeof element && !("string" == typeof element.type); +}, markBegin = function(debugID, markType) { + if (shouldMark(debugID)) { + var markName = debugID + "::" + markType; + lastMarkTimeStamp = performanceNow(), performance.mark(markName); + } +}, markEnd = function(debugID, markType) { + if (shouldMark(debugID)) { + var markName = debugID + "::" + markType, displayName = ReactComponentTreeHook.getDisplayName(debugID) || "Unknown"; + if (performanceNow() - lastMarkTimeStamp > .1) { + var measurementName = displayName + " [" + markType + "]"; + performance.measure(measurementName, markName); + } + performance.clearMarks(markName), measurementName && performance.clearMeasures(measurementName); + } +}; + +ReactDebugTool = { + addHook: function(hook) { + hooks.push(hook); + }, + removeHook: function(hook) { + for (var i = 0; i < hooks.length; i++) hooks[i] === hook && (hooks.splice(i, 1), + i--); + }, + isProfiling: function() { + return isProfiling; + }, + beginProfiling: function() { + isProfiling || (isProfiling = !0, flushHistory.length = 0, resetMeasurements(), + ReactDebugTool.addHook(ReactHostOperationHistoryHook_1)); + }, + endProfiling: function() { + isProfiling && (isProfiling = !1, resetMeasurements(), ReactDebugTool.removeHook(ReactHostOperationHistoryHook_1)); + }, + getFlushHistory: function() { + return flushHistory; + }, + onBeginFlush: function() { + currentFlushNesting++, resetMeasurements(), pauseCurrentLifeCycleTimer(), emitEvent("onBeginFlush"); + }, + onEndFlush: function() { + resetMeasurements(), currentFlushNesting--, resumeCurrentLifeCycleTimer(), emitEvent("onEndFlush"); + }, + onBeginLifeCycleTimer: function(debugID, timerType) { + checkDebugID(debugID), emitEvent("onBeginLifeCycleTimer", debugID, timerType), markBegin(debugID, timerType), + beginLifeCycleTimer(debugID, timerType); + }, + onEndLifeCycleTimer: function(debugID, timerType) { + checkDebugID(debugID), endLifeCycleTimer(debugID, timerType), markEnd(debugID, timerType), + emitEvent("onEndLifeCycleTimer", debugID, timerType); + }, + onBeginProcessingChildContext: function() { + emitEvent("onBeginProcessingChildContext"); + }, + onEndProcessingChildContext: function() { + emitEvent("onEndProcessingChildContext"); + }, + onHostOperation: function(operation) { + checkDebugID(operation.instanceID), emitEvent("onHostOperation", operation); + }, + onSetState: function() { + emitEvent("onSetState"); + }, + onSetChildren: function(debugID, childDebugIDs) { + checkDebugID(debugID), childDebugIDs.forEach(checkDebugID), emitEvent("onSetChildren", debugID, childDebugIDs); + }, + onBeforeMountComponent: function(debugID, element, parentDebugID) { + checkDebugID(debugID), checkDebugID(parentDebugID, !0), emitEvent("onBeforeMountComponent", debugID, element, parentDebugID), + markBegin(debugID, "mount"); + }, + onMountComponent: function(debugID) { + checkDebugID(debugID), markEnd(debugID, "mount"), emitEvent("onMountComponent", debugID); + }, + onBeforeUpdateComponent: function(debugID, element) { + checkDebugID(debugID), emitEvent("onBeforeUpdateComponent", debugID, element), markBegin(debugID, "update"); + }, + onUpdateComponent: function(debugID) { + checkDebugID(debugID), markEnd(debugID, "update"), emitEvent("onUpdateComponent", debugID); + }, + onBeforeUnmountComponent: function(debugID) { + checkDebugID(debugID), emitEvent("onBeforeUnmountComponent", debugID), markBegin(debugID, "unmount"); + }, + onUnmountComponent: function(debugID) { + checkDebugID(debugID), markEnd(debugID, "unmount"), emitEvent("onUnmountComponent", debugID); + }, + onTestEvent: function() { + emitEvent("onTestEvent"); + } +}, ReactDebugTool.addHook(ReactInvalidSetStateWarningHook_1), ReactDebugTool.addHook(ReactComponentTreeHook); + +var url = ExecutionEnvironment.canUseDOM && window.location.href || ""; + +/[?&]react_perf\b/.test(url) && ReactDebugTool.beginProfiling(); + +var ReactDebugTool_1 = ReactDebugTool, lowPriorityWarning = function() {}, printWarning = function(format) { + for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) args[_key - 1] = arguments[_key]; + var argIndex = 0, message = "Warning: " + format.replace(/%s/g, function() { + return args[argIndex++]; + }); + "undefined" != typeof console && console.warn(message); + try { + throw new Error(message); + } catch (x) {} +}; + +lowPriorityWarning = function(condition, format) { + if (void 0 === format) throw new Error("`warning(condition, format, ...args)` requires a warning " + "message argument"); + if (!condition) { + for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) args[_key2 - 2] = arguments[_key2]; + printWarning.apply(void 0, [ format ].concat(args)); + } +}; + +var lowPriorityWarning_1 = lowPriorityWarning, _extends$3 = Object.assign || function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]); + } + return target; +}; + +function roundFloat(val) { + var base = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 2, n = Math.pow(10, base); + return Math.floor(val * n) / n; +} + +function consoleTable(table) { + console.table(table); +} + +function getLastMeasurements() { + return ReactDebugTool_1.getFlushHistory(); +} + +function getExclusive() { + var flushHistory = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : getLastMeasurements(), aggregatedStats = {}, affectedIDs = {}; + function updateAggregatedStats(treeSnapshot, instanceID, timerType, applyUpdate) { + var displayName = treeSnapshot[instanceID].displayName, key = displayName, stats = aggregatedStats[key]; + stats || (affectedIDs[key] = {}, stats = aggregatedStats[key] = { + key: key, + instanceCount: 0, + counts: {}, + durations: {}, + totalDuration: 0 + }), stats.durations[timerType] || (stats.durations[timerType] = 0), stats.counts[timerType] || (stats.counts[timerType] = 0), + affectedIDs[key][instanceID] = !0, applyUpdate(stats); + } + return flushHistory.forEach(function(flush) { + var measurements = flush.measurements, treeSnapshot = flush.treeSnapshot; + measurements.forEach(function(measurement) { + var duration = measurement.duration, instanceID = measurement.instanceID, timerType = measurement.timerType; + updateAggregatedStats(treeSnapshot, instanceID, timerType, function(stats) { + stats.totalDuration += duration, stats.durations[timerType] += duration, stats.counts[timerType]++; + }); + }); + }), Object.keys(aggregatedStats).map(function(key) { + return _extends$3({}, aggregatedStats[key], { + instanceCount: Object.keys(affectedIDs[key]).length + }); + }).sort(function(a, b) { + return b.totalDuration - a.totalDuration; + }); +} + +function getInclusive() { + var flushHistory = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : getLastMeasurements(), aggregatedStats = {}, affectedIDs = {}; + function updateAggregatedStats(treeSnapshot, instanceID, applyUpdate) { + var _treeSnapshot$instanc = treeSnapshot[instanceID], displayName = _treeSnapshot$instanc.displayName, ownerID = _treeSnapshot$instanc.ownerID, owner = treeSnapshot[ownerID], key = (owner ? owner.displayName + " > " : "") + displayName, stats = aggregatedStats[key]; + stats || (affectedIDs[key] = {}, stats = aggregatedStats[key] = { + key: key, + instanceCount: 0, + inclusiveRenderDuration: 0, + renderCount: 0 + }), affectedIDs[key][instanceID] = !0, applyUpdate(stats); + } + var isCompositeByID = {}; + return flushHistory.forEach(function(flush) { + flush.measurements.forEach(function(measurement) { + var instanceID = measurement.instanceID; + "render" === measurement.timerType && (isCompositeByID[instanceID] = !0); + }); + }), flushHistory.forEach(function(flush) { + var measurements = flush.measurements, treeSnapshot = flush.treeSnapshot; + measurements.forEach(function(measurement) { + var duration = measurement.duration, instanceID = measurement.instanceID; + if ("render" === measurement.timerType) { + updateAggregatedStats(treeSnapshot, instanceID, function(stats) { + stats.renderCount++; + }); + for (var nextParentID = instanceID; nextParentID; ) isCompositeByID[nextParentID] && updateAggregatedStats(treeSnapshot, nextParentID, function(stats) { + stats.inclusiveRenderDuration += duration; + }), nextParentID = treeSnapshot[nextParentID].parentID; + } + }); + }), Object.keys(aggregatedStats).map(function(key) { + return _extends$3({}, aggregatedStats[key], { + instanceCount: Object.keys(affectedIDs[key]).length + }); + }).sort(function(a, b) { + return b.inclusiveRenderDuration - a.inclusiveRenderDuration; + }); +} + +function getWasted() { + var flushHistory = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : getLastMeasurements(), aggregatedStats = {}, affectedIDs = {}; + function updateAggregatedStats(treeSnapshot, instanceID, applyUpdate) { + var _treeSnapshot$instanc2 = treeSnapshot[instanceID], displayName = _treeSnapshot$instanc2.displayName, ownerID = _treeSnapshot$instanc2.ownerID, owner = treeSnapshot[ownerID], key = (owner ? owner.displayName + " > " : "") + displayName, stats = aggregatedStats[key]; + stats || (affectedIDs[key] = {}, stats = aggregatedStats[key] = { + key: key, + instanceCount: 0, + inclusiveRenderDuration: 0, + renderCount: 0 + }), affectedIDs[key][instanceID] = !0, applyUpdate(stats); + } + return flushHistory.forEach(function(flush) { + var measurements = flush.measurements, treeSnapshot = flush.treeSnapshot, operations = flush.operations, isDefinitelyNotWastedByID = {}; + operations.forEach(function(operation) { + for (var instanceID = operation.instanceID, nextParentID = instanceID; nextParentID; ) isDefinitelyNotWastedByID[nextParentID] = !0, + nextParentID = treeSnapshot[nextParentID].parentID; + }); + var renderedCompositeIDs = {}; + measurements.forEach(function(measurement) { + var instanceID = measurement.instanceID; + "render" === measurement.timerType && (renderedCompositeIDs[instanceID] = !0); + }), measurements.forEach(function(measurement) { + var duration = measurement.duration, instanceID = measurement.instanceID; + if ("render" === measurement.timerType) { + var updateCount = treeSnapshot[instanceID].updateCount; + if (!isDefinitelyNotWastedByID[instanceID] && 0 !== updateCount) { + updateAggregatedStats(treeSnapshot, instanceID, function(stats) { + stats.renderCount++; + }); + for (var nextParentID = instanceID; nextParentID; ) renderedCompositeIDs[nextParentID] && !isDefinitelyNotWastedByID[nextParentID] && updateAggregatedStats(treeSnapshot, nextParentID, function(stats) { + stats.inclusiveRenderDuration += duration; + }), nextParentID = treeSnapshot[nextParentID].parentID; + } + } + }); + }), Object.keys(aggregatedStats).map(function(key) { + return _extends$3({}, aggregatedStats[key], { + instanceCount: Object.keys(affectedIDs[key]).length + }); + }).sort(function(a, b) { + return b.inclusiveRenderDuration - a.inclusiveRenderDuration; + }); +} + +function getOperations() { + var flushHistory = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : getLastMeasurements(), stats = []; + return flushHistory.forEach(function(flush, flushIndex) { + var operations = flush.operations, treeSnapshot = flush.treeSnapshot; + operations.forEach(function(operation) { + var instanceID = operation.instanceID, type = operation.type, payload = operation.payload, _treeSnapshot$instanc3 = treeSnapshot[instanceID], displayName = _treeSnapshot$instanc3.displayName, ownerID = _treeSnapshot$instanc3.ownerID, owner = treeSnapshot[ownerID], key = (owner ? owner.displayName + " > " : "") + displayName; + stats.push({ + flushIndex: flushIndex, + instanceID: instanceID, + key: key, + type: type, + ownerID: ownerID, + payload: payload + }); + }); + }), stats; +} + +function printExclusive(flushHistory) { + consoleTable(getExclusive(flushHistory).map(function(item) { + var key = item.key, instanceCount = item.instanceCount, totalDuration = item.totalDuration, renderCount = item.counts.render || 0, renderDuration = item.durations.render || 0; + return { + Component: key, + "Total time (ms)": roundFloat(totalDuration), + "Instance count": instanceCount, + "Total render time (ms)": roundFloat(renderDuration), + "Average render time (ms)": renderCount ? roundFloat(renderDuration / renderCount) : void 0, + "Render count": renderCount, + "Total lifecycle time (ms)": roundFloat(totalDuration - renderDuration) + }; + })); +} + +function printInclusive(flushHistory) { + consoleTable(getInclusive(flushHistory).map(function(item) { + var key = item.key, instanceCount = item.instanceCount, inclusiveRenderDuration = item.inclusiveRenderDuration, renderCount = item.renderCount; + return { + "Owner > Component": key, + "Inclusive render time (ms)": roundFloat(inclusiveRenderDuration), + "Instance count": instanceCount, + "Render count": renderCount + }; + })); +} + +function printWasted(flushHistory) { + consoleTable(getWasted(flushHistory).map(function(item) { + var key = item.key, instanceCount = item.instanceCount, inclusiveRenderDuration = item.inclusiveRenderDuration, renderCount = item.renderCount; + return { + "Owner > Component": key, + "Inclusive wasted time (ms)": roundFloat(inclusiveRenderDuration), + "Instance count": instanceCount, + "Render count": renderCount + }; + })); +} + +function printOperations(flushHistory) { + consoleTable(getOperations(flushHistory).map(function(stat) { + return { + "Owner > Node": stat.key, + Operation: stat.type, + Payload: "object" == typeof stat.payload ? JSON.stringify(stat.payload) : stat.payload, + "Flush index": stat.flushIndex, + "Owner Component ID": stat.ownerID, + "DOM Component ID": stat.instanceID + }; + })); +} + +var warnedAboutPrintDOM = !1; + +function printDOM(measurements) { + return lowPriorityWarning_1(warnedAboutPrintDOM, "`ReactPerf.printDOM(...)` is deprecated. Use " + "`ReactPerf.printOperations(...)` instead."), + warnedAboutPrintDOM = !0, printOperations(measurements); +} + +var warnedAboutGetMeasurementsSummaryMap = !1; + +function getMeasurementsSummaryMap(measurements) { + return lowPriorityWarning_1(warnedAboutGetMeasurementsSummaryMap, "`ReactPerf.getMeasurementsSummaryMap(...)` is deprecated. Use " + "`ReactPerf.getWasted(...)` instead."), + warnedAboutGetMeasurementsSummaryMap = !0, getWasted(measurements); +} + +function start() { + ReactDebugTool_1.beginProfiling(); +} + +function stop() { + ReactDebugTool_1.endProfiling(); +} + +function isRunning() { + return ReactDebugTool_1.isProfiling(); +} + +var ReactPerfAnalysis = { + getLastMeasurements: getLastMeasurements, + getExclusive: getExclusive, + getInclusive: getInclusive, + getWasted: getWasted, + getOperations: getOperations, + printExclusive: printExclusive, + printInclusive: printInclusive, + printWasted: printWasted, + printOperations: printOperations, + start: start, + stop: stop, + isRunning: isRunning, + printDOM: printDOM, + getMeasurementsSummaryMap: getMeasurementsSummaryMap +}, ReactPerf = ReactPerfAnalysis, injectInternals = ReactFiberDevToolsHook.injectInternals; + +ReactNativeInjection.inject(), ReactGenericBatching_1.injection.injectFiberBatchedUpdates(ReactNativeFiberRenderer.batchedUpdates); + +var roots = new Map(); + +ReactFiberErrorLogger.injection.injectDialog(ReactNativeFiberErrorDialog_1.showDialog); + +var ReactNative = { + findNodeHandle: findNumericNodeHandleFiber, + render: function(element, containerTag, callback) { + var root = roots.get(containerTag); + return root || (root = ReactNativeFiberRenderer.createContainer(containerTag), roots.set(containerTag, root)), + ReactNativeFiberRenderer.updateContainer(element, root, null, callback), ReactNativeFiberRenderer.getPublicRootInstance(root); + }, + unmountComponentAtNode: function(containerTag) { + var root = roots.get(containerTag); + root && ReactNativeFiberRenderer.updateContainer(null, root, null, function() { + roots.delete(containerTag); + }); + }, + unmountComponentAtNodeAndRemoveContainer: function(containerTag) { + ReactNative.unmountComponentAtNode(containerTag), UIManager.removeRootView(containerTag); + }, + unstable_createPortal: function(children, containerTag) { + var key = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : null; + return ReactPortal.createPortal(children, containerTag, null, key); + }, + unstable_batchedUpdates: ReactGenericBatching_1.batchedUpdates, + __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: { + NativeMethodsMixin: NativeMethodsMixin_1, + ReactGlobalSharedState: ReactGlobalSharedState_1, + ReactNativeComponentTree: ReactNativeComponentTree_1, + ReactNativePropRegistry: ReactNativePropRegistry_1, + TouchHistoryMath: TouchHistoryMath_1, + createReactNativeComponentClass: createReactNativeComponentClass, + takeSnapshot: takeSnapshot_1 + } +}; + +Object.assign(ReactNative.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, { + ReactDebugTool: ReactDebugTool_1, + ReactPerf: ReactPerf +}), "function" == typeof injectInternals && injectInternals({ + findFiberByHostInstance: ReactNativeComponentTree_1.getClosestInstanceFromNode, + findHostInstanceByFiber: ReactNativeFiberRenderer.findHostInstance, + getInspectorDataForViewTag: ReactNativeFiberInspector.getInspectorDataForViewTag, + bundleType: 1, + version: ReactVersion +}); + +var ReactNativeFiber = ReactNative; + +module.exports = ReactNativeFiber; diff --git a/Libraries/Renderer/ReactNativeFiber-prod.js b/Libraries/Renderer/ReactNativeFiber-prod.js new file mode 100644 index 0000000000..bd89d2f0ac --- /dev/null +++ b/Libraries/Renderer/ReactNativeFiber-prod.js @@ -0,0 +1,3710 @@ +/** + * Copyright 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @noflow + * @providesModule ReactNativeFiber-prod + */ +"use strict"; + +var invariant = require("fbjs/lib/invariant"), warning = require("fbjs/lib/warning"), ExceptionsManager = require("ExceptionsManager"); + +require("InitializeCore"); + +var RCTEventEmitter = require("RCTEventEmitter"), emptyFunction = require("fbjs/lib/emptyFunction"), UIManager = require("UIManager"); + +require("prop-types/checkPropTypes"); + +var emptyObject = require("fbjs/lib/emptyObject"), react = require("react"), shallowEqual = require("fbjs/lib/shallowEqual"), deepDiffer = require("deepDiffer"), flattenStyle = require("flattenStyle"), TextInputState = require("TextInputState"); + +require("deepFreezeAndThrowOnMutationInDev"), require("ReactNativeFeatureFlags"); + +var defaultShowDialog = function() { + return !0; +}, showDialog = defaultShowDialog; + +function logCapturedError(capturedError) { + if (!1 !== showDialog(capturedError)) { + var _error = capturedError.error; + console.error("React caught an error thrown by one of your components.\n\n" + _error.stack); + } +} + +var injection = { + injectDialog: function(fn) { + invariant(showDialog === defaultShowDialog, "The custom dialog was already injected."), + invariant("function" == typeof fn, "Injected showDialog() must be a function."), + showDialog = fn; + } +}, logCapturedError_1 = logCapturedError, ReactFiberErrorLogger = { + injection: injection, + logCapturedError: logCapturedError_1 +}, caughtError = null, invokeGuardedCallback = 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) { + return error; + } + return null; +}, rethrowCaughtError = function() { + if (caughtError) { + var error = caughtError; + throw caughtError = null, error; + } +}, ReactErrorUtils = { + injection: { + injectErrorUtils: function(injectedErrorUtils) { + invariant("function" == typeof injectedErrorUtils.invokeGuardedCallback, "Injected invokeGuardedCallback() must be a function."), + invokeGuardedCallback = injectedErrorUtils.invokeGuardedCallback; + } + }, + invokeGuardedCallback: function(name, func, context, a, b, c, d, e, f) { + return invokeGuardedCallback.apply(this, arguments); + }, + invokeGuardedCallbackAndCatchFirstError: function(name, func, context, a, b, c, d, e, f) { + var error = ReactErrorUtils.invokeGuardedCallback.apply(this, arguments); + null !== error && null === caughtError && (caughtError = error); + }, + rethrowCaughtError: function() { + return rethrowCaughtError.apply(this, arguments); + } +}, ReactErrorUtils_1 = ReactErrorUtils, ComponentTree, injection$1 = { + injectComponentTree: function(Injected) { + ComponentTree = Injected; + } +}; + +function isEndish(topLevelType) { + return "topMouseUp" === topLevelType || "topTouchEnd" === topLevelType || "topTouchCancel" === topLevelType; +} + +function isMoveish(topLevelType) { + return "topMouseMove" === topLevelType || "topTouchMove" === topLevelType; +} + +function isStartish(topLevelType) { + return "topMouseDown" === topLevelType || "topTouchStart" === topLevelType; +} + +function executeDispatch(event, simulated, listener, inst) { + var type = event.type || "unknown-event"; + event.currentTarget = EventPluginUtils.getNodeFromInstance(inst), ReactErrorUtils_1.invokeGuardedCallbackAndCatchFirstError(type, listener, void 0, event), + event.currentTarget = null; +} + +function executeDispatchesInOrder(event, simulated) { + var dispatchListeners = event._dispatchListeners, dispatchInstances = event._dispatchInstances; + if (Array.isArray(dispatchListeners)) for (var i = 0; i < dispatchListeners.length && !event.isPropagationStopped(); i++) executeDispatch(event, simulated, dispatchListeners[i], dispatchInstances[i]); else dispatchListeners && executeDispatch(event, simulated, dispatchListeners, dispatchInstances); + event._dispatchListeners = null, event._dispatchInstances = null; +} + +function executeDispatchesInOrderStopAtTrueImpl(event) { + var dispatchListeners = event._dispatchListeners, dispatchInstances = event._dispatchInstances; + if (Array.isArray(dispatchListeners)) { + for (var i = 0; i < dispatchListeners.length && !event.isPropagationStopped(); i++) if (dispatchListeners[i](event, dispatchInstances[i])) return dispatchInstances[i]; + } else if (dispatchListeners && dispatchListeners(event, dispatchInstances)) return dispatchInstances; + return null; +} + +function executeDispatchesInOrderStopAtTrue(event) { + var ret = executeDispatchesInOrderStopAtTrueImpl(event); + return event._dispatchInstances = null, event._dispatchListeners = null, ret; +} + +function executeDirectDispatch(event) { + var dispatchListener = event._dispatchListeners, dispatchInstance = event._dispatchInstances; + invariant(!Array.isArray(dispatchListener), "executeDirectDispatch(...): Invalid `event`."), + event.currentTarget = dispatchListener ? EventPluginUtils.getNodeFromInstance(dispatchInstance) : null; + var res = dispatchListener ? dispatchListener(event) : null; + return event.currentTarget = null, event._dispatchListeners = null, event._dispatchInstances = null, + res; +} + +function hasDispatches(event) { + return !!event._dispatchListeners; +} + +var EventPluginUtils = { + isEndish: isEndish, + isMoveish: isMoveish, + isStartish: isStartish, + executeDirectDispatch: executeDirectDispatch, + executeDispatchesInOrder: executeDispatchesInOrder, + executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue, + hasDispatches: hasDispatches, + getFiberCurrentPropsFromNode: function(node) { + return ComponentTree.getFiberCurrentPropsFromNode(node); + }, + getInstanceFromNode: function(node) { + return ComponentTree.getInstanceFromNode(node); + }, + getNodeFromInstance: function(node) { + return ComponentTree.getNodeFromInstance(node); + }, + injection: injection$1 +}, EventPluginUtils_1 = EventPluginUtils, fiberHostComponent = null, ReactControlledComponentInjection = { + injectFiberControlledHostComponent: function(hostComponentImpl) { + fiberHostComponent = hostComponentImpl; + } +}, restoreTarget = null, restoreQueue = null; + +function restoreStateOfTarget(target) { + var internalInstance = EventPluginUtils_1.getInstanceFromNode(target); + if (internalInstance) { + if ("number" == typeof internalInstance.tag) { + invariant(fiberHostComponent && "function" == typeof fiberHostComponent.restoreControlledState, "Fiber needs to be injected to handle a fiber target for controlled " + "events."); + var props = EventPluginUtils_1.getFiberCurrentPropsFromNode(internalInstance.stateNode); + return void fiberHostComponent.restoreControlledState(internalInstance.stateNode, internalInstance.type, props); + } + invariant("function" == typeof internalInstance.restoreControlledState, "The internal instance must be a React host component."), + internalInstance.restoreControlledState(); + } +} + +var ReactControlledComponent = { + injection: ReactControlledComponentInjection, + enqueueStateRestore: function(target) { + restoreTarget ? restoreQueue ? restoreQueue.push(target) : restoreQueue = [ target ] : restoreTarget = target; + }, + restoreStateIfNeeded: function() { + if (restoreTarget) { + var target = restoreTarget, queuedTargets = restoreQueue; + if (restoreTarget = null, restoreQueue = null, restoreStateOfTarget(target), queuedTargets) for (var i = 0; i < queuedTargets.length; i++) restoreStateOfTarget(queuedTargets[i]); + } + } +}, ReactControlledComponent_1 = ReactControlledComponent, stackBatchedUpdates = function(fn, a, b, c, d, e) { + return fn(a, b, c, d, e); +}, fiberBatchedUpdates = function(fn, bookkeeping) { + return fn(bookkeeping); +}; + +function performFiberBatchedUpdates(fn, bookkeeping) { + return fiberBatchedUpdates(fn, bookkeeping); +} + +function batchedUpdates(fn, bookkeeping) { + return stackBatchedUpdates(performFiberBatchedUpdates, fn, bookkeeping); +} + +var isNestingBatched = !1; + +function batchedUpdatesWithControlledComponents(fn, bookkeeping) { + if (isNestingBatched) return batchedUpdates(fn, bookkeeping); + isNestingBatched = !0; + try { + return batchedUpdates(fn, bookkeeping); + } finally { + isNestingBatched = !1, ReactControlledComponent_1.restoreStateIfNeeded(); + } +} + +var ReactGenericBatchingInjection = { + injectStackBatchedUpdates: function(_batchedUpdates) { + stackBatchedUpdates = _batchedUpdates; + }, + injectFiberBatchedUpdates: function(_batchedUpdates) { + fiberBatchedUpdates = _batchedUpdates; + } +}, ReactGenericBatching = { + batchedUpdates: batchedUpdatesWithControlledComponents, + injection: ReactGenericBatchingInjection +}, ReactGenericBatching_1 = ReactGenericBatching; + +function ReactNativeFiberErrorDialog(capturedError) { + var componentStack = capturedError.componentStack, error = capturedError.error, errorMessage = void 0, errorStack = void 0, errorType = void 0; + if (error && "object" == typeof error) { + var message = error.message, name = error.name; + errorMessage = (message ? name + ": " + message : name) + "\n\nThis error is located at:" + componentStack, + errorStack = error.stack, errorType = error.constructor; + } else errorMessage = "Unspecified error at:" + componentStack, errorStack = "", + errorType = Error; + var newError = new errorType(errorMessage); + return newError.stack = errorStack, ExceptionsManager.handleException(newError, !1), + !1; +} + +var showDialog$1 = ReactNativeFiberErrorDialog, ReactNativeFiberErrorDialog_1 = { + showDialog: showDialog$1 +}, eventPluginOrder = null, namesToPlugins = {}; + +function recomputePluginOrdering() { + if (eventPluginOrder) for (var pluginName in namesToPlugins) { + var pluginModule = namesToPlugins[pluginName], pluginIndex = eventPluginOrder.indexOf(pluginName); + if (invariant(pluginIndex > -1, "EventPluginRegistry: Cannot inject event plugins that do not exist in " + "the plugin ordering, `%s`.", pluginName), + !EventPluginRegistry.plugins[pluginIndex]) { + invariant(pluginModule.extractEvents, "EventPluginRegistry: Event plugins must implement an `extractEvents` " + "method, but `%s` does not.", pluginName), + EventPluginRegistry.plugins[pluginIndex] = pluginModule; + var publishedEvents = pluginModule.eventTypes; + for (var eventName in publishedEvents) invariant(publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName), "EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.", eventName, pluginName); + } + } +} + +function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { + invariant(!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName), "EventPluginHub: More than one plugin attempted to publish the same " + "event name, `%s`.", eventName), + EventPluginRegistry.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 !0; + } + return !!dispatchConfig.registrationName && (publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName), + !0); +} + +function publishRegistrationName(registrationName, pluginModule, eventName) { + invariant(!EventPluginRegistry.registrationNameModules[registrationName], "EventPluginHub: More than one plugin attempted to publish the same " + "registration name, `%s`.", registrationName), + EventPluginRegistry.registrationNameModules[registrationName] = pluginModule, EventPluginRegistry.registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies; +} + +var EventPluginRegistry = { + plugins: [], + eventNameDispatchConfigs: {}, + registrationNameModules: {}, + registrationNameDependencies: {}, + possibleRegistrationNames: null, + injectEventPluginOrder: function(injectedEventPluginOrder) { + invariant(!eventPluginOrder, "EventPluginRegistry: Cannot inject event plugin ordering more than " + "once. You are likely trying to load more than one copy of React."), + eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder), recomputePluginOrdering(); + }, + injectEventPluginsByName: function(injectedNamesToPlugins) { + var isOrderingDirty = !1; + for (var pluginName in injectedNamesToPlugins) if (injectedNamesToPlugins.hasOwnProperty(pluginName)) { + var pluginModule = injectedNamesToPlugins[pluginName]; + namesToPlugins.hasOwnProperty(pluginName) && namesToPlugins[pluginName] === pluginModule || (invariant(!namesToPlugins[pluginName], "EventPluginRegistry: Cannot inject two different event plugins " + "using the same name, `%s`.", pluginName), + namesToPlugins[pluginName] = pluginModule, isOrderingDirty = !0); + } + isOrderingDirty && recomputePluginOrdering(); + } +}, EventPluginRegistry_1 = EventPluginRegistry; + +function accumulateInto(current, next) { + return invariant(null != next, "accumulateInto(...): Accumulated items must not be null or undefined."), + null == current ? next : Array.isArray(current) ? Array.isArray(next) ? (current.push.apply(current, next), + current) : (current.push(next), current) : Array.isArray(next) ? [ current ].concat(next) : [ current, next ]; +} + +var accumulateInto_1 = accumulateInto; + +function forEachAccumulated(arr, cb, scope) { + Array.isArray(arr) ? arr.forEach(cb, scope) : arr && cb.call(scope, arr); +} + +var forEachAccumulated_1 = forEachAccumulated, eventQueue = null, executeDispatchesAndRelease = function(event, simulated) { + event && (EventPluginUtils_1.executeDispatchesInOrder(event, simulated), event.isPersistent() || event.constructor.release(event)); +}, executeDispatchesAndReleaseSimulated = function(e) { + return executeDispatchesAndRelease(e, !0); +}, executeDispatchesAndReleaseTopLevel = function(e) { + return executeDispatchesAndRelease(e, !1); +}; + +function isInteractive(tag) { + return "button" === tag || "input" === tag || "select" === tag || "textarea" === tag; +} + +function shouldPreventMouseEvent(name, type, props) { + switch (name) { + case "onClick": + case "onClickCapture": + case "onDoubleClick": + case "onDoubleClickCapture": + case "onMouseDown": + case "onMouseDownCapture": + case "onMouseMove": + case "onMouseMoveCapture": + case "onMouseUp": + case "onMouseUpCapture": + return !(!props.disabled || !isInteractive(type)); + + default: + return !1; + } +} + +var EventPluginHub = { + injection: { + injectEventPluginOrder: EventPluginRegistry_1.injectEventPluginOrder, + injectEventPluginsByName: EventPluginRegistry_1.injectEventPluginsByName + }, + getListener: function(inst, registrationName) { + var listener; + if ("number" == typeof inst.tag) { + var stateNode = inst.stateNode; + if (!stateNode) return null; + var props = EventPluginUtils_1.getFiberCurrentPropsFromNode(stateNode); + if (!props) return null; + if (listener = props[registrationName], shouldPreventMouseEvent(registrationName, inst.type, props)) return null; + } else { + var currentElement = inst._currentElement; + if ("string" == typeof currentElement || "number" == typeof currentElement) return null; + if (!inst._rootNodeID) return null; + var _props = currentElement.props; + if (listener = _props[registrationName], shouldPreventMouseEvent(registrationName, currentElement.type, _props)) return null; + } + return invariant(!listener || "function" == typeof listener, "Expected %s listener to be a function, instead got type %s", registrationName, typeof listener), + listener; + }, + extractEvents: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) { + for (var events, plugins = EventPluginRegistry_1.plugins, i = 0; i < plugins.length; i++) { + var possiblePlugin = plugins[i]; + if (possiblePlugin) { + var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); + extractedEvents && (events = accumulateInto_1(events, extractedEvents)); + } + } + return events; + }, + enqueueEvents: function(events) { + events && (eventQueue = accumulateInto_1(eventQueue, events)); + }, + processEventQueue: function(simulated) { + var processingEventQueue = eventQueue; + eventQueue = null, simulated ? forEachAccumulated_1(processingEventQueue, executeDispatchesAndReleaseSimulated) : forEachAccumulated_1(processingEventQueue, executeDispatchesAndReleaseTopLevel), + invariant(!eventQueue, "processEventQueue(): Additional events were enqueued while processing " + "an event queue. Support for this has not yet been implemented."), + ReactErrorUtils_1.rethrowCaughtError(); + } +}, EventPluginHub_1 = EventPluginHub, ReactTypeOfWork = { + IndeterminateComponent: 0, + FunctionalComponent: 1, + ClassComponent: 2, + HostRoot: 3, + HostPortal: 4, + HostComponent: 5, + HostText: 6, + CoroutineComponent: 7, + CoroutineHandlerPhase: 8, + YieldComponent: 9, + Fragment: 10 +}, HostComponent = ReactTypeOfWork.HostComponent; + +function getParent(inst) { + if (void 0 !== inst._hostParent) return inst._hostParent; + if ("number" == typeof inst.tag) { + do { + inst = inst.return; + } while (inst && inst.tag !== HostComponent); + if (inst) return inst; + } + return null; +} + +function getLowestCommonAncestor(instA, instB) { + for (var depthA = 0, tempA = instA; tempA; tempA = getParent(tempA)) depthA++; + for (var depthB = 0, tempB = instB; tempB; tempB = getParent(tempB)) depthB++; + for (;depthA - depthB > 0; ) instA = getParent(instA), depthA--; + for (;depthB - depthA > 0; ) instB = getParent(instB), depthB--; + for (var depth = depthA; depth--; ) { + if (instA === instB || instA === instB.alternate) return instA; + instA = getParent(instA), instB = getParent(instB); + } + return null; +} + +function isAncestor(instA, instB) { + for (;instB; ) { + if (instA === instB || instA === instB.alternate) return !0; + instB = getParent(instB); + } + return !1; +} + +function getParentInstance(inst) { + return getParent(inst); +} + +function traverseTwoPhase(inst, fn, arg) { + for (var path = []; inst; ) path.push(inst), inst = getParent(inst); + var i; + for (i = path.length; i-- > 0; ) fn(path[i], "captured", arg); + for (i = 0; i < path.length; i++) fn(path[i], "bubbled", arg); +} + +function traverseEnterLeave(from, to, fn, argFrom, argTo) { + for (var common = from && to ? getLowestCommonAncestor(from, to) : null, pathFrom = []; from && from !== common; ) pathFrom.push(from), + from = getParent(from); + for (var pathTo = []; to && to !== common; ) pathTo.push(to), to = getParent(to); + var i; + for (i = 0; i < pathFrom.length; i++) fn(pathFrom[i], "bubbled", argFrom); + for (i = pathTo.length; i-- > 0; ) fn(pathTo[i], "captured", argTo); +} + +var ReactTreeTraversal = { + isAncestor: isAncestor, + getLowestCommonAncestor: getLowestCommonAncestor, + getParentInstance: getParentInstance, + traverseTwoPhase: traverseTwoPhase, + traverseEnterLeave: traverseEnterLeave +}, getListener = EventPluginHub_1.getListener; + +function listenerAtPhase(inst, event, propagationPhase) { + var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; + return getListener(inst, registrationName); +} + +function accumulateDirectionalDispatches(inst, phase, event) { + var listener = listenerAtPhase(inst, event, phase); + listener && (event._dispatchListeners = accumulateInto_1(event._dispatchListeners, listener), + event._dispatchInstances = accumulateInto_1(event._dispatchInstances, inst)); +} + +function accumulateTwoPhaseDispatchesSingle(event) { + event && event.dispatchConfig.phasedRegistrationNames && ReactTreeTraversal.traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event); +} + +function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { + if (event && event.dispatchConfig.phasedRegistrationNames) { + var targetInst = event._targetInst, parentInst = targetInst ? ReactTreeTraversal.getParentInstance(targetInst) : null; + ReactTreeTraversal.traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event); + } +} + +function accumulateDispatches(inst, ignoredDirection, event) { + if (inst && event && event.dispatchConfig.registrationName) { + var registrationName = event.dispatchConfig.registrationName, listener = getListener(inst, registrationName); + listener && (event._dispatchListeners = accumulateInto_1(event._dispatchListeners, listener), + event._dispatchInstances = accumulateInto_1(event._dispatchInstances, inst)); + } +} + +function accumulateDirectDispatchesSingle(event) { + event && event.dispatchConfig.registrationName && accumulateDispatches(event._targetInst, null, event); +} + +function accumulateTwoPhaseDispatches(events) { + forEachAccumulated_1(events, accumulateTwoPhaseDispatchesSingle); +} + +function accumulateTwoPhaseDispatchesSkipTarget(events) { + forEachAccumulated_1(events, accumulateTwoPhaseDispatchesSingleSkipTarget); +} + +function accumulateEnterLeaveDispatches(leave, enter, from, to) { + ReactTreeTraversal.traverseEnterLeave(from, to, accumulateDispatches, leave, enter); +} + +function accumulateDirectDispatches(events) { + forEachAccumulated_1(events, accumulateDirectDispatchesSingle); +} + +var EventPropagators = { + accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches, + accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget, + accumulateDirectDispatches: accumulateDirectDispatches, + accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches +}, EventPropagators_1 = EventPropagators, oneArgumentPooler = function(copyFieldsFrom) { + var Klass = this; + if (Klass.instancePool.length) { + var instance = Klass.instancePool.pop(); + return Klass.call(instance, copyFieldsFrom), instance; + } + return new Klass(copyFieldsFrom); +}, twoArgumentPooler = function(a1, a2) { + var Klass = this; + if (Klass.instancePool.length) { + var instance = Klass.instancePool.pop(); + return Klass.call(instance, a1, a2), instance; + } + return new Klass(a1, a2); +}, threeArgumentPooler = function(a1, a2, a3) { + var Klass = this; + if (Klass.instancePool.length) { + var instance = Klass.instancePool.pop(); + return Klass.call(instance, a1, a2, a3), instance; + } + return new Klass(a1, a2, a3); +}, fourArgumentPooler = function(a1, a2, a3, a4) { + var Klass = this; + if (Klass.instancePool.length) { + var instance = Klass.instancePool.pop(); + return Klass.call(instance, a1, a2, a3, a4), instance; + } + return new Klass(a1, a2, a3, a4); +}, standardReleaser = function(instance) { + var Klass = this; + invariant(instance instanceof Klass, "Trying to release an instance into a pool of a different type."), + instance.destructor(), Klass.instancePool.length < Klass.poolSize && Klass.instancePool.push(instance); +}, DEFAULT_POOL_SIZE = 10, DEFAULT_POOLER = oneArgumentPooler, addPoolingTo = function(CopyConstructor, pooler) { + var NewKlass = CopyConstructor; + return NewKlass.instancePool = [], NewKlass.getPooled = pooler || DEFAULT_POOLER, + NewKlass.poolSize || (NewKlass.poolSize = DEFAULT_POOL_SIZE), NewKlass.release = standardReleaser, + NewKlass; +}, PooledClass = { + addPoolingTo: addPoolingTo, + oneArgumentPooler: oneArgumentPooler, + twoArgumentPooler: twoArgumentPooler, + threeArgumentPooler: threeArgumentPooler, + fourArgumentPooler: fourArgumentPooler +}, PooledClass_1 = PooledClass, shouldBeReleasedProperties = [ "dispatchConfig", "_targetInst", "nativeEvent", "isDefaultPrevented", "isPropagationStopped", "_dispatchListeners", "_dispatchInstances" ], EventInterface = { + type: null, + target: null, + currentTarget: emptyFunction.thatReturnsNull, + eventPhase: null, + bubbles: null, + cancelable: null, + timeStamp: function(event) { + return event.timeStamp || Date.now(); + }, + defaultPrevented: null, + isTrusted: null +}; + +function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) { + this.dispatchConfig = dispatchConfig, this._targetInst = targetInst, this.nativeEvent = nativeEvent; + var Interface = this.constructor.Interface; + for (var propName in Interface) if (Interface.hasOwnProperty(propName)) { + var normalize = Interface[propName]; + normalize ? this[propName] = normalize(nativeEvent) : "target" === propName ? this.target = nativeEventTarget : this[propName] = nativeEvent[propName]; + } + var defaultPrevented = null != nativeEvent.defaultPrevented ? nativeEvent.defaultPrevented : !1 === nativeEvent.returnValue; + return this.isDefaultPrevented = defaultPrevented ? emptyFunction.thatReturnsTrue : emptyFunction.thatReturnsFalse, + this.isPropagationStopped = emptyFunction.thatReturnsFalse, this; +} + +Object.assign(SyntheticEvent.prototype, { + preventDefault: function() { + this.defaultPrevented = !0; + var event = this.nativeEvent; + event && (event.preventDefault ? event.preventDefault() : "unknown" != typeof event.returnValue && (event.returnValue = !1), + this.isDefaultPrevented = emptyFunction.thatReturnsTrue); + }, + stopPropagation: function() { + var event = this.nativeEvent; + event && (event.stopPropagation ? event.stopPropagation() : "unknown" != typeof event.cancelBubble && (event.cancelBubble = !0), + this.isPropagationStopped = emptyFunction.thatReturnsTrue); + }, + persist: function() { + this.isPersistent = emptyFunction.thatReturnsTrue; + }, + isPersistent: emptyFunction.thatReturnsFalse, + destructor: function() { + var Interface = this.constructor.Interface; + for (var propName in Interface) this[propName] = null; + for (var i = 0; i < shouldBeReleasedProperties.length; i++) this[shouldBeReleasedProperties[i]] = null; + } +}), SyntheticEvent.Interface = EventInterface, SyntheticEvent.augmentClass = function(Class, Interface) { + var Super = this, E = function() {}; + E.prototype = Super.prototype; + var prototype = new E(); + Object.assign(prototype, Class.prototype), Class.prototype = prototype, Class.prototype.constructor = Class, + Class.Interface = Object.assign({}, Super.Interface, Interface), Class.augmentClass = Super.augmentClass, + PooledClass_1.addPoolingTo(Class, PooledClass_1.fourArgumentPooler); +}, PooledClass_1.addPoolingTo(SyntheticEvent, PooledClass_1.fourArgumentPooler); + +var SyntheticEvent_1 = SyntheticEvent, _extends = Object.assign || function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]); + } + return target; +}, customBubblingEventTypes = UIManager.customBubblingEventTypes, customDirectEventTypes = UIManager.customDirectEventTypes, allTypesByEventName = {}; + +for (var bubblingTypeName in customBubblingEventTypes) allTypesByEventName[bubblingTypeName] = customBubblingEventTypes[bubblingTypeName]; + +for (var directTypeName in customDirectEventTypes) warning(!customBubblingEventTypes[directTypeName], "Event cannot be both direct and bubbling: %s", directTypeName), +allTypesByEventName[directTypeName] = customDirectEventTypes[directTypeName]; + +var ReactNativeBridgeEventPlugin = { + eventTypes: _extends({}, customBubblingEventTypes, customDirectEventTypes), + extractEvents: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) { + var bubbleDispatchConfig = customBubblingEventTypes[topLevelType], directDispatchConfig = customDirectEventTypes[topLevelType], event = SyntheticEvent_1.getPooled(bubbleDispatchConfig || directDispatchConfig, targetInst, nativeEvent, nativeEventTarget); + if (bubbleDispatchConfig) EventPropagators_1.accumulateTwoPhaseDispatches(event); else { + if (!directDispatchConfig) return null; + EventPropagators_1.accumulateDirectDispatches(event); + } + return event; + } +}, ReactNativeBridgeEventPlugin_1 = ReactNativeBridgeEventPlugin, instanceCache = {}, instanceProps = {}; + +function getRenderedHostOrTextFromComponent(component) { + for (var rendered; rendered = component._renderedComponent; ) component = rendered; + return component; +} + +function precacheNode(inst, tag) { + var nativeInst = getRenderedHostOrTextFromComponent(inst); + instanceCache[tag] = nativeInst; +} + +function precacheFiberNode(hostInst, tag) { + instanceCache[tag] = hostInst; +} + +function uncacheNode(inst) { + var tag = inst._rootNodeID; + tag && delete instanceCache[tag]; +} + +function uncacheFiberNode(tag) { + delete instanceCache[tag], delete instanceProps[tag]; +} + +function getInstanceFromTag(tag) { + return instanceCache[tag] || null; +} + +function getTagFromInstance(inst) { + var tag = "number" != typeof inst.tag ? inst._rootNodeID : inst.stateNode._nativeTag; + return invariant(tag, "All native instances should have a tag."), tag; +} + +function getFiberCurrentPropsFromNode(stateNode) { + return instanceProps[stateNode._nativeTag] || null; +} + +function updateFiberProps(tag, props) { + instanceProps[tag] = props; +} + +var ReactNativeComponentTree = { + getClosestInstanceFromNode: getInstanceFromTag, + getInstanceFromNode: getInstanceFromTag, + getNodeFromInstance: getTagFromInstance, + precacheFiberNode: precacheFiberNode, + precacheNode: precacheNode, + uncacheFiberNode: uncacheFiberNode, + uncacheNode: uncacheNode, + getFiberCurrentPropsFromNode: getFiberCurrentPropsFromNode, + updateFiberProps: updateFiberProps +}, ReactNativeComponentTree_1 = ReactNativeComponentTree; + +function runEventQueueInBatch(events) { + EventPluginHub_1.enqueueEvents(events), EventPluginHub_1.processEventQueue(!1); +} + +var ReactEventEmitterMixin = { + handleTopLevel: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) { + runEventQueueInBatch(EventPluginHub_1.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget)); + } +}, ReactEventEmitterMixin_1 = ReactEventEmitterMixin, INITIAL_TAG_COUNT = 1, ReactNativeTagHandles = { + tagsStartAt: INITIAL_TAG_COUNT, + tagCount: INITIAL_TAG_COUNT, + allocateTag: function() { + for (;this.reactTagIsNativeTopRootID(ReactNativeTagHandles.tagCount); ) ReactNativeTagHandles.tagCount++; + var tag = ReactNativeTagHandles.tagCount; + return ReactNativeTagHandles.tagCount++, tag; + }, + assertRootTag: function(tag) { + invariant(this.reactTagIsNativeTopRootID(tag), "Expect a native root tag, instead got %s", tag); + }, + reactTagIsNativeTopRootID: function(reactTag) { + return reactTag % 10 == 1; + } +}, ReactNativeTagHandles_1 = ReactNativeTagHandles, _extends$1 = Object.assign || function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]); + } + return target; +}, EMPTY_NATIVE_EVENT = {}, touchSubsequence = function(touches, indices) { + for (var ret = [], i = 0; i < indices.length; i++) ret.push(touches[indices[i]]); + return ret; +}, removeTouchesAtIndices = function(touches, indices) { + for (var rippedOut = [], temp = touches, i = 0; i < indices.length; i++) { + var index = indices[i]; + rippedOut.push(touches[index]), temp[index] = null; + } + for (var fillAt = 0, j = 0; j < temp.length; j++) { + var cur = temp[j]; + null !== cur && (temp[fillAt++] = cur); + } + return temp.length = fillAt, rippedOut; +}, ReactNativeEventEmitter = _extends$1({}, ReactEventEmitterMixin_1, { + registrationNames: EventPluginRegistry_1.registrationNameModules, + getListener: EventPluginHub_1.getListener, + _receiveRootNodeIDEvent: function(rootNodeID, topLevelType, nativeEventParam) { + var nativeEvent = nativeEventParam || EMPTY_NATIVE_EVENT, inst = ReactNativeComponentTree_1.getInstanceFromNode(rootNodeID); + ReactGenericBatching_1.batchedUpdates(function() { + ReactNativeEventEmitter.handleTopLevel(topLevelType, inst, nativeEvent, nativeEvent.target); + }); + }, + receiveEvent: function(tag, topLevelType, nativeEventParam) { + var rootNodeID = tag; + ReactNativeEventEmitter._receiveRootNodeIDEvent(rootNodeID, topLevelType, nativeEventParam); + }, + receiveTouches: function(eventTopLevelType, touches, changedIndices) { + for (var changedTouches = "topTouchEnd" === eventTopLevelType || "topTouchCancel" === eventTopLevelType ? removeTouchesAtIndices(touches, changedIndices) : touchSubsequence(touches, changedIndices), jj = 0; jj < changedTouches.length; jj++) { + var touch = changedTouches[jj]; + touch.changedTouches = changedTouches, touch.touches = touches; + var nativeEvent = touch, rootNodeID = null, target = nativeEvent.target; + null !== target && void 0 !== target && (target < ReactNativeTagHandles_1.tagsStartAt || (rootNodeID = target)), + ReactNativeEventEmitter._receiveRootNodeIDEvent(rootNodeID, eventTopLevelType, nativeEvent); + } + } +}), ReactNativeEventEmitter_1 = ReactNativeEventEmitter, ReactNativeEventPluginOrder = [ "ResponderEventPlugin", "ReactNativeBridgeEventPlugin" ], ReactNativeEventPluginOrder_1 = ReactNativeEventPluginOrder, ReactNativeGlobalResponderHandler = { + onChange: function(from, to, blockNativeResponder) { + if (null !== to) { + var tag = "number" != typeof to.tag ? to._rootNodeID : to.stateNode._nativeTag; + UIManager.setJSResponder(tag, blockNativeResponder); + } else UIManager.clearJSResponder(); + } +}, ReactNativeGlobalResponderHandler_1 = ReactNativeGlobalResponderHandler, ResponderEventInterface = { + touchHistory: function(nativeEvent) { + return null; + } +}; + +function ResponderSyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { + return SyntheticEvent_1.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); +} + +SyntheticEvent_1.augmentClass(ResponderSyntheticEvent, ResponderEventInterface); + +var ResponderSyntheticEvent_1 = ResponderSyntheticEvent, isEndish$2 = EventPluginUtils_1.isEndish, isMoveish$2 = EventPluginUtils_1.isMoveish, isStartish$2 = EventPluginUtils_1.isStartish, MAX_TOUCH_BANK = 20, touchBank = [], touchHistory = { + touchBank: touchBank, + numberActiveTouches: 0, + indexOfSingleActiveTouch: -1, + mostRecentTimeStamp: 0 +}; + +function timestampForTouch(touch) { + return touch.timeStamp || touch.timestamp; +} + +function createTouchRecord(touch) { + return { + touchActive: !0, + startPageX: touch.pageX, + startPageY: touch.pageY, + startTimeStamp: timestampForTouch(touch), + currentPageX: touch.pageX, + currentPageY: touch.pageY, + currentTimeStamp: timestampForTouch(touch), + previousPageX: touch.pageX, + previousPageY: touch.pageY, + previousTimeStamp: timestampForTouch(touch) + }; +} + +function resetTouchRecord(touchRecord, touch) { + touchRecord.touchActive = !0, touchRecord.startPageX = touch.pageX, touchRecord.startPageY = touch.pageY, + touchRecord.startTimeStamp = timestampForTouch(touch), touchRecord.currentPageX = touch.pageX, + touchRecord.currentPageY = touch.pageY, touchRecord.currentTimeStamp = timestampForTouch(touch), + touchRecord.previousPageX = touch.pageX, touchRecord.previousPageY = touch.pageY, + touchRecord.previousTimeStamp = timestampForTouch(touch); +} + +function getTouchIdentifier(_ref) { + var identifier = _ref.identifier; + return invariant(null != identifier, "Touch object is missing identifier."), warning(identifier <= MAX_TOUCH_BANK, "Touch identifier %s is greater than maximum supported %s which causes " + "performance issues backfilling array locations for all of the indices.", identifier, MAX_TOUCH_BANK), + identifier; +} + +function recordTouchStart(touch) { + var identifier = getTouchIdentifier(touch), touchRecord = touchBank[identifier]; + touchRecord ? resetTouchRecord(touchRecord, touch) : touchBank[identifier] = createTouchRecord(touch), + touchHistory.mostRecentTimeStamp = timestampForTouch(touch); +} + +function recordTouchMove(touch) { + var touchRecord = touchBank[getTouchIdentifier(touch)]; + touchRecord ? (touchRecord.touchActive = !0, touchRecord.previousPageX = touchRecord.currentPageX, + touchRecord.previousPageY = touchRecord.currentPageY, touchRecord.previousTimeStamp = touchRecord.currentTimeStamp, + touchRecord.currentPageX = touch.pageX, touchRecord.currentPageY = touch.pageY, + touchRecord.currentTimeStamp = timestampForTouch(touch), touchHistory.mostRecentTimeStamp = timestampForTouch(touch)) : console.error("Cannot record touch move without a touch start.\n" + "Touch Move: %s\n", "Touch Bank: %s", printTouch(touch), printTouchBank()); +} + +function recordTouchEnd(touch) { + var touchRecord = touchBank[getTouchIdentifier(touch)]; + touchRecord ? (touchRecord.touchActive = !1, touchRecord.previousPageX = touchRecord.currentPageX, + touchRecord.previousPageY = touchRecord.currentPageY, touchRecord.previousTimeStamp = touchRecord.currentTimeStamp, + touchRecord.currentPageX = touch.pageX, touchRecord.currentPageY = touch.pageY, + touchRecord.currentTimeStamp = timestampForTouch(touch), touchHistory.mostRecentTimeStamp = timestampForTouch(touch)) : console.error("Cannot record touch end without a touch start.\n" + "Touch End: %s\n", "Touch Bank: %s", printTouch(touch), printTouchBank()); +} + +function printTouch(touch) { + return JSON.stringify({ + identifier: touch.identifier, + pageX: touch.pageX, + pageY: touch.pageY, + timestamp: timestampForTouch(touch) + }); +} + +function printTouchBank() { + var printed = JSON.stringify(touchBank.slice(0, MAX_TOUCH_BANK)); + return touchBank.length > MAX_TOUCH_BANK && (printed += " (original size: " + touchBank.length + ")"), + printed; +} + +var ResponderTouchHistoryStore = { + recordTouchTrack: function(topLevelType, nativeEvent) { + if (isMoveish$2(topLevelType)) nativeEvent.changedTouches.forEach(recordTouchMove); else if (isStartish$2(topLevelType)) nativeEvent.changedTouches.forEach(recordTouchStart), + touchHistory.numberActiveTouches = nativeEvent.touches.length, 1 === touchHistory.numberActiveTouches && (touchHistory.indexOfSingleActiveTouch = nativeEvent.touches[0].identifier); else if (isEndish$2(topLevelType) && (nativeEvent.changedTouches.forEach(recordTouchEnd), + touchHistory.numberActiveTouches = nativeEvent.touches.length, 1 === touchHistory.numberActiveTouches)) for (var i = 0; i < touchBank.length; i++) { + var touchTrackToCheck = touchBank[i]; + if (null != touchTrackToCheck && touchTrackToCheck.touchActive) { + touchHistory.indexOfSingleActiveTouch = i; + break; + } + } + }, + touchHistory: touchHistory +}, ResponderTouchHistoryStore_1 = ResponderTouchHistoryStore; + +function accumulate(current, next) { + return invariant(null != next, "accumulate(...): Accumulated items must be not be null or undefined."), + null == current ? next : Array.isArray(current) ? current.concat(next) : Array.isArray(next) ? [ current ].concat(next) : [ current, next ]; +} + +var accumulate_1 = accumulate, isStartish$1 = EventPluginUtils_1.isStartish, isMoveish$1 = EventPluginUtils_1.isMoveish, isEndish$1 = EventPluginUtils_1.isEndish, executeDirectDispatch$1 = EventPluginUtils_1.executeDirectDispatch, hasDispatches$1 = EventPluginUtils_1.hasDispatches, executeDispatchesInOrderStopAtTrue$1 = EventPluginUtils_1.executeDispatchesInOrderStopAtTrue, responderInst = null, trackedTouchCount = 0, previousActiveTouches = 0, changeResponder = function(nextResponderInst, blockHostResponder) { + var oldResponderInst = responderInst; + responderInst = nextResponderInst, null !== ResponderEventPlugin.GlobalResponderHandler && ResponderEventPlugin.GlobalResponderHandler.onChange(oldResponderInst, nextResponderInst, blockHostResponder); +}, eventTypes = { + startShouldSetResponder: { + phasedRegistrationNames: { + bubbled: "onStartShouldSetResponder", + captured: "onStartShouldSetResponderCapture" + } + }, + scrollShouldSetResponder: { + phasedRegistrationNames: { + bubbled: "onScrollShouldSetResponder", + captured: "onScrollShouldSetResponderCapture" + } + }, + selectionChangeShouldSetResponder: { + phasedRegistrationNames: { + bubbled: "onSelectionChangeShouldSetResponder", + captured: "onSelectionChangeShouldSetResponderCapture" + } + }, + moveShouldSetResponder: { + phasedRegistrationNames: { + bubbled: "onMoveShouldSetResponder", + captured: "onMoveShouldSetResponderCapture" + } + }, + responderStart: { + registrationName: "onResponderStart" + }, + responderMove: { + registrationName: "onResponderMove" + }, + responderEnd: { + registrationName: "onResponderEnd" + }, + responderRelease: { + registrationName: "onResponderRelease" + }, + responderTerminationRequest: { + registrationName: "onResponderTerminationRequest" + }, + responderGrant: { + registrationName: "onResponderGrant" + }, + responderReject: { + registrationName: "onResponderReject" + }, + responderTerminate: { + registrationName: "onResponderTerminate" + } +}; + +function setResponderAndExtractTransfer(topLevelType, targetInst, nativeEvent, nativeEventTarget) { + var shouldSetEventType = isStartish$1(topLevelType) ? eventTypes.startShouldSetResponder : isMoveish$1(topLevelType) ? eventTypes.moveShouldSetResponder : "topSelectionChange" === topLevelType ? eventTypes.selectionChangeShouldSetResponder : eventTypes.scrollShouldSetResponder, bubbleShouldSetFrom = responderInst ? ReactTreeTraversal.getLowestCommonAncestor(responderInst, targetInst) : targetInst, skipOverBubbleShouldSetFrom = bubbleShouldSetFrom === responderInst, shouldSetEvent = ResponderSyntheticEvent_1.getPooled(shouldSetEventType, bubbleShouldSetFrom, nativeEvent, nativeEventTarget); + shouldSetEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, skipOverBubbleShouldSetFrom ? EventPropagators_1.accumulateTwoPhaseDispatchesSkipTarget(shouldSetEvent) : EventPropagators_1.accumulateTwoPhaseDispatches(shouldSetEvent); + var wantsResponderInst = executeDispatchesInOrderStopAtTrue$1(shouldSetEvent); + if (shouldSetEvent.isPersistent() || shouldSetEvent.constructor.release(shouldSetEvent), + !wantsResponderInst || wantsResponderInst === responderInst) return null; + var extracted, grantEvent = ResponderSyntheticEvent_1.getPooled(eventTypes.responderGrant, wantsResponderInst, nativeEvent, nativeEventTarget); + grantEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, EventPropagators_1.accumulateDirectDispatches(grantEvent); + var blockHostResponder = !0 === executeDirectDispatch$1(grantEvent); + if (responderInst) { + var terminationRequestEvent = ResponderSyntheticEvent_1.getPooled(eventTypes.responderTerminationRequest, responderInst, nativeEvent, nativeEventTarget); + terminationRequestEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, + EventPropagators_1.accumulateDirectDispatches(terminationRequestEvent); + var shouldSwitch = !hasDispatches$1(terminationRequestEvent) || executeDirectDispatch$1(terminationRequestEvent); + if (terminationRequestEvent.isPersistent() || terminationRequestEvent.constructor.release(terminationRequestEvent), + shouldSwitch) { + var terminateEvent = ResponderSyntheticEvent_1.getPooled(eventTypes.responderTerminate, responderInst, nativeEvent, nativeEventTarget); + terminateEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, EventPropagators_1.accumulateDirectDispatches(terminateEvent), + extracted = accumulate_1(extracted, [ grantEvent, terminateEvent ]), changeResponder(wantsResponderInst, blockHostResponder); + } else { + var rejectEvent = ResponderSyntheticEvent_1.getPooled(eventTypes.responderReject, wantsResponderInst, nativeEvent, nativeEventTarget); + rejectEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, EventPropagators_1.accumulateDirectDispatches(rejectEvent), + extracted = accumulate_1(extracted, rejectEvent); + } + } else extracted = accumulate_1(extracted, grantEvent), changeResponder(wantsResponderInst, blockHostResponder); + return extracted; +} + +function canTriggerTransfer(topLevelType, topLevelInst, nativeEvent) { + return topLevelInst && ("topScroll" === topLevelType && !nativeEvent.responderIgnoreScroll || trackedTouchCount > 0 && "topSelectionChange" === topLevelType || isStartish$1(topLevelType) || isMoveish$1(topLevelType)); +} + +function noResponderTouches(nativeEvent) { + var touches = nativeEvent.touches; + if (!touches || 0 === touches.length) return !0; + for (var i = 0; i < touches.length; i++) { + var activeTouch = touches[i], target = activeTouch.target; + if (null !== target && void 0 !== target && 0 !== target) { + var targetInst = EventPluginUtils_1.getInstanceFromNode(target); + if (ReactTreeTraversal.isAncestor(responderInst, targetInst)) return !1; + } + } + return !0; +} + +var ResponderEventPlugin = { + _getResponder: function() { + return responderInst; + }, + eventTypes: eventTypes, + extractEvents: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) { + if (isStartish$1(topLevelType)) trackedTouchCount += 1; else if (isEndish$1(topLevelType)) { + if (!(trackedTouchCount >= 0)) return console.error("Ended a touch event which was not counted in `trackedTouchCount`."), + null; + trackedTouchCount -= 1; + } + ResponderTouchHistoryStore_1.recordTouchTrack(topLevelType, nativeEvent); + var extracted = canTriggerTransfer(topLevelType, targetInst, nativeEvent) ? setResponderAndExtractTransfer(topLevelType, targetInst, nativeEvent, nativeEventTarget) : null, isResponderTouchStart = responderInst && isStartish$1(topLevelType), isResponderTouchMove = responderInst && isMoveish$1(topLevelType), isResponderTouchEnd = responderInst && isEndish$1(topLevelType), incrementalTouch = isResponderTouchStart ? eventTypes.responderStart : isResponderTouchMove ? eventTypes.responderMove : isResponderTouchEnd ? eventTypes.responderEnd : null; + if (incrementalTouch) { + var gesture = ResponderSyntheticEvent_1.getPooled(incrementalTouch, responderInst, nativeEvent, nativeEventTarget); + gesture.touchHistory = ResponderTouchHistoryStore_1.touchHistory, EventPropagators_1.accumulateDirectDispatches(gesture), + extracted = accumulate_1(extracted, gesture); + } + var isResponderTerminate = responderInst && "topTouchCancel" === topLevelType, isResponderRelease = responderInst && !isResponderTerminate && isEndish$1(topLevelType) && noResponderTouches(nativeEvent), finalTouch = isResponderTerminate ? eventTypes.responderTerminate : isResponderRelease ? eventTypes.responderRelease : null; + if (finalTouch) { + var finalEvent = ResponderSyntheticEvent_1.getPooled(finalTouch, responderInst, nativeEvent, nativeEventTarget); + finalEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, EventPropagators_1.accumulateDirectDispatches(finalEvent), + extracted = accumulate_1(extracted, finalEvent), changeResponder(null); + } + var numberActiveTouches = ResponderTouchHistoryStore_1.touchHistory.numberActiveTouches; + return ResponderEventPlugin.GlobalInteractionHandler && numberActiveTouches !== previousActiveTouches && ResponderEventPlugin.GlobalInteractionHandler.onChange(numberActiveTouches), + previousActiveTouches = numberActiveTouches, extracted; + }, + GlobalResponderHandler: null, + GlobalInteractionHandler: null, + injection: { + injectGlobalResponderHandler: function(GlobalResponderHandler) { + ResponderEventPlugin.GlobalResponderHandler = GlobalResponderHandler; + }, + injectGlobalInteractionHandler: function(GlobalInteractionHandler) { + ResponderEventPlugin.GlobalInteractionHandler = GlobalInteractionHandler; + } + } +}, ResponderEventPlugin_1 = ResponderEventPlugin; + +function inject() { + RCTEventEmitter.register(ReactNativeEventEmitter_1), EventPluginHub_1.injection.injectEventPluginOrder(ReactNativeEventPluginOrder_1), + EventPluginUtils_1.injection.injectComponentTree(ReactNativeComponentTree_1), ResponderEventPlugin_1.injection.injectGlobalResponderHandler(ReactNativeGlobalResponderHandler_1), + EventPluginHub_1.injection.injectEventPluginsByName({ + ResponderEventPlugin: ResponderEventPlugin_1, + ReactNativeBridgeEventPlugin: ReactNativeBridgeEventPlugin_1 + }); +} + +var ReactNativeInjection = { + inject: inject +}, REACT_PORTAL_TYPE = "function" == typeof Symbol && Symbol.for && Symbol.for("react.portal") || 60106, createPortal = function(children, containerInfo, implementation) { + var key = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : null; + return { + $$typeof: REACT_PORTAL_TYPE, + key: null == key ? null : "" + key, + children: children, + containerInfo: containerInfo, + implementation: implementation + }; +}, isPortal = function(object) { + return "object" == typeof object && null !== object && object.$$typeof === REACT_PORTAL_TYPE; +}, REACT_PORTAL_TYPE_1 = REACT_PORTAL_TYPE, ReactPortal = { + createPortal: createPortal, + isPortal: isPortal, + REACT_PORTAL_TYPE: REACT_PORTAL_TYPE_1 +}, commonjsGlobal = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof self ? self : {}, ReactFeatureFlags = { + logTopLevelRenders: !1, + prepareNewChildrenBeforeUnmountInStack: !0, + disableNewFiberFeatures: !1, + enableAsyncSubtreeAPI: !1 +}, ReactFeatureFlags_1 = ReactFeatureFlags, ReactTypeOfSideEffect = { + NoEffect: 0, + Placement: 1, + Update: 2, + PlacementAndUpdate: 3, + Deletion: 4, + ContentReset: 8, + Callback: 16, + Err: 32, + Ref: 64 +}, ReactPriorityLevel = { + NoWork: 0, + SynchronousPriority: 1, + TaskPriority: 2, + AnimationPriority: 3, + HighPriority: 4, + LowPriority: 5, + OffscreenPriority: 6 +}, CallbackEffect = ReactTypeOfSideEffect.Callback, NoWork = ReactPriorityLevel.NoWork, SynchronousPriority = ReactPriorityLevel.SynchronousPriority, TaskPriority = ReactPriorityLevel.TaskPriority; + +function comparePriority(a, b) { + return a !== TaskPriority && a !== SynchronousPriority || b !== TaskPriority && b !== SynchronousPriority ? a === NoWork && b !== NoWork ? -255 : a !== NoWork && b === NoWork ? 255 : a - b : 0; +} + +function ensureUpdateQueue(fiber) { + if (null !== fiber.updateQueue) return fiber.updateQueue; + var queue = void 0; + return queue = { + first: null, + last: null, + hasForceUpdate: !1, + callbackList: null + }, fiber.updateQueue = queue, queue; +} + +function cloneUpdateQueue(current, workInProgress) { + var currentQueue = current.updateQueue; + if (null === currentQueue) return workInProgress.updateQueue = null, null; + var altQueue = null !== workInProgress.updateQueue ? workInProgress.updateQueue : {}; + return altQueue.first = currentQueue.first, altQueue.last = currentQueue.last, altQueue.hasForceUpdate = !1, + altQueue.callbackList = null, altQueue.isProcessing = !1, workInProgress.updateQueue = altQueue, + altQueue; +} + +var cloneUpdateQueue_1 = cloneUpdateQueue; + +function cloneUpdate(update) { + return { + priorityLevel: update.priorityLevel, + partialState: update.partialState, + callback: update.callback, + isReplace: update.isReplace, + isForced: update.isForced, + isTopLevelUnmount: update.isTopLevelUnmount, + next: null + }; +} + +function insertUpdateIntoQueue(queue, update, insertAfter, insertBefore) { + null !== insertAfter ? insertAfter.next = update : (update.next = queue.first, queue.first = update), + null !== insertBefore ? update.next = insertBefore : queue.last = update; +} + +function findInsertionPosition(queue, update) { + var priorityLevel = update.priorityLevel, insertAfter = null, insertBefore = null; + if (null !== queue.last && comparePriority(queue.last.priorityLevel, priorityLevel) <= 0) insertAfter = queue.last; else for (insertBefore = queue.first; null !== insertBefore && comparePriority(insertBefore.priorityLevel, priorityLevel) <= 0; ) insertAfter = insertBefore, + insertBefore = insertBefore.next; + return insertAfter; +} + +function insertUpdate(fiber, update) { + var queue1 = ensureUpdateQueue(fiber), queue2 = null !== fiber.alternate ? ensureUpdateQueue(fiber.alternate) : null, insertAfter1 = findInsertionPosition(queue1, update), insertBefore1 = null !== insertAfter1 ? insertAfter1.next : queue1.first; + if (null === queue2) return insertUpdateIntoQueue(queue1, update, insertAfter1, insertBefore1), + null; + var insertAfter2 = findInsertionPosition(queue2, update), insertBefore2 = null !== insertAfter2 ? insertAfter2.next : queue2.first; + if (insertUpdateIntoQueue(queue1, update, insertAfter1, insertBefore1), insertBefore1 !== insertBefore2) { + var update2 = cloneUpdate(update); + return insertUpdateIntoQueue(queue2, update2, insertAfter2, insertBefore2), update2; + } + return null === insertAfter2 && (queue2.first = update), null === insertBefore2 && (queue2.last = null), + null; +} + +function addUpdate(fiber, partialState, callback, priorityLevel) { + insertUpdate(fiber, { + priorityLevel: priorityLevel, + partialState: partialState, + callback: callback, + isReplace: !1, + isForced: !1, + isTopLevelUnmount: !1, + next: null + }); +} + +var addUpdate_1 = addUpdate; + +function addReplaceUpdate(fiber, state, callback, priorityLevel) { + insertUpdate(fiber, { + priorityLevel: priorityLevel, + partialState: state, + callback: callback, + isReplace: !0, + isForced: !1, + isTopLevelUnmount: !1, + next: null + }); +} + +var addReplaceUpdate_1 = addReplaceUpdate; + +function addForceUpdate(fiber, callback, priorityLevel) { + insertUpdate(fiber, { + priorityLevel: priorityLevel, + partialState: null, + callback: callback, + isReplace: !1, + isForced: !0, + isTopLevelUnmount: !1, + next: null + }); +} + +var addForceUpdate_1 = addForceUpdate; + +function getPendingPriority(queue) { + return null !== queue.first ? queue.first.priorityLevel : NoWork; +} + +var getPendingPriority_1 = getPendingPriority; + +function addTopLevelUpdate$1(fiber, partialState, callback, priorityLevel) { + var isTopLevelUnmount = null === partialState.element, update = { + priorityLevel: priorityLevel, + partialState: partialState, + callback: callback, + isReplace: !1, + isForced: !1, + isTopLevelUnmount: isTopLevelUnmount, + next: null + }, update2 = insertUpdate(fiber, update); + if (isTopLevelUnmount) { + var queue1 = fiber.updateQueue, queue2 = null !== fiber.alternate ? fiber.alternate.updateQueue : null; + null !== queue1 && null !== update.next && (update.next = null, queue1.last = update), + null !== queue2 && null !== update2 && null !== update2.next && (update2.next = null, + queue2.last = update); + } +} + +var addTopLevelUpdate_1 = addTopLevelUpdate$1; + +function getStateFromUpdate(update, instance, prevState, props) { + var partialState = update.partialState; + if ("function" == typeof partialState) { + return partialState.call(instance, prevState, props); + } + return partialState; +} + +function beginUpdateQueue(workInProgress, queue, instance, prevState, props, priorityLevel) { + queue.hasForceUpdate = !1; + for (var state = prevState, dontMutatePrevState = !0, callbackList = queue.callbackList, update = queue.first; null !== update && comparePriority(update.priorityLevel, priorityLevel) <= 0; ) { + queue.first = update.next, null === queue.first && (queue.last = null); + var _partialState = void 0; + update.isReplace ? (state = getStateFromUpdate(update, instance, state, props), + dontMutatePrevState = !0) : (_partialState = getStateFromUpdate(update, instance, state, props)) && (state = dontMutatePrevState ? Object.assign({}, state, _partialState) : Object.assign(state, _partialState), + dontMutatePrevState = !1), update.isForced && (queue.hasForceUpdate = !0), null === update.callback || update.isTopLevelUnmount && null !== update.next || (callbackList = callbackList || [], + callbackList.push(update.callback), workInProgress.effectTag |= CallbackEffect), + update = update.next; + } + return queue.callbackList = callbackList, null !== queue.first || null !== callbackList || queue.hasForceUpdate || (workInProgress.updateQueue = null), + state; +} + +var beginUpdateQueue_1 = beginUpdateQueue; + +function commitCallbacks(finishedWork, queue, context) { + var callbackList = queue.callbackList; + if (null !== callbackList) for (var i = 0; i < callbackList.length; i++) { + var _callback = callbackList[i]; + invariant("function" == typeof _callback, "Invalid argument passed as callback. Expected a function. Instead " + "received: %s", _callback), + _callback.call(context); + } +} + +var commitCallbacks_1 = commitCallbacks, ReactFiberUpdateQueue = { + cloneUpdateQueue: cloneUpdateQueue_1, + addUpdate: addUpdate_1, + addReplaceUpdate: addReplaceUpdate_1, + addForceUpdate: addForceUpdate_1, + getPendingPriority: getPendingPriority_1, + addTopLevelUpdate: addTopLevelUpdate_1, + beginUpdateQueue: beginUpdateQueue_1, + commitCallbacks: commitCallbacks_1 +}; + +function getComponentName$1(instanceOrFiber) { + if ("function" == typeof instanceOrFiber.getName) { + return instanceOrFiber.getName(); + } + if ("number" == typeof instanceOrFiber.tag) { + var fiber = instanceOrFiber, type = fiber.type; + if ("string" == typeof type) return type; + if ("function" == typeof type) return type.displayName || type.name; + } + return null; +} + +var getComponentName_1 = getComponentName$1, ReactInstanceMap = { + remove: function(key) { + key._reactInternalInstance = void 0; + }, + get: function(key) { + return key._reactInternalInstance; + }, + has: function(key) { + return void 0 !== key._reactInternalInstance; + }, + set: function(key, value) { + key._reactInternalInstance = value; + } +}, ReactInstanceMap_1 = ReactInstanceMap, ReactInternals = react.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, ReactGlobalSharedState = { + ReactCurrentOwner: ReactInternals.ReactCurrentOwner +}, ReactGlobalSharedState_1 = ReactGlobalSharedState, HostRoot$1 = ReactTypeOfWork.HostRoot, HostComponent$1 = ReactTypeOfWork.HostComponent, HostText = ReactTypeOfWork.HostText, NoEffect = ReactTypeOfSideEffect.NoEffect, Placement = ReactTypeOfSideEffect.Placement, MOUNTING = 1, MOUNTED = 2, UNMOUNTED = 3; + +function isFiberMountedImpl(fiber) { + var node = fiber; + if (fiber.alternate) for (;node.return; ) node = node.return; else { + if ((node.effectTag & Placement) !== NoEffect) return MOUNTING; + for (;node.return; ) if (node = node.return, (node.effectTag & Placement) !== NoEffect) return MOUNTING; + } + return node.tag === HostRoot$1 ? MOUNTED : UNMOUNTED; +} + +var isFiberMounted$1 = function(fiber) { + return isFiberMountedImpl(fiber) === MOUNTED; +}, isMounted = function(component) { + var fiber = ReactInstanceMap_1.get(component); + return !!fiber && isFiberMountedImpl(fiber) === MOUNTED; +}; + +function assertIsMounted(fiber) { + invariant(isFiberMountedImpl(fiber) === MOUNTED, "Unable to find node on an unmounted component."); +} + +function findCurrentFiberUsingSlowPath(fiber) { + var alternate = fiber.alternate; + if (!alternate) { + var state = isFiberMountedImpl(fiber); + return invariant(state !== UNMOUNTED, "Unable to find node on an unmounted component."), + state === MOUNTING ? null : fiber; + } + for (var a = fiber, b = alternate; !0; ) { + var parentA = a.return, parentB = parentA ? parentA.alternate : null; + if (!parentA || !parentB) break; + if (parentA.child === parentB.child) { + for (var child = parentA.child; child; ) { + if (child === a) return assertIsMounted(parentA), fiber; + if (child === b) return assertIsMounted(parentA), alternate; + child = child.sibling; + } + invariant(!1, "Unable to find node on an unmounted component."); + } + if (a.return !== b.return) a = parentA, b = parentB; else { + for (var didFindChild = !1, _child = parentA.child; _child; ) { + if (_child === a) { + didFindChild = !0, a = parentA, b = parentB; + break; + } + if (_child === b) { + didFindChild = !0, b = parentA, a = parentB; + break; + } + _child = _child.sibling; + } + if (!didFindChild) { + for (_child = parentB.child; _child; ) { + if (_child === a) { + didFindChild = !0, a = parentB, b = parentA; + break; + } + if (_child === b) { + didFindChild = !0, b = parentB, a = parentA; + break; + } + _child = _child.sibling; + } + invariant(didFindChild, "Child was not found in either parent set. This indicates a bug " + "related to the return pointer."); + } + } + invariant(a.alternate === b, "Return fibers should always be each others' alternates."); + } + return invariant(a.tag === HostRoot$1, "Unable to find node on an unmounted component."), + a.stateNode.current === a ? fiber : alternate; +} + +var findCurrentFiberUsingSlowPath_1 = findCurrentFiberUsingSlowPath, findCurrentHostFiber$1 = function(parent) { + var currentParent = findCurrentFiberUsingSlowPath(parent); + if (!currentParent) return null; + for (var node = currentParent; !0; ) { + if (node.tag === HostComponent$1 || node.tag === HostText) return node; + if (node.child) node.child.return = node, node = node.child; else { + if (node === currentParent) return null; + for (;!node.sibling; ) { + if (!node.return || node.return === currentParent) return null; + node = node.return; + } + node.sibling.return = node.return, node = node.sibling; + } + } + return null; +}, ReactFiberTreeReflection = { + isFiberMounted: isFiberMounted$1, + isMounted: isMounted, + findCurrentFiberUsingSlowPath: findCurrentFiberUsingSlowPath_1, + findCurrentHostFiber: findCurrentHostFiber$1 +}, valueStack = [], index = -1, createCursor$1 = function(defaultValue) { + return { + current: defaultValue + }; +}, isEmpty = function() { + return -1 === index; +}, pop$1 = function(cursor, fiber) { + index < 0 || (cursor.current = valueStack[index], valueStack[index] = null, index--); +}, push$1 = function(cursor, value, fiber) { + index++, valueStack[index] = cursor.current, cursor.current = value; +}, reset = function() { + for (;index > -1; ) valueStack[index] = null, index--; +}, ReactFiberStack = { + createCursor: createCursor$1, + isEmpty: isEmpty, + pop: pop$1, + push: push$1, + reset: reset +}, _extends$2 = Object.assign || function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]); + } + return target; +}, isFiberMounted = ReactFiberTreeReflection.isFiberMounted, ClassComponent = ReactTypeOfWork.ClassComponent, HostRoot = ReactTypeOfWork.HostRoot, createCursor = ReactFiberStack.createCursor, pop = ReactFiberStack.pop, push = ReactFiberStack.push, contextStackCursor = createCursor(emptyObject), didPerformWorkStackCursor = createCursor(!1), previousContext = emptyObject; + +function getUnmaskedContext(workInProgress) { + return isContextProvider$1(workInProgress) ? previousContext : contextStackCursor.current; +} + +var getUnmaskedContext_1 = getUnmaskedContext; + +function cacheContext(workInProgress, unmaskedContext, maskedContext) { + var instance = workInProgress.stateNode; + instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext, instance.__reactInternalMemoizedMaskedChildContext = maskedContext; +} + +var cacheContext_1 = cacheContext, getMaskedContext = function(workInProgress, unmaskedContext) { + var type = workInProgress.type, contextTypes = type.contextTypes; + if (!contextTypes) return emptyObject; + var instance = workInProgress.stateNode; + if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) return instance.__reactInternalMemoizedMaskedChildContext; + var context = {}; + for (var key in contextTypes) context[key] = unmaskedContext[key]; + return instance && cacheContext(workInProgress, unmaskedContext, context), context; +}, hasContextChanged = function() { + return didPerformWorkStackCursor.current; +}; + +function isContextConsumer(fiber) { + return fiber.tag === ClassComponent && null != fiber.type.contextTypes; +} + +var isContextConsumer_1 = isContextConsumer; + +function isContextProvider$1(fiber) { + return fiber.tag === ClassComponent && null != fiber.type.childContextTypes; +} + +var isContextProvider_1 = isContextProvider$1; + +function popContextProvider(fiber) { + isContextProvider$1(fiber) && (pop(didPerformWorkStackCursor, fiber), pop(contextStackCursor, fiber)); +} + +var popContextProvider_1 = popContextProvider, pushTopLevelContextObject = function(fiber, context, didChange) { + invariant(null == contextStackCursor.cursor, "Unexpected context found on stack"), + push(contextStackCursor, context, fiber), push(didPerformWorkStackCursor, didChange, fiber); +}; + +function processChildContext$1(fiber, parentContext, isReconciling) { + var instance = fiber.stateNode, childContextTypes = fiber.type.childContextTypes; + if ("function" != typeof instance.getChildContext) return parentContext; + var childContext = void 0; + childContext = instance.getChildContext(); + for (var contextKey in childContext) invariant(contextKey in childContextTypes, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', getComponentName_1(fiber) || "Unknown", contextKey); + return _extends$2({}, parentContext, childContext); +} + +var processChildContext_1 = processChildContext$1, pushContextProvider = function(workInProgress) { + if (!isContextProvider$1(workInProgress)) return !1; + var instance = workInProgress.stateNode, memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyObject; + return previousContext = contextStackCursor.current, push(contextStackCursor, memoizedMergedChildContext, workInProgress), + push(didPerformWorkStackCursor, !1, workInProgress), !0; +}, invalidateContextProvider = function(workInProgress) { + var instance = workInProgress.stateNode; + invariant(instance, "Expected to have an instance by this point."); + var mergedContext = processChildContext$1(workInProgress, previousContext, !0); + instance.__reactInternalMemoizedMergedChildContext = mergedContext, pop(didPerformWorkStackCursor, workInProgress), + pop(contextStackCursor, workInProgress), push(contextStackCursor, mergedContext, workInProgress), + push(didPerformWorkStackCursor, !0, workInProgress); +}, resetContext = function() { + previousContext = emptyObject, contextStackCursor.current = emptyObject, didPerformWorkStackCursor.current = !1; +}, findCurrentUnmaskedContext$1 = function(fiber) { + invariant(isFiberMounted(fiber) && fiber.tag === ClassComponent, "Expected subtree parent to be a mounted class component"); + for (var node = fiber; node.tag !== HostRoot; ) { + if (isContextProvider$1(node)) return node.stateNode.__reactInternalMemoizedMergedChildContext; + var parent = node.return; + invariant(parent, "Found unexpected detached subtree parent"), node = parent; + } + return node.stateNode.context; +}, ReactFiberContext = { + getUnmaskedContext: getUnmaskedContext_1, + cacheContext: cacheContext_1, + getMaskedContext: getMaskedContext, + hasContextChanged: hasContextChanged, + isContextConsumer: isContextConsumer_1, + isContextProvider: isContextProvider_1, + popContextProvider: popContextProvider_1, + pushTopLevelContextObject: pushTopLevelContextObject, + processChildContext: processChildContext_1, + pushContextProvider: pushContextProvider, + invalidateContextProvider: invalidateContextProvider, + resetContext: resetContext, + findCurrentUnmaskedContext: findCurrentUnmaskedContext$1 +}, ReactTypeOfInternalContext = { + NoContext: 0, + AsyncUpdates: 1 +}, IndeterminateComponent = ReactTypeOfWork.IndeterminateComponent, ClassComponent$2 = ReactTypeOfWork.ClassComponent, HostRoot$2 = ReactTypeOfWork.HostRoot, HostComponent$2 = ReactTypeOfWork.HostComponent, HostText$1 = ReactTypeOfWork.HostText, HostPortal = ReactTypeOfWork.HostPortal, CoroutineComponent = ReactTypeOfWork.CoroutineComponent, YieldComponent = ReactTypeOfWork.YieldComponent, Fragment = ReactTypeOfWork.Fragment, NoWork$1 = ReactPriorityLevel.NoWork, NoContext = ReactTypeOfInternalContext.NoContext, NoEffect$1 = ReactTypeOfSideEffect.NoEffect, cloneUpdateQueue$1 = ReactFiberUpdateQueue.cloneUpdateQueue, createFiber = function(tag, key, internalContextTag) { + return { + tag: tag, + key: key, + type: null, + stateNode: null, + return: null, + child: null, + sibling: null, + index: 0, + ref: null, + pendingProps: null, + memoizedProps: null, + updateQueue: null, + memoizedState: null, + internalContextTag: internalContextTag, + effectTag: NoEffect$1, + nextEffect: null, + firstEffect: null, + lastEffect: null, + pendingWorkPriority: NoWork$1, + progressedPriority: NoWork$1, + progressedChild: null, + progressedFirstDeletion: null, + progressedLastDeletion: null, + alternate: null + }; +}; + +function shouldConstruct(Component) { + return !(!Component.prototype || !Component.prototype.isReactComponent); +} + +var cloneFiber = function(fiber, priorityLevel) { + var alt = fiber.alternate; + return null !== alt ? (alt.effectTag = NoEffect$1, alt.nextEffect = null, alt.firstEffect = null, + alt.lastEffect = null) : (alt = createFiber(fiber.tag, fiber.key, fiber.internalContextTag), + alt.type = fiber.type, alt.progressedChild = fiber.progressedChild, alt.progressedPriority = fiber.progressedPriority, + alt.alternate = fiber, fiber.alternate = alt), alt.stateNode = fiber.stateNode, + alt.child = fiber.child, alt.sibling = fiber.sibling, alt.index = fiber.index, alt.ref = fiber.ref, + alt.pendingProps = fiber.pendingProps, cloneUpdateQueue$1(fiber, alt), alt.pendingWorkPriority = priorityLevel, + alt.memoizedProps = fiber.memoizedProps, alt.memoizedState = fiber.memoizedState, + alt; +}, createHostRootFiber$1 = function() { + return createFiber(HostRoot$2, null, NoContext); +}, createFiberFromElement = function(element, internalContextTag, priorityLevel) { + var owner = null, fiber = createFiberFromElementType(element.type, element.key, internalContextTag, owner); + return fiber.pendingProps = element.props, fiber.pendingWorkPriority = priorityLevel, + fiber; +}, createFiberFromFragment = function(elements, internalContextTag, priorityLevel) { + var fiber = createFiber(Fragment, null, internalContextTag); + return fiber.pendingProps = elements, fiber.pendingWorkPriority = priorityLevel, + fiber; +}, createFiberFromText = function(content, internalContextTag, priorityLevel) { + var fiber = createFiber(HostText$1, null, internalContextTag); + return fiber.pendingProps = content, fiber.pendingWorkPriority = priorityLevel, + fiber; +}; + +function createFiberFromElementType(type, key, internalContextTag, debugOwner) { + var fiber = void 0; + if ("function" == typeof type) fiber = shouldConstruct(type) ? createFiber(ClassComponent$2, key, internalContextTag) : createFiber(IndeterminateComponent, key, internalContextTag), + fiber.type = type; else if ("string" == typeof type) fiber = createFiber(HostComponent$2, key, internalContextTag), + fiber.type = type; else if ("object" == typeof type && null !== type && "number" == typeof type.tag) fiber = type; else { + var info = ""; + invariant(!1, "Element type is invalid: expected a string (for built-in components) " + "or a class/function (for composite components) but got: %s.%s", null == type ? type : typeof type, info); + } + return fiber; +} + +var createFiberFromElementType_1 = createFiberFromElementType, createFiberFromHostInstanceForDeletion = function() { + var fiber = createFiber(HostComponent$2, null, NoContext); + return fiber.type = "DELETED", fiber; +}, createFiberFromCoroutine = function(coroutine, internalContextTag, priorityLevel) { + var fiber = createFiber(CoroutineComponent, coroutine.key, internalContextTag); + return fiber.type = coroutine.handler, fiber.pendingProps = coroutine, fiber.pendingWorkPriority = priorityLevel, + fiber; +}, createFiberFromYield = function(yieldNode, internalContextTag, priorityLevel) { + return createFiber(YieldComponent, null, internalContextTag); +}, createFiberFromPortal = function(portal, internalContextTag, priorityLevel) { + var fiber = createFiber(HostPortal, portal.key, internalContextTag); + return fiber.pendingProps = portal.children || [], fiber.pendingWorkPriority = priorityLevel, + fiber.stateNode = { + containerInfo: portal.containerInfo, + implementation: portal.implementation + }, fiber; +}, ReactFiber = { + cloneFiber: cloneFiber, + createHostRootFiber: createHostRootFiber$1, + createFiberFromElement: createFiberFromElement, + createFiberFromFragment: createFiberFromFragment, + createFiberFromText: createFiberFromText, + createFiberFromElementType: createFiberFromElementType_1, + createFiberFromHostInstanceForDeletion: createFiberFromHostInstanceForDeletion, + createFiberFromCoroutine: createFiberFromCoroutine, + createFiberFromYield: createFiberFromYield, + createFiberFromPortal: createFiberFromPortal +}, createHostRootFiber = ReactFiber.createHostRootFiber, createFiberRoot$1 = function(containerInfo) { + var uninitializedFiber = createHostRootFiber(), root = { + current: uninitializedFiber, + containerInfo: containerInfo, + isScheduled: !1, + nextScheduledRoot: null, + context: null, + pendingContext: null + }; + return uninitializedFiber.stateNode = root, root; +}, ReactFiberRoot = { + createFiberRoot: createFiberRoot$1 +}, IndeterminateComponent$1 = ReactTypeOfWork.IndeterminateComponent, FunctionalComponent = ReactTypeOfWork.FunctionalComponent, ClassComponent$4 = ReactTypeOfWork.ClassComponent, HostComponent$4 = ReactTypeOfWork.HostComponent; + +function describeComponentFrame(name, source, ownerName) { + return "\n in " + (name || "Unknown") + (source ? " (at " + source.fileName.replace(/^.*[\\\/]/, "") + ":" + source.lineNumber + ")" : ownerName ? " (created by " + ownerName + ")" : ""); +} + +function describeFiber(fiber) { + switch (fiber.tag) { + case IndeterminateComponent$1: + case FunctionalComponent: + case ClassComponent$4: + case HostComponent$4: + var owner = fiber._debugOwner, source = fiber._debugSource, name = getComponentName_1(fiber), ownerName = null; + return owner && (ownerName = getComponentName_1(owner)), describeComponentFrame(name, source, ownerName); + + default: + return ""; + } +} + +function getStackAddendumByWorkInProgressFiber$1(workInProgress) { + var info = "", node = workInProgress; + do { + info += describeFiber(node), node = node.return; + } while (node); + return info; +} + +var ReactFiberComponentTreeHook = { + getStackAddendumByWorkInProgressFiber: getStackAddendumByWorkInProgressFiber$1, + describeComponentFrame: describeComponentFrame +}, REACT_ELEMENT_TYPE = "function" == typeof Symbol && Symbol.for && Symbol.for("react.element") || 60103, ReactElementSymbol = REACT_ELEMENT_TYPE, REACT_COROUTINE_TYPE$1, REACT_YIELD_TYPE$1; + +"function" == typeof Symbol && Symbol.for ? (REACT_COROUTINE_TYPE$1 = Symbol.for("react.coroutine"), +REACT_YIELD_TYPE$1 = Symbol.for("react.yield")) : (REACT_COROUTINE_TYPE$1 = 60104, +REACT_YIELD_TYPE$1 = 60105); + +var createCoroutine = function(children, handler, props) { + var key = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : null; + return { + $$typeof: REACT_COROUTINE_TYPE$1, + key: null == key ? null : "" + key, + children: children, + handler: handler, + props: props + }; +}, createYield = function(value) { + return { + $$typeof: REACT_YIELD_TYPE$1, + value: value + }; +}, isCoroutine = function(object) { + return "object" == typeof object && null !== object && object.$$typeof === REACT_COROUTINE_TYPE$1; +}, isYield = function(object) { + return "object" == typeof object && null !== object && object.$$typeof === REACT_YIELD_TYPE$1; +}, REACT_YIELD_TYPE_1 = REACT_YIELD_TYPE$1, REACT_COROUTINE_TYPE_1 = REACT_COROUTINE_TYPE$1, ReactCoroutine = { + createCoroutine: createCoroutine, + createYield: createYield, + isCoroutine: isCoroutine, + isYield: isYield, + REACT_YIELD_TYPE: REACT_YIELD_TYPE_1, + REACT_COROUTINE_TYPE: REACT_COROUTINE_TYPE_1 +}, ITERATOR_SYMBOL = "function" == typeof Symbol && Symbol.iterator, FAUX_ITERATOR_SYMBOL = "@@iterator"; + +function getIteratorFn(maybeIterable) { + var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); + if ("function" == typeof iteratorFn) return iteratorFn; +} + +var getIteratorFn_1 = getIteratorFn, REACT_COROUTINE_TYPE = ReactCoroutine.REACT_COROUTINE_TYPE, REACT_YIELD_TYPE = ReactCoroutine.REACT_YIELD_TYPE, REACT_PORTAL_TYPE$1 = ReactPortal.REACT_PORTAL_TYPE, cloneFiber$2 = ReactFiber.cloneFiber, createFiberFromElement$1 = ReactFiber.createFiberFromElement, createFiberFromFragment$1 = ReactFiber.createFiberFromFragment, createFiberFromText$1 = ReactFiber.createFiberFromText, createFiberFromCoroutine$1 = ReactFiber.createFiberFromCoroutine, createFiberFromYield$1 = ReactFiber.createFiberFromYield, createFiberFromPortal$1 = ReactFiber.createFiberFromPortal, isArray = Array.isArray, FunctionalComponent$2 = ReactTypeOfWork.FunctionalComponent, ClassComponent$6 = ReactTypeOfWork.ClassComponent, HostText$3 = ReactTypeOfWork.HostText, HostPortal$3 = ReactTypeOfWork.HostPortal, CoroutineComponent$2 = ReactTypeOfWork.CoroutineComponent, YieldComponent$2 = ReactTypeOfWork.YieldComponent, Fragment$2 = ReactTypeOfWork.Fragment, NoEffect$3 = ReactTypeOfSideEffect.NoEffect, Placement$3 = ReactTypeOfSideEffect.Placement, Deletion$1 = ReactTypeOfSideEffect.Deletion; + +function coerceRef(current, element) { + var mixedRef = element.ref; + if (null !== mixedRef && "function" != typeof mixedRef && element._owner) { + var owner = element._owner, inst = void 0; + if (owner) if ("number" == typeof owner.tag) { + var ownerFiber = owner; + invariant(ownerFiber.tag === ClassComponent$6, "Stateless function components cannot have refs."), + inst = ownerFiber.stateNode; + } else inst = owner.getPublicInstance(); + invariant(inst, "Missing owner for string ref %s. This error is likely caused by a " + "bug in React. Please file an issue.", mixedRef); + var stringRef = "" + mixedRef; + if (null !== current && null !== current.ref && current.ref._stringRef === stringRef) return current.ref; + var ref = function(value) { + var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs; + null === value ? delete refs[stringRef] : refs[stringRef] = value; + }; + return ref._stringRef = stringRef, ref; + } + return mixedRef; +} + +function throwOnInvalidObjectType(returnFiber, newChild) { + if ("textarea" !== returnFiber.type) { + invariant(!1, "Objects are not valid as a React child (found: %s).%s", "[object Object]" === Object.prototype.toString.call(newChild) ? "object with keys {" + Object.keys(newChild).join(", ") + "}" : newChild, ""); + } +} + +function ChildReconciler(shouldClone, shouldTrackSideEffects) { + function deleteChild(returnFiber, childToDelete) { + if (shouldTrackSideEffects) { + if (!shouldClone) { + if (null === childToDelete.alternate) return; + childToDelete = childToDelete.alternate; + } + var last = returnFiber.progressedLastDeletion; + null !== last ? (last.nextEffect = childToDelete, returnFiber.progressedLastDeletion = childToDelete) : returnFiber.progressedFirstDeletion = returnFiber.progressedLastDeletion = childToDelete, + childToDelete.nextEffect = null, childToDelete.effectTag = Deletion$1; + } + } + function deleteRemainingChildren(returnFiber, currentFirstChild) { + if (!shouldTrackSideEffects) return null; + for (var childToDelete = currentFirstChild; null !== childToDelete; ) deleteChild(returnFiber, childToDelete), + childToDelete = childToDelete.sibling; + return null; + } + function mapRemainingChildren(returnFiber, currentFirstChild) { + for (var existingChildren = new Map(), existingChild = currentFirstChild; null !== existingChild; ) null !== existingChild.key ? existingChildren.set(existingChild.key, existingChild) : existingChildren.set(existingChild.index, existingChild), + existingChild = existingChild.sibling; + return existingChildren; + } + function useFiber(fiber, priority) { + if (shouldClone) { + var clone = cloneFiber$2(fiber, priority); + return clone.index = 0, clone.sibling = null, clone; + } + return fiber.pendingWorkPriority = priority, fiber.effectTag = NoEffect$3, fiber.index = 0, + fiber.sibling = null, fiber; + } + function placeChild(newFiber, lastPlacedIndex, newIndex) { + if (newFiber.index = newIndex, !shouldTrackSideEffects) return lastPlacedIndex; + var current = newFiber.alternate; + if (null !== current) { + var oldIndex = current.index; + return oldIndex < lastPlacedIndex ? (newFiber.effectTag = Placement$3, lastPlacedIndex) : oldIndex; + } + return newFiber.effectTag = Placement$3, lastPlacedIndex; + } + function placeSingleChild(newFiber) { + return shouldTrackSideEffects && null === newFiber.alternate && (newFiber.effectTag = Placement$3), + newFiber; + } + function updateTextNode(returnFiber, current, textContent, priority) { + if (null === current || current.tag !== HostText$3) { + var created = createFiberFromText$1(textContent, returnFiber.internalContextTag, priority); + return created.return = returnFiber, created; + } + var existing = useFiber(current, priority); + return existing.pendingProps = textContent, existing.return = returnFiber, existing; + } + function updateElement(returnFiber, current, element, priority) { + if (null === current || current.type !== element.type) { + var created = createFiberFromElement$1(element, returnFiber.internalContextTag, priority); + return created.ref = coerceRef(current, element), created.return = returnFiber, + created; + } + var existing = useFiber(current, priority); + return existing.ref = coerceRef(current, element), existing.pendingProps = element.props, + existing.return = returnFiber, existing; + } + function updateCoroutine(returnFiber, current, coroutine, priority) { + if (null === current || current.tag !== CoroutineComponent$2) { + var created = createFiberFromCoroutine$1(coroutine, returnFiber.internalContextTag, priority); + return created.return = returnFiber, created; + } + var existing = useFiber(current, priority); + return existing.pendingProps = coroutine, existing.return = returnFiber, existing; + } + function updateYield(returnFiber, current, yieldNode, priority) { + if (null === current || current.tag !== YieldComponent$2) { + var created = createFiberFromYield$1(yieldNode, returnFiber.internalContextTag, priority); + return created.type = yieldNode.value, created.return = returnFiber, created; + } + var existing = useFiber(current, priority); + return existing.type = yieldNode.value, existing.return = returnFiber, existing; + } + function updatePortal(returnFiber, current, portal, priority) { + if (null === current || current.tag !== HostPortal$3 || current.stateNode.containerInfo !== portal.containerInfo || current.stateNode.implementation !== portal.implementation) { + var created = createFiberFromPortal$1(portal, returnFiber.internalContextTag, priority); + return created.return = returnFiber, created; + } + var existing = useFiber(current, priority); + return existing.pendingProps = portal.children || [], existing.return = returnFiber, + existing; + } + function updateFragment(returnFiber, current, fragment, priority) { + if (null === current || current.tag !== Fragment$2) { + var created = createFiberFromFragment$1(fragment, returnFiber.internalContextTag, priority); + return created.return = returnFiber, created; + } + var existing = useFiber(current, priority); + return existing.pendingProps = fragment, existing.return = returnFiber, existing; + } + function createChild(returnFiber, newChild, priority) { + if ("string" == typeof newChild || "number" == typeof newChild) { + var created = createFiberFromText$1("" + newChild, returnFiber.internalContextTag, priority); + return created.return = returnFiber, created; + } + if ("object" == typeof newChild && null !== newChild) { + switch (newChild.$$typeof) { + case ReactElementSymbol: + var _created = createFiberFromElement$1(newChild, returnFiber.internalContextTag, priority); + return _created.ref = coerceRef(null, newChild), _created.return = returnFiber, + _created; + + case REACT_COROUTINE_TYPE: + var _created2 = createFiberFromCoroutine$1(newChild, returnFiber.internalContextTag, priority); + return _created2.return = returnFiber, _created2; + + case REACT_YIELD_TYPE: + var _created3 = createFiberFromYield$1(newChild, returnFiber.internalContextTag, priority); + return _created3.type = newChild.value, _created3.return = returnFiber, _created3; + + case REACT_PORTAL_TYPE$1: + var _created4 = createFiberFromPortal$1(newChild, returnFiber.internalContextTag, priority); + return _created4.return = returnFiber, _created4; + } + if (isArray(newChild) || getIteratorFn_1(newChild)) { + var _created5 = createFiberFromFragment$1(newChild, returnFiber.internalContextTag, priority); + return _created5.return = returnFiber, _created5; + } + throwOnInvalidObjectType(returnFiber, newChild); + } + return null; + } + function updateSlot(returnFiber, oldFiber, newChild, priority) { + var key = null !== oldFiber ? oldFiber.key : null; + if ("string" == typeof newChild || "number" == typeof newChild) return null !== key ? null : updateTextNode(returnFiber, oldFiber, "" + newChild, priority); + if ("object" == typeof newChild && null !== newChild) { + switch (newChild.$$typeof) { + case ReactElementSymbol: + return newChild.key === key ? updateElement(returnFiber, oldFiber, newChild, priority) : null; + + case REACT_COROUTINE_TYPE: + return newChild.key === key ? updateCoroutine(returnFiber, oldFiber, newChild, priority) : null; + + case REACT_YIELD_TYPE: + return null === key ? updateYield(returnFiber, oldFiber, newChild, priority) : null; + + case REACT_PORTAL_TYPE$1: + return newChild.key === key ? updatePortal(returnFiber, oldFiber, newChild, priority) : null; + } + if (isArray(newChild) || getIteratorFn_1(newChild)) return null !== key ? null : updateFragment(returnFiber, oldFiber, newChild, priority); + throwOnInvalidObjectType(returnFiber, newChild); + } + return null; + } + function updateFromMap(existingChildren, returnFiber, newIdx, newChild, priority) { + if ("string" == typeof newChild || "number" == typeof newChild) { + return updateTextNode(returnFiber, existingChildren.get(newIdx) || null, "" + newChild, priority); + } + if ("object" == typeof newChild && null !== newChild) { + switch (newChild.$$typeof) { + case ReactElementSymbol: + return updateElement(returnFiber, existingChildren.get(null === newChild.key ? newIdx : newChild.key) || null, newChild, priority); + + case REACT_COROUTINE_TYPE: + return updateCoroutine(returnFiber, existingChildren.get(null === newChild.key ? newIdx : newChild.key) || null, newChild, priority); + + case REACT_YIELD_TYPE: + return updateYield(returnFiber, existingChildren.get(newIdx) || null, newChild, priority); + + case REACT_PORTAL_TYPE$1: + return updatePortal(returnFiber, existingChildren.get(null === newChild.key ? newIdx : newChild.key) || null, newChild, priority); + } + if (isArray(newChild) || getIteratorFn_1(newChild)) { + return updateFragment(returnFiber, existingChildren.get(newIdx) || null, newChild, priority); + } + throwOnInvalidObjectType(returnFiber, newChild); + } + return null; + } + function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, priority) { + for (var resultingFirstChild = null, previousNewFiber = null, oldFiber = currentFirstChild, lastPlacedIndex = 0, newIdx = 0, nextOldFiber = null; null !== oldFiber && newIdx < newChildren.length; newIdx++) { + oldFiber.index > newIdx ? (nextOldFiber = oldFiber, oldFiber = null) : nextOldFiber = oldFiber.sibling; + var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], priority); + if (null === newFiber) { + null === oldFiber && (oldFiber = nextOldFiber); + break; + } + shouldTrackSideEffects && oldFiber && null === newFiber.alternate && deleteChild(returnFiber, oldFiber), + lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx), null === previousNewFiber ? resultingFirstChild = newFiber : previousNewFiber.sibling = newFiber, + previousNewFiber = newFiber, oldFiber = nextOldFiber; + } + if (newIdx === newChildren.length) return deleteRemainingChildren(returnFiber, oldFiber), + resultingFirstChild; + if (null === oldFiber) { + for (;newIdx < newChildren.length; newIdx++) { + var _newFiber = createChild(returnFiber, newChildren[newIdx], priority); + _newFiber && (lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx), + null === previousNewFiber ? resultingFirstChild = _newFiber : previousNewFiber.sibling = _newFiber, + previousNewFiber = _newFiber); + } + return resultingFirstChild; + } + for (var existingChildren = mapRemainingChildren(returnFiber, oldFiber); newIdx < newChildren.length; newIdx++) { + var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], priority); + _newFiber2 && (shouldTrackSideEffects && null !== _newFiber2.alternate && existingChildren.delete(null === _newFiber2.key ? newIdx : _newFiber2.key), + lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx), null === previousNewFiber ? resultingFirstChild = _newFiber2 : previousNewFiber.sibling = _newFiber2, + previousNewFiber = _newFiber2); + } + return shouldTrackSideEffects && existingChildren.forEach(function(child) { + return deleteChild(returnFiber, child); + }), resultingFirstChild; + } + function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, priority) { + var iteratorFn = getIteratorFn_1(newChildrenIterable); + invariant("function" == typeof iteratorFn, "An object is not an iterable. This error is likely caused by a bug in " + "React. Please file an issue."); + var newChildren = iteratorFn.call(newChildrenIterable); + invariant(null != newChildren, "An iterable object provided no iterator."); + for (var resultingFirstChild = null, previousNewFiber = null, oldFiber = currentFirstChild, lastPlacedIndex = 0, newIdx = 0, nextOldFiber = null, step = newChildren.next(); null !== oldFiber && !step.done; newIdx++, + step = newChildren.next()) { + oldFiber.index > newIdx ? (nextOldFiber = oldFiber, oldFiber = null) : nextOldFiber = oldFiber.sibling; + var newFiber = updateSlot(returnFiber, oldFiber, step.value, priority); + if (null === newFiber) { + oldFiber || (oldFiber = nextOldFiber); + break; + } + shouldTrackSideEffects && oldFiber && null === newFiber.alternate && deleteChild(returnFiber, oldFiber), + lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx), null === previousNewFiber ? resultingFirstChild = newFiber : previousNewFiber.sibling = newFiber, + previousNewFiber = newFiber, oldFiber = nextOldFiber; + } + if (step.done) return deleteRemainingChildren(returnFiber, oldFiber), resultingFirstChild; + if (null === oldFiber) { + for (;!step.done; newIdx++, step = newChildren.next()) { + var _newFiber3 = createChild(returnFiber, step.value, priority); + null !== _newFiber3 && (lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx), + null === previousNewFiber ? resultingFirstChild = _newFiber3 : previousNewFiber.sibling = _newFiber3, + previousNewFiber = _newFiber3); + } + return resultingFirstChild; + } + for (var existingChildren = mapRemainingChildren(returnFiber, oldFiber); !step.done; newIdx++, + step = newChildren.next()) { + var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, priority); + null !== _newFiber4 && (shouldTrackSideEffects && null !== _newFiber4.alternate && existingChildren.delete(null === _newFiber4.key ? newIdx : _newFiber4.key), + lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx), null === previousNewFiber ? resultingFirstChild = _newFiber4 : previousNewFiber.sibling = _newFiber4, + previousNewFiber = _newFiber4); + } + return shouldTrackSideEffects && existingChildren.forEach(function(child) { + return deleteChild(returnFiber, child); + }), resultingFirstChild; + } + function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, priority) { + if (null !== currentFirstChild && currentFirstChild.tag === HostText$3) { + deleteRemainingChildren(returnFiber, currentFirstChild.sibling); + var existing = useFiber(currentFirstChild, priority); + return existing.pendingProps = textContent, existing.return = returnFiber, existing; + } + deleteRemainingChildren(returnFiber, currentFirstChild); + var created = createFiberFromText$1(textContent, returnFiber.internalContextTag, priority); + return created.return = returnFiber, created; + } + function reconcileSingleElement(returnFiber, currentFirstChild, element, priority) { + for (var key = element.key, child = currentFirstChild; null !== child; ) { + if (child.key === key) { + if (child.type === element.type) { + deleteRemainingChildren(returnFiber, child.sibling); + var existing = useFiber(child, priority); + return existing.ref = coerceRef(child, element), existing.pendingProps = element.props, + existing.return = returnFiber, existing; + } + deleteRemainingChildren(returnFiber, child); + break; + } + deleteChild(returnFiber, child), child = child.sibling; + } + var created = createFiberFromElement$1(element, returnFiber.internalContextTag, priority); + return created.ref = coerceRef(currentFirstChild, element), created.return = returnFiber, + created; + } + function reconcileSingleCoroutine(returnFiber, currentFirstChild, coroutine, priority) { + for (var key = coroutine.key, child = currentFirstChild; null !== child; ) { + if (child.key === key) { + if (child.tag === CoroutineComponent$2) { + deleteRemainingChildren(returnFiber, child.sibling); + var existing = useFiber(child, priority); + return existing.pendingProps = coroutine, existing.return = returnFiber, existing; + } + deleteRemainingChildren(returnFiber, child); + break; + } + deleteChild(returnFiber, child), child = child.sibling; + } + var created = createFiberFromCoroutine$1(coroutine, returnFiber.internalContextTag, priority); + return created.return = returnFiber, created; + } + function reconcileSingleYield(returnFiber, currentFirstChild, yieldNode, priority) { + var child = currentFirstChild; + if (null !== child) { + if (child.tag === YieldComponent$2) { + deleteRemainingChildren(returnFiber, child.sibling); + var existing = useFiber(child, priority); + return existing.type = yieldNode.value, existing.return = returnFiber, existing; + } + deleteRemainingChildren(returnFiber, child); + } + var created = createFiberFromYield$1(yieldNode, returnFiber.internalContextTag, priority); + return created.type = yieldNode.value, created.return = returnFiber, created; + } + function reconcileSinglePortal(returnFiber, currentFirstChild, portal, priority) { + for (var key = portal.key, child = currentFirstChild; null !== child; ) { + if (child.key === key) { + if (child.tag === HostPortal$3 && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) { + deleteRemainingChildren(returnFiber, child.sibling); + var existing = useFiber(child, priority); + return existing.pendingProps = portal.children || [], existing.return = returnFiber, + existing; + } + deleteRemainingChildren(returnFiber, child); + break; + } + deleteChild(returnFiber, child), child = child.sibling; + } + var created = createFiberFromPortal$1(portal, returnFiber.internalContextTag, priority); + return created.return = returnFiber, created; + } + function reconcileChildFibers(returnFiber, currentFirstChild, newChild, priority) { + var disableNewFiberFeatures = ReactFeatureFlags_1.disableNewFiberFeatures, isObject = "object" == typeof newChild && null !== newChild; + if (isObject) if (disableNewFiberFeatures) switch (newChild.$$typeof) { + case ReactElementSymbol: + return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, priority)); + + case REACT_PORTAL_TYPE$1: + return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, priority)); + } else switch (newChild.$$typeof) { + case ReactElementSymbol: + return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, priority)); + + case REACT_COROUTINE_TYPE: + return placeSingleChild(reconcileSingleCoroutine(returnFiber, currentFirstChild, newChild, priority)); + + case REACT_YIELD_TYPE: + return placeSingleChild(reconcileSingleYield(returnFiber, currentFirstChild, newChild, priority)); + + case REACT_PORTAL_TYPE$1: + return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, priority)); + } + if (disableNewFiberFeatures) switch (returnFiber.tag) { + case ClassComponent$6: + var Component = returnFiber.type; + invariant(null === newChild || !1 === newChild, "%s.render(): A valid React element (or null) must be returned. " + "You may have returned undefined, an array or some other " + "invalid object.", Component.displayName || Component.name || "Component"); + break; + + case FunctionalComponent$2: + var _Component = returnFiber.type; + invariant(null === newChild || !1 === newChild, "%s(...): A valid React element (or null) must be returned. " + "You may have returned undefined, an array or some other " + "invalid object.", _Component.displayName || _Component.name || "Component"); + } + if ("string" == typeof newChild || "number" == typeof newChild) return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, "" + newChild, priority)); + if (isArray(newChild)) return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, priority); + if (getIteratorFn_1(newChild)) return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, priority); + if (isObject && throwOnInvalidObjectType(returnFiber, newChild), !disableNewFiberFeatures && void 0 === newChild) switch (returnFiber.tag) { + case ClassComponent$6: + case FunctionalComponent$2: + var _Component2 = returnFiber.type; + invariant(!1, "%s(...): Nothing was returned from render. This usually means a " + "return statement is missing. Or, to render nothing, " + "return null.", _Component2.displayName || _Component2.name || "Component"); + } + return deleteRemainingChildren(returnFiber, currentFirstChild); + } + return reconcileChildFibers; +} + +var reconcileChildFibers$1 = ChildReconciler(!0, !0), reconcileChildFibersInPlace$1 = ChildReconciler(!1, !0), mountChildFibersInPlace$1 = ChildReconciler(!1, !1), cloneChildFibers$1 = function(current, workInProgress) { + if (workInProgress.child) if (null !== current && workInProgress.child === current.child) { + var currentChild = workInProgress.child, newChild = cloneFiber$2(currentChild, currentChild.pendingWorkPriority); + for (workInProgress.child = newChild, newChild.return = workInProgress; null !== currentChild.sibling; ) currentChild = currentChild.sibling, + newChild = newChild.sibling = cloneFiber$2(currentChild, currentChild.pendingWorkPriority), + newChild.return = workInProgress; + newChild.sibling = null; + } else for (var child = workInProgress.child; null !== child; ) child.return = workInProgress, + child = child.sibling; +}, ReactChildFiber = { + reconcileChildFibers: reconcileChildFibers$1, + reconcileChildFibersInPlace: reconcileChildFibersInPlace$1, + mountChildFibersInPlace: mountChildFibersInPlace$1, + cloneChildFibers: cloneChildFibers$1 +}, Update$1 = ReactTypeOfSideEffect.Update, AsyncUpdates$1 = ReactTypeOfInternalContext.AsyncUpdates, cacheContext$1 = ReactFiberContext.cacheContext, getMaskedContext$2 = ReactFiberContext.getMaskedContext, getUnmaskedContext$2 = ReactFiberContext.getUnmaskedContext, isContextConsumer$1 = ReactFiberContext.isContextConsumer, addUpdate$1 = ReactFiberUpdateQueue.addUpdate, addReplaceUpdate$1 = ReactFiberUpdateQueue.addReplaceUpdate, addForceUpdate$1 = ReactFiberUpdateQueue.addForceUpdate, beginUpdateQueue$2 = ReactFiberUpdateQueue.beginUpdateQueue, _require5$1 = ReactFiberContext, hasContextChanged$2 = _require5$1.hasContextChanged, isMounted$1 = ReactFiberTreeReflection.isMounted, ReactFiberClassComponent = function(scheduleUpdate, getPriorityContext, memoizeProps, memoizeState) { + var updater = { + isMounted: isMounted$1, + enqueueSetState: function(instance, partialState, callback) { + var fiber = ReactInstanceMap_1.get(instance), priorityLevel = getPriorityContext(fiber, !1); + callback = void 0 === callback ? null : callback, addUpdate$1(fiber, partialState, callback, priorityLevel), + scheduleUpdate(fiber, priorityLevel); + }, + enqueueReplaceState: function(instance, state, callback) { + var fiber = ReactInstanceMap_1.get(instance), priorityLevel = getPriorityContext(fiber, !1); + callback = void 0 === callback ? null : callback, addReplaceUpdate$1(fiber, state, callback, priorityLevel), + scheduleUpdate(fiber, priorityLevel); + }, + enqueueForceUpdate: function(instance, callback) { + var fiber = ReactInstanceMap_1.get(instance), priorityLevel = getPriorityContext(fiber, !1); + callback = void 0 === callback ? null : callback, addForceUpdate$1(fiber, callback, priorityLevel), + scheduleUpdate(fiber, priorityLevel); + } + }; + function checkShouldComponentUpdate(workInProgress, oldProps, newProps, oldState, newState, newContext) { + if (null === oldProps || null !== workInProgress.updateQueue && workInProgress.updateQueue.hasForceUpdate) return !0; + var instance = workInProgress.stateNode, type = workInProgress.type; + if ("function" == typeof instance.shouldComponentUpdate) { + return instance.shouldComponentUpdate(newProps, newState, newContext); + } + return !type.prototype || !type.prototype.isPureReactComponent || (!shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState)); + } + function resetInputPointers(workInProgress, instance) { + instance.props = workInProgress.memoizedProps, instance.state = workInProgress.memoizedState; + } + function adoptClassInstance(workInProgress, instance) { + instance.updater = updater, workInProgress.stateNode = instance, ReactInstanceMap_1.set(instance, workInProgress); + } + function constructClassInstance(workInProgress, props) { + var ctor = workInProgress.type, unmaskedContext = getUnmaskedContext$2(workInProgress), needsContext = isContextConsumer$1(workInProgress), context = needsContext ? getMaskedContext$2(workInProgress, unmaskedContext) : emptyObject, instance = new ctor(props, context); + return adoptClassInstance(workInProgress, instance), needsContext && cacheContext$1(workInProgress, unmaskedContext, context), + instance; + } + function callComponentWillMount(workInProgress, instance) { + var oldState = instance.state; + instance.componentWillMount(), oldState !== instance.state && updater.enqueueReplaceState(instance, instance.state, null); + } + function callComponentWillReceiveProps(workInProgress, instance, newProps, newContext) { + var oldState = instance.state; + instance.componentWillReceiveProps(newProps, newContext), instance.state !== oldState && updater.enqueueReplaceState(instance, instance.state, null); + } + function mountClassInstance(workInProgress, priorityLevel) { + var instance = workInProgress.stateNode, state = instance.state || null, props = workInProgress.pendingProps; + invariant(props, "There must be pending props for an initial mount. This error is " + "likely caused by a bug in React. Please file an issue."); + var unmaskedContext = getUnmaskedContext$2(workInProgress); + if (instance.props = props, instance.state = state, instance.refs = emptyObject, + instance.context = getMaskedContext$2(workInProgress, unmaskedContext), ReactFeatureFlags_1.enableAsyncSubtreeAPI && null != workInProgress.type && !0 === workInProgress.type.unstable_asyncUpdates && (workInProgress.internalContextTag |= AsyncUpdates$1), + "function" == typeof instance.componentWillMount) { + callComponentWillMount(workInProgress, instance); + var updateQueue = workInProgress.updateQueue; + null !== updateQueue && (instance.state = beginUpdateQueue$2(workInProgress, updateQueue, instance, state, props, priorityLevel)); + } + "function" == typeof instance.componentDidMount && (workInProgress.effectTag |= Update$1); + } + function resumeMountClassInstance(workInProgress, priorityLevel) { + var instance = workInProgress.stateNode; + resetInputPointers(workInProgress, instance); + var newState = workInProgress.memoizedState, newProps = workInProgress.pendingProps; + newProps || (newProps = workInProgress.memoizedProps, invariant(null != newProps, "There should always be pending or memoized props. This error is " + "likely caused by a bug in React. Please file an issue.")); + var newUnmaskedContext = getUnmaskedContext$2(workInProgress), newContext = getMaskedContext$2(workInProgress, newUnmaskedContext), oldContext = instance.context, oldProps = workInProgress.memoizedProps; + "function" != typeof instance.componentWillReceiveProps || oldProps === newProps && oldContext === newContext || callComponentWillReceiveProps(workInProgress, instance, newProps, newContext); + var updateQueue = workInProgress.updateQueue; + if (null !== updateQueue && (newState = beginUpdateQueue$2(workInProgress, updateQueue, instance, newState, newProps, priorityLevel)), + !checkShouldComponentUpdate(workInProgress, workInProgress.memoizedProps, newProps, workInProgress.memoizedState, newState, newContext)) return instance.props = newProps, + instance.state = newState, instance.context = newContext, !1; + if (instance.props = newProps, instance.state = newState, instance.context = newContext, + "function" == typeof instance.componentWillMount) { + callComponentWillMount(workInProgress, instance); + var newUpdateQueue = workInProgress.updateQueue; + null !== newUpdateQueue && (newState = beginUpdateQueue$2(workInProgress, newUpdateQueue, instance, newState, newProps, priorityLevel)); + } + return "function" == typeof instance.componentDidMount && (workInProgress.effectTag |= Update$1), + instance.state = newState, !0; + } + function updateClassInstance(current, workInProgress, priorityLevel) { + var instance = workInProgress.stateNode; + resetInputPointers(workInProgress, instance); + var oldProps = workInProgress.memoizedProps, newProps = workInProgress.pendingProps; + newProps || (newProps = oldProps, invariant(null != newProps, "There should always be pending or memoized props. This error is " + "likely caused by a bug in React. Please file an issue.")); + var oldContext = instance.context, newUnmaskedContext = getUnmaskedContext$2(workInProgress), newContext = getMaskedContext$2(workInProgress, newUnmaskedContext); + "function" != typeof instance.componentWillReceiveProps || oldProps === newProps && oldContext === newContext || callComponentWillReceiveProps(workInProgress, instance, newProps, newContext); + var updateQueue = workInProgress.updateQueue, oldState = workInProgress.memoizedState, newState = void 0; + if (newState = null !== updateQueue ? beginUpdateQueue$2(workInProgress, updateQueue, instance, oldState, newProps, priorityLevel) : oldState, + !(oldProps !== newProps || oldState !== newState || hasContextChanged$2() || null !== updateQueue && updateQueue.hasForceUpdate)) return "function" == typeof instance.componentDidUpdate && (oldProps === current.memoizedProps && oldState === current.memoizedState || (workInProgress.effectTag |= Update$1)), + !1; + var shouldUpdate = checkShouldComponentUpdate(workInProgress, oldProps, newProps, oldState, newState, newContext); + return shouldUpdate ? ("function" == typeof instance.componentWillUpdate && instance.componentWillUpdate(newProps, newState, newContext), + "function" == typeof instance.componentDidUpdate && (workInProgress.effectTag |= Update$1)) : ("function" == typeof instance.componentDidUpdate && (oldProps === current.memoizedProps && oldState === current.memoizedState || (workInProgress.effectTag |= Update$1)), + memoizeProps(workInProgress, newProps), memoizeState(workInProgress, newState)), + instance.props = newProps, instance.state = newState, instance.context = newContext, + shouldUpdate; + } + return { + adoptClassInstance: adoptClassInstance, + constructClassInstance: constructClassInstance, + mountClassInstance: mountClassInstance, + resumeMountClassInstance: resumeMountClassInstance, + updateClassInstance: updateClassInstance + }; +}, mountChildFibersInPlace = ReactChildFiber.mountChildFibersInPlace, reconcileChildFibers = ReactChildFiber.reconcileChildFibers, reconcileChildFibersInPlace = ReactChildFiber.reconcileChildFibersInPlace, cloneChildFibers = ReactChildFiber.cloneChildFibers, beginUpdateQueue$1 = ReactFiberUpdateQueue.beginUpdateQueue, getMaskedContext$1 = ReactFiberContext.getMaskedContext, getUnmaskedContext$1 = ReactFiberContext.getUnmaskedContext, hasContextChanged$1 = ReactFiberContext.hasContextChanged, pushContextProvider$1 = ReactFiberContext.pushContextProvider, pushTopLevelContextObject$1 = ReactFiberContext.pushTopLevelContextObject, invalidateContextProvider$1 = ReactFiberContext.invalidateContextProvider, IndeterminateComponent$2 = ReactTypeOfWork.IndeterminateComponent, FunctionalComponent$1 = ReactTypeOfWork.FunctionalComponent, ClassComponent$5 = ReactTypeOfWork.ClassComponent, HostRoot$4 = ReactTypeOfWork.HostRoot, HostComponent$5 = ReactTypeOfWork.HostComponent, HostText$2 = ReactTypeOfWork.HostText, HostPortal$2 = ReactTypeOfWork.HostPortal, CoroutineComponent$1 = ReactTypeOfWork.CoroutineComponent, CoroutineHandlerPhase = ReactTypeOfWork.CoroutineHandlerPhase, YieldComponent$1 = ReactTypeOfWork.YieldComponent, Fragment$1 = ReactTypeOfWork.Fragment, NoWork$3 = ReactPriorityLevel.NoWork, OffscreenPriority$1 = ReactPriorityLevel.OffscreenPriority, Placement$2 = ReactTypeOfSideEffect.Placement, ContentReset$1 = ReactTypeOfSideEffect.ContentReset, Err$1 = ReactTypeOfSideEffect.Err, Ref$1 = ReactTypeOfSideEffect.Ref, ReactCurrentOwner$2 = ReactGlobalSharedState_1.ReactCurrentOwner, ReactFiberBeginWork = function(config, hostContext, hydrationContext, scheduleUpdate, getPriorityContext) { + var shouldSetTextContent = config.shouldSetTextContent, useSyncScheduling = config.useSyncScheduling, shouldDeprioritizeSubtree = config.shouldDeprioritizeSubtree, pushHostContext = hostContext.pushHostContext, pushHostContainer = hostContext.pushHostContainer, enterHydrationState = hydrationContext.enterHydrationState, resetHydrationState = hydrationContext.resetHydrationState, tryToClaimNextHydratableInstance = hydrationContext.tryToClaimNextHydratableInstance, _ReactFiberClassCompo = ReactFiberClassComponent(scheduleUpdate, getPriorityContext, memoizeProps, memoizeState), adoptClassInstance = _ReactFiberClassCompo.adoptClassInstance, constructClassInstance = _ReactFiberClassCompo.constructClassInstance, mountClassInstance = _ReactFiberClassCompo.mountClassInstance, resumeMountClassInstance = _ReactFiberClassCompo.resumeMountClassInstance, updateClassInstance = _ReactFiberClassCompo.updateClassInstance; + function markChildAsProgressed(current, workInProgress, priorityLevel) { + workInProgress.progressedChild = workInProgress.child, workInProgress.progressedPriority = priorityLevel, + null !== current && (current.progressedChild = workInProgress.progressedChild, current.progressedPriority = workInProgress.progressedPriority); + } + function clearDeletions(workInProgress) { + workInProgress.progressedFirstDeletion = workInProgress.progressedLastDeletion = null; + } + function transferDeletions(workInProgress) { + workInProgress.firstEffect = workInProgress.progressedFirstDeletion, workInProgress.lastEffect = workInProgress.progressedLastDeletion; + } + function reconcileChildren(current, workInProgress, nextChildren) { + reconcileChildrenAtPriority(current, workInProgress, nextChildren, workInProgress.pendingWorkPriority); + } + function reconcileChildrenAtPriority(current, workInProgress, nextChildren, priorityLevel) { + workInProgress.memoizedProps = null, null === current ? workInProgress.child = mountChildFibersInPlace(workInProgress, workInProgress.child, nextChildren, priorityLevel) : current.child === workInProgress.child ? (clearDeletions(workInProgress), + workInProgress.child = reconcileChildFibers(workInProgress, workInProgress.child, nextChildren, priorityLevel), + transferDeletions(workInProgress)) : (workInProgress.child = reconcileChildFibersInPlace(workInProgress, workInProgress.child, nextChildren, priorityLevel), + transferDeletions(workInProgress)), markChildAsProgressed(current, workInProgress, priorityLevel); + } + function updateFragment(current, workInProgress) { + var nextChildren = workInProgress.pendingProps; + if (hasContextChanged$1()) null === nextChildren && (nextChildren = workInProgress.memoizedProps); else if (null === nextChildren || workInProgress.memoizedProps === nextChildren) return bailoutOnAlreadyFinishedWork(current, workInProgress); + return reconcileChildren(current, workInProgress, nextChildren), memoizeProps(workInProgress, nextChildren), + workInProgress.child; + } + function markRef(current, workInProgress) { + var ref = workInProgress.ref; + null === ref || current && current.ref === ref || (workInProgress.effectTag |= Ref$1); + } + function updateFunctionalComponent(current, workInProgress) { + var fn = workInProgress.type, nextProps = workInProgress.pendingProps, memoizedProps = workInProgress.memoizedProps; + if (hasContextChanged$1()) null === nextProps && (nextProps = memoizedProps); else { + if (null === nextProps || memoizedProps === nextProps) return bailoutOnAlreadyFinishedWork(current, workInProgress); + if ("function" == typeof fn.shouldComponentUpdate && !fn.shouldComponentUpdate(memoizedProps, nextProps)) return memoizeProps(workInProgress, nextProps), + bailoutOnAlreadyFinishedWork(current, workInProgress); + } + var nextChildren, unmaskedContext = getUnmaskedContext$1(workInProgress), context = getMaskedContext$1(workInProgress, unmaskedContext); + return nextChildren = fn(nextProps, context), reconcileChildren(current, workInProgress, nextChildren), + memoizeProps(workInProgress, nextProps), workInProgress.child; + } + function updateClassComponent(current, workInProgress, priorityLevel) { + var hasContext = pushContextProvider$1(workInProgress), shouldUpdate = void 0; + return null === current ? workInProgress.stateNode ? shouldUpdate = resumeMountClassInstance(workInProgress, priorityLevel) : (constructClassInstance(workInProgress, workInProgress.pendingProps), + mountClassInstance(workInProgress, priorityLevel), shouldUpdate = !0) : shouldUpdate = updateClassInstance(current, workInProgress, priorityLevel), + finishClassComponent(current, workInProgress, shouldUpdate, hasContext); + } + function finishClassComponent(current, workInProgress, shouldUpdate, hasContext) { + if (markRef(current, workInProgress), !shouldUpdate) return bailoutOnAlreadyFinishedWork(current, workInProgress); + var instance = workInProgress.stateNode; + ReactCurrentOwner$2.current = workInProgress; + var nextChildren = void 0; + return nextChildren = instance.render(), reconcileChildren(current, workInProgress, nextChildren), + memoizeState(workInProgress, instance.state), memoizeProps(workInProgress, instance.props), + hasContext && invalidateContextProvider$1(workInProgress), workInProgress.child; + } + function updateHostRoot(current, workInProgress, priorityLevel) { + var root = workInProgress.stateNode; + root.pendingContext ? pushTopLevelContextObject$1(workInProgress, root.pendingContext, root.pendingContext !== root.context) : root.context && pushTopLevelContextObject$1(workInProgress, root.context, !1), + pushHostContainer(workInProgress, root.containerInfo); + var updateQueue = workInProgress.updateQueue; + if (null !== updateQueue) { + var prevState = workInProgress.memoizedState, state = beginUpdateQueue$1(workInProgress, updateQueue, null, prevState, null, priorityLevel); + if (prevState === state) return resetHydrationState(), bailoutOnAlreadyFinishedWork(current, workInProgress); + var element = state.element; + return null !== current && null !== current.child || !enterHydrationState(workInProgress) ? (resetHydrationState(), + reconcileChildren(current, workInProgress, element), memoizeState(workInProgress, state), + workInProgress.child) : (workInProgress.effectTag |= Placement$2, workInProgress.child = mountChildFibersInPlace(workInProgress, workInProgress.child, element, priorityLevel), + markChildAsProgressed(current, workInProgress, priorityLevel), workInProgress.child); + } + return resetHydrationState(), bailoutOnAlreadyFinishedWork(current, workInProgress); + } + function updateHostComponent(current, workInProgress) { + pushHostContext(workInProgress), null === current && tryToClaimNextHydratableInstance(workInProgress); + var nextProps = workInProgress.pendingProps, prevProps = null !== current ? current.memoizedProps : null, memoizedProps = workInProgress.memoizedProps; + if (hasContextChanged$1()) null === nextProps && (nextProps = memoizedProps, invariant(null !== nextProps, "We should always have pending or current props. This error is " + "likely caused by a bug in React. Please file an issue.")); else if (null === nextProps || memoizedProps === nextProps) { + if (!useSyncScheduling && shouldDeprioritizeSubtree(workInProgress.type, memoizedProps) && workInProgress.pendingWorkPriority !== OffscreenPriority$1) { + for (var child = workInProgress.progressedChild; null !== child; ) child.pendingWorkPriority = OffscreenPriority$1, + child = child.sibling; + return null; + } + return bailoutOnAlreadyFinishedWork(current, workInProgress); + } + var nextChildren = nextProps.children; + if (shouldSetTextContent(nextProps) ? nextChildren = null : prevProps && shouldSetTextContent(prevProps) && (workInProgress.effectTag |= ContentReset$1), + markRef(current, workInProgress), !useSyncScheduling && shouldDeprioritizeSubtree(workInProgress.type, nextProps) && workInProgress.pendingWorkPriority !== OffscreenPriority$1) { + if (workInProgress.progressedPriority === OffscreenPriority$1 && (workInProgress.child = workInProgress.progressedChild), + reconcileChildrenAtPriority(current, workInProgress, nextChildren, OffscreenPriority$1), + memoizeProps(workInProgress, nextProps), workInProgress.child = null !== current ? current.child : null, + null === current) for (var _child = workInProgress.progressedChild; null !== _child; ) _child.effectTag = Placement$2, + _child = _child.sibling; + return null; + } + return reconcileChildren(current, workInProgress, nextChildren), memoizeProps(workInProgress, nextProps), + workInProgress.child; + } + function updateHostText(current, workInProgress) { + null === current && tryToClaimNextHydratableInstance(workInProgress); + var nextProps = workInProgress.pendingProps; + return null === nextProps && (nextProps = workInProgress.memoizedProps), memoizeProps(workInProgress, nextProps), + null; + } + function mountIndeterminateComponent(current, workInProgress, priorityLevel) { + invariant(null === current, "An indeterminate component should never have mounted. This error is " + "likely caused by a bug in React. Please file an issue."); + var value, fn = workInProgress.type, props = workInProgress.pendingProps, unmaskedContext = getUnmaskedContext$1(workInProgress), context = getMaskedContext$1(workInProgress, unmaskedContext); + if ("object" == typeof (value = fn(props, context)) && null !== value && "function" == typeof value.render) { + workInProgress.tag = ClassComponent$5; + var hasContext = pushContextProvider$1(workInProgress); + return adoptClassInstance(workInProgress, value), mountClassInstance(workInProgress, priorityLevel), + finishClassComponent(current, workInProgress, !0, hasContext); + } + return workInProgress.tag = FunctionalComponent$1, reconcileChildren(current, workInProgress, value), + memoizeProps(workInProgress, props), workInProgress.child; + } + function updateCoroutineComponent(current, workInProgress) { + var nextCoroutine = workInProgress.pendingProps; + hasContextChanged$1() ? null === nextCoroutine && (nextCoroutine = current && current.memoizedProps, + invariant(null !== nextCoroutine, "We should always have pending or current props. This error is " + "likely caused by a bug in React. Please file an issue.")) : null !== nextCoroutine && workInProgress.memoizedProps !== nextCoroutine || (nextCoroutine = workInProgress.memoizedProps); + var nextChildren = nextCoroutine.children, priorityLevel = workInProgress.pendingWorkPriority; + return workInProgress.memoizedProps = null, null === current ? workInProgress.stateNode = mountChildFibersInPlace(workInProgress, workInProgress.stateNode, nextChildren, priorityLevel) : current.child === workInProgress.child ? (clearDeletions(workInProgress), + workInProgress.stateNode = reconcileChildFibers(workInProgress, workInProgress.stateNode, nextChildren, priorityLevel), + transferDeletions(workInProgress)) : (workInProgress.stateNode = reconcileChildFibersInPlace(workInProgress, workInProgress.stateNode, nextChildren, priorityLevel), + transferDeletions(workInProgress)), memoizeProps(workInProgress, nextCoroutine), + workInProgress.stateNode; + } + function updatePortalComponent(current, workInProgress) { + pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); + var priorityLevel = workInProgress.pendingWorkPriority, nextChildren = workInProgress.pendingProps; + if (hasContextChanged$1()) null === nextChildren && (nextChildren = current && current.memoizedProps, + invariant(null != nextChildren, "We should always have pending or current props. This error is " + "likely caused by a bug in React. Please file an issue.")); else if (null === nextChildren || workInProgress.memoizedProps === nextChildren) return bailoutOnAlreadyFinishedWork(current, workInProgress); + return null === current ? (workInProgress.child = reconcileChildFibersInPlace(workInProgress, workInProgress.child, nextChildren, priorityLevel), + memoizeProps(workInProgress, nextChildren), markChildAsProgressed(current, workInProgress, priorityLevel)) : (reconcileChildren(current, workInProgress, nextChildren), + memoizeProps(workInProgress, nextChildren)), workInProgress.child; + } + function bailoutOnAlreadyFinishedWork(current, workInProgress) { + var priorityLevel = workInProgress.pendingWorkPriority; + return current && workInProgress.child === current.child && clearDeletions(workInProgress), + cloneChildFibers(current, workInProgress), markChildAsProgressed(current, workInProgress, priorityLevel), + workInProgress.child; + } + function bailoutOnLowPriority(current, workInProgress) { + switch (workInProgress.tag) { + case ClassComponent$5: + pushContextProvider$1(workInProgress); + break; + + case HostPortal$2: + pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); + } + return null; + } + function memoizeProps(workInProgress, nextProps) { + workInProgress.memoizedProps = nextProps, workInProgress.pendingProps = null; + } + function memoizeState(workInProgress, nextState) { + workInProgress.memoizedState = nextState; + } + function beginWork(current, workInProgress, priorityLevel) { + if (workInProgress.pendingWorkPriority === NoWork$3 || workInProgress.pendingWorkPriority > priorityLevel) return bailoutOnLowPriority(current, workInProgress); + switch (workInProgress.firstEffect = null, workInProgress.lastEffect = null, workInProgress.progressedPriority === priorityLevel && (workInProgress.child = workInProgress.progressedChild), + workInProgress.tag) { + case IndeterminateComponent$2: + return mountIndeterminateComponent(current, workInProgress, priorityLevel); + + case FunctionalComponent$1: + return updateFunctionalComponent(current, workInProgress); + + case ClassComponent$5: + return updateClassComponent(current, workInProgress, priorityLevel); + + case HostRoot$4: + return updateHostRoot(current, workInProgress, priorityLevel); + + case HostComponent$5: + return updateHostComponent(current, workInProgress); + + case HostText$2: + return updateHostText(current, workInProgress); + + case CoroutineHandlerPhase: + workInProgress.tag = CoroutineComponent$1; + + case CoroutineComponent$1: + return updateCoroutineComponent(current, workInProgress); + + case YieldComponent$1: + return null; + + case HostPortal$2: + return updatePortalComponent(current, workInProgress); + + case Fragment$1: + return updateFragment(current, workInProgress); + + default: + invariant(!1, "Unknown unit of work tag. This error is likely caused by a bug in " + "React. Please file an issue."); + } + } + function beginFailedWork(current, workInProgress, priorityLevel) { + if (invariant(workInProgress.tag === ClassComponent$5 || workInProgress.tag === HostRoot$4, "Invalid type of work. This error is likely caused by a bug in React. " + "Please file an issue."), + workInProgress.effectTag |= Err$1, workInProgress.pendingWorkPriority === NoWork$3 || workInProgress.pendingWorkPriority > priorityLevel) return bailoutOnLowPriority(current, workInProgress); + if (workInProgress.firstEffect = null, workInProgress.lastEffect = null, reconcileChildren(current, workInProgress, null), + workInProgress.tag === ClassComponent$5) { + var instance = workInProgress.stateNode; + workInProgress.memoizedProps = instance.props, workInProgress.memoizedState = instance.state, + workInProgress.pendingProps = null; + } + return workInProgress.child; + } + return { + beginWork: beginWork, + beginFailedWork: beginFailedWork + }; +}, reconcileChildFibers$2 = ReactChildFiber.reconcileChildFibers, popContextProvider$2 = ReactFiberContext.popContextProvider, IndeterminateComponent$3 = ReactTypeOfWork.IndeterminateComponent, FunctionalComponent$3 = ReactTypeOfWork.FunctionalComponent, ClassComponent$7 = ReactTypeOfWork.ClassComponent, HostRoot$5 = ReactTypeOfWork.HostRoot, HostComponent$6 = ReactTypeOfWork.HostComponent, HostText$4 = ReactTypeOfWork.HostText, HostPortal$4 = ReactTypeOfWork.HostPortal, CoroutineComponent$3 = ReactTypeOfWork.CoroutineComponent, CoroutineHandlerPhase$1 = ReactTypeOfWork.CoroutineHandlerPhase, YieldComponent$3 = ReactTypeOfWork.YieldComponent, Fragment$3 = ReactTypeOfWork.Fragment, Placement$4 = ReactTypeOfSideEffect.Placement, Ref$2 = ReactTypeOfSideEffect.Ref, Update$2 = ReactTypeOfSideEffect.Update, ReactFiberCompleteWork = function(config, hostContext, hydrationContext) { + var createInstance = config.createInstance, createTextInstance = config.createTextInstance, appendInitialChild = config.appendInitialChild, finalizeInitialChildren = config.finalizeInitialChildren, prepareUpdate = config.prepareUpdate, getRootHostContainer = hostContext.getRootHostContainer, popHostContext = hostContext.popHostContext, getHostContext = hostContext.getHostContext, popHostContainer = hostContext.popHostContainer, hydrateHostInstance = hydrationContext.hydrateHostInstance, hydrateHostTextInstance = hydrationContext.hydrateHostTextInstance, popHydrationState = hydrationContext.popHydrationState; + function markChildAsProgressed(current, workInProgress, priorityLevel) { + workInProgress.progressedChild = workInProgress.child, workInProgress.progressedPriority = priorityLevel, + null !== current && (current.progressedChild = workInProgress.progressedChild, current.progressedPriority = workInProgress.progressedPriority); + } + function markUpdate(workInProgress) { + workInProgress.effectTag |= Update$2; + } + function markRef(workInProgress) { + workInProgress.effectTag |= Ref$2; + } + function appendAllYields(yields, workInProgress) { + var node = workInProgress.stateNode; + for (node && (node.return = workInProgress); null !== node; ) { + if (node.tag === HostComponent$6 || node.tag === HostText$4 || node.tag === HostPortal$4) invariant(!1, "A coroutine cannot have host component children."); else if (node.tag === YieldComponent$3) yields.push(node.type); else if (null !== node.child) { + node.child.return = node, node = node.child; + continue; + } + for (;null === node.sibling; ) { + if (null === node.return || node.return === workInProgress) return; + node = node.return; + } + node.sibling.return = node.return, node = node.sibling; + } + } + function moveCoroutineToHandlerPhase(current, workInProgress) { + var coroutine = workInProgress.memoizedProps; + invariant(coroutine, "Should be resolved by now. This error is likely caused by a bug in " + "React. Please file an issue."), + workInProgress.tag = CoroutineHandlerPhase$1; + var yields = []; + appendAllYields(yields, workInProgress); + var fn = coroutine.handler, props = coroutine.props, nextChildren = fn(props, yields), currentFirstChild = null !== current ? current.child : null, priority = workInProgress.pendingWorkPriority; + return workInProgress.child = reconcileChildFibers$2(workInProgress, currentFirstChild, nextChildren, priority), + markChildAsProgressed(current, workInProgress, priority), workInProgress.child; + } + function appendAllChildren(parent, workInProgress) { + for (var node = workInProgress.child; null !== node; ) { + if (node.tag === HostComponent$6 || node.tag === HostText$4) appendInitialChild(parent, node.stateNode); else if (node.tag === HostPortal$4) ; else if (null !== node.child) { + node = node.child; + continue; + } + if (node === workInProgress) return; + for (;null === node.sibling; ) { + if (null === node.return || node.return === workInProgress) return; + node = node.return; + } + node = node.sibling; + } + } + function completeWork(current, workInProgress) { + switch (workInProgress.tag) { + case FunctionalComponent$3: + return null; + + case ClassComponent$7: + return popContextProvider$2(workInProgress), null; + + case HostRoot$5: + var fiberRoot = workInProgress.stateNode; + return fiberRoot.pendingContext && (fiberRoot.context = fiberRoot.pendingContext, + fiberRoot.pendingContext = null), null !== current && null !== current.child || (popHydrationState(workInProgress), + workInProgress.effectTag &= ~Placement$4), null; + + case HostComponent$6: + popHostContext(workInProgress); + var rootContainerInstance = getRootHostContainer(), type = workInProgress.type, newProps = workInProgress.memoizedProps; + if (null !== current && null != workInProgress.stateNode) { + var oldProps = current.memoizedProps, instance = workInProgress.stateNode, currentHostContext = getHostContext(), updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext); + workInProgress.updateQueue = updatePayload, updatePayload && markUpdate(workInProgress), + current.ref !== workInProgress.ref && markRef(workInProgress); + } else { + if (!newProps) return invariant(null !== workInProgress.stateNode, "We must have new props for new mounts. This error is likely " + "caused by a bug in React. Please file an issue."), + null; + var _currentHostContext = getHostContext(), _instance = void 0; + popHydrationState(workInProgress) ? _instance = hydrateHostInstance(workInProgress, rootContainerInstance) : (_instance = createInstance(type, newProps, rootContainerInstance, _currentHostContext, workInProgress), + appendAllChildren(_instance, workInProgress), finalizeInitialChildren(_instance, type, newProps, rootContainerInstance) && markUpdate(workInProgress)), + workInProgress.stateNode = _instance, null !== workInProgress.ref && markRef(workInProgress); + } + return null; + + case HostText$4: + var newText = workInProgress.memoizedProps; + if (current && null != workInProgress.stateNode) { + current.memoizedProps !== newText && markUpdate(workInProgress); + } else { + if ("string" != typeof newText) return invariant(null !== workInProgress.stateNode, "We must have new props for new mounts. This error is likely " + "caused by a bug in React. Please file an issue."), + null; + var _rootContainerInstance = getRootHostContainer(), _currentHostContext2 = getHostContext(), textInstance = void 0; + textInstance = popHydrationState(workInProgress) ? hydrateHostTextInstance(workInProgress, _rootContainerInstance) : createTextInstance(newText, _rootContainerInstance, _currentHostContext2, workInProgress), + workInProgress.stateNode = textInstance; + } + return null; + + case CoroutineComponent$3: + return moveCoroutineToHandlerPhase(current, workInProgress); + + case CoroutineHandlerPhase$1: + return workInProgress.tag = CoroutineComponent$3, null; + + case YieldComponent$3: + case Fragment$3: + return null; + + case HostPortal$4: + return markUpdate(workInProgress), popHostContainer(workInProgress), null; + + case IndeterminateComponent$3: + invariant(!1, "An indeterminate component should have become determinate before " + "completing. This error is likely caused by a bug in React. Please " + "file an issue."); + + default: + invariant(!1, "Unknown unit of work tag. This error is likely caused by a bug in " + "React. Please file an issue."); + } + } + return { + completeWork: completeWork + }; +}, rendererID = null, injectInternals$1 = null, onCommitRoot$1 = null, onCommitUnmount$1 = null; + +if ("undefined" != typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && __REACT_DEVTOOLS_GLOBAL_HOOK__.supportsFiber) { + var inject$1 = __REACT_DEVTOOLS_GLOBAL_HOOK__.inject, onCommitFiberRoot = __REACT_DEVTOOLS_GLOBAL_HOOK__.onCommitFiberRoot, onCommitFiberUnmount = __REACT_DEVTOOLS_GLOBAL_HOOK__.onCommitFiberUnmount; + injectInternals$1 = function(internals) { + warning(null == rendererID, "Cannot inject into DevTools twice."), rendererID = inject$1(internals); + }, onCommitRoot$1 = function(root) { + if (null != rendererID) try { + onCommitFiberRoot(rendererID, root); + } catch (err) {} + }, onCommitUnmount$1 = function(fiber) { + if (null != rendererID) try { + onCommitFiberUnmount(rendererID, fiber); + } catch (err) {} + }; +} + +var injectInternals_1 = injectInternals$1, onCommitRoot_1 = onCommitRoot$1, onCommitUnmount_1 = onCommitUnmount$1, ReactFiberDevToolsHook = { + injectInternals: injectInternals_1, + onCommitRoot: onCommitRoot_1, + onCommitUnmount: onCommitUnmount_1 +}, ClassComponent$8 = ReactTypeOfWork.ClassComponent, HostRoot$6 = ReactTypeOfWork.HostRoot, HostComponent$7 = ReactTypeOfWork.HostComponent, HostText$5 = ReactTypeOfWork.HostText, HostPortal$5 = ReactTypeOfWork.HostPortal, CoroutineComponent$4 = ReactTypeOfWork.CoroutineComponent, commitCallbacks$1 = ReactFiberUpdateQueue.commitCallbacks, onCommitUnmount = ReactFiberDevToolsHook.onCommitUnmount, Placement$5 = ReactTypeOfSideEffect.Placement, Update$3 = ReactTypeOfSideEffect.Update, Callback$1 = ReactTypeOfSideEffect.Callback, ContentReset$2 = ReactTypeOfSideEffect.ContentReset, ReactFiberCommitWork = function(config, captureError) { + var commitMount = config.commitMount, commitUpdate = config.commitUpdate, resetTextContent = config.resetTextContent, commitTextUpdate = config.commitTextUpdate, appendChild = config.appendChild, insertBefore = config.insertBefore, removeChild = config.removeChild, getPublicInstance = config.getPublicInstance; + function safelyCallComponentWillUnmount(current, instance) { + try { + instance.componentWillUnmount(); + } catch (unmountError) { + captureError(current, unmountError); + } + } + function safelyDetachRef(current) { + var ref = current.ref; + if (null !== ref) { + try { + ref(null); + } catch (refError) { + captureError(current, refError); + } + } + } + function getHostParent(fiber) { + for (var parent = fiber.return; null !== parent; ) { + switch (parent.tag) { + case HostComponent$7: + return parent.stateNode; + + case HostRoot$6: + case HostPortal$5: + return parent.stateNode.containerInfo; + } + parent = parent.return; + } + invariant(!1, "Expected to find a host parent. This error is likely caused by a bug " + "in React. Please file an issue."); + } + function getHostParentFiber(fiber) { + for (var parent = fiber.return; null !== parent; ) { + if (isHostParent(parent)) return parent; + parent = parent.return; + } + invariant(!1, "Expected to find a host parent. This error is likely caused by a bug " + "in React. Please file an issue."); + } + function isHostParent(fiber) { + return fiber.tag === HostComponent$7 || fiber.tag === HostRoot$6 || fiber.tag === HostPortal$5; + } + function getHostSibling(fiber) { + var node = fiber; + siblings: for (;!0; ) { + for (;null === node.sibling; ) { + if (null === node.return || isHostParent(node.return)) return null; + node = node.return; + } + for (node.sibling.return = node.return, node = node.sibling; node.tag !== HostComponent$7 && node.tag !== HostText$5; ) { + if (node.effectTag & Placement$5) continue siblings; + if (null === node.child || node.tag === HostPortal$5) continue siblings; + node.child.return = node, node = node.child; + } + if (!(node.effectTag & Placement$5)) return node.stateNode; + } + } + function commitPlacement(finishedWork) { + var parentFiber = getHostParentFiber(finishedWork), parent = void 0; + switch (parentFiber.tag) { + case HostComponent$7: + parent = parentFiber.stateNode; + break; + + case HostRoot$6: + case HostPortal$5: + parent = parentFiber.stateNode.containerInfo; + break; + + default: + invariant(!1, "Invalid host parent fiber. This error is likely caused by a bug " + "in React. Please file an issue."); + } + parentFiber.effectTag & ContentReset$2 && (resetTextContent(parent), parentFiber.effectTag &= ~ContentReset$2); + for (var before = getHostSibling(finishedWork), node = finishedWork; !0; ) { + if (node.tag === HostComponent$7 || node.tag === HostText$5) before ? insertBefore(parent, node.stateNode, before) : appendChild(parent, node.stateNode); else if (node.tag === HostPortal$5) ; else if (null !== node.child) { + node.child.return = node, node = node.child; + continue; + } + if (node === finishedWork) return; + for (;null === node.sibling; ) { + if (null === node.return || node.return === finishedWork) return; + node = node.return; + } + node.sibling.return = node.return, node = node.sibling; + } + } + function commitNestedUnmounts(root) { + for (var node = root; !0; ) if (commitUnmount(node), null === node.child || node.tag === HostPortal$5) { + if (node === root) return; + for (;null === node.sibling; ) { + if (null === node.return || node.return === root) return; + node = node.return; + } + node.sibling.return = node.return, node = node.sibling; + } else node.child.return = node, node = node.child; + } + function unmountHostComponents(parent, current) { + for (var node = current; !0; ) { + if (node.tag === HostComponent$7 || node.tag === HostText$5) commitNestedUnmounts(node), + removeChild(parent, node.stateNode); else if (node.tag === HostPortal$5) { + if (parent = node.stateNode.containerInfo, null !== node.child) { + node.child.return = node, node = node.child; + continue; + } + } else if (commitUnmount(node), null !== node.child) { + node.child.return = node, node = node.child; + continue; + } + if (node === current) return; + for (;null === node.sibling; ) { + if (null === node.return || node.return === current) return; + node = node.return, node.tag === HostPortal$5 && (parent = getHostParent(node)); + } + node.sibling.return = node.return, node = node.sibling; + } + } + function commitDeletion(current) { + unmountHostComponents(getHostParent(current), current), current.return = null, current.child = null, + current.alternate && (current.alternate.child = null, current.alternate.return = null); + } + function commitUnmount(current) { + switch ("function" == typeof onCommitUnmount && onCommitUnmount(current), current.tag) { + case ClassComponent$8: + safelyDetachRef(current); + var instance = current.stateNode; + return void ("function" == typeof instance.componentWillUnmount && safelyCallComponentWillUnmount(current, instance)); + + case HostComponent$7: + return void safelyDetachRef(current); + + case CoroutineComponent$4: + return void commitNestedUnmounts(current.stateNode); + + case HostPortal$5: + return void unmountHostComponents(getHostParent(current), current); + } + } + function commitWork(current, finishedWork) { + switch (finishedWork.tag) { + case ClassComponent$8: + return; + + case HostComponent$7: + var instance = finishedWork.stateNode; + if (null != instance && null !== current) { + var newProps = finishedWork.memoizedProps, oldProps = current.memoizedProps, type = finishedWork.type, updatePayload = finishedWork.updateQueue; + finishedWork.updateQueue = null, null !== updatePayload && commitUpdate(instance, updatePayload, type, oldProps, newProps, finishedWork); + } + return; + + case HostText$5: + invariant(null !== finishedWork.stateNode && null !== current, "This should only be done during updates. This error is likely " + "caused by a bug in React. Please file an issue."); + var textInstance = finishedWork.stateNode, newText = finishedWork.memoizedProps, oldText = current.memoizedProps; + return void commitTextUpdate(textInstance, oldText, newText); + + case HostRoot$6: + case HostPortal$5: + return; + + default: + invariant(!1, "This unit of work tag should not have side-effects. This error is " + "likely caused by a bug in React. Please file an issue."); + } + } + function commitLifeCycles(current, finishedWork) { + switch (finishedWork.tag) { + case ClassComponent$8: + var instance = finishedWork.stateNode; + if (finishedWork.effectTag & Update$3) if (null === current) instance.componentDidMount(); else { + var prevProps = current.memoizedProps, prevState = current.memoizedState; + instance.componentDidUpdate(prevProps, prevState); + } + return void (finishedWork.effectTag & Callback$1 && null !== finishedWork.updateQueue && commitCallbacks$1(finishedWork, finishedWork.updateQueue, instance)); + + case HostRoot$6: + var updateQueue = finishedWork.updateQueue; + if (null !== updateQueue) { + var _instance = finishedWork.child && finishedWork.child.stateNode; + commitCallbacks$1(finishedWork, updateQueue, _instance); + } + return; + + case HostComponent$7: + var _instance2 = finishedWork.stateNode; + if (null === current && finishedWork.effectTag & Update$3) { + var type = finishedWork.type, props = finishedWork.memoizedProps; + commitMount(_instance2, type, props, finishedWork); + } + return; + + case HostText$5: + case HostPortal$5: + return; + + default: + invariant(!1, "This unit of work tag should not have side-effects. This error is " + "likely caused by a bug in React. Please file an issue."); + } + } + function commitAttachRef(finishedWork) { + var ref = finishedWork.ref; + if (null !== ref) { + ref(getPublicInstance(finishedWork.stateNode)); + } + } + function commitDetachRef(current) { + var currentRef = current.ref; + null !== currentRef && currentRef(null); + } + return { + commitPlacement: commitPlacement, + commitDeletion: commitDeletion, + commitWork: commitWork, + commitLifeCycles: commitLifeCycles, + commitAttachRef: commitAttachRef, + commitDetachRef: commitDetachRef + }; +}, createCursor$2 = ReactFiberStack.createCursor, pop$2 = ReactFiberStack.pop, push$2 = ReactFiberStack.push, NO_CONTEXT = {}, ReactFiberHostContext = function(config) { + var getChildHostContext = config.getChildHostContext, getRootHostContext = config.getRootHostContext, contextStackCursor = createCursor$2(NO_CONTEXT), contextFiberStackCursor = createCursor$2(NO_CONTEXT), rootInstanceStackCursor = createCursor$2(NO_CONTEXT); + function requiredContext(c) { + return invariant(c !== NO_CONTEXT, "Expected host context to exist. This error is likely caused by a bug " + "in React. Please file an issue."), + c; + } + function getRootHostContainer() { + return requiredContext(rootInstanceStackCursor.current); + } + function pushHostContainer(fiber, nextRootInstance) { + push$2(rootInstanceStackCursor, nextRootInstance, fiber); + var nextRootContext = getRootHostContext(nextRootInstance); + push$2(contextFiberStackCursor, fiber, fiber), push$2(contextStackCursor, nextRootContext, fiber); + } + function popHostContainer(fiber) { + pop$2(contextStackCursor, fiber), pop$2(contextFiberStackCursor, fiber), pop$2(rootInstanceStackCursor, fiber); + } + function getHostContext() { + return requiredContext(contextStackCursor.current); + } + function pushHostContext(fiber) { + var rootInstance = requiredContext(rootInstanceStackCursor.current), context = requiredContext(contextStackCursor.current), nextContext = getChildHostContext(context, fiber.type, rootInstance); + context !== nextContext && (push$2(contextFiberStackCursor, fiber, fiber), push$2(contextStackCursor, nextContext, fiber)); + } + function popHostContext(fiber) { + contextFiberStackCursor.current === fiber && (pop$2(contextStackCursor, fiber), + pop$2(contextFiberStackCursor, fiber)); + } + function resetHostContainer() { + contextStackCursor.current = NO_CONTEXT, rootInstanceStackCursor.current = NO_CONTEXT; + } + return { + getHostContext: getHostContext, + getRootHostContainer: getRootHostContainer, + popHostContainer: popHostContainer, + popHostContext: popHostContext, + pushHostContainer: pushHostContainer, + pushHostContext: pushHostContext, + resetHostContainer: resetHostContainer + }; +}, HostComponent$8 = ReactTypeOfWork.HostComponent, HostRoot$7 = ReactTypeOfWork.HostRoot, Deletion$2 = ReactTypeOfSideEffect.Deletion, Placement$6 = ReactTypeOfSideEffect.Placement, createFiberFromHostInstanceForDeletion$1 = ReactFiber.createFiberFromHostInstanceForDeletion, ReactFiberHydrationContext = function(config) { + var shouldSetTextContent = config.shouldSetTextContent, canHydrateInstance = config.canHydrateInstance, canHydrateTextInstance = config.canHydrateTextInstance, getNextHydratableSibling = config.getNextHydratableSibling, getFirstHydratableChild = config.getFirstHydratableChild, hydrateInstance = config.hydrateInstance, hydrateTextInstance = config.hydrateTextInstance; + if (!(canHydrateInstance && canHydrateTextInstance && getNextHydratableSibling && getFirstHydratableChild && hydrateInstance && hydrateTextInstance)) return { + enterHydrationState: function() { + return !1; + }, + resetHydrationState: function() {}, + tryToClaimNextHydratableInstance: function() {}, + hydrateHostInstance: function() { + invariant(!1, "React bug."); + }, + hydrateHostTextInstance: function() { + invariant(!1, "React bug."); + }, + popHydrationState: function(fiber) { + return !1; + } + }; + var hydrationParentFiber = null, nextHydratableInstance = null, isHydrating = !1; + function enterHydrationState(fiber) { + var parentInstance = fiber.stateNode.containerInfo; + return nextHydratableInstance = getFirstHydratableChild(parentInstance), hydrationParentFiber = fiber, + isHydrating = !0, !0; + } + function deleteHydratableInstance(returnFiber, instance) { + var childToDelete = createFiberFromHostInstanceForDeletion$1(); + childToDelete.stateNode = instance, childToDelete.return = returnFiber; + var last = returnFiber.progressedLastDeletion; + null !== last ? (last.nextEffect = childToDelete, returnFiber.progressedLastDeletion = childToDelete) : returnFiber.progressedFirstDeletion = returnFiber.progressedLastDeletion = childToDelete, + childToDelete.effectTag = Deletion$2, null !== returnFiber.lastEffect ? (returnFiber.lastEffect.nextEffect = childToDelete, + returnFiber.lastEffect = childToDelete) : returnFiber.firstEffect = returnFiber.lastEffect = childToDelete; + } + function tryToClaimNextHydratableInstance(fiber) { + if (isHydrating) { + var nextInstance = nextHydratableInstance; + if (!nextInstance) return fiber.effectTag |= Placement$6, isHydrating = !1, void (hydrationParentFiber = fiber); + var type = fiber.type, props = fiber.memoizedProps; + if (!canHydrateInstance(nextInstance, type, props)) { + if (!(nextInstance = getNextHydratableSibling(nextInstance)) || !canHydrateInstance(nextInstance, type, props)) return fiber.effectTag |= Placement$6, + isHydrating = !1, void (hydrationParentFiber = fiber); + deleteHydratableInstance(hydrationParentFiber, nextHydratableInstance); + } + fiber.stateNode = nextInstance, hydrationParentFiber = fiber, nextHydratableInstance = getFirstHydratableChild(nextInstance); + } + } + function hydrateHostInstance(fiber, rootContainerInstance) { + var instance = fiber.stateNode; + return hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, fiber), + instance; + } + function hydrateHostTextInstance(fiber) { + var textInstance = fiber.stateNode; + return hydrateTextInstance(textInstance, fiber), textInstance; + } + function popToNextHostParent(fiber) { + for (var parent = fiber.return; null !== parent && parent.tag !== HostComponent$8 && parent.tag !== HostRoot$7; ) parent = parent.return; + hydrationParentFiber = parent; + } + function popHydrationState(fiber) { + if (fiber !== hydrationParentFiber) return !1; + if (!isHydrating) return popToNextHostParent(fiber), isHydrating = !0, !1; + if (fiber.tag !== HostComponent$8 || "head" !== fiber.type && "body" !== fiber.type && !shouldSetTextContent(fiber.memoizedProps)) for (var nextInstance = nextHydratableInstance; nextInstance; ) deleteHydratableInstance(fiber, nextInstance), + nextInstance = getNextHydratableSibling(nextInstance); + return popToNextHostParent(fiber), nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null, + !0; + } + function resetHydrationState() { + hydrationParentFiber = null, nextHydratableInstance = null, isHydrating = !1; + } + return { + enterHydrationState: enterHydrationState, + resetHydrationState: resetHydrationState, + tryToClaimNextHydratableInstance: tryToClaimNextHydratableInstance, + hydrateHostInstance: hydrateHostInstance, + hydrateHostTextInstance: hydrateHostTextInstance, + popHydrationState: popHydrationState + }; +}, popContextProvider$1 = ReactFiberContext.popContextProvider, reset$1 = ReactFiberStack.reset, getStackAddendumByWorkInProgressFiber = ReactFiberComponentTreeHook.getStackAddendumByWorkInProgressFiber, logCapturedError$1 = ReactFiberErrorLogger.logCapturedError, ReactCurrentOwner$1 = ReactGlobalSharedState_1.ReactCurrentOwner, cloneFiber$1 = ReactFiber.cloneFiber, onCommitRoot = ReactFiberDevToolsHook.onCommitRoot, NoWork$2 = ReactPriorityLevel.NoWork, SynchronousPriority$1 = ReactPriorityLevel.SynchronousPriority, TaskPriority$1 = ReactPriorityLevel.TaskPriority, AnimationPriority = ReactPriorityLevel.AnimationPriority, HighPriority = ReactPriorityLevel.HighPriority, LowPriority = ReactPriorityLevel.LowPriority, OffscreenPriority = ReactPriorityLevel.OffscreenPriority, AsyncUpdates = ReactTypeOfInternalContext.AsyncUpdates, NoEffect$2 = ReactTypeOfSideEffect.NoEffect, Placement$1 = ReactTypeOfSideEffect.Placement, Update = ReactTypeOfSideEffect.Update, PlacementAndUpdate = ReactTypeOfSideEffect.PlacementAndUpdate, Deletion = ReactTypeOfSideEffect.Deletion, ContentReset = ReactTypeOfSideEffect.ContentReset, Callback = ReactTypeOfSideEffect.Callback, Err = ReactTypeOfSideEffect.Err, Ref = ReactTypeOfSideEffect.Ref, HostRoot$3 = ReactTypeOfWork.HostRoot, HostComponent$3 = ReactTypeOfWork.HostComponent, HostPortal$1 = ReactTypeOfWork.HostPortal, ClassComponent$3 = ReactTypeOfWork.ClassComponent, getPendingPriority$1 = ReactFiberUpdateQueue.getPendingPriority, _require14 = ReactFiberContext, resetContext$1 = _require14.resetContext, ReactFiberInstrumentation$1, timeHeuristicForUnitOfWork = 1, ReactFiberScheduler = function(config) { + var hostContext = ReactFiberHostContext(config), hydrationContext = ReactFiberHydrationContext(config), popHostContainer = hostContext.popHostContainer, popHostContext = hostContext.popHostContext, resetHostContainer = hostContext.resetHostContainer, _ReactFiberBeginWork = ReactFiberBeginWork(config, hostContext, hydrationContext, scheduleUpdate, getPriorityContext), beginWork = _ReactFiberBeginWork.beginWork, beginFailedWork = _ReactFiberBeginWork.beginFailedWork, _ReactFiberCompleteWo = ReactFiberCompleteWork(config, hostContext, hydrationContext), completeWork = _ReactFiberCompleteWo.completeWork, _ReactFiberCommitWork = ReactFiberCommitWork(config, captureError), commitPlacement = _ReactFiberCommitWork.commitPlacement, commitDeletion = _ReactFiberCommitWork.commitDeletion, commitWork = _ReactFiberCommitWork.commitWork, commitLifeCycles = _ReactFiberCommitWork.commitLifeCycles, commitAttachRef = _ReactFiberCommitWork.commitAttachRef, commitDetachRef = _ReactFiberCommitWork.commitDetachRef, hostScheduleAnimationCallback = config.scheduleAnimationCallback, hostScheduleDeferredCallback = config.scheduleDeferredCallback, useSyncScheduling = config.useSyncScheduling, prepareForCommit = config.prepareForCommit, resetAfterCommit = config.resetAfterCommit, priorityContext = NoWork$2, priorityContextBeforeReconciliation = NoWork$2, isPerformingWork = !1, deadlineHasExpired = !1, isBatchingUpdates = !1, nextUnitOfWork = null, nextPriorityLevel = NoWork$2, nextEffect = null, pendingCommit = null, nextScheduledRoot = null, lastScheduledRoot = null, isAnimationCallbackScheduled = !1, isDeferredCallbackScheduled = !1, capturedErrors = null, failedBoundaries = null, commitPhaseBoundaries = null, firstUncaughtError = null, fatalError = null, isCommitting = !1, isUnmounting = !1; + function scheduleAnimationCallback(callback) { + isAnimationCallbackScheduled || (isAnimationCallbackScheduled = !0, hostScheduleAnimationCallback(callback)); + } + function scheduleDeferredCallback(callback) { + isDeferredCallbackScheduled || (isDeferredCallbackScheduled = !0, hostScheduleDeferredCallback(callback)); + } + function resetContextStack() { + reset$1(), resetContext$1(), resetHostContainer(); + } + function findNextUnitOfWork() { + for (;null !== nextScheduledRoot && nextScheduledRoot.current.pendingWorkPriority === NoWork$2; ) { + nextScheduledRoot.isScheduled = !1; + var next = nextScheduledRoot.nextScheduledRoot; + if (nextScheduledRoot.nextScheduledRoot = null, nextScheduledRoot === lastScheduledRoot) return nextScheduledRoot = null, + lastScheduledRoot = null, nextPriorityLevel = NoWork$2, null; + nextScheduledRoot = next; + } + for (var root = nextScheduledRoot, highestPriorityRoot = null, highestPriorityLevel = NoWork$2; null !== root; ) root.current.pendingWorkPriority !== NoWork$2 && (highestPriorityLevel === NoWork$2 || highestPriorityLevel > root.current.pendingWorkPriority) && (highestPriorityLevel = root.current.pendingWorkPriority, + highestPriorityRoot = root), root = root.nextScheduledRoot; + return null !== highestPriorityRoot ? (nextPriorityLevel = highestPriorityLevel, + priorityContext = nextPriorityLevel, resetContextStack(), cloneFiber$1(highestPriorityRoot.current, highestPriorityLevel)) : (nextPriorityLevel = NoWork$2, + null); + } + function commitAllHostEffects() { + for (;null !== nextEffect; ) { + var effectTag = nextEffect.effectTag; + if (effectTag & ContentReset && config.resetTextContent(nextEffect.stateNode), effectTag & Ref) { + var current = nextEffect.alternate; + null !== current && commitDetachRef(current); + } + switch (effectTag & ~(Callback | Err | ContentReset | Ref)) { + case Placement$1: + commitPlacement(nextEffect), nextEffect.effectTag &= ~Placement$1; + break; + + case PlacementAndUpdate: + commitPlacement(nextEffect), nextEffect.effectTag &= ~Placement$1; + var _current = nextEffect.alternate; + commitWork(_current, nextEffect); + break; + + case Update: + var _current2 = nextEffect.alternate; + commitWork(_current2, nextEffect); + break; + + case Deletion: + isUnmounting = !0, commitDeletion(nextEffect), isUnmounting = !1; + } + nextEffect = nextEffect.nextEffect; + } + } + function commitAllLifeCycles() { + for (;null !== nextEffect; ) { + var effectTag = nextEffect.effectTag; + if (effectTag & (Update | Callback)) { + var current = nextEffect.alternate; + commitLifeCycles(current, nextEffect); + } + effectTag & Ref && commitAttachRef(nextEffect), effectTag & Err && commitErrorHandling(nextEffect); + var next = nextEffect.nextEffect; + nextEffect.nextEffect = null, nextEffect = next; + } + } + function commitAllWork(finishedWork) { + isCommitting = !0, pendingCommit = null; + var root = finishedWork.stateNode; + invariant(root.current !== finishedWork, "Cannot commit the same tree as before. This is probably a bug " + "related to the return field. This error is likely caused by a bug " + "in React. Please file an issue."), + ReactCurrentOwner$1.current = null; + var previousPriorityContext = priorityContext; + priorityContext = TaskPriority$1; + var firstEffect = void 0; + finishedWork.effectTag !== NoEffect$2 ? null !== finishedWork.lastEffect ? (finishedWork.lastEffect.nextEffect = finishedWork, + firstEffect = finishedWork.firstEffect) : firstEffect = finishedWork : firstEffect = finishedWork.firstEffect; + var commitInfo = prepareForCommit(); + for (nextEffect = firstEffect; null !== nextEffect; ) { + var _error = null; + try { + commitAllHostEffects(finishedWork); + } catch (e) { + _error = e; + } + null !== _error && (invariant(null !== nextEffect, "Should have next effect. This error is likely caused by a bug " + "in React. Please file an issue."), + captureError(nextEffect, _error), null !== nextEffect && (nextEffect = nextEffect.nextEffect)); + } + for (resetAfterCommit(commitInfo), root.current = finishedWork, nextEffect = firstEffect; null !== nextEffect; ) { + var _error2 = null; + try { + commitAllLifeCycles(finishedWork); + } catch (e) { + _error2 = e; + } + null !== _error2 && (invariant(null !== nextEffect, "Should have next effect. This error is likely caused by a bug " + "in React. Please file an issue."), + captureError(nextEffect, _error2), null !== nextEffect && (nextEffect = nextEffect.nextEffect)); + } + isCommitting = !1, "function" == typeof onCommitRoot && onCommitRoot(finishedWork.stateNode), + !1 && ReactFiberInstrumentation$1.debugTool && ReactFiberInstrumentation$1.debugTool.onCommitWork(finishedWork), + commitPhaseBoundaries && (commitPhaseBoundaries.forEach(scheduleErrorRecovery), + commitPhaseBoundaries = null), priorityContext = previousPriorityContext; + } + function resetWorkPriority(workInProgress) { + var newPriority = NoWork$2, queue = workInProgress.updateQueue, tag = workInProgress.tag; + null === queue || tag !== ClassComponent$3 && tag !== HostRoot$3 || (newPriority = getPendingPriority$1(queue)); + for (var child = workInProgress.progressedChild; null !== child; ) child.pendingWorkPriority !== NoWork$2 && (newPriority === NoWork$2 || newPriority > child.pendingWorkPriority) && (newPriority = child.pendingWorkPriority), + child = child.sibling; + workInProgress.pendingWorkPriority = newPriority; + } + function completeUnitOfWork(workInProgress) { + for (;!0; ) { + var current = workInProgress.alternate, next = completeWork(current, workInProgress), returnFiber = workInProgress.return, siblingFiber = workInProgress.sibling; + if (resetWorkPriority(workInProgress), null !== next) return !1 && ReactFiberInstrumentation$1.debugTool && ReactFiberInstrumentation$1.debugTool.onCompleteWork(workInProgress), + next; + if (null !== returnFiber && (null === returnFiber.firstEffect && (returnFiber.firstEffect = workInProgress.firstEffect), + null !== workInProgress.lastEffect && (null !== returnFiber.lastEffect && (returnFiber.lastEffect.nextEffect = workInProgress.firstEffect), + returnFiber.lastEffect = workInProgress.lastEffect), workInProgress.effectTag !== NoEffect$2 && (null !== returnFiber.lastEffect ? returnFiber.lastEffect.nextEffect = workInProgress : returnFiber.firstEffect = workInProgress, + returnFiber.lastEffect = workInProgress)), !1 && ReactFiberInstrumentation$1.debugTool && ReactFiberInstrumentation$1.debugTool.onCompleteWork(workInProgress), + null !== siblingFiber) return siblingFiber; + if (null === returnFiber) return nextPriorityLevel < HighPriority ? commitAllWork(workInProgress) : pendingCommit = workInProgress, + null; + workInProgress = returnFiber; + } + return null; + } + function performUnitOfWork(workInProgress) { + var current = workInProgress.alternate, next = beginWork(current, workInProgress, nextPriorityLevel); + return !1 && ReactFiberInstrumentation$1.debugTool && ReactFiberInstrumentation$1.debugTool.onBeginWork(workInProgress), + null === next && (next = completeUnitOfWork(workInProgress)), ReactCurrentOwner$1.current = null, + next; + } + function performFailedUnitOfWork(workInProgress) { + var current = workInProgress.alternate, next = beginFailedWork(current, workInProgress, nextPriorityLevel); + return !1 && ReactFiberInstrumentation$1.debugTool && ReactFiberInstrumentation$1.debugTool.onBeginWork(workInProgress), + null === next && (next = completeUnitOfWork(workInProgress)), ReactCurrentOwner$1.current = null, + next; + } + function performDeferredWork(deadline) { + isDeferredCallbackScheduled = !1, performWork(OffscreenPriority, deadline); + } + function performAnimationWork() { + isAnimationCallbackScheduled = !1, performWork(AnimationPriority, null); + } + function clearErrors() { + for (null === nextUnitOfWork && (nextUnitOfWork = findNextUnitOfWork()); null !== capturedErrors && capturedErrors.size && null !== nextUnitOfWork && nextPriorityLevel !== NoWork$2 && nextPriorityLevel <= TaskPriority$1; ) null === (nextUnitOfWork = hasCapturedError(nextUnitOfWork) ? performFailedUnitOfWork(nextUnitOfWork) : performUnitOfWork(nextUnitOfWork)) && (nextUnitOfWork = findNextUnitOfWork()); + } + function workLoop(priorityLevel, deadline) { + clearErrors(), null === nextUnitOfWork && (nextUnitOfWork = findNextUnitOfWork()); + var hostRootTimeMarker = void 0; + if (ReactFeatureFlags_1.logTopLevelRenders && null !== nextUnitOfWork && nextUnitOfWork.tag === HostRoot$3 && null !== nextUnitOfWork.child) { + hostRootTimeMarker = "React update: " + (getComponentName_1(nextUnitOfWork.child) || ""), + console.time(hostRootTimeMarker); + } + if (null !== deadline && priorityLevel > TaskPriority$1) for (;null !== nextUnitOfWork && !deadlineHasExpired; ) deadline.timeRemaining() > timeHeuristicForUnitOfWork ? null === (nextUnitOfWork = performUnitOfWork(nextUnitOfWork)) && null !== pendingCommit && (deadline.timeRemaining() > timeHeuristicForUnitOfWork ? (commitAllWork(pendingCommit), + nextUnitOfWork = findNextUnitOfWork(), clearErrors()) : deadlineHasExpired = !0) : deadlineHasExpired = !0; else for (;null !== nextUnitOfWork && nextPriorityLevel !== NoWork$2 && nextPriorityLevel <= priorityLevel; ) null === (nextUnitOfWork = performUnitOfWork(nextUnitOfWork)) && (nextUnitOfWork = findNextUnitOfWork(), + clearErrors()); + hostRootTimeMarker && console.timeEnd(hostRootTimeMarker); + } + function performWork(priorityLevel, deadline) { + invariant(!isPerformingWork, "performWork was called recursively. This error is likely caused " + "by a bug in React. Please file an issue."), + isPerformingWork = !0; + for (var isPerformingDeferredWork = !!deadline; priorityLevel !== NoWork$2 && !fatalError; ) { + invariant(null !== deadline || priorityLevel < HighPriority, "Cannot perform deferred work without a deadline. This error is " + "likely caused by a bug in React. Please file an issue."), + null === pendingCommit || deadlineHasExpired || commitAllWork(pendingCommit), priorityContextBeforeReconciliation = priorityContext; + var _error3 = null; + try { + workLoop(priorityLevel, deadline); + } catch (e) { + _error3 = e; + } + if (priorityContext = priorityContextBeforeReconciliation, null !== _error3) { + var failedWork = nextUnitOfWork; + if (null !== failedWork) { + var maybeBoundary = captureError(failedWork, _error3); + if (null !== maybeBoundary) { + var boundary = maybeBoundary; + beginFailedWork(boundary.alternate, boundary, priorityLevel), unwindContexts(failedWork, boundary), + nextUnitOfWork = completeUnitOfWork(boundary); + } + continue; + } + null === fatalError && (fatalError = _error3); + } + if (priorityLevel = NoWork$2, nextPriorityLevel === NoWork$2 || !isPerformingDeferredWork || deadlineHasExpired) switch (nextPriorityLevel) { + case SynchronousPriority$1: + case TaskPriority$1: + priorityLevel = nextPriorityLevel; + break; + + case AnimationPriority: + scheduleAnimationCallback(performAnimationWork), scheduleDeferredCallback(performDeferredWork); + break; + + case HighPriority: + case LowPriority: + case OffscreenPriority: + scheduleDeferredCallback(performDeferredWork); + } else priorityLevel = nextPriorityLevel; + } + var errorToThrow = fatalError || firstUncaughtError; + if (isPerformingWork = !1, deadlineHasExpired = !1, fatalError = null, firstUncaughtError = null, + capturedErrors = null, failedBoundaries = null, null !== errorToThrow) throw errorToThrow; + } + function captureError(failedWork, error) { + ReactCurrentOwner$1.current = null, nextUnitOfWork = null; + var boundary = null, errorBoundaryFound = !1, willRetry = !1, errorBoundaryName = null; + if (failedWork.tag === HostRoot$3) boundary = failedWork, isFailedBoundary(failedWork) && (fatalError = error); else for (var node = failedWork.return; null !== node && null === boundary; ) { + if (node.tag === ClassComponent$3) { + var instance = node.stateNode; + "function" == typeof instance.unstable_handleError && (errorBoundaryFound = !0, + errorBoundaryName = getComponentName_1(node), boundary = node, willRetry = !0); + } else node.tag === HostRoot$3 && (boundary = node); + if (isFailedBoundary(node)) { + if (isUnmounting) return null; + if (null !== commitPhaseBoundaries && (commitPhaseBoundaries.has(node) || null !== node.alternate && commitPhaseBoundaries.has(node.alternate))) return null; + boundary = null, willRetry = !1; + } + node = node.return; + } + if (null !== boundary) { + null === failedBoundaries && (failedBoundaries = new Set()), failedBoundaries.add(boundary); + var _componentStack = getStackAddendumByWorkInProgressFiber(failedWork), _componentName2 = getComponentName_1(failedWork); + return null === capturedErrors && (capturedErrors = new Map()), capturedErrors.set(boundary, { + componentName: _componentName2, + componentStack: _componentStack, + error: error, + errorBoundary: errorBoundaryFound ? boundary.stateNode : null, + errorBoundaryFound: errorBoundaryFound, + errorBoundaryName: errorBoundaryName, + willRetry: willRetry + }), isCommitting ? (null === commitPhaseBoundaries && (commitPhaseBoundaries = new Set()), + commitPhaseBoundaries.add(boundary)) : scheduleErrorRecovery(boundary), boundary; + } + return null === firstUncaughtError && (firstUncaughtError = error), null; + } + function hasCapturedError(fiber) { + return null !== capturedErrors && (capturedErrors.has(fiber) || null !== fiber.alternate && capturedErrors.has(fiber.alternate)); + } + function isFailedBoundary(fiber) { + return null !== failedBoundaries && (failedBoundaries.has(fiber) || null !== fiber.alternate && failedBoundaries.has(fiber.alternate)); + } + function commitErrorHandling(effectfulFiber) { + var capturedError = void 0; + null !== capturedErrors && (capturedError = capturedErrors.get(effectfulFiber), + capturedErrors.delete(effectfulFiber), null == capturedError && null !== effectfulFiber.alternate && (effectfulFiber = effectfulFiber.alternate, + capturedError = capturedErrors.get(effectfulFiber), capturedErrors.delete(effectfulFiber))), + invariant(null != capturedError, "No error for given unit of work. This error is likely caused by a " + "bug in React. Please file an issue."); + var error = capturedError.error; + try { + logCapturedError$1(capturedError); + } catch (e) { + console.error(e); + } + switch (effectfulFiber.tag) { + case ClassComponent$3: + var instance = effectfulFiber.stateNode, info = { + componentStack: capturedError.componentStack + }; + return void instance.unstable_handleError(error, info); + + case HostRoot$3: + return void (null === firstUncaughtError && (firstUncaughtError = error)); + + default: + invariant(!1, "Invalid type of work. This error is likely caused by a bug in " + "React. Please file an issue."); + } + } + function unwindContexts(from, to) { + for (var node = from; null !== node && node !== to && node.alternate !== to; ) { + switch (node.tag) { + case ClassComponent$3: + popContextProvider$1(node); + break; + + case HostComponent$3: + popHostContext(node); + break; + + case HostRoot$3: + case HostPortal$1: + popHostContainer(node); + } + node = node.return; + } + } + function scheduleRoot(root, priorityLevel) { + priorityLevel !== NoWork$2 && (root.isScheduled || (root.isScheduled = !0, lastScheduledRoot ? (lastScheduledRoot.nextScheduledRoot = root, + lastScheduledRoot = root) : (nextScheduledRoot = root, lastScheduledRoot = root))); + } + function scheduleUpdate(fiber, priorityLevel) { + priorityLevel <= nextPriorityLevel && (nextUnitOfWork = null); + for (var node = fiber, shouldContinue = !0; null !== node && shouldContinue; ) { + if (shouldContinue = !1, (node.pendingWorkPriority === NoWork$2 || node.pendingWorkPriority > priorityLevel) && (shouldContinue = !0, + node.pendingWorkPriority = priorityLevel), null !== node.alternate && (node.alternate.pendingWorkPriority === NoWork$2 || node.alternate.pendingWorkPriority > priorityLevel) && (shouldContinue = !0, + node.alternate.pendingWorkPriority = priorityLevel), null === node.return) { + if (node.tag !== HostRoot$3) return; + switch (scheduleRoot(node.stateNode, priorityLevel), priorityLevel) { + case SynchronousPriority$1: + return void performWork(SynchronousPriority$1, null); + + case TaskPriority$1: + return; + + case AnimationPriority: + return void scheduleAnimationCallback(performAnimationWork); + + case HighPriority: + case LowPriority: + case OffscreenPriority: + return void scheduleDeferredCallback(performDeferredWork); + } + } + node = node.return; + } + } + function getPriorityContext(fiber, forceAsync) { + var priorityLevel = priorityContext; + return priorityLevel === NoWork$2 && (priorityLevel = !useSyncScheduling || fiber.internalContextTag & AsyncUpdates || forceAsync ? LowPriority : SynchronousPriority$1), + priorityLevel === SynchronousPriority$1 && (isPerformingWork || isBatchingUpdates) ? TaskPriority$1 : priorityLevel; + } + function scheduleErrorRecovery(fiber) { + scheduleUpdate(fiber, TaskPriority$1); + } + function performWithPriority(priorityLevel, fn) { + var previousPriorityContext = priorityContext; + priorityContext = priorityLevel; + try { + fn(); + } finally { + priorityContext = previousPriorityContext; + } + } + function batchedUpdates(fn, a) { + var previousIsBatchingUpdates = isBatchingUpdates; + isBatchingUpdates = !0; + try { + return fn(a); + } finally { + isBatchingUpdates = previousIsBatchingUpdates, isPerformingWork || isBatchingUpdates || performWork(TaskPriority$1, null); + } + } + function unbatchedUpdates(fn) { + var previousIsBatchingUpdates = isBatchingUpdates; + isBatchingUpdates = !1; + try { + return fn(); + } finally { + isBatchingUpdates = previousIsBatchingUpdates; + } + } + function syncUpdates(fn) { + var previousPriorityContext = priorityContext; + priorityContext = SynchronousPriority$1; + try { + return fn(); + } finally { + priorityContext = previousPriorityContext; + } + } + function deferredUpdates(fn) { + var previousPriorityContext = priorityContext; + priorityContext = LowPriority; + try { + return fn(); + } finally { + priorityContext = previousPriorityContext; + } + } + return { + scheduleUpdate: scheduleUpdate, + getPriorityContext: getPriorityContext, + performWithPriority: performWithPriority, + batchedUpdates: batchedUpdates, + unbatchedUpdates: unbatchedUpdates, + syncUpdates: syncUpdates, + deferredUpdates: deferredUpdates + }; +}, getContextFiber = function(arg) { + invariant(!1, "Missing injection for fiber getContextForSubtree"); +}; + +function getContextForSubtree(parentComponent) { + if (!parentComponent) return emptyObject; + var instance = ReactInstanceMap_1.get(parentComponent); + return "number" == typeof instance.tag ? getContextFiber(instance) : instance._processChildContext(instance._context); +} + +getContextForSubtree._injectFiber = function(fn) { + getContextFiber = fn; +}; + +var getContextForSubtree_1 = getContextForSubtree, addTopLevelUpdate = ReactFiberUpdateQueue.addTopLevelUpdate, findCurrentUnmaskedContext = ReactFiberContext.findCurrentUnmaskedContext, isContextProvider = ReactFiberContext.isContextProvider, processChildContext = ReactFiberContext.processChildContext, createFiberRoot = ReactFiberRoot.createFiberRoot, findCurrentHostFiber = ReactFiberTreeReflection.findCurrentHostFiber; + +getContextForSubtree_1._injectFiber(function(fiber) { + var parentContext = findCurrentUnmaskedContext(fiber); + return isContextProvider(fiber) ? processChildContext(fiber, parentContext, !1) : parentContext; +}); + +var ReactFiberReconciler = function(config) { + var _ReactFiberScheduler = ReactFiberScheduler(config), scheduleUpdate = _ReactFiberScheduler.scheduleUpdate, getPriorityContext = _ReactFiberScheduler.getPriorityContext, performWithPriority = _ReactFiberScheduler.performWithPriority, batchedUpdates = _ReactFiberScheduler.batchedUpdates, unbatchedUpdates = _ReactFiberScheduler.unbatchedUpdates, syncUpdates = _ReactFiberScheduler.syncUpdates, deferredUpdates = _ReactFiberScheduler.deferredUpdates; + function scheduleTopLevelUpdate(current, element, callback) { + var forceAsync = ReactFeatureFlags_1.enableAsyncSubtreeAPI && null != element && null != element.type && !0 === element.type.unstable_asyncUpdates, priorityLevel = getPriorityContext(current, forceAsync), nextState = { + element: element + }; + callback = void 0 === callback ? null : callback, addTopLevelUpdate(current, nextState, callback, priorityLevel), + scheduleUpdate(current, priorityLevel); + } + return { + createContainer: function(containerInfo) { + return createFiberRoot(containerInfo); + }, + updateContainer: function(element, container, parentComponent, callback) { + var current = container.current, context = getContextForSubtree_1(parentComponent); + null === container.context ? container.context = context : container.pendingContext = context, + scheduleTopLevelUpdate(current, element, callback); + }, + performWithPriority: performWithPriority, + batchedUpdates: batchedUpdates, + unbatchedUpdates: unbatchedUpdates, + syncUpdates: syncUpdates, + deferredUpdates: deferredUpdates, + getPublicRootInstance: function(container) { + var containerFiber = container.current; + return containerFiber.child ? containerFiber.child.stateNode : null; + }, + findHostInstance: function(fiber) { + var hostFiber = findCurrentHostFiber(fiber); + return null === hostFiber ? null : hostFiber.stateNode; + } + }; +}; + +function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); +} + +var objects = {}, uniqueID = 1, emptyObject$3 = {}, ReactNativePropRegistry = function() { + function ReactNativePropRegistry() { + _classCallCheck(this, ReactNativePropRegistry); + } + return ReactNativePropRegistry.register = function(object) { + var id = ++uniqueID; + return objects[id] = object, id; + }, ReactNativePropRegistry.getByID = function(id) { + if (!id) return emptyObject$3; + var object = objects[id]; + return object || (console.warn("Invalid style with id `" + id + "`. Skipping ..."), + emptyObject$3); + }, ReactNativePropRegistry; +}(), ReactNativePropRegistry_1 = ReactNativePropRegistry, emptyObject$2 = {}, removedKeys = null, removedKeyCount = 0; + +function defaultDiffer(prevProp, nextProp) { + return "object" != typeof nextProp || null === nextProp || deepDiffer(prevProp, nextProp); +} + +function resolveObject(idOrObject) { + return "number" == typeof idOrObject ? ReactNativePropRegistry_1.getByID(idOrObject) : idOrObject; +} + +function restoreDeletedValuesInNestedArray(updatePayload, node, validAttributes) { + if (Array.isArray(node)) for (var i = node.length; i-- && removedKeyCount > 0; ) restoreDeletedValuesInNestedArray(updatePayload, node[i], validAttributes); else if (node && removedKeyCount > 0) { + var obj = resolveObject(node); + for (var propKey in removedKeys) if (removedKeys[propKey]) { + var nextProp = obj[propKey]; + if (void 0 !== nextProp) { + var attributeConfig = validAttributes[propKey]; + if (attributeConfig) { + if ("function" == typeof nextProp && (nextProp = !0), void 0 === nextProp && (nextProp = null), + "object" != typeof attributeConfig) updatePayload[propKey] = nextProp; else if ("function" == typeof attributeConfig.diff || "function" == typeof attributeConfig.process) { + var nextValue = "function" == typeof attributeConfig.process ? attributeConfig.process(nextProp) : nextProp; + updatePayload[propKey] = nextValue; + } + removedKeys[propKey] = !1, removedKeyCount--; + } + } + } + } +} + +function diffNestedArrayProperty(updatePayload, prevArray, nextArray, validAttributes) { + var i, minLength = prevArray.length < nextArray.length ? prevArray.length : nextArray.length; + for (i = 0; i < minLength; i++) updatePayload = diffNestedProperty(updatePayload, prevArray[i], nextArray[i], validAttributes); + for (;i < prevArray.length; i++) updatePayload = clearNestedProperty(updatePayload, prevArray[i], validAttributes); + for (;i < nextArray.length; i++) updatePayload = addNestedProperty(updatePayload, nextArray[i], validAttributes); + return updatePayload; +} + +function diffNestedProperty(updatePayload, prevProp, nextProp, validAttributes) { + return updatePayload || prevProp !== nextProp ? prevProp && nextProp ? Array.isArray(prevProp) || Array.isArray(nextProp) ? Array.isArray(prevProp) && Array.isArray(nextProp) ? diffNestedArrayProperty(updatePayload, prevProp, nextProp, validAttributes) : Array.isArray(prevProp) ? diffProperties(updatePayload, flattenStyle(prevProp), resolveObject(nextProp), validAttributes) : diffProperties(updatePayload, resolveObject(prevProp), flattenStyle(nextProp), validAttributes) : diffProperties(updatePayload, resolveObject(prevProp), resolveObject(nextProp), validAttributes) : nextProp ? addNestedProperty(updatePayload, nextProp, validAttributes) : prevProp ? clearNestedProperty(updatePayload, prevProp, validAttributes) : updatePayload : updatePayload; +} + +function addNestedProperty(updatePayload, nextProp, validAttributes) { + if (!nextProp) return updatePayload; + if (!Array.isArray(nextProp)) return addProperties(updatePayload, resolveObject(nextProp), validAttributes); + for (var i = 0; i < nextProp.length; i++) updatePayload = addNestedProperty(updatePayload, nextProp[i], validAttributes); + return updatePayload; +} + +function clearNestedProperty(updatePayload, prevProp, validAttributes) { + if (!prevProp) return updatePayload; + if (!Array.isArray(prevProp)) return clearProperties(updatePayload, resolveObject(prevProp), validAttributes); + for (var i = 0; i < prevProp.length; i++) updatePayload = clearNestedProperty(updatePayload, prevProp[i], validAttributes); + return updatePayload; +} + +function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { + var attributeConfig, nextProp, prevProp; + for (var propKey in nextProps) if (attributeConfig = validAttributes[propKey]) if (prevProp = prevProps[propKey], + nextProp = nextProps[propKey], "function" == typeof nextProp && (nextProp = !0, + "function" == typeof prevProp && (prevProp = !0)), void 0 === nextProp && (nextProp = null, + void 0 === prevProp && (prevProp = null)), removedKeys && (removedKeys[propKey] = !1), + updatePayload && void 0 !== updatePayload[propKey]) { + if ("object" != typeof attributeConfig) updatePayload[propKey] = nextProp; else if ("function" == typeof attributeConfig.diff || "function" == typeof attributeConfig.process) { + var nextValue = "function" == typeof attributeConfig.process ? attributeConfig.process(nextProp) : nextProp; + updatePayload[propKey] = nextValue; + } + } else if (prevProp !== nextProp) if ("object" != typeof attributeConfig) defaultDiffer(prevProp, nextProp) && ((updatePayload || (updatePayload = {}))[propKey] = nextProp); else if ("function" == typeof attributeConfig.diff || "function" == typeof attributeConfig.process) { + var shouldUpdate = void 0 === prevProp || ("function" == typeof attributeConfig.diff ? attributeConfig.diff(prevProp, nextProp) : defaultDiffer(prevProp, nextProp)); + shouldUpdate && (nextValue = "function" == typeof attributeConfig.process ? attributeConfig.process(nextProp) : nextProp, + (updatePayload || (updatePayload = {}))[propKey] = nextValue); + } else removedKeys = null, removedKeyCount = 0, updatePayload = diffNestedProperty(updatePayload, prevProp, nextProp, attributeConfig), + removedKeyCount > 0 && updatePayload && (restoreDeletedValuesInNestedArray(updatePayload, nextProp, attributeConfig), + removedKeys = null); + for (propKey in prevProps) void 0 === nextProps[propKey] && (attributeConfig = validAttributes[propKey]) && (updatePayload && void 0 !== updatePayload[propKey] || void 0 !== (prevProp = prevProps[propKey]) && ("object" != typeof attributeConfig || "function" == typeof attributeConfig.diff || "function" == typeof attributeConfig.process ? ((updatePayload || (updatePayload = {}))[propKey] = null, + removedKeys || (removedKeys = {}), removedKeys[propKey] || (removedKeys[propKey] = !0, + removedKeyCount++)) : updatePayload = clearNestedProperty(updatePayload, prevProp, attributeConfig))); + return updatePayload; +} + +function addProperties(updatePayload, props, validAttributes) { + return diffProperties(updatePayload, emptyObject$2, props, validAttributes); +} + +function clearProperties(updatePayload, prevProps, validAttributes) { + return diffProperties(updatePayload, prevProps, emptyObject$2, validAttributes); +} + +var ReactNativeAttributePayload = { + create: function(props, validAttributes) { + return addProperties(null, props, validAttributes); + }, + diff: function(prevProps, nextProps, validAttributes) { + return diffProperties(null, prevProps, nextProps, validAttributes); + } +}, ReactNativeAttributePayload_1 = ReactNativeAttributePayload; + +function mountSafeCallback$1(context, callback) { + return function() { + if (callback) { + if ("boolean" == typeof context.__isMounted) { + if (!context.__isMounted) return; + } else if ("function" == typeof context.isMounted && !context.isMounted()) return; + return callback.apply(context, arguments); + } + }; +} + +function throwOnStylesProp(component, props) { + if (void 0 !== props.styles) { + var owner = component._owner || null, name = component.constructor.displayName, msg = "`styles` is not a supported property of `" + name + "`, did " + "you mean `style` (singular)?"; + throw owner && owner.constructor && owner.constructor.displayName && (msg += "\n\nCheck the `" + owner.constructor.displayName + "` parent " + " component."), + new Error(msg); + } +} + +function warnForStyleProps$1(props, validAttributes) { + for (var key in validAttributes.style) validAttributes[key] || void 0 === props[key] || console.error("You are setting the style `{ " + key + ": ... }` as a prop. You " + "should nest it in a style object. " + "E.g. `{ style: { " + key + ": ... } }`"); +} + +var NativeMethodsMixinUtils = { + mountSafeCallback: mountSafeCallback$1, + throwOnStylesProp: throwOnStylesProp, + warnForStyleProps: warnForStyleProps$1 +}; + +function _classCallCheck$1(instance, Constructor) { + if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); +} + +var mountSafeCallback = NativeMethodsMixinUtils.mountSafeCallback, ReactNativeFiberHostComponent = function() { + function ReactNativeFiberHostComponent(tag, viewConfig) { + _classCallCheck$1(this, ReactNativeFiberHostComponent), this._nativeTag = tag, this._children = [], + this.viewConfig = viewConfig; + } + return ReactNativeFiberHostComponent.prototype.blur = function() { + TextInputState.blurTextInput(this._nativeTag); + }, ReactNativeFiberHostComponent.prototype.focus = function() { + TextInputState.focusTextInput(this._nativeTag); + }, ReactNativeFiberHostComponent.prototype.measure = function(callback) { + UIManager.measure(this._nativeTag, mountSafeCallback(this, callback)); + }, ReactNativeFiberHostComponent.prototype.measureInWindow = function(callback) { + UIManager.measureInWindow(this._nativeTag, mountSafeCallback(this, callback)); + }, ReactNativeFiberHostComponent.prototype.measureLayout = function(relativeToNativeNode, onSuccess, onFail) { + UIManager.measureLayout(this._nativeTag, relativeToNativeNode, mountSafeCallback(this, onFail), mountSafeCallback(this, onSuccess)); + }, ReactNativeFiberHostComponent.prototype.setNativeProps = function(nativeProps) { + var updatePayload = ReactNativeAttributePayload_1.create(nativeProps, this.viewConfig.validAttributes); + UIManager.updateView(this._nativeTag, this.viewConfig.uiViewClassName, updatePayload); + }, ReactNativeFiberHostComponent; +}(), ReactNativeFiberHostComponent_1 = ReactNativeFiberHostComponent, viewConfigs = new Map(), prefix = "topsecret-", ReactNativeViewConfigRegistry = { + register: function(viewConfig) { + var name = viewConfig.uiViewClassName; + invariant(!viewConfigs.has(name), "Tried to register two views with the same name %s", name); + var secretName = prefix + name; + return viewConfigs.set(secretName, viewConfig), secretName; + }, + get: function(secretName) { + var config = viewConfigs.get(secretName); + return invariant(config, "View config not found for name %s", secretName), config; + } +}, ReactNativeViewConfigRegistry_1 = ReactNativeViewConfigRegistry, precacheFiberNode$1 = ReactNativeComponentTree_1.precacheFiberNode, uncacheFiberNode$1 = ReactNativeComponentTree_1.uncacheFiberNode, updateFiberProps$1 = ReactNativeComponentTree_1.updateFiberProps; + +function recursivelyUncacheFiberNode(node) { + "number" == typeof node ? uncacheFiberNode$1(node) : (uncacheFiberNode$1(node._nativeTag), + node._children.forEach(recursivelyUncacheFiberNode)); +} + +var NativeRenderer = ReactFiberReconciler({ + appendChild: function(parentInstance, child) { + var childTag = "number" == typeof child ? child : child._nativeTag; + if ("number" == typeof parentInstance) UIManager.setChildren(parentInstance, [ childTag ]); else { + var children = parentInstance._children, index = children.indexOf(child); + index >= 0 ? (children.splice(index, 1), children.push(child), UIManager.manageChildren(parentInstance._nativeTag, [ index ], [ children.length - 1 ], [], [], [])) : (children.push(child), + UIManager.manageChildren(parentInstance._nativeTag, [], [], [ childTag ], [ children.length - 1 ], [])); + } + }, + appendInitialChild: function(parentInstance, child) { + parentInstance._children.push(child); + }, + commitTextUpdate: function(textInstance, oldText, newText) { + UIManager.updateView(textInstance, "RCTRawText", { + text: newText + }); + }, + commitMount: function(instance, type, newProps, internalInstanceHandle) {}, + commitUpdate: function(instance, updatePayloadTODO, type, oldProps, newProps, internalInstanceHandle) { + var viewConfig = instance.viewConfig; + updateFiberProps$1(instance._nativeTag, newProps); + var updatePayload = ReactNativeAttributePayload_1.diff(oldProps, newProps, viewConfig.validAttributes); + UIManager.updateView(instance._nativeTag, viewConfig.uiViewClassName, updatePayload); + }, + createInstance: function(type, props, rootContainerInstance, hostContext, internalInstanceHandle) { + var tag = ReactNativeTagHandles_1.allocateTag(), viewConfig = ReactNativeViewConfigRegistry_1.get(type), updatePayload = ReactNativeAttributePayload_1.create(props, viewConfig.validAttributes); + UIManager.createView(tag, viewConfig.uiViewClassName, rootContainerInstance, updatePayload); + var component = new ReactNativeFiberHostComponent_1(tag, viewConfig); + return precacheFiberNode$1(internalInstanceHandle, tag), updateFiberProps$1(tag, props), + component; + }, + createTextInstance: function(text, rootContainerInstance, hostContext, internalInstanceHandle) { + var tag = ReactNativeTagHandles_1.allocateTag(); + return UIManager.createView(tag, "RCTRawText", rootContainerInstance, { + text: text + }), precacheFiberNode$1(internalInstanceHandle, tag), tag; + }, + finalizeInitialChildren: function(parentInstance, type, props, rootContainerInstance) { + if (0 === parentInstance._children.length) return !1; + var nativeTags = parentInstance._children.map(function(child) { + return "number" == typeof child ? child : child._nativeTag; + }); + return UIManager.setChildren(parentInstance._nativeTag, nativeTags), !1; + }, + getRootHostContext: function() { + return emptyObject; + }, + getChildHostContext: function() { + return emptyObject; + }, + getPublicInstance: function(instance) { + return instance; + }, + insertBefore: function(parentInstance, child, beforeChild) { + invariant("number" != typeof parentInstance, "Container does not support insertBefore operation"); + var children = parentInstance._children, index = children.indexOf(child); + if (index >= 0) { + children.splice(index, 1); + var beforeChildIndex = children.indexOf(beforeChild); + children.splice(beforeChildIndex, 0, child), UIManager.manageChildren(parentInstance._nativeTag, [ index ], [ beforeChildIndex ], [], [], []); + } else { + var _beforeChildIndex = children.indexOf(beforeChild); + children.splice(_beforeChildIndex, 0, child); + var childTag = "number" == typeof child ? child : child._nativeTag; + UIManager.manageChildren(parentInstance._nativeTag, [], [], [ childTag ], [ _beforeChildIndex ], []); + } + }, + prepareForCommit: function() {}, + prepareUpdate: function(instance, type, oldProps, newProps, rootContainerInstance, hostContext) { + return emptyObject; + }, + removeChild: function(parentInstance, child) { + if (recursivelyUncacheFiberNode(child), "number" == typeof parentInstance) UIManager.manageChildren(parentInstance, [], [], [], [], [ 0 ]); else { + var children = parentInstance._children, index = children.indexOf(child); + children.splice(index, 1), UIManager.manageChildren(parentInstance._nativeTag, [], [], [], [], [ index ]); + } + }, + resetAfterCommit: function() {}, + resetTextContent: function(instance) {}, + shouldDeprioritizeSubtree: function(type, props) { + return !1; + }, + scheduleAnimationCallback: commonjsGlobal.requestAnimationFrame, + scheduleDeferredCallback: commonjsGlobal.requestIdleCallback, + shouldSetTextContent: function(props) { + return !1; + }, + useSyncScheduling: !0 +}), ReactNativeFiberRenderer = NativeRenderer, getInspectorDataForViewTag = void 0; + +getInspectorDataForViewTag = function() { + invariant(!1, "getInspectorDataForViewTag() is not available in production"); +}; + +var ReactNativeFiberInspector = { + getInspectorDataForViewTag: getInspectorDataForViewTag +}, ReactVersion = "16.0.0-alpha.12", ReactNativeFeatureFlags$2 = { + useFiber: !0 +}, ReactNativeFeatureFlags_1 = ReactNativeFeatureFlags$2, ReactNativeFeatureFlags$3 = Object.freeze({ + default: ReactNativeFeatureFlags_1, + __moduleExports: ReactNativeFeatureFlags_1 +}), ReactNativeFeatureFlags$1 = ReactNativeFeatureFlags$3 && ReactNativeFeatureFlags_1 || ReactNativeFeatureFlags$3, injectedFindNode = ReactNativeFeatureFlags$1.useFiber ? function(fiber) { + return ReactNativeFiberRenderer.findHostInstance(fiber); +} : function(instance) { + return instance; +}; + +function findNodeHandle(componentOrHandle) { + if (null == componentOrHandle) return null; + if ("number" == typeof componentOrHandle) return componentOrHandle; + var component = componentOrHandle, internalInstance = ReactInstanceMap_1.get(component); + return internalInstance ? injectedFindNode(internalInstance) : component || (invariant("object" == typeof component && ("_rootNodeID" in component || "_nativeTag" in component) || null != component.render && "function" == typeof component.render, "findNodeHandle(...): Argument is not a component " + "(type: %s, keys: %s)", typeof component, Object.keys(component)), + void invariant(!1, "findNodeHandle(...): Unable to find node handle for unmounted " + "component.")); +} + +var findNodeHandle_1 = findNodeHandle, findNumericNodeHandleFiber = function(componentOrHandle) { + var instance = findNodeHandle_1(componentOrHandle); + return null == instance || "number" == typeof instance ? instance : instance._nativeTag; +}, DevOnlyStubShim = null, mountSafeCallback$2 = NativeMethodsMixinUtils.mountSafeCallback, findNumericNodeHandle = ReactNativeFeatureFlags$1.useFiber ? findNumericNodeHandleFiber : DevOnlyStubShim, NativeMethodsMixin = { + measure: function(callback) { + UIManager.measure(findNumericNodeHandle(this), mountSafeCallback$2(this, callback)); + }, + measureInWindow: function(callback) { + UIManager.measureInWindow(findNumericNodeHandle(this), mountSafeCallback$2(this, callback)); + }, + measureLayout: function(relativeToNativeNode, onSuccess, onFail) { + UIManager.measureLayout(findNumericNodeHandle(this), relativeToNativeNode, mountSafeCallback$2(this, onFail), mountSafeCallback$2(this, onSuccess)); + }, + setNativeProps: function(nativeProps) { + injectedSetNativeProps(this, nativeProps); + }, + focus: function() { + TextInputState.focusTextInput(findNumericNodeHandle(this)); + }, + blur: function() { + TextInputState.blurTextInput(findNumericNodeHandle(this)); + } +}; + +function setNativePropsFiber(componentOrHandle, nativeProps) { + var maybeInstance = void 0; + try { + maybeInstance = findNodeHandle_1(componentOrHandle); + } catch (error) {} + if (null != maybeInstance) { + var viewConfig = maybeInstance.viewConfig, updatePayload = ReactNativeAttributePayload_1.create(nativeProps, viewConfig.validAttributes); + UIManager.updateView(maybeInstance._nativeTag, viewConfig.uiViewClassName, updatePayload); + } +} + +function setNativePropsStack(componentOrHandle, nativeProps) { + var maybeInstance = findNodeHandle_1(componentOrHandle); + if (null != maybeInstance) { + var viewConfig = void 0; + if (void 0 !== maybeInstance.viewConfig) viewConfig = maybeInstance.viewConfig; else if (void 0 !== maybeInstance._instance && void 0 !== maybeInstance._instance.viewConfig) viewConfig = maybeInstance._instance.viewConfig; else { + for (;void 0 !== maybeInstance._renderedComponent; ) maybeInstance = maybeInstance._renderedComponent; + viewConfig = maybeInstance.viewConfig; + } + var tag = "function" == typeof maybeInstance.getHostNode ? maybeInstance.getHostNode() : maybeInstance._rootNodeID, updatePayload = ReactNativeAttributePayload_1.create(nativeProps, viewConfig.validAttributes); + UIManager.updateView(tag, viewConfig.uiViewClassName, updatePayload); + } +} + +var injectedSetNativeProps = void 0; + +injectedSetNativeProps = ReactNativeFeatureFlags$1.useFiber ? setNativePropsFiber : setNativePropsStack; + +var NativeMethodsMixin_1 = NativeMethodsMixin, TouchHistoryMath = { + centroidDimension: function(touchHistory, touchesChangedAfter, isXAxis, ofCurrent) { + var touchBank = touchHistory.touchBank, total = 0, count = 0, oneTouchData = 1 === touchHistory.numberActiveTouches ? touchHistory.touchBank[touchHistory.indexOfSingleActiveTouch] : null; + if (null !== oneTouchData) oneTouchData.touchActive && oneTouchData.currentTimeStamp > touchesChangedAfter && (total += ofCurrent && isXAxis ? oneTouchData.currentPageX : ofCurrent && !isXAxis ? oneTouchData.currentPageY : !ofCurrent && isXAxis ? oneTouchData.previousPageX : oneTouchData.previousPageY, + count = 1); else for (var i = 0; i < touchBank.length; i++) { + var touchTrack = touchBank[i]; + if (null !== touchTrack && void 0 !== touchTrack && touchTrack.touchActive && touchTrack.currentTimeStamp >= touchesChangedAfter) { + var toAdd; + toAdd = ofCurrent && isXAxis ? touchTrack.currentPageX : ofCurrent && !isXAxis ? touchTrack.currentPageY : !ofCurrent && isXAxis ? touchTrack.previousPageX : touchTrack.previousPageY, + total += toAdd, count++; + } + } + return count > 0 ? total / count : TouchHistoryMath.noCentroid; + }, + currentCentroidXOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) { + return TouchHistoryMath.centroidDimension(touchHistory, touchesChangedAfter, !0, !0); + }, + currentCentroidYOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) { + return TouchHistoryMath.centroidDimension(touchHistory, touchesChangedAfter, !1, !0); + }, + previousCentroidXOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) { + return TouchHistoryMath.centroidDimension(touchHistory, touchesChangedAfter, !0, !1); + }, + previousCentroidYOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) { + return TouchHistoryMath.centroidDimension(touchHistory, touchesChangedAfter, !1, !1); + }, + currentCentroidX: function(touchHistory) { + return TouchHistoryMath.centroidDimension(touchHistory, 0, !0, !0); + }, + currentCentroidY: function(touchHistory) { + return TouchHistoryMath.centroidDimension(touchHistory, 0, !1, !0); + }, + noCentroid: -1 +}, TouchHistoryMath_1 = TouchHistoryMath, createReactNativeComponentClassFiber = function(viewConfig) { + return ReactNativeViewConfigRegistry_1.register(viewConfig); +}, createReactNativeComponentClassFiber_1 = createReactNativeComponentClassFiber, createReactNativeComponentClass = ReactNativeFeatureFlags$1.useFiber ? createReactNativeComponentClassFiber_1 : DevOnlyStubShim, findNumericNodeHandle$1 = ReactNativeFeatureFlags$1.useFiber ? findNumericNodeHandleFiber : DevOnlyStubShim; + +function takeSnapshot(view, options) { + return "number" != typeof view && "window" !== view && (view = findNumericNodeHandle$1(view) || "window"), + UIManager.__takeSnapshot(view, options); +} + +var takeSnapshot_1 = takeSnapshot, injectInternals = ReactFiberDevToolsHook.injectInternals; + +ReactNativeInjection.inject(), ReactGenericBatching_1.injection.injectFiberBatchedUpdates(ReactNativeFiberRenderer.batchedUpdates); + +var roots = new Map(); + +ReactFiberErrorLogger.injection.injectDialog(ReactNativeFiberErrorDialog_1.showDialog); + +var ReactNative = { + findNodeHandle: findNumericNodeHandleFiber, + render: function(element, containerTag, callback) { + var root = roots.get(containerTag); + return root || (root = ReactNativeFiberRenderer.createContainer(containerTag), roots.set(containerTag, root)), + ReactNativeFiberRenderer.updateContainer(element, root, null, callback), ReactNativeFiberRenderer.getPublicRootInstance(root); + }, + unmountComponentAtNode: function(containerTag) { + var root = roots.get(containerTag); + root && ReactNativeFiberRenderer.updateContainer(null, root, null, function() { + roots.delete(containerTag); + }); + }, + unmountComponentAtNodeAndRemoveContainer: function(containerTag) { + ReactNative.unmountComponentAtNode(containerTag), UIManager.removeRootView(containerTag); + }, + unstable_createPortal: function(children, containerTag) { + var key = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : null; + return ReactPortal.createPortal(children, containerTag, null, key); + }, + unstable_batchedUpdates: ReactGenericBatching_1.batchedUpdates, + __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: { + NativeMethodsMixin: NativeMethodsMixin_1, + ReactGlobalSharedState: ReactGlobalSharedState_1, + ReactNativeComponentTree: ReactNativeComponentTree_1, + ReactNativePropRegistry: ReactNativePropRegistry_1, + TouchHistoryMath: TouchHistoryMath_1, + createReactNativeComponentClass: createReactNativeComponentClass, + takeSnapshot: takeSnapshot_1 + } +}; + +"function" == typeof injectInternals && injectInternals({ + findFiberByHostInstance: ReactNativeComponentTree_1.getClosestInstanceFromNode, + findHostInstanceByFiber: ReactNativeFiberRenderer.findHostInstance, + getInspectorDataForViewTag: ReactNativeFiberInspector.getInspectorDataForViewTag, + bundleType: 0, + version: ReactVersion +}); + +var ReactNativeFiber = ReactNative; + +module.exports = ReactNativeFiber; diff --git a/Libraries/Renderer/ReactNativeStack-dev.js b/Libraries/Renderer/ReactNativeStack-dev.js new file mode 100644 index 0000000000..703214bcfa --- /dev/null +++ b/Libraries/Renderer/ReactNativeStack-dev.js @@ -0,0 +1,3254 @@ +/** + * Copyright 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @noflow + * @providesModule ReactNativeStack-dev + */ +"use strict"; + +var invariant = require("fbjs/lib/invariant"); + +require("InitializeCore"); + +var warning = require("fbjs/lib/warning"), RCTEventEmitter = require("RCTEventEmitter"), emptyFunction = require("fbjs/lib/emptyFunction"), UIManager = require("UIManager"), React = require("react"), ExecutionEnvironment = require("fbjs/lib/ExecutionEnvironment"), performanceNow = require("fbjs/lib/performanceNow"), emptyObject = require("fbjs/lib/emptyObject"), checkPropTypes = require("prop-types/checkPropTypes"), shallowEqual = require("fbjs/lib/shallowEqual"); + +require("ReactNativeFeatureFlags"); + +var deepDiffer = require("deepDiffer"), flattenStyle = require("flattenStyle"), TextInputState = require("TextInputState"), deepFreezeAndThrowOnMutationInDev = require("deepFreezeAndThrowOnMutationInDev"), instanceCache = {}, instanceProps = {}; + +function getRenderedHostOrTextFromComponent(component) { + for (var rendered; rendered = component._renderedComponent; ) component = rendered; + return component; +} + +function precacheNode(inst, tag) { + var nativeInst = getRenderedHostOrTextFromComponent(inst); + instanceCache[tag] = nativeInst; +} + +function precacheFiberNode(hostInst, tag) { + instanceCache[tag] = hostInst; +} + +function uncacheNode(inst) { + var tag = inst._rootNodeID; + tag && delete instanceCache[tag]; +} + +function uncacheFiberNode(tag) { + delete instanceCache[tag], delete instanceProps[tag]; +} + +function getInstanceFromTag(tag) { + return instanceCache[tag] || null; +} + +function getTagFromInstance(inst) { + var tag = "number" != typeof inst.tag ? inst._rootNodeID : inst.stateNode._nativeTag; + return invariant(tag, "All native instances should have a tag."), tag; +} + +function getFiberCurrentPropsFromNode(stateNode) { + return instanceProps[stateNode._nativeTag] || null; +} + +function updateFiberProps(tag, props) { + instanceProps[tag] = props; +} + +var ReactNativeComponentTree = { + getClosestInstanceFromNode: getInstanceFromTag, + getInstanceFromNode: getInstanceFromTag, + getNodeFromInstance: getTagFromInstance, + precacheFiberNode: precacheFiberNode, + precacheNode: precacheNode, + uncacheFiberNode: uncacheFiberNode, + uncacheNode: uncacheNode, + getFiberCurrentPropsFromNode: getFiberCurrentPropsFromNode, + updateFiberProps: updateFiberProps +}, ReactNativeComponentTree_1 = ReactNativeComponentTree, eventPluginOrder = null, namesToPlugins = {}; + +function recomputePluginOrdering() { + if (eventPluginOrder) for (var pluginName in namesToPlugins) { + var pluginModule = namesToPlugins[pluginName], pluginIndex = eventPluginOrder.indexOf(pluginName); + if (invariant(pluginIndex > -1, "EventPluginRegistry: Cannot inject event plugins that do not exist in " + "the plugin ordering, `%s`.", pluginName), + !EventPluginRegistry.plugins[pluginIndex]) { + invariant(pluginModule.extractEvents, "EventPluginRegistry: Event plugins must implement an `extractEvents` " + "method, but `%s` does not.", pluginName), + EventPluginRegistry.plugins[pluginIndex] = pluginModule; + var publishedEvents = pluginModule.eventTypes; + for (var eventName in publishedEvents) invariant(publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName), "EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.", eventName, pluginName); + } + } +} + +function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { + invariant(!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName), "EventPluginHub: More than one plugin attempted to publish the same " + "event name, `%s`.", eventName), + EventPluginRegistry.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 !0; + } + return !!dispatchConfig.registrationName && (publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName), + !0); +} + +function publishRegistrationName(registrationName, pluginModule, eventName) { + invariant(!EventPluginRegistry.registrationNameModules[registrationName], "EventPluginHub: More than one plugin attempted to publish the same " + "registration name, `%s`.", registrationName), + EventPluginRegistry.registrationNameModules[registrationName] = pluginModule, EventPluginRegistry.registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies; + var lowerCasedName = registrationName.toLowerCase(); + EventPluginRegistry.possibleRegistrationNames[lowerCasedName] = registrationName, + "onDoubleClick" === registrationName && (EventPluginRegistry.possibleRegistrationNames.ondblclick = registrationName); +} + +var EventPluginRegistry = { + plugins: [], + eventNameDispatchConfigs: {}, + registrationNameModules: {}, + registrationNameDependencies: {}, + possibleRegistrationNames: {}, + injectEventPluginOrder: function(injectedEventPluginOrder) { + invariant(!eventPluginOrder, "EventPluginRegistry: Cannot inject event plugin ordering more than " + "once. You are likely trying to load more than one copy of React."), + eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder), recomputePluginOrdering(); + }, + injectEventPluginsByName: function(injectedNamesToPlugins) { + var isOrderingDirty = !1; + for (var pluginName in injectedNamesToPlugins) if (injectedNamesToPlugins.hasOwnProperty(pluginName)) { + var pluginModule = injectedNamesToPlugins[pluginName]; + namesToPlugins.hasOwnProperty(pluginName) && namesToPlugins[pluginName] === pluginModule || (invariant(!namesToPlugins[pluginName], "EventPluginRegistry: Cannot inject two different event plugins " + "using the same name, `%s`.", pluginName), + namesToPlugins[pluginName] = pluginModule, isOrderingDirty = !0); + } + isOrderingDirty && recomputePluginOrdering(); + } +}, EventPluginRegistry_1 = EventPluginRegistry, caughtError = null, invokeGuardedCallback = 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) { + return error; + } + return null; +}; + +if ("undefined" != typeof window && "function" == typeof window.dispatchEvent && "undefined" != typeof document && "function" == typeof document.createEvent) { + var fakeNode = document.createElement("react"), depth = 0; + invokeGuardedCallback = function(name, func, context, a, b, c, d, e, f) { + depth++; + var thisDepth = depth, funcArgs = Array.prototype.slice.call(arguments, 3), boundFunc = function() { + func.apply(context, funcArgs); + }, fakeEventError = null, onFakeEventError = function(event) { + depth === thisDepth && (fakeEventError = event.error); + }, evtType = "react-" + (name || "invokeguardedcallback") + "-" + depth; + window.addEventListener("error", onFakeEventError), fakeNode.addEventListener(evtType, boundFunc, !1); + var evt = document.createEvent("Event"); + return evt.initEvent(evtType, !1, !1), fakeNode.dispatchEvent(evt), fakeNode.removeEventListener(evtType, boundFunc, !1), + window.removeEventListener("error", onFakeEventError), depth--, fakeEventError; + }; +} + +var rethrowCaughtError = function() { + if (caughtError) { + var error = caughtError; + throw caughtError = null, error; + } +}, ReactErrorUtils = { + injection: { + injectErrorUtils: function(injectedErrorUtils) { + invariant("function" == typeof injectedErrorUtils.invokeGuardedCallback, "Injected invokeGuardedCallback() must be a function."), + invokeGuardedCallback = injectedErrorUtils.invokeGuardedCallback; + } + }, + invokeGuardedCallback: function(name, func, context, a, b, c, d, e, f) { + return invokeGuardedCallback.apply(this, arguments); + }, + invokeGuardedCallbackAndCatchFirstError: function(name, func, context, a, b, c, d, e, f) { + var error = ReactErrorUtils.invokeGuardedCallback.apply(this, arguments); + null !== error && null === caughtError && (caughtError = error); + }, + rethrowCaughtError: function() { + return rethrowCaughtError.apply(this, arguments); + } +}, ReactErrorUtils_1 = ReactErrorUtils, ComponentTree, injection = { + injectComponentTree: function(Injected) { + ComponentTree = Injected, warning(Injected && Injected.getNodeFromInstance && Injected.getInstanceFromNode, "EventPluginUtils.injection.injectComponentTree(...): Injected " + "module is missing getNodeFromInstance or getInstanceFromNode."); + } +}; + +function isEndish(topLevelType) { + return "topMouseUp" === topLevelType || "topTouchEnd" === topLevelType || "topTouchCancel" === topLevelType; +} + +function isMoveish(topLevelType) { + return "topMouseMove" === topLevelType || "topTouchMove" === topLevelType; +} + +function isStartish(topLevelType) { + return "topMouseDown" === topLevelType || "topTouchStart" === topLevelType; +} + +var validateEventDispatches; + +validateEventDispatches = function(event) { + var dispatchListeners = event._dispatchListeners, dispatchInstances = event._dispatchInstances, listenersIsArr = Array.isArray(dispatchListeners), listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0, instancesIsArr = Array.isArray(dispatchInstances), instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0; + warning(instancesIsArr === listenersIsArr && instancesLen === listenersLen, "EventPluginUtils: Invalid `event`."); +}; + +function executeDispatch(event, simulated, listener, inst) { + var type = event.type || "unknown-event"; + event.currentTarget = EventPluginUtils.getNodeFromInstance(inst), ReactErrorUtils_1.invokeGuardedCallbackAndCatchFirstError(type, listener, void 0, event), + event.currentTarget = null; +} + +function executeDispatchesInOrder(event, simulated) { + var dispatchListeners = event._dispatchListeners, dispatchInstances = event._dispatchInstances; + if (validateEventDispatches(event), Array.isArray(dispatchListeners)) for (var i = 0; i < dispatchListeners.length && !event.isPropagationStopped(); i++) executeDispatch(event, simulated, dispatchListeners[i], dispatchInstances[i]); else dispatchListeners && executeDispatch(event, simulated, dispatchListeners, dispatchInstances); + event._dispatchListeners = null, event._dispatchInstances = null; +} + +function executeDispatchesInOrderStopAtTrueImpl(event) { + var dispatchListeners = event._dispatchListeners, dispatchInstances = event._dispatchInstances; + if (validateEventDispatches(event), Array.isArray(dispatchListeners)) { + for (var i = 0; i < dispatchListeners.length && !event.isPropagationStopped(); i++) if (dispatchListeners[i](event, dispatchInstances[i])) return dispatchInstances[i]; + } else if (dispatchListeners && dispatchListeners(event, dispatchInstances)) return dispatchInstances; + return null; +} + +function executeDispatchesInOrderStopAtTrue(event) { + var ret = executeDispatchesInOrderStopAtTrueImpl(event); + return event._dispatchInstances = null, event._dispatchListeners = null, ret; +} + +function executeDirectDispatch(event) { + validateEventDispatches(event); + var dispatchListener = event._dispatchListeners, dispatchInstance = event._dispatchInstances; + invariant(!Array.isArray(dispatchListener), "executeDirectDispatch(...): Invalid `event`."), + event.currentTarget = dispatchListener ? EventPluginUtils.getNodeFromInstance(dispatchInstance) : null; + var res = dispatchListener ? dispatchListener(event) : null; + return event.currentTarget = null, event._dispatchListeners = null, event._dispatchInstances = null, + res; +} + +function hasDispatches(event) { + return !!event._dispatchListeners; +} + +var EventPluginUtils = { + isEndish: isEndish, + isMoveish: isMoveish, + isStartish: isStartish, + executeDirectDispatch: executeDirectDispatch, + executeDispatchesInOrder: executeDispatchesInOrder, + executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue, + hasDispatches: hasDispatches, + getFiberCurrentPropsFromNode: function(node) { + return ComponentTree.getFiberCurrentPropsFromNode(node); + }, + getInstanceFromNode: function(node) { + return ComponentTree.getInstanceFromNode(node); + }, + getNodeFromInstance: function(node) { + return ComponentTree.getNodeFromInstance(node); + }, + injection: injection +}, EventPluginUtils_1 = EventPluginUtils; + +function accumulateInto(current, next) { + return invariant(null != next, "accumulateInto(...): Accumulated items must not be null or undefined."), + null == current ? next : Array.isArray(current) ? Array.isArray(next) ? (current.push.apply(current, next), + current) : (current.push(next), current) : Array.isArray(next) ? [ current ].concat(next) : [ current, next ]; +} + +var accumulateInto_1 = accumulateInto; + +function forEachAccumulated(arr, cb, scope) { + Array.isArray(arr) ? arr.forEach(cb, scope) : arr && cb.call(scope, arr); +} + +var forEachAccumulated_1 = forEachAccumulated, eventQueue = null, executeDispatchesAndRelease = function(event, simulated) { + event && (EventPluginUtils_1.executeDispatchesInOrder(event, simulated), event.isPersistent() || event.constructor.release(event)); +}, executeDispatchesAndReleaseSimulated = function(e) { + return executeDispatchesAndRelease(e, !0); +}, executeDispatchesAndReleaseTopLevel = function(e) { + return executeDispatchesAndRelease(e, !1); +}; + +function isInteractive(tag) { + return "button" === tag || "input" === tag || "select" === tag || "textarea" === tag; +} + +function shouldPreventMouseEvent(name, type, props) { + switch (name) { + case "onClick": + case "onClickCapture": + case "onDoubleClick": + case "onDoubleClickCapture": + case "onMouseDown": + case "onMouseDownCapture": + case "onMouseMove": + case "onMouseMoveCapture": + case "onMouseUp": + case "onMouseUpCapture": + return !(!props.disabled || !isInteractive(type)); + + default: + return !1; + } +} + +var EventPluginHub = { + injection: { + injectEventPluginOrder: EventPluginRegistry_1.injectEventPluginOrder, + injectEventPluginsByName: EventPluginRegistry_1.injectEventPluginsByName + }, + getListener: function(inst, registrationName) { + var listener; + if ("number" == typeof inst.tag) { + var stateNode = inst.stateNode; + if (!stateNode) return null; + var props = EventPluginUtils_1.getFiberCurrentPropsFromNode(stateNode); + if (!props) return null; + if (listener = props[registrationName], shouldPreventMouseEvent(registrationName, inst.type, props)) return null; + } else { + var currentElement = inst._currentElement; + if ("string" == typeof currentElement || "number" == typeof currentElement) return null; + if (!inst._rootNodeID) return null; + var _props = currentElement.props; + if (listener = _props[registrationName], shouldPreventMouseEvent(registrationName, currentElement.type, _props)) return null; + } + return invariant(!listener || "function" == typeof listener, "Expected %s listener to be a function, instead got type %s", registrationName, typeof listener), + listener; + }, + extractEvents: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) { + for (var events, plugins = EventPluginRegistry_1.plugins, i = 0; i < plugins.length; i++) { + var possiblePlugin = plugins[i]; + if (possiblePlugin) { + var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); + extractedEvents && (events = accumulateInto_1(events, extractedEvents)); + } + } + return events; + }, + enqueueEvents: function(events) { + events && (eventQueue = accumulateInto_1(eventQueue, events)); + }, + processEventQueue: function(simulated) { + var processingEventQueue = eventQueue; + eventQueue = null, simulated ? forEachAccumulated_1(processingEventQueue, executeDispatchesAndReleaseSimulated) : forEachAccumulated_1(processingEventQueue, executeDispatchesAndReleaseTopLevel), + invariant(!eventQueue, "processEventQueue(): Additional events were enqueued while processing " + "an event queue. Support for this has not yet been implemented."), + ReactErrorUtils_1.rethrowCaughtError(); + } +}, EventPluginHub_1 = EventPluginHub, ReactTypeOfWork = { + IndeterminateComponent: 0, + FunctionalComponent: 1, + ClassComponent: 2, + HostRoot: 3, + HostPortal: 4, + HostComponent: 5, + HostText: 6, + CoroutineComponent: 7, + CoroutineHandlerPhase: 8, + YieldComponent: 9, + Fragment: 10 +}, HostComponent = ReactTypeOfWork.HostComponent; + +function getParent(inst) { + if (void 0 !== inst._hostParent) return inst._hostParent; + if ("number" == typeof inst.tag) { + do { + inst = inst.return; + } while (inst && inst.tag !== HostComponent); + if (inst) return inst; + } + return null; +} + +function getLowestCommonAncestor(instA, instB) { + for (var depthA = 0, tempA = instA; tempA; tempA = getParent(tempA)) depthA++; + for (var depthB = 0, tempB = instB; tempB; tempB = getParent(tempB)) depthB++; + for (;depthA - depthB > 0; ) instA = getParent(instA), depthA--; + for (;depthB - depthA > 0; ) instB = getParent(instB), depthB--; + for (var depth = depthA; depth--; ) { + if (instA === instB || instA === instB.alternate) return instA; + instA = getParent(instA), instB = getParent(instB); + } + return null; +} + +function isAncestor(instA, instB) { + for (;instB; ) { + if (instA === instB || instA === instB.alternate) return !0; + instB = getParent(instB); + } + return !1; +} + +function getParentInstance(inst) { + return getParent(inst); +} + +function traverseTwoPhase(inst, fn, arg) { + for (var path = []; inst; ) path.push(inst), inst = getParent(inst); + var i; + for (i = path.length; i-- > 0; ) fn(path[i], "captured", arg); + for (i = 0; i < path.length; i++) fn(path[i], "bubbled", arg); +} + +function traverseEnterLeave(from, to, fn, argFrom, argTo) { + for (var common = from && to ? getLowestCommonAncestor(from, to) : null, pathFrom = []; from && from !== common; ) pathFrom.push(from), + from = getParent(from); + for (var pathTo = []; to && to !== common; ) pathTo.push(to), to = getParent(to); + var i; + for (i = 0; i < pathFrom.length; i++) fn(pathFrom[i], "bubbled", argFrom); + for (i = pathTo.length; i-- > 0; ) fn(pathTo[i], "captured", argTo); +} + +var ReactTreeTraversal = { + isAncestor: isAncestor, + getLowestCommonAncestor: getLowestCommonAncestor, + getParentInstance: getParentInstance, + traverseTwoPhase: traverseTwoPhase, + traverseEnterLeave: traverseEnterLeave +}, getListener = EventPluginHub_1.getListener; + +function listenerAtPhase(inst, event, propagationPhase) { + var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; + return getListener(inst, registrationName); +} + +function accumulateDirectionalDispatches(inst, phase, event) { + warning(inst, "Dispatching inst must not be null"); + var listener = listenerAtPhase(inst, event, phase); + listener && (event._dispatchListeners = accumulateInto_1(event._dispatchListeners, listener), + event._dispatchInstances = accumulateInto_1(event._dispatchInstances, inst)); +} + +function accumulateTwoPhaseDispatchesSingle(event) { + event && event.dispatchConfig.phasedRegistrationNames && ReactTreeTraversal.traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event); +} + +function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { + if (event && event.dispatchConfig.phasedRegistrationNames) { + var targetInst = event._targetInst, parentInst = targetInst ? ReactTreeTraversal.getParentInstance(targetInst) : null; + ReactTreeTraversal.traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event); + } +} + +function accumulateDispatches(inst, ignoredDirection, event) { + if (inst && event && event.dispatchConfig.registrationName) { + var registrationName = event.dispatchConfig.registrationName, listener = getListener(inst, registrationName); + listener && (event._dispatchListeners = accumulateInto_1(event._dispatchListeners, listener), + event._dispatchInstances = accumulateInto_1(event._dispatchInstances, inst)); + } +} + +function accumulateDirectDispatchesSingle(event) { + event && event.dispatchConfig.registrationName && accumulateDispatches(event._targetInst, null, event); +} + +function accumulateTwoPhaseDispatches(events) { + forEachAccumulated_1(events, accumulateTwoPhaseDispatchesSingle); +} + +function accumulateTwoPhaseDispatchesSkipTarget(events) { + forEachAccumulated_1(events, accumulateTwoPhaseDispatchesSingleSkipTarget); +} + +function accumulateEnterLeaveDispatches(leave, enter, from, to) { + ReactTreeTraversal.traverseEnterLeave(from, to, accumulateDispatches, leave, enter); +} + +function accumulateDirectDispatches(events) { + forEachAccumulated_1(events, accumulateDirectDispatchesSingle); +} + +var EventPropagators = { + accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches, + accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget, + accumulateDirectDispatches: accumulateDirectDispatches, + accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches +}, EventPropagators_1 = EventPropagators, oneArgumentPooler = function(copyFieldsFrom) { + var Klass = this; + if (Klass.instancePool.length) { + var instance = Klass.instancePool.pop(); + return Klass.call(instance, copyFieldsFrom), instance; + } + return new Klass(copyFieldsFrom); +}, twoArgumentPooler = function(a1, a2) { + var Klass = this; + if (Klass.instancePool.length) { + var instance = Klass.instancePool.pop(); + return Klass.call(instance, a1, a2), instance; + } + return new Klass(a1, a2); +}, threeArgumentPooler = function(a1, a2, a3) { + var Klass = this; + if (Klass.instancePool.length) { + var instance = Klass.instancePool.pop(); + return Klass.call(instance, a1, a2, a3), instance; + } + return new Klass(a1, a2, a3); +}, fourArgumentPooler = function(a1, a2, a3, a4) { + var Klass = this; + if (Klass.instancePool.length) { + var instance = Klass.instancePool.pop(); + return Klass.call(instance, a1, a2, a3, a4), instance; + } + return new Klass(a1, a2, a3, a4); +}, standardReleaser = function(instance) { + var Klass = this; + invariant(instance instanceof Klass, "Trying to release an instance into a pool of a different type."), + instance.destructor(), Klass.instancePool.length < Klass.poolSize && Klass.instancePool.push(instance); +}, DEFAULT_POOL_SIZE = 10, DEFAULT_POOLER = oneArgumentPooler, addPoolingTo = function(CopyConstructor, pooler) { + var NewKlass = CopyConstructor; + return NewKlass.instancePool = [], NewKlass.getPooled = pooler || DEFAULT_POOLER, + NewKlass.poolSize || (NewKlass.poolSize = DEFAULT_POOL_SIZE), NewKlass.release = standardReleaser, + NewKlass; +}, PooledClass = { + addPoolingTo: addPoolingTo, + oneArgumentPooler: oneArgumentPooler, + twoArgumentPooler: twoArgumentPooler, + threeArgumentPooler: threeArgumentPooler, + fourArgumentPooler: fourArgumentPooler +}, PooledClass_1 = PooledClass, didWarnForAddedNewProperty = !1, isProxySupported = "function" == typeof Proxy, shouldBeReleasedProperties = [ "dispatchConfig", "_targetInst", "nativeEvent", "isDefaultPrevented", "isPropagationStopped", "_dispatchListeners", "_dispatchInstances" ], EventInterface = { + type: null, + target: null, + currentTarget: emptyFunction.thatReturnsNull, + eventPhase: null, + bubbles: null, + cancelable: null, + timeStamp: function(event) { + return event.timeStamp || Date.now(); + }, + defaultPrevented: null, + isTrusted: null +}; + +function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) { + delete this.nativeEvent, delete this.preventDefault, delete this.stopPropagation, + this.dispatchConfig = dispatchConfig, this._targetInst = targetInst, this.nativeEvent = nativeEvent; + var Interface = this.constructor.Interface; + for (var propName in Interface) if (Interface.hasOwnProperty(propName)) { + delete this[propName]; + var normalize = Interface[propName]; + normalize ? this[propName] = normalize(nativeEvent) : "target" === propName ? this.target = nativeEventTarget : this[propName] = nativeEvent[propName]; + } + var defaultPrevented = null != nativeEvent.defaultPrevented ? nativeEvent.defaultPrevented : !1 === nativeEvent.returnValue; + return this.isDefaultPrevented = defaultPrevented ? emptyFunction.thatReturnsTrue : emptyFunction.thatReturnsFalse, + this.isPropagationStopped = emptyFunction.thatReturnsFalse, this; +} + +Object.assign(SyntheticEvent.prototype, { + preventDefault: function() { + this.defaultPrevented = !0; + var event = this.nativeEvent; + event && (event.preventDefault ? event.preventDefault() : "unknown" != typeof event.returnValue && (event.returnValue = !1), + this.isDefaultPrevented = emptyFunction.thatReturnsTrue); + }, + stopPropagation: function() { + var event = this.nativeEvent; + event && (event.stopPropagation ? event.stopPropagation() : "unknown" != typeof event.cancelBubble && (event.cancelBubble = !0), + this.isPropagationStopped = emptyFunction.thatReturnsTrue); + }, + persist: function() { + this.isPersistent = emptyFunction.thatReturnsTrue; + }, + isPersistent: emptyFunction.thatReturnsFalse, + destructor: function() { + var Interface = this.constructor.Interface; + for (var propName in Interface) Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName])); + for (var i = 0; i < shouldBeReleasedProperties.length; i++) this[shouldBeReleasedProperties[i]] = null; + Object.defineProperty(this, "nativeEvent", getPooledWarningPropertyDefinition("nativeEvent", null)), + Object.defineProperty(this, "preventDefault", getPooledWarningPropertyDefinition("preventDefault", emptyFunction)), + Object.defineProperty(this, "stopPropagation", getPooledWarningPropertyDefinition("stopPropagation", emptyFunction)); + } +}), SyntheticEvent.Interface = EventInterface, isProxySupported && (SyntheticEvent = new Proxy(SyntheticEvent, { + construct: function(target, args) { + return this.apply(target, Object.create(target.prototype), args); + }, + apply: function(constructor, that, args) { + return new Proxy(constructor.apply(that, args), { + set: function(target, prop, value) { + return "isPersistent" === prop || target.constructor.Interface.hasOwnProperty(prop) || -1 !== shouldBeReleasedProperties.indexOf(prop) || (warning(didWarnForAddedNewProperty || target.isPersistent(), "This synthetic event is reused for performance reasons. If you're " + "seeing this, you're adding a new property in the synthetic event object. " + "The property is never released. See " + "https://fb.me/react-event-pooling for more information."), + didWarnForAddedNewProperty = !0), target[prop] = value, !0; + } + }); + } +})), SyntheticEvent.augmentClass = function(Class, Interface) { + var Super = this, E = function() {}; + E.prototype = Super.prototype; + var prototype = new E(); + Object.assign(prototype, Class.prototype), Class.prototype = prototype, Class.prototype.constructor = Class, + Class.Interface = Object.assign({}, Super.Interface, Interface), Class.augmentClass = Super.augmentClass, + PooledClass_1.addPoolingTo(Class, PooledClass_1.fourArgumentPooler); +}, PooledClass_1.addPoolingTo(SyntheticEvent, PooledClass_1.fourArgumentPooler); + +var SyntheticEvent_1 = SyntheticEvent; + +function getPooledWarningPropertyDefinition(propName, getVal) { + var isFunction = "function" == typeof getVal; + return { + configurable: !0, + set: set, + get: get + }; + function set(val) { + return warn(isFunction ? "setting the method" : "setting the property", "This is effectively a no-op"), + val; + } + function get() { + return warn(isFunction ? "accessing the method" : "accessing the property", isFunction ? "This is a no-op function" : "This is set to null"), + getVal; + } + function warn(action, result) { + warning(!1, "This synthetic event is reused for performance reasons. If you're seeing this, " + "you're %s `%s` on a released/nullified synthetic event. %s. " + "If you must keep the original synthetic event around, use event.persist(). " + "See https://fb.me/react-event-pooling for more information.", action, propName, result); + } +} + +var _extends = Object.assign || function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]); + } + return target; +}, customBubblingEventTypes = UIManager.customBubblingEventTypes, customDirectEventTypes = UIManager.customDirectEventTypes, allTypesByEventName = {}; + +for (var bubblingTypeName in customBubblingEventTypes) allTypesByEventName[bubblingTypeName] = customBubblingEventTypes[bubblingTypeName]; + +for (var directTypeName in customDirectEventTypes) warning(!customBubblingEventTypes[directTypeName], "Event cannot be both direct and bubbling: %s", directTypeName), +allTypesByEventName[directTypeName] = customDirectEventTypes[directTypeName]; + +var ReactNativeBridgeEventPlugin = { + eventTypes: _extends({}, customBubblingEventTypes, customDirectEventTypes), + extractEvents: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) { + var bubbleDispatchConfig = customBubblingEventTypes[topLevelType], directDispatchConfig = customDirectEventTypes[topLevelType], event = SyntheticEvent_1.getPooled(bubbleDispatchConfig || directDispatchConfig, targetInst, nativeEvent, nativeEventTarget); + if (bubbleDispatchConfig) EventPropagators_1.accumulateTwoPhaseDispatches(event); else { + if (!directDispatchConfig) return null; + EventPropagators_1.accumulateDirectDispatches(event); + } + return event; + } +}, ReactNativeBridgeEventPlugin_1 = ReactNativeBridgeEventPlugin; + +function runEventQueueInBatch(events) { + EventPluginHub_1.enqueueEvents(events), EventPluginHub_1.processEventQueue(!1); +} + +var ReactEventEmitterMixin = { + handleTopLevel: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) { + runEventQueueInBatch(EventPluginHub_1.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget)); + } +}, ReactEventEmitterMixin_1 = ReactEventEmitterMixin, INITIAL_TAG_COUNT = 1, ReactNativeTagHandles = { + tagsStartAt: INITIAL_TAG_COUNT, + tagCount: INITIAL_TAG_COUNT, + allocateTag: function() { + for (;this.reactTagIsNativeTopRootID(ReactNativeTagHandles.tagCount); ) ReactNativeTagHandles.tagCount++; + var tag = ReactNativeTagHandles.tagCount; + return ReactNativeTagHandles.tagCount++, tag; + }, + assertRootTag: function(tag) { + invariant(this.reactTagIsNativeTopRootID(tag), "Expect a native root tag, instead got %s", tag); + }, + reactTagIsNativeTopRootID: function(reactTag) { + return reactTag % 10 == 1; + } +}, ReactNativeTagHandles_1 = ReactNativeTagHandles, fiberHostComponent = null, ReactControlledComponentInjection = { + injectFiberControlledHostComponent: function(hostComponentImpl) { + fiberHostComponent = hostComponentImpl; + } +}, restoreTarget = null, restoreQueue = null; + +function restoreStateOfTarget(target) { + var internalInstance = EventPluginUtils_1.getInstanceFromNode(target); + if (internalInstance) { + if ("number" == typeof internalInstance.tag) { + invariant(fiberHostComponent && "function" == typeof fiberHostComponent.restoreControlledState, "Fiber needs to be injected to handle a fiber target for controlled " + "events."); + var props = EventPluginUtils_1.getFiberCurrentPropsFromNode(internalInstance.stateNode); + return void fiberHostComponent.restoreControlledState(internalInstance.stateNode, internalInstance.type, props); + } + invariant("function" == typeof internalInstance.restoreControlledState, "The internal instance must be a React host component."), + internalInstance.restoreControlledState(); + } +} + +var ReactControlledComponent = { + injection: ReactControlledComponentInjection, + enqueueStateRestore: function(target) { + restoreTarget ? restoreQueue ? restoreQueue.push(target) : restoreQueue = [ target ] : restoreTarget = target; + }, + restoreStateIfNeeded: function() { + if (restoreTarget) { + var target = restoreTarget, queuedTargets = restoreQueue; + if (restoreTarget = null, restoreQueue = null, restoreStateOfTarget(target), queuedTargets) for (var i = 0; i < queuedTargets.length; i++) restoreStateOfTarget(queuedTargets[i]); + } + } +}, ReactControlledComponent_1 = ReactControlledComponent, stackBatchedUpdates = function(fn, a, b, c, d, e) { + return fn(a, b, c, d, e); +}, fiberBatchedUpdates = function(fn, bookkeeping) { + return fn(bookkeeping); +}; + +function performFiberBatchedUpdates(fn, bookkeeping) { + return fiberBatchedUpdates(fn, bookkeeping); +} + +function batchedUpdates(fn, bookkeeping) { + return stackBatchedUpdates(performFiberBatchedUpdates, fn, bookkeeping); +} + +var isNestingBatched = !1; + +function batchedUpdatesWithControlledComponents(fn, bookkeeping) { + if (isNestingBatched) return batchedUpdates(fn, bookkeeping); + isNestingBatched = !0; + try { + return batchedUpdates(fn, bookkeeping); + } finally { + isNestingBatched = !1, ReactControlledComponent_1.restoreStateIfNeeded(); + } +} + +var ReactGenericBatchingInjection = { + injectStackBatchedUpdates: function(_batchedUpdates) { + stackBatchedUpdates = _batchedUpdates; + }, + injectFiberBatchedUpdates: function(_batchedUpdates) { + fiberBatchedUpdates = _batchedUpdates; + } +}, ReactGenericBatching = { + batchedUpdates: batchedUpdatesWithControlledComponents, + injection: ReactGenericBatchingInjection +}, ReactGenericBatching_1 = ReactGenericBatching, _extends$1 = Object.assign || function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]); + } + return target; +}, EMPTY_NATIVE_EVENT = {}, touchSubsequence = function(touches, indices) { + for (var ret = [], i = 0; i < indices.length; i++) ret.push(touches[indices[i]]); + return ret; +}, removeTouchesAtIndices = function(touches, indices) { + for (var rippedOut = [], temp = touches, i = 0; i < indices.length; i++) { + var index = indices[i]; + rippedOut.push(touches[index]), temp[index] = null; + } + for (var fillAt = 0, j = 0; j < temp.length; j++) { + var cur = temp[j]; + null !== cur && (temp[fillAt++] = cur); + } + return temp.length = fillAt, rippedOut; +}, ReactNativeEventEmitter = _extends$1({}, ReactEventEmitterMixin_1, { + registrationNames: EventPluginRegistry_1.registrationNameModules, + getListener: EventPluginHub_1.getListener, + _receiveRootNodeIDEvent: function(rootNodeID, topLevelType, nativeEventParam) { + var nativeEvent = nativeEventParam || EMPTY_NATIVE_EVENT, inst = ReactNativeComponentTree_1.getInstanceFromNode(rootNodeID); + ReactGenericBatching_1.batchedUpdates(function() { + ReactNativeEventEmitter.handleTopLevel(topLevelType, inst, nativeEvent, nativeEvent.target); + }); + }, + receiveEvent: function(tag, topLevelType, nativeEventParam) { + var rootNodeID = tag; + ReactNativeEventEmitter._receiveRootNodeIDEvent(rootNodeID, topLevelType, nativeEventParam); + }, + receiveTouches: function(eventTopLevelType, touches, changedIndices) { + for (var changedTouches = "topTouchEnd" === eventTopLevelType || "topTouchCancel" === eventTopLevelType ? removeTouchesAtIndices(touches, changedIndices) : touchSubsequence(touches, changedIndices), jj = 0; jj < changedTouches.length; jj++) { + var touch = changedTouches[jj]; + touch.changedTouches = changedTouches, touch.touches = touches; + var nativeEvent = touch, rootNodeID = null, target = nativeEvent.target; + null !== target && void 0 !== target && (target < ReactNativeTagHandles_1.tagsStartAt ? warning(!1, "A view is reporting that a touch occurred on tag zero.") : rootNodeID = target), + ReactNativeEventEmitter._receiveRootNodeIDEvent(rootNodeID, eventTopLevelType, nativeEvent); + } + } +}), ReactNativeEventEmitter_1 = ReactNativeEventEmitter, ReactNativeEventPluginOrder = [ "ResponderEventPlugin", "ReactNativeBridgeEventPlugin" ], ReactNativeEventPluginOrder_1 = ReactNativeEventPluginOrder, ReactNativeGlobalResponderHandler = { + onChange: function(from, to, blockNativeResponder) { + if (null !== to) { + var tag = "number" != typeof to.tag ? to._rootNodeID : to.stateNode._nativeTag; + UIManager.setJSResponder(tag, blockNativeResponder); + } else UIManager.clearJSResponder(); + } +}, ReactNativeGlobalResponderHandler_1 = ReactNativeGlobalResponderHandler, ResponderEventInterface = { + touchHistory: function(nativeEvent) { + return null; + } +}; + +function ResponderSyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { + return SyntheticEvent_1.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); +} + +SyntheticEvent_1.augmentClass(ResponderSyntheticEvent, ResponderEventInterface); + +var ResponderSyntheticEvent_1 = ResponderSyntheticEvent, isEndish$2 = EventPluginUtils_1.isEndish, isMoveish$2 = EventPluginUtils_1.isMoveish, isStartish$2 = EventPluginUtils_1.isStartish, MAX_TOUCH_BANK = 20, touchBank = [], touchHistory = { + touchBank: touchBank, + numberActiveTouches: 0, + indexOfSingleActiveTouch: -1, + mostRecentTimeStamp: 0 +}; + +function timestampForTouch(touch) { + return touch.timeStamp || touch.timestamp; +} + +function createTouchRecord(touch) { + return { + touchActive: !0, + startPageX: touch.pageX, + startPageY: touch.pageY, + startTimeStamp: timestampForTouch(touch), + currentPageX: touch.pageX, + currentPageY: touch.pageY, + currentTimeStamp: timestampForTouch(touch), + previousPageX: touch.pageX, + previousPageY: touch.pageY, + previousTimeStamp: timestampForTouch(touch) + }; +} + +function resetTouchRecord(touchRecord, touch) { + touchRecord.touchActive = !0, touchRecord.startPageX = touch.pageX, touchRecord.startPageY = touch.pageY, + touchRecord.startTimeStamp = timestampForTouch(touch), touchRecord.currentPageX = touch.pageX, + touchRecord.currentPageY = touch.pageY, touchRecord.currentTimeStamp = timestampForTouch(touch), + touchRecord.previousPageX = touch.pageX, touchRecord.previousPageY = touch.pageY, + touchRecord.previousTimeStamp = timestampForTouch(touch); +} + +function getTouchIdentifier(_ref) { + var identifier = _ref.identifier; + return invariant(null != identifier, "Touch object is missing identifier."), warning(identifier <= MAX_TOUCH_BANK, "Touch identifier %s is greater than maximum supported %s which causes " + "performance issues backfilling array locations for all of the indices.", identifier, MAX_TOUCH_BANK), + identifier; +} + +function recordTouchStart(touch) { + var identifier = getTouchIdentifier(touch), touchRecord = touchBank[identifier]; + touchRecord ? resetTouchRecord(touchRecord, touch) : touchBank[identifier] = createTouchRecord(touch), + touchHistory.mostRecentTimeStamp = timestampForTouch(touch); +} + +function recordTouchMove(touch) { + var touchRecord = touchBank[getTouchIdentifier(touch)]; + touchRecord ? (touchRecord.touchActive = !0, touchRecord.previousPageX = touchRecord.currentPageX, + touchRecord.previousPageY = touchRecord.currentPageY, touchRecord.previousTimeStamp = touchRecord.currentTimeStamp, + touchRecord.currentPageX = touch.pageX, touchRecord.currentPageY = touch.pageY, + touchRecord.currentTimeStamp = timestampForTouch(touch), touchHistory.mostRecentTimeStamp = timestampForTouch(touch)) : console.error("Cannot record touch move without a touch start.\n" + "Touch Move: %s\n", "Touch Bank: %s", printTouch(touch), printTouchBank()); +} + +function recordTouchEnd(touch) { + var touchRecord = touchBank[getTouchIdentifier(touch)]; + touchRecord ? (touchRecord.touchActive = !1, touchRecord.previousPageX = touchRecord.currentPageX, + touchRecord.previousPageY = touchRecord.currentPageY, touchRecord.previousTimeStamp = touchRecord.currentTimeStamp, + touchRecord.currentPageX = touch.pageX, touchRecord.currentPageY = touch.pageY, + touchRecord.currentTimeStamp = timestampForTouch(touch), touchHistory.mostRecentTimeStamp = timestampForTouch(touch)) : console.error("Cannot record touch end without a touch start.\n" + "Touch End: %s\n", "Touch Bank: %s", printTouch(touch), printTouchBank()); +} + +function printTouch(touch) { + return JSON.stringify({ + identifier: touch.identifier, + pageX: touch.pageX, + pageY: touch.pageY, + timestamp: timestampForTouch(touch) + }); +} + +function printTouchBank() { + var printed = JSON.stringify(touchBank.slice(0, MAX_TOUCH_BANK)); + return touchBank.length > MAX_TOUCH_BANK && (printed += " (original size: " + touchBank.length + ")"), + printed; +} + +var ResponderTouchHistoryStore = { + recordTouchTrack: function(topLevelType, nativeEvent) { + if (isMoveish$2(topLevelType)) nativeEvent.changedTouches.forEach(recordTouchMove); else if (isStartish$2(topLevelType)) nativeEvent.changedTouches.forEach(recordTouchStart), + touchHistory.numberActiveTouches = nativeEvent.touches.length, 1 === touchHistory.numberActiveTouches && (touchHistory.indexOfSingleActiveTouch = nativeEvent.touches[0].identifier); else if (isEndish$2(topLevelType) && (nativeEvent.changedTouches.forEach(recordTouchEnd), + touchHistory.numberActiveTouches = nativeEvent.touches.length, 1 === touchHistory.numberActiveTouches)) { + for (var i = 0; i < touchBank.length; i++) { + var touchTrackToCheck = touchBank[i]; + if (null != touchTrackToCheck && touchTrackToCheck.touchActive) { + touchHistory.indexOfSingleActiveTouch = i; + break; + } + } + var activeRecord = touchBank[touchHistory.indexOfSingleActiveTouch]; + warning(null != activeRecord && activeRecord.touchActive, "Cannot find single active touch."); + } + }, + touchHistory: touchHistory +}, ResponderTouchHistoryStore_1 = ResponderTouchHistoryStore; + +function accumulate(current, next) { + return invariant(null != next, "accumulate(...): Accumulated items must be not be null or undefined."), + null == current ? next : Array.isArray(current) ? current.concat(next) : Array.isArray(next) ? [ current ].concat(next) : [ current, next ]; +} + +var accumulate_1 = accumulate, isStartish$1 = EventPluginUtils_1.isStartish, isMoveish$1 = EventPluginUtils_1.isMoveish, isEndish$1 = EventPluginUtils_1.isEndish, executeDirectDispatch$1 = EventPluginUtils_1.executeDirectDispatch, hasDispatches$1 = EventPluginUtils_1.hasDispatches, executeDispatchesInOrderStopAtTrue$1 = EventPluginUtils_1.executeDispatchesInOrderStopAtTrue, responderInst = null, trackedTouchCount = 0, previousActiveTouches = 0, changeResponder = function(nextResponderInst, blockHostResponder) { + var oldResponderInst = responderInst; + responderInst = nextResponderInst, null !== ResponderEventPlugin.GlobalResponderHandler && ResponderEventPlugin.GlobalResponderHandler.onChange(oldResponderInst, nextResponderInst, blockHostResponder); +}, eventTypes = { + startShouldSetResponder: { + phasedRegistrationNames: { + bubbled: "onStartShouldSetResponder", + captured: "onStartShouldSetResponderCapture" + } + }, + scrollShouldSetResponder: { + phasedRegistrationNames: { + bubbled: "onScrollShouldSetResponder", + captured: "onScrollShouldSetResponderCapture" + } + }, + selectionChangeShouldSetResponder: { + phasedRegistrationNames: { + bubbled: "onSelectionChangeShouldSetResponder", + captured: "onSelectionChangeShouldSetResponderCapture" + } + }, + moveShouldSetResponder: { + phasedRegistrationNames: { + bubbled: "onMoveShouldSetResponder", + captured: "onMoveShouldSetResponderCapture" + } + }, + responderStart: { + registrationName: "onResponderStart" + }, + responderMove: { + registrationName: "onResponderMove" + }, + responderEnd: { + registrationName: "onResponderEnd" + }, + responderRelease: { + registrationName: "onResponderRelease" + }, + responderTerminationRequest: { + registrationName: "onResponderTerminationRequest" + }, + responderGrant: { + registrationName: "onResponderGrant" + }, + responderReject: { + registrationName: "onResponderReject" + }, + responderTerminate: { + registrationName: "onResponderTerminate" + } +}; + +function setResponderAndExtractTransfer(topLevelType, targetInst, nativeEvent, nativeEventTarget) { + var shouldSetEventType = isStartish$1(topLevelType) ? eventTypes.startShouldSetResponder : isMoveish$1(topLevelType) ? eventTypes.moveShouldSetResponder : "topSelectionChange" === topLevelType ? eventTypes.selectionChangeShouldSetResponder : eventTypes.scrollShouldSetResponder, bubbleShouldSetFrom = responderInst ? ReactTreeTraversal.getLowestCommonAncestor(responderInst, targetInst) : targetInst, skipOverBubbleShouldSetFrom = bubbleShouldSetFrom === responderInst, shouldSetEvent = ResponderSyntheticEvent_1.getPooled(shouldSetEventType, bubbleShouldSetFrom, nativeEvent, nativeEventTarget); + shouldSetEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, skipOverBubbleShouldSetFrom ? EventPropagators_1.accumulateTwoPhaseDispatchesSkipTarget(shouldSetEvent) : EventPropagators_1.accumulateTwoPhaseDispatches(shouldSetEvent); + var wantsResponderInst = executeDispatchesInOrderStopAtTrue$1(shouldSetEvent); + if (shouldSetEvent.isPersistent() || shouldSetEvent.constructor.release(shouldSetEvent), + !wantsResponderInst || wantsResponderInst === responderInst) return null; + var extracted, grantEvent = ResponderSyntheticEvent_1.getPooled(eventTypes.responderGrant, wantsResponderInst, nativeEvent, nativeEventTarget); + grantEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, EventPropagators_1.accumulateDirectDispatches(grantEvent); + var blockHostResponder = !0 === executeDirectDispatch$1(grantEvent); + if (responderInst) { + var terminationRequestEvent = ResponderSyntheticEvent_1.getPooled(eventTypes.responderTerminationRequest, responderInst, nativeEvent, nativeEventTarget); + terminationRequestEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, + EventPropagators_1.accumulateDirectDispatches(terminationRequestEvent); + var shouldSwitch = !hasDispatches$1(terminationRequestEvent) || executeDirectDispatch$1(terminationRequestEvent); + if (terminationRequestEvent.isPersistent() || terminationRequestEvent.constructor.release(terminationRequestEvent), + shouldSwitch) { + var terminateEvent = ResponderSyntheticEvent_1.getPooled(eventTypes.responderTerminate, responderInst, nativeEvent, nativeEventTarget); + terminateEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, EventPropagators_1.accumulateDirectDispatches(terminateEvent), + extracted = accumulate_1(extracted, [ grantEvent, terminateEvent ]), changeResponder(wantsResponderInst, blockHostResponder); + } else { + var rejectEvent = ResponderSyntheticEvent_1.getPooled(eventTypes.responderReject, wantsResponderInst, nativeEvent, nativeEventTarget); + rejectEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, EventPropagators_1.accumulateDirectDispatches(rejectEvent), + extracted = accumulate_1(extracted, rejectEvent); + } + } else extracted = accumulate_1(extracted, grantEvent), changeResponder(wantsResponderInst, blockHostResponder); + return extracted; +} + +function canTriggerTransfer(topLevelType, topLevelInst, nativeEvent) { + return topLevelInst && ("topScroll" === topLevelType && !nativeEvent.responderIgnoreScroll || trackedTouchCount > 0 && "topSelectionChange" === topLevelType || isStartish$1(topLevelType) || isMoveish$1(topLevelType)); +} + +function noResponderTouches(nativeEvent) { + var touches = nativeEvent.touches; + if (!touches || 0 === touches.length) return !0; + for (var i = 0; i < touches.length; i++) { + var activeTouch = touches[i], target = activeTouch.target; + if (null !== target && void 0 !== target && 0 !== target) { + var targetInst = EventPluginUtils_1.getInstanceFromNode(target); + if (ReactTreeTraversal.isAncestor(responderInst, targetInst)) return !1; + } + } + return !0; +} + +var ResponderEventPlugin = { + _getResponder: function() { + return responderInst; + }, + eventTypes: eventTypes, + extractEvents: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) { + if (isStartish$1(topLevelType)) trackedTouchCount += 1; else if (isEndish$1(topLevelType)) { + if (!(trackedTouchCount >= 0)) return console.error("Ended a touch event which was not counted in `trackedTouchCount`."), + null; + trackedTouchCount -= 1; + } + ResponderTouchHistoryStore_1.recordTouchTrack(topLevelType, nativeEvent); + var extracted = canTriggerTransfer(topLevelType, targetInst, nativeEvent) ? setResponderAndExtractTransfer(topLevelType, targetInst, nativeEvent, nativeEventTarget) : null, isResponderTouchStart = responderInst && isStartish$1(topLevelType), isResponderTouchMove = responderInst && isMoveish$1(topLevelType), isResponderTouchEnd = responderInst && isEndish$1(topLevelType), incrementalTouch = isResponderTouchStart ? eventTypes.responderStart : isResponderTouchMove ? eventTypes.responderMove : isResponderTouchEnd ? eventTypes.responderEnd : null; + if (incrementalTouch) { + var gesture = ResponderSyntheticEvent_1.getPooled(incrementalTouch, responderInst, nativeEvent, nativeEventTarget); + gesture.touchHistory = ResponderTouchHistoryStore_1.touchHistory, EventPropagators_1.accumulateDirectDispatches(gesture), + extracted = accumulate_1(extracted, gesture); + } + var isResponderTerminate = responderInst && "topTouchCancel" === topLevelType, isResponderRelease = responderInst && !isResponderTerminate && isEndish$1(topLevelType) && noResponderTouches(nativeEvent), finalTouch = isResponderTerminate ? eventTypes.responderTerminate : isResponderRelease ? eventTypes.responderRelease : null; + if (finalTouch) { + var finalEvent = ResponderSyntheticEvent_1.getPooled(finalTouch, responderInst, nativeEvent, nativeEventTarget); + finalEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, EventPropagators_1.accumulateDirectDispatches(finalEvent), + extracted = accumulate_1(extracted, finalEvent), changeResponder(null); + } + var numberActiveTouches = ResponderTouchHistoryStore_1.touchHistory.numberActiveTouches; + return ResponderEventPlugin.GlobalInteractionHandler && numberActiveTouches !== previousActiveTouches && ResponderEventPlugin.GlobalInteractionHandler.onChange(numberActiveTouches), + previousActiveTouches = numberActiveTouches, extracted; + }, + GlobalResponderHandler: null, + GlobalInteractionHandler: null, + injection: { + injectGlobalResponderHandler: function(GlobalResponderHandler) { + ResponderEventPlugin.GlobalResponderHandler = GlobalResponderHandler; + }, + injectGlobalInteractionHandler: function(GlobalInteractionHandler) { + ResponderEventPlugin.GlobalInteractionHandler = GlobalInteractionHandler; + } + } +}, ResponderEventPlugin_1 = ResponderEventPlugin; + +function inject() { + RCTEventEmitter.register(ReactNativeEventEmitter_1), EventPluginHub_1.injection.injectEventPluginOrder(ReactNativeEventPluginOrder_1), + EventPluginUtils_1.injection.injectComponentTree(ReactNativeComponentTree_1), ResponderEventPlugin_1.injection.injectGlobalResponderHandler(ReactNativeGlobalResponderHandler_1), + EventPluginHub_1.injection.injectEventPluginsByName({ + ResponderEventPlugin: ResponderEventPlugin_1, + ReactNativeBridgeEventPlugin: ReactNativeBridgeEventPlugin_1 + }); +} + +var ReactNativeInjection = { + inject: inject +}, ReactInvalidSetStateWarningHook = {}, processingChildContext = !1, warnInvalidSetState = function() { + warning(!processingChildContext, "setState(...): Cannot call setState() inside getChildContext()"); +}; + +ReactInvalidSetStateWarningHook = { + onBeginProcessingChildContext: function() { + processingChildContext = !0; + }, + onEndProcessingChildContext: function() { + processingChildContext = !1; + }, + onSetState: function() { + warnInvalidSetState(); + } +}; + +var ReactInvalidSetStateWarningHook_1 = ReactInvalidSetStateWarningHook, ReactHostOperationHistoryHook = null, history = []; + +ReactHostOperationHistoryHook = { + onHostOperation: function(operation) { + history.push(operation); + }, + clearHistory: function() { + ReactHostOperationHistoryHook._preventClearing || (history = []); + }, + getHistory: function() { + return history; + } +}; + +var ReactHostOperationHistoryHook_1 = ReactHostOperationHistoryHook, ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, ReactGlobalSharedState = { + ReactCurrentOwner: ReactInternals.ReactCurrentOwner +}; + +Object.assign(ReactGlobalSharedState, { + ReactComponentTreeHook: ReactInternals.ReactComponentTreeHook, + ReactDebugCurrentFrame: ReactInternals.ReactDebugCurrentFrame +}); + +var ReactGlobalSharedState_1 = ReactGlobalSharedState, ReactComponentTreeHook = ReactGlobalSharedState_1.ReactComponentTreeHook, ReactDebugTool$1 = null, hooks = [], didHookThrowForEvent = {}, callHook = function(event, fn, context, arg1, arg2, arg3, arg4, arg5) { + try { + fn.call(context, arg1, arg2, arg3, arg4, arg5); + } catch (e) { + warning(didHookThrowForEvent[event], "Exception thrown by hook while handling %s: %s", event, e + "\n" + e.stack), + didHookThrowForEvent[event] = !0; + } +}, emitEvent = function(event, arg1, arg2, arg3, arg4, arg5) { + for (var i = 0; i < hooks.length; i++) { + var hook = hooks[i], fn = hook[event]; + fn && callHook(event, fn, hook, arg1, arg2, arg3, arg4, arg5); + } +}, isProfiling = !1, flushHistory = [], lifeCycleTimerStack = [], currentFlushNesting = 0, currentFlushMeasurements = [], currentFlushStartTime = 0, currentTimerDebugID = null, currentTimerStartTime = 0, currentTimerNestedFlushDuration = 0, currentTimerType = null, lifeCycleTimerHasWarned = !1, clearHistory = function() { + ReactComponentTreeHook.purgeUnmountedComponents(), ReactHostOperationHistoryHook_1.clearHistory(); +}, getTreeSnapshot = function(registeredIDs) { + return registeredIDs.reduce(function(tree, id) { + var ownerID = ReactComponentTreeHook.getOwnerID(id), parentID = ReactComponentTreeHook.getParentID(id); + return tree[id] = { + displayName: ReactComponentTreeHook.getDisplayName(id), + text: ReactComponentTreeHook.getText(id), + updateCount: ReactComponentTreeHook.getUpdateCount(id), + childIDs: ReactComponentTreeHook.getChildIDs(id), + ownerID: ownerID || parentID && ReactComponentTreeHook.getOwnerID(parentID) || 0, + parentID: parentID + }, tree; + }, {}); +}, resetMeasurements = function() { + var previousStartTime = currentFlushStartTime, previousMeasurements = currentFlushMeasurements, previousOperations = ReactHostOperationHistoryHook_1.getHistory(); + if (0 === currentFlushNesting) return currentFlushStartTime = 0, currentFlushMeasurements = [], + void clearHistory(); + if (previousMeasurements.length || previousOperations.length) { + var registeredIDs = ReactComponentTreeHook.getRegisteredIDs(); + flushHistory.push({ + duration: performanceNow() - previousStartTime, + measurements: previousMeasurements || [], + operations: previousOperations || [], + treeSnapshot: getTreeSnapshot(registeredIDs) + }); + } + clearHistory(), currentFlushStartTime = performanceNow(), currentFlushMeasurements = []; +}, checkDebugID = function(debugID) { + arguments.length > 1 && void 0 !== arguments[1] && arguments[1] && 0 === debugID || debugID || warning(!1, "ReactDebugTool: debugID may not be empty."); +}, beginLifeCycleTimer = function(debugID, timerType) { + 0 !== currentFlushNesting && (currentTimerType && !lifeCycleTimerHasWarned && (warning(!1, "There is an internal error in the React performance measurement code." + "\n\nDid not expect %s timer to start while %s timer is still in " + "progress for %s instance.", timerType, currentTimerType || "no", debugID === currentTimerDebugID ? "the same" : "another"), + lifeCycleTimerHasWarned = !0), currentTimerStartTime = performanceNow(), currentTimerNestedFlushDuration = 0, + currentTimerDebugID = debugID, currentTimerType = timerType); +}, endLifeCycleTimer = function(debugID, timerType) { + 0 !== currentFlushNesting && (currentTimerType === timerType || lifeCycleTimerHasWarned || (warning(!1, "There is an internal error in the React performance measurement code. " + "We did not expect %s timer to stop while %s timer is still in " + "progress for %s instance. Please report this as a bug in React.", timerType, currentTimerType || "no", debugID === currentTimerDebugID ? "the same" : "another"), + lifeCycleTimerHasWarned = !0), isProfiling && currentFlushMeasurements.push({ + timerType: timerType, + instanceID: debugID, + duration: performanceNow() - currentTimerStartTime - currentTimerNestedFlushDuration + }), currentTimerStartTime = 0, currentTimerNestedFlushDuration = 0, currentTimerDebugID = null, + currentTimerType = null); +}, pauseCurrentLifeCycleTimer = function() { + var currentTimer = { + startTime: currentTimerStartTime, + nestedFlushStartTime: performanceNow(), + debugID: currentTimerDebugID, + timerType: currentTimerType + }; + lifeCycleTimerStack.push(currentTimer), currentTimerStartTime = 0, currentTimerNestedFlushDuration = 0, + currentTimerDebugID = null, currentTimerType = null; +}, resumeCurrentLifeCycleTimer = function() { + var _lifeCycleTimerStack$ = lifeCycleTimerStack.pop(), startTime = _lifeCycleTimerStack$.startTime, nestedFlushStartTime = _lifeCycleTimerStack$.nestedFlushStartTime, debugID = _lifeCycleTimerStack$.debugID, timerType = _lifeCycleTimerStack$.timerType, nestedFlushDuration = performanceNow() - nestedFlushStartTime; + currentTimerStartTime = startTime, currentTimerNestedFlushDuration += nestedFlushDuration, + currentTimerDebugID = debugID, currentTimerType = timerType; +}, lastMarkTimeStamp = 0, canUsePerformanceMeasure = "undefined" != typeof performance && "function" == typeof performance.mark && "function" == typeof performance.clearMarks && "function" == typeof performance.measure && "function" == typeof performance.clearMeasures, shouldMark = function(debugID) { + if (!isProfiling || !canUsePerformanceMeasure) return !1; + var element = ReactComponentTreeHook.getElement(debugID); + return null != element && "object" == typeof element && !("string" == typeof element.type); +}, markBegin = function(debugID, markType) { + if (shouldMark(debugID)) { + var markName = debugID + "::" + markType; + lastMarkTimeStamp = performanceNow(), performance.mark(markName); + } +}, markEnd = function(debugID, markType) { + if (shouldMark(debugID)) { + var markName = debugID + "::" + markType, displayName = ReactComponentTreeHook.getDisplayName(debugID) || "Unknown"; + if (performanceNow() - lastMarkTimeStamp > .1) { + var measurementName = displayName + " [" + markType + "]"; + performance.measure(measurementName, markName); + } + performance.clearMarks(markName), measurementName && performance.clearMeasures(measurementName); + } +}; + +ReactDebugTool$1 = { + addHook: function(hook) { + hooks.push(hook); + }, + removeHook: function(hook) { + for (var i = 0; i < hooks.length; i++) hooks[i] === hook && (hooks.splice(i, 1), + i--); + }, + isProfiling: function() { + return isProfiling; + }, + beginProfiling: function() { + isProfiling || (isProfiling = !0, flushHistory.length = 0, resetMeasurements(), + ReactDebugTool$1.addHook(ReactHostOperationHistoryHook_1)); + }, + endProfiling: function() { + isProfiling && (isProfiling = !1, resetMeasurements(), ReactDebugTool$1.removeHook(ReactHostOperationHistoryHook_1)); + }, + getFlushHistory: function() { + return flushHistory; + }, + onBeginFlush: function() { + currentFlushNesting++, resetMeasurements(), pauseCurrentLifeCycleTimer(), emitEvent("onBeginFlush"); + }, + onEndFlush: function() { + resetMeasurements(), currentFlushNesting--, resumeCurrentLifeCycleTimer(), emitEvent("onEndFlush"); + }, + onBeginLifeCycleTimer: function(debugID, timerType) { + checkDebugID(debugID), emitEvent("onBeginLifeCycleTimer", debugID, timerType), markBegin(debugID, timerType), + beginLifeCycleTimer(debugID, timerType); + }, + onEndLifeCycleTimer: function(debugID, timerType) { + checkDebugID(debugID), endLifeCycleTimer(debugID, timerType), markEnd(debugID, timerType), + emitEvent("onEndLifeCycleTimer", debugID, timerType); + }, + onBeginProcessingChildContext: function() { + emitEvent("onBeginProcessingChildContext"); + }, + onEndProcessingChildContext: function() { + emitEvent("onEndProcessingChildContext"); + }, + onHostOperation: function(operation) { + checkDebugID(operation.instanceID), emitEvent("onHostOperation", operation); + }, + onSetState: function() { + emitEvent("onSetState"); + }, + onSetChildren: function(debugID, childDebugIDs) { + checkDebugID(debugID), childDebugIDs.forEach(checkDebugID), emitEvent("onSetChildren", debugID, childDebugIDs); + }, + onBeforeMountComponent: function(debugID, element, parentDebugID) { + checkDebugID(debugID), checkDebugID(parentDebugID, !0), emitEvent("onBeforeMountComponent", debugID, element, parentDebugID), + markBegin(debugID, "mount"); + }, + onMountComponent: function(debugID) { + checkDebugID(debugID), markEnd(debugID, "mount"), emitEvent("onMountComponent", debugID); + }, + onBeforeUpdateComponent: function(debugID, element) { + checkDebugID(debugID), emitEvent("onBeforeUpdateComponent", debugID, element), markBegin(debugID, "update"); + }, + onUpdateComponent: function(debugID) { + checkDebugID(debugID), markEnd(debugID, "update"), emitEvent("onUpdateComponent", debugID); + }, + onBeforeUnmountComponent: function(debugID) { + checkDebugID(debugID), emitEvent("onBeforeUnmountComponent", debugID), markBegin(debugID, "unmount"); + }, + onUnmountComponent: function(debugID) { + checkDebugID(debugID), markEnd(debugID, "unmount"), emitEvent("onUnmountComponent", debugID); + }, + onTestEvent: function() { + emitEvent("onTestEvent"); + } +}, ReactDebugTool$1.addHook(ReactInvalidSetStateWarningHook_1), ReactDebugTool$1.addHook(ReactComponentTreeHook); + +var url = ExecutionEnvironment.canUseDOM && window.location.href || ""; + +/[?&]react_perf\b/.test(url) && ReactDebugTool$1.beginProfiling(); + +var ReactDebugTool_1 = ReactDebugTool$1, debugTool = null, ReactDebugTool = ReactDebugTool_1; + +debugTool = ReactDebugTool; + +var ReactInstrumentation = { + debugTool: debugTool +}; + +function ReactNativeContainerInfo(tag) { + return { + _tag: tag + }; +} + +var ReactNativeContainerInfo_1 = ReactNativeContainerInfo, ClassComponent = ReactTypeOfWork.ClassComponent; + +function isValidOwner(object) { + return !(!object || "function" != typeof object.attachRef || "function" != typeof object.detachRef); +} + +var ReactOwner = { + addComponentAsRefTo: function(component, ref, owner) { + if (owner && owner.tag === ClassComponent) { + var inst = owner.stateNode; + (inst.refs === emptyObject ? inst.refs = {} : inst.refs)[ref] = component.getPublicInstance(); + } else invariant(isValidOwner(owner), "addComponentAsRefTo(...): Only a ReactOwner can have refs. You might " + "be adding a ref to a component that was not created inside a component's " + "`render` method, or you have multiple copies of React loaded " + "(details: https://fb.me/react-refs-must-have-owner)."), + owner.attachRef(ref, component); + }, + removeComponentAsRefFrom: function(component, ref, owner) { + if (owner && owner.tag === ClassComponent) { + var inst = owner.stateNode; + inst && inst.refs[ref] === component.getPublicInstance() && delete inst.refs[ref]; + } else { + invariant(isValidOwner(owner), "removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might " + "be removing a ref to a component that was not created inside a component's " + "`render` method, or you have multiple copies of React loaded " + "(details: https://fb.me/react-refs-must-have-owner)."); + var ownerPublicInstance = owner.getPublicInstance(); + ownerPublicInstance && ownerPublicInstance.refs[ref] === component.getPublicInstance() && owner.detachRef(ref); + } + } +}, ReactOwner_1 = ReactOwner, ReactCompositeComponentTypes$1 = { + ImpureClass: 0, + PureClass: 1, + StatelessFunctional: 2 +}, ReactRef = {}, ReactCompositeComponentTypes = ReactCompositeComponentTypes$1, _require$1 = ReactGlobalSharedState_1, ReactComponentTreeHook$1 = _require$1.ReactComponentTreeHook, warning$2 = warning, warnedAboutStatelessRefs = {}; + +function attachRef(ref, component, owner) { + if (component._compositeType === ReactCompositeComponentTypes.StatelessFunctional) { + var info = "", ownerName = void 0; + owner && ("function" == typeof owner.getName && (ownerName = owner.getName()), ownerName && (info += "\n\nCheck the render method of `" + ownerName + "`.")); + var warningKey = ownerName || component._debugID, element = component._currentElement; + element && element._source && (warningKey = element._source.fileName + ":" + element._source.lineNumber), + warnedAboutStatelessRefs[warningKey] || (warnedAboutStatelessRefs[warningKey] = !0, + warning$2(!1, "Stateless function components cannot be given refs. " + "Attempts to access this ref will fail.%s%s", info, ReactComponentTreeHook$1.getStackAddendumByID(component._debugID))); + } + "function" == typeof ref ? ref(component.getPublicInstance()) : ReactOwner_1.addComponentAsRefTo(component, ref, owner); +} + +function detachRef(ref, component, owner) { + "function" == typeof ref ? ref(null) : ReactOwner_1.removeComponentAsRefFrom(component, ref, owner); +} + +ReactRef.attachRefs = function(instance, element) { + if (null !== element && "object" == typeof element) { + var ref = element.ref; + null != ref && attachRef(ref, instance, element._owner); + } +}, ReactRef.shouldUpdateRefs = function(prevElement, nextElement) { + var prevRef = null, prevOwner = null; + null !== prevElement && "object" == typeof prevElement && (prevRef = prevElement.ref, + prevOwner = prevElement._owner); + var nextRef = null, nextOwner = null; + return null !== nextElement && "object" == typeof nextElement && (nextRef = nextElement.ref, + nextOwner = nextElement._owner), prevRef !== nextRef || "string" == typeof nextRef && nextOwner !== prevOwner; +}, ReactRef.detachRefs = function(instance, element) { + if (null !== element && "object" == typeof element) { + var ref = element.ref; + null != ref && detachRef(ref, instance, element._owner); + } +}; + +var ReactRef_1 = ReactRef; + +function attachRefs() { + ReactRef_1.attachRefs(this, this._currentElement); +} + +var ReactReconciler = { + mountComponent: function(internalInstance, transaction, hostParent, hostContainerInfo, context, parentDebugID) { + 0 !== internalInstance._debugID && ReactInstrumentation.debugTool.onBeforeMountComponent(internalInstance._debugID, internalInstance._currentElement, parentDebugID); + var markup = internalInstance.mountComponent(transaction, hostParent, hostContainerInfo, context, parentDebugID); + return internalInstance._currentElement && null != internalInstance._currentElement.ref && transaction.getReactMountReady().enqueue(attachRefs, internalInstance), + 0 !== internalInstance._debugID && ReactInstrumentation.debugTool.onMountComponent(internalInstance._debugID), + markup; + }, + getHostNode: function(internalInstance) { + return internalInstance.getHostNode(); + }, + unmountComponent: function(internalInstance, safely, skipLifecycle) { + 0 !== internalInstance._debugID && ReactInstrumentation.debugTool.onBeforeUnmountComponent(internalInstance._debugID), + ReactRef_1.detachRefs(internalInstance, internalInstance._currentElement), internalInstance.unmountComponent(safely, skipLifecycle), + 0 !== internalInstance._debugID && ReactInstrumentation.debugTool.onUnmountComponent(internalInstance._debugID); + }, + receiveComponent: function(internalInstance, nextElement, transaction, context) { + var prevElement = internalInstance._currentElement; + if (nextElement !== prevElement || context !== internalInstance._context) { + 0 !== internalInstance._debugID && ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, nextElement); + var refsChanged = ReactRef_1.shouldUpdateRefs(prevElement, nextElement); + refsChanged && ReactRef_1.detachRefs(internalInstance, prevElement), internalInstance.receiveComponent(nextElement, transaction, context), + refsChanged && internalInstance._currentElement && null != internalInstance._currentElement.ref && transaction.getReactMountReady().enqueue(attachRefs, internalInstance), + 0 !== internalInstance._debugID && ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID); + } + }, + performUpdateIfNecessary: function(internalInstance, transaction, updateBatchNumber) { + if (internalInstance._updateBatchNumber !== updateBatchNumber) return void warning(null == internalInstance._updateBatchNumber || internalInstance._updateBatchNumber === updateBatchNumber + 1, "performUpdateIfNecessary: Unexpected batch number (current %s, " + "pending %s)", updateBatchNumber, internalInstance._updateBatchNumber); + 0 !== internalInstance._debugID && ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, internalInstance._currentElement), + internalInstance.performUpdateIfNecessary(transaction), 0 !== internalInstance._debugID && ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID); + } +}, ReactReconciler_1 = ReactReconciler, ReactInstanceMap = { + remove: function(key) { + key._reactInternalInstance = void 0; + }, + get: function(key) { + return key._reactInternalInstance; + }, + has: function(key) { + return void 0 !== key._reactInternalInstance; + }, + set: function(key, value) { + key._reactInternalInstance = value; + } +}, ReactInstanceMap_1 = ReactInstanceMap, ReactFeatureFlags = { + logTopLevelRenders: !1, + prepareNewChildrenBeforeUnmountInStack: !0, + disableNewFiberFeatures: !1, + enableAsyncSubtreeAPI: !1 +}, ReactFeatureFlags_1 = ReactFeatureFlags, OBSERVED_ERROR = {}, TransactionImpl = { + reinitializeTransaction: function() { + this.transactionWrappers = this.getTransactionWrappers(), this.wrapperInitData ? this.wrapperInitData.length = 0 : this.wrapperInitData = [], + this._isInTransaction = !1; + }, + _isInTransaction: !1, + getTransactionWrappers: null, + isInTransaction: function() { + return !!this._isInTransaction; + }, + perform: function(method, scope, a, b, c, d, e, f) { + invariant(!this.isInTransaction(), "Transaction.perform(...): Cannot initialize a transaction when there " + "is already an outstanding transaction."); + var errorThrown, ret; + try { + this._isInTransaction = !0, errorThrown = !0, this.initializeAll(0), ret = method.call(scope, a, b, c, d, e, f), + errorThrown = !1; + } finally { + try { + if (errorThrown) try { + this.closeAll(0); + } catch (err) {} else this.closeAll(0); + } finally { + this._isInTransaction = !1; + } + } + return ret; + }, + initializeAll: function(startIndex) { + for (var transactionWrappers = this.transactionWrappers, i = startIndex; i < transactionWrappers.length; i++) { + var wrapper = transactionWrappers[i]; + try { + this.wrapperInitData[i] = OBSERVED_ERROR, this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null; + } finally { + if (this.wrapperInitData[i] === OBSERVED_ERROR) try { + this.initializeAll(i + 1); + } catch (err) {} + } + } + }, + closeAll: function(startIndex) { + invariant(this.isInTransaction(), "Transaction.closeAll(): Cannot close transaction when none are open."); + for (var transactionWrappers = this.transactionWrappers, i = startIndex; i < transactionWrappers.length; i++) { + var errorThrown, wrapper = transactionWrappers[i], initData = this.wrapperInitData[i]; + try { + errorThrown = !0, initData !== OBSERVED_ERROR && wrapper.close && wrapper.close.call(this, initData), + errorThrown = !1; + } finally { + if (errorThrown) try { + this.closeAll(i + 1); + } catch (e) {} + } + } + this.wrapperInitData.length = 0; + } +}, Transaction = TransactionImpl, dirtyComponents = [], updateBatchNumber = 0, batchingStrategy = null; + +function ensureInjected() { + invariant(ReactUpdates.ReactReconcileTransaction && batchingStrategy, "ReactUpdates: must inject a reconcile transaction class and batching " + "strategy"); +} + +var NESTED_UPDATES = { + initialize: function() { + this.dirtyComponentsLength = dirtyComponents.length; + }, + close: function() { + this.dirtyComponentsLength !== dirtyComponents.length ? (dirtyComponents.splice(0, this.dirtyComponentsLength), + flushBatchedUpdates()) : dirtyComponents.length = 0; + } +}, TRANSACTION_WRAPPERS = [ NESTED_UPDATES ]; + +function ReactUpdatesFlushTransaction() { + this.reinitializeTransaction(), this.dirtyComponentsLength = null, this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled(!0); +} + +Object.assign(ReactUpdatesFlushTransaction.prototype, Transaction, { + getTransactionWrappers: function() { + return TRANSACTION_WRAPPERS; + }, + destructor: function() { + this.dirtyComponentsLength = null, ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction), + this.reconcileTransaction = null; + }, + perform: function(method, scope, a) { + return Transaction.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a); + } +}), PooledClass_1.addPoolingTo(ReactUpdatesFlushTransaction); + +function batchedUpdates$1(callback, a, b, c, d, e) { + return ensureInjected(), batchingStrategy.batchedUpdates(callback, a, b, c, d, e); +} + +function mountOrderComparator(c1, c2) { + return c1._mountOrder - c2._mountOrder; +} + +function runBatchedUpdates(transaction) { + var len = transaction.dirtyComponentsLength; + invariant(len === dirtyComponents.length, "Expected flush transaction's stored dirty-components length (%s) to " + "match dirty-components array length (%s).", len, dirtyComponents.length), + dirtyComponents.sort(mountOrderComparator), updateBatchNumber++; + for (var i = 0; i < len; i++) { + var markerName, component = dirtyComponents[i]; + if (ReactFeatureFlags_1.logTopLevelRenders) { + var namedComponent = component; + component._currentElement.type.isReactTopLevelWrapper && (namedComponent = component._renderedComponent), + markerName = "React update: " + namedComponent.getName(), console.time(markerName); + } + ReactReconciler_1.performUpdateIfNecessary(component, transaction.reconcileTransaction, updateBatchNumber), + markerName && console.timeEnd(markerName); + } +} + +var flushBatchedUpdates = function() { + for (;dirtyComponents.length; ) { + var transaction = ReactUpdatesFlushTransaction.getPooled(); + transaction.perform(runBatchedUpdates, null, transaction), ReactUpdatesFlushTransaction.release(transaction); + } +}; + +function enqueueUpdate$1(component) { + if (ensureInjected(), !batchingStrategy.isBatchingUpdates) return void batchingStrategy.batchedUpdates(enqueueUpdate$1, component); + dirtyComponents.push(component), null == component._updateBatchNumber && (component._updateBatchNumber = updateBatchNumber + 1); +} + +var ReactUpdatesInjection = { + injectReconcileTransaction: function(ReconcileTransaction) { + invariant(ReconcileTransaction, "ReactUpdates: must provide a reconcile transaction class"), + ReactUpdates.ReactReconcileTransaction = ReconcileTransaction; + }, + injectBatchingStrategy: function(_batchingStrategy) { + invariant(_batchingStrategy, "ReactUpdates: must provide a batching strategy"), + invariant("function" == typeof _batchingStrategy.batchedUpdates, "ReactUpdates: must provide a batchedUpdates() function"), + invariant("boolean" == typeof _batchingStrategy.isBatchingUpdates, "ReactUpdates: must provide an isBatchingUpdates boolean attribute"), + batchingStrategy = _batchingStrategy; + }, + getBatchingStrategy: function() { + return batchingStrategy; + } +}, ReactUpdates = { + ReactReconcileTransaction: null, + batchedUpdates: batchedUpdates$1, + enqueueUpdate: enqueueUpdate$1, + flushBatchedUpdates: flushBatchedUpdates, + injection: ReactUpdatesInjection +}, ReactUpdates_1 = ReactUpdates, ReactCurrentOwner = ReactGlobalSharedState_1.ReactCurrentOwner, warning$3 = warning, warnOnInvalidCallback = function(callback, callerName) { + warning$3(null === callback || "function" == typeof callback, "%s(...): Expected the last optional `callback` argument to be a " + "function. Instead received: %s.", callerName, "" + callback); +}; + +function enqueueUpdate(internalInstance) { + ReactUpdates_1.enqueueUpdate(internalInstance); +} + +function getInternalInstanceReadyForUpdate(publicInstance, callerName) { + var internalInstance = ReactInstanceMap_1.get(publicInstance); + if (!internalInstance) { + var ctor = publicInstance.constructor; + return warning$3(!1, "Can only update a mounted or mounting component. This usually means " + "you called setState, replaceState, or forceUpdate on an unmounted " + "component. This is a no-op.\n\nPlease check the code for the " + "%s component.", ctor && (ctor.displayName || ctor.name) || "ReactClass"), + null; + } + return warning$3(null == ReactCurrentOwner.current, "Cannot update during an existing state transition (such as within " + "`render` or another component's constructor). Render methods should " + "be a pure function of props and state; constructor side-effects are " + "an anti-pattern, but can be moved to `componentWillMount`."), + internalInstance; +} + +var ReactUpdateQueue = { + isMounted: function(publicInstance) { + var owner = ReactCurrentOwner.current; + null !== owner && (warning$3(owner._warnedAboutRefsInRender, "%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.", owner.getName() || "A component"), + owner._warnedAboutRefsInRender = !0); + var internalInstance = ReactInstanceMap_1.get(publicInstance); + return !!internalInstance && !!internalInstance._renderedComponent; + }, + enqueueCallbackInternal: function(internalInstance, callback) { + internalInstance._pendingCallbacks ? internalInstance._pendingCallbacks.push(callback) : internalInstance._pendingCallbacks = [ callback ], + enqueueUpdate(internalInstance); + }, + enqueueForceUpdate: function(publicInstance, callback, callerName) { + var internalInstance = getInternalInstanceReadyForUpdate(publicInstance); + internalInstance && (callback = void 0 === callback ? null : callback, null !== callback && (warnOnInvalidCallback(callback, callerName), + internalInstance._pendingCallbacks ? internalInstance._pendingCallbacks.push(callback) : internalInstance._pendingCallbacks = [ callback ]), + internalInstance._pendingForceUpdate = !0, enqueueUpdate(internalInstance)); + }, + enqueueReplaceState: function(publicInstance, completeState, callback, callerName) { + var internalInstance = getInternalInstanceReadyForUpdate(publicInstance); + internalInstance && (internalInstance._pendingStateQueue = [ completeState ], internalInstance._pendingReplaceState = !0, + callback = void 0 === callback ? null : callback, null !== callback && (warnOnInvalidCallback(callback, callerName), + internalInstance._pendingCallbacks ? internalInstance._pendingCallbacks.push(callback) : internalInstance._pendingCallbacks = [ callback ]), + enqueueUpdate(internalInstance)); + }, + enqueueSetState: function(publicInstance, partialState, callback, callerName) { + ReactInstrumentation.debugTool.onSetState(), warning$3(null != partialState, "setState(...): You passed an undefined or null state object; " + "instead, use forceUpdate()."); + var internalInstance = getInternalInstanceReadyForUpdate(publicInstance); + if (internalInstance) { + (internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = [])).push(partialState), + callback = void 0 === callback ? null : callback, null !== callback && (warnOnInvalidCallback(callback, callerName), + internalInstance._pendingCallbacks ? internalInstance._pendingCallbacks.push(callback) : internalInstance._pendingCallbacks = [ callback ]), + enqueueUpdate(internalInstance); + } + }, + enqueueElementInternal: function(internalInstance, nextElement, nextContext) { + internalInstance._pendingElement = nextElement, internalInstance._context = nextContext, + enqueueUpdate(internalInstance); + } +}, ReactUpdateQueue_1 = ReactUpdateQueue, injected = !1, ReactComponentEnvironment = { + replaceNodeWithMarkup: null, + processChildrenUpdates: null, + injection: { + injectEnvironment: function(environment) { + invariant(!injected, "ReactCompositeComponent: injectEnvironment() can only be called once."), + ReactComponentEnvironment.replaceNodeWithMarkup = environment.replaceNodeWithMarkup, + ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates, + injected = !0; + } + } +}, ReactComponentEnvironment_1 = ReactComponentEnvironment, ReactNodeTypes = { + HOST: 0, + COMPOSITE: 1, + EMPTY: 2, + getType: function(node) { + return null === node || !1 === node ? ReactNodeTypes.EMPTY : React.isValidElement(node) ? "function" == typeof node.type ? ReactNodeTypes.COMPOSITE : ReactNodeTypes.HOST : void invariant(!1, "Unexpected node: %s", node); + } +}, ReactNodeTypes_1 = ReactNodeTypes; + +function shouldUpdateReactComponent(prevElement, nextElement) { + var prevEmpty = null === prevElement || !1 === prevElement, nextEmpty = null === nextElement || !1 === nextElement; + if (prevEmpty || nextEmpty) return prevEmpty === nextEmpty; + var prevType = typeof prevElement, nextType = typeof nextElement; + return "string" === prevType || "number" === prevType ? "string" === nextType || "number" === nextType : "object" === nextType && prevElement.type === nextElement.type && prevElement.key === nextElement.key; +} + +var shouldUpdateReactComponent_1 = shouldUpdateReactComponent, ReactCurrentOwner$1 = ReactGlobalSharedState_1.ReactCurrentOwner, _require2 = ReactGlobalSharedState_1, ReactDebugCurrentFrame = _require2.ReactDebugCurrentFrame, warningAboutMissingGetChildContext = {}; + +function StatelessComponent(Component) {} + +StatelessComponent.prototype.render = function() { + return (0, ReactInstanceMap_1.get(this)._currentElement.type)(this.props, this.context, this.updater); +}; + +function shouldConstruct(Component) { + return !(!Component.prototype || !Component.prototype.isReactComponent); +} + +function isPureComponent(Component) { + return !(!Component.prototype || !Component.prototype.isPureReactComponent); +} + +function measureLifeCyclePerf(fn, debugID, timerType) { + if (0 === debugID) return fn(); + ReactInstrumentation.debugTool.onBeginLifeCycleTimer(debugID, timerType); + try { + return fn(); + } finally { + ReactInstrumentation.debugTool.onEndLifeCycleTimer(debugID, timerType); + } +} + +var nextMountID = 1, ReactCompositeComponent = { + construct: function(element) { + this._currentElement = element, this._rootNodeID = 0, this._compositeType = null, + this._instance = null, this._hostParent = null, this._hostContainerInfo = null, + this._updateBatchNumber = null, this._pendingElement = null, this._pendingStateQueue = null, + this._pendingReplaceState = !1, this._pendingForceUpdate = !1, this._renderedNodeType = null, + this._renderedComponent = null, this._context = null, this._mountOrder = 0, this._topLevelWrapper = null, + this._pendingCallbacks = null, this._calledComponentWillUnmount = !1, this._warnedAboutRefsInRender = !1; + }, + mountComponent: function(transaction, hostParent, hostContainerInfo, context) { + var _this = this; + this._context = context, this._mountOrder = nextMountID++, this._hostParent = hostParent, + this._hostContainerInfo = hostContainerInfo; + var renderedElement, publicProps = this._currentElement.props, publicContext = this._processContext(context), Component = this._currentElement.type, updateQueue = transaction.getUpdateQueue(), doConstruct = shouldConstruct(Component), inst = this._constructComponent(doConstruct, publicProps, publicContext, updateQueue); + doConstruct || null != inst && null != inst.render ? isPureComponent(Component) ? this._compositeType = ReactCompositeComponentTypes$1.PureClass : this._compositeType = ReactCompositeComponentTypes$1.ImpureClass : (renderedElement = inst, + warning(!Component.childContextTypes, "%s(...): childContextTypes cannot be defined on a functional component.", Component.displayName || Component.name || "Component"), + invariant(null === inst || !1 === inst || React.isValidElement(inst), "%s(...): A valid React element (or null) must be returned. You may have " + "returned undefined, an array or some other invalid object.", Component.displayName || Component.name || "Component"), + inst = new StatelessComponent(Component), this._compositeType = ReactCompositeComponentTypes$1.StatelessFunctional), + null == inst.render && warning(!1, "%s(...): No `render` method found on the returned component " + "instance: you may have forgotten to define `render`.", Component.displayName || Component.name || "Component"); + var propsMutated = inst.props !== publicProps, componentName = Component.displayName || Component.name || "Component"; + warning(void 0 === inst.props || !propsMutated, "%s(...): When calling super() in `%s`, make sure to pass " + "up the same props that your component's constructor was passed.", componentName, componentName), + inst.props = publicProps, inst.context = publicContext, inst.refs = emptyObject, + inst.updater = updateQueue, this._instance = inst, ReactInstanceMap_1.set(inst, this), + warning(!inst.getInitialState || inst.getInitialState.isReactClassApproved || inst.state, "getInitialState was defined on %s, a plain JavaScript class. " + "This is only supported for classes created using React.createClass. " + "Did you mean to define a state property instead?", this.getName() || "a component"), + warning(!inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved, "getDefaultProps was defined on %s, a plain JavaScript class. " + "This is only supported for classes created using React.createClass. " + "Use a static property to define defaultProps instead.", this.getName() || "a component"), + warning(!inst.propTypes, "propTypes was defined as an instance property on %s. Use a static " + "property to define propTypes instead.", this.getName() || "a component"), + warning(!inst.contextTypes, "contextTypes was defined as an instance property on %s. Use a " + "static property to define contextTypes instead.", this.getName() || "a component"), + warning("function" != typeof inst.componentShouldUpdate, "%s has a method called " + "componentShouldUpdate(). Did you mean shouldComponentUpdate()? " + "The name is phrased as a question because the function is " + "expected to return a value.", this.getName() || "A component"), + warning("function" != typeof inst.componentDidUnmount, "%s has a method called " + "componentDidUnmount(). But there is no such lifecycle method. " + "Did you mean componentWillUnmount()?", this.getName() || "A component"), + warning("function" != typeof inst.componentWillRecieveProps, "%s has a method called " + "componentWillRecieveProps(). Did you mean componentWillReceiveProps()?", this.getName() || "A component"), + isPureComponent(Component) && void 0 !== inst.shouldComponentUpdate && warning(!1, "%s has a method called shouldComponentUpdate(). " + "shouldComponentUpdate should not be used when extending React.PureComponent. " + "Please extend React.Component if shouldComponentUpdate is used.", this.getName() || "A pure component"), + warning(!inst.defaultProps, "Setting defaultProps as an instance property on %s is not supported and will be ignored." + " Instead, define defaultProps as a static property on %s.", this.getName() || "a component", this.getName() || "a component"); + var initialState = inst.state; + void 0 === initialState && (inst.state = initialState = null), invariant("object" == typeof initialState && !Array.isArray(initialState), "%s.state: must be set to an object or null", this.getName() || "ReactCompositeComponent"), + this._pendingStateQueue = null, this._pendingReplaceState = !1, this._pendingForceUpdate = !1, + inst.componentWillMount && (measureLifeCyclePerf(function() { + return inst.componentWillMount(); + }, this._debugID, "componentWillMount"), this._pendingStateQueue && (inst.state = this._processPendingState(inst.props, inst.context))); + var markup; + markup = inst.unstable_handleError ? this.performInitialMountWithErrorHandling(renderedElement, hostParent, hostContainerInfo, transaction, context) : this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context), + inst.componentDidMount && transaction.getReactMountReady().enqueue(function() { + measureLifeCyclePerf(function() { + return inst.componentDidMount(); + }, _this._debugID, "componentDidMount"); + }); + var callbacks = this._pendingCallbacks; + if (callbacks) { + this._pendingCallbacks = null; + for (var i = 0; i < callbacks.length; i++) transaction.getReactMountReady().enqueue(callbacks[i], inst); + } + return markup; + }, + _constructComponent: function(doConstruct, publicProps, publicContext, updateQueue) { + ReactCurrentOwner$1.current = this; + try { + return this._constructComponentWithoutOwner(doConstruct, publicProps, publicContext, updateQueue); + } finally { + ReactCurrentOwner$1.current = null; + } + }, + _constructComponentWithoutOwner: function(doConstruct, publicProps, publicContext, updateQueue) { + var Component = this._currentElement.type; + return doConstruct ? measureLifeCyclePerf(function() { + return new Component(publicProps, publicContext, updateQueue); + }, this._debugID, "ctor") : measureLifeCyclePerf(function() { + return Component(publicProps, publicContext, updateQueue); + }, this._debugID, "render"); + }, + performInitialMountWithErrorHandling: function(renderedElement, hostParent, hostContainerInfo, transaction, context) { + var markup, checkpoint = transaction.checkpoint(); + try { + markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context); + } catch (e) { + transaction.rollback(checkpoint), this._instance.unstable_handleError(e), this._pendingStateQueue && (this._instance.state = this._processPendingState(this._instance.props, this._instance.context)), + checkpoint = transaction.checkpoint(), this._renderedComponent.unmountComponent(!0, !0), + transaction.rollback(checkpoint), markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context); + } + return markup; + }, + performInitialMount: function(renderedElement, hostParent, hostContainerInfo, transaction, context) { + void 0 === renderedElement && (renderedElement = this._renderValidatedComponent()); + var nodeType = ReactNodeTypes_1.getType(renderedElement); + this._renderedNodeType = nodeType; + var child = this._instantiateReactComponent(renderedElement, nodeType !== ReactNodeTypes_1.EMPTY); + this._renderedComponent = child; + var debugID = 0; + debugID = this._debugID; + var markup = ReactReconciler_1.mountComponent(child, transaction, hostParent, hostContainerInfo, this._processChildContext(context), debugID); + if (0 !== debugID) { + var childDebugIDs = 0 !== child._debugID ? [ child._debugID ] : []; + ReactInstrumentation.debugTool.onSetChildren(debugID, childDebugIDs); + } + return markup; + }, + getHostNode: function() { + return ReactReconciler_1.getHostNode(this._renderedComponent); + }, + unmountComponent: function(safely, skipLifecycle) { + if (this._renderedComponent) { + var inst = this._instance; + if (inst.componentWillUnmount && !inst._calledComponentWillUnmount) if (inst._calledComponentWillUnmount = !0, + safely) { + if (!skipLifecycle) { + var name = this.getName() + ".componentWillUnmount()"; + ReactErrorUtils_1.invokeGuardedCallbackAndCatchFirstError(name, inst.componentWillUnmount, inst); + } + } else measureLifeCyclePerf(function() { + return inst.componentWillUnmount(); + }, this._debugID, "componentWillUnmount"); + this._renderedComponent && (ReactReconciler_1.unmountComponent(this._renderedComponent, safely, skipLifecycle), + this._renderedNodeType = null, this._renderedComponent = null, this._instance = null), + this._pendingStateQueue = null, this._pendingReplaceState = !1, this._pendingForceUpdate = !1, + this._pendingCallbacks = null, this._pendingElement = null, this._context = null, + this._rootNodeID = 0, this._topLevelWrapper = null, ReactInstanceMap_1.remove(inst); + } + }, + _maskContext: function(context) { + var Component = this._currentElement.type, contextTypes = Component.contextTypes; + if (!contextTypes) return emptyObject; + var maskedContext = {}; + for (var contextName in contextTypes) maskedContext[contextName] = context[contextName]; + return maskedContext; + }, + _processContext: function(context) { + var maskedContext = this._maskContext(context), Component = this._currentElement.type; + return Component.contextTypes && this._checkContextTypes(Component.contextTypes, maskedContext, "context"), + maskedContext; + }, + _processChildContext: function(currentContext) { + var childContext, Component = this._currentElement.type, inst = this._instance; + if ("function" == typeof inst.getChildContext) { + ReactInstrumentation.debugTool.onBeginProcessingChildContext(); + try { + childContext = inst.getChildContext(); + } finally { + ReactInstrumentation.debugTool.onEndProcessingChildContext(); + } + invariant("object" == typeof Component.childContextTypes, "%s.getChildContext(): childContextTypes must be defined in order to " + "use getChildContext().", this.getName() || "ReactCompositeComponent"), + this._checkContextTypes(Component.childContextTypes, childContext, "child context"); + for (var name in childContext) invariant(name in Component.childContextTypes, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || "ReactCompositeComponent", name); + return Object.assign({}, currentContext, childContext); + } + var componentName = this.getName(); + return warningAboutMissingGetChildContext[componentName] || (warningAboutMissingGetChildContext[componentName] = !0, + warning(!Component.childContextTypes, "%s.childContextTypes is specified but there is no getChildContext() method " + "on the instance. You can either define getChildContext() on %s or remove " + "childContextTypes from it.", componentName, componentName)), + currentContext; + }, + _checkContextTypes: function(typeSpecs, values, location) { + ReactDebugCurrentFrame.current = this._debugID, checkPropTypes(typeSpecs, values, location, this.getName(), ReactDebugCurrentFrame.getStackAddendum), + ReactDebugCurrentFrame.current = null; + }, + receiveComponent: function(nextElement, transaction, nextContext) { + var prevElement = this._currentElement, prevContext = this._context; + this._pendingElement = null, this.updateComponent(transaction, prevElement, nextElement, prevContext, nextContext); + }, + performUpdateIfNecessary: function(transaction) { + if (null != this._pendingElement) ReactReconciler_1.receiveComponent(this, this._pendingElement, transaction, this._context); else if (null !== this._pendingStateQueue || this._pendingForceUpdate) this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context); else { + var callbacks = this._pendingCallbacks; + if (this._pendingCallbacks = null, callbacks) for (var j = 0; j < callbacks.length; j++) transaction.getReactMountReady().enqueue(callbacks[j], this.getPublicInstance()); + this._updateBatchNumber = null; + } + }, + updateComponent: function(transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext) { + var inst = this._instance; + invariant(null != inst, "Attempted to update component `%s` that has already been unmounted " + "(or failed to mount).", this.getName() || "ReactCompositeComponent"); + var nextContext, willReceive = !1; + this._context === nextUnmaskedContext ? nextContext = inst.context : (nextContext = this._processContext(nextUnmaskedContext), + willReceive = !0); + var prevProps = prevParentElement.props, nextProps = nextParentElement.props; + if (prevParentElement !== nextParentElement && (willReceive = !0), willReceive && inst.componentWillReceiveProps) { + var beforeState = inst.state; + measureLifeCyclePerf(function() { + return inst.componentWillReceiveProps(nextProps, nextContext); + }, this._debugID, "componentWillReceiveProps"); + var afterState = inst.state; + beforeState !== afterState && (inst.state = beforeState, inst.updater.enqueueReplaceState(inst, afterState), + warning(!1, "%s.componentWillReceiveProps(): Assigning directly to " + "this.state is deprecated (except inside a component's " + "constructor). Use setState instead.", this.getName() || "ReactCompositeComponent")); + } + var callbacks = this._pendingCallbacks; + this._pendingCallbacks = null; + var nextState = this._processPendingState(nextProps, nextContext), shouldUpdate = !0; + if (!this._pendingForceUpdate) { + var prevState = inst.state; + shouldUpdate = willReceive || nextState !== prevState, inst.shouldComponentUpdate ? shouldUpdate = measureLifeCyclePerf(function() { + return inst.shouldComponentUpdate(nextProps, nextState, nextContext); + }, this._debugID, "shouldComponentUpdate") : this._compositeType === ReactCompositeComponentTypes$1.PureClass && (shouldUpdate = !shallowEqual(prevProps, nextProps) || !shallowEqual(inst.state, nextState)); + } + if (warning(void 0 !== shouldUpdate, "%s.shouldComponentUpdate(): Returned undefined instead of a " + "boolean value. Make sure to return true or false.", this.getName() || "ReactCompositeComponent"), + this._updateBatchNumber = null, shouldUpdate ? (this._pendingForceUpdate = !1, this._performComponentUpdate(nextParentElement, nextProps, nextState, nextContext, transaction, nextUnmaskedContext)) : (this._currentElement = nextParentElement, + this._context = nextUnmaskedContext, inst.props = nextProps, inst.state = nextState, + inst.context = nextContext), callbacks) for (var j = 0; j < callbacks.length; j++) transaction.getReactMountReady().enqueue(callbacks[j], this.getPublicInstance()); + }, + _processPendingState: function(props, context) { + var inst = this._instance, queue = this._pendingStateQueue, replace = this._pendingReplaceState; + if (this._pendingReplaceState = !1, this._pendingStateQueue = null, !queue) return inst.state; + if (replace && 1 === queue.length) return queue[0]; + for (var nextState = replace ? queue[0] : inst.state, dontMutate = !0, i = replace ? 1 : 0; i < queue.length; i++) { + var partial = queue[i], partialState = "function" == typeof partial ? partial.call(inst, nextState, props, context) : partial; + partialState && (dontMutate ? (dontMutate = !1, nextState = Object.assign({}, nextState, partialState)) : Object.assign(nextState, partialState)); + } + return nextState; + }, + _performComponentUpdate: function(nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext) { + var prevProps, prevState, _this2 = this, inst = this._instance, hasComponentDidUpdate = !!inst.componentDidUpdate; + hasComponentDidUpdate && (prevProps = inst.props, prevState = inst.state), inst.componentWillUpdate && measureLifeCyclePerf(function() { + return inst.componentWillUpdate(nextProps, nextState, nextContext); + }, this._debugID, "componentWillUpdate"), this._currentElement = nextElement, this._context = unmaskedContext, + inst.props = nextProps, inst.state = nextState, inst.context = nextContext, inst.unstable_handleError ? this._updateRenderedComponentWithErrorHandling(transaction, unmaskedContext) : this._updateRenderedComponent(transaction, unmaskedContext), + hasComponentDidUpdate && transaction.getReactMountReady().enqueue(function() { + measureLifeCyclePerf(inst.componentDidUpdate.bind(inst, prevProps, prevState), _this2._debugID, "componentDidUpdate"); + }); + }, + _updateRenderedComponentWithErrorHandling: function(transaction, context) { + var checkpoint = transaction.checkpoint(); + try { + this._updateRenderedComponent(transaction, context); + } catch (e) { + transaction.rollback(checkpoint), this._instance.unstable_handleError(e), this._pendingStateQueue && (this._instance.state = this._processPendingState(this._instance.props, this._instance.context)), + checkpoint = transaction.checkpoint(), this._updateRenderedComponentWithNextElement(transaction, context, null, !0), + this._updateRenderedComponent(transaction, context); + } + }, + _updateRenderedComponent: function(transaction, context) { + var nextRenderedElement = this._renderValidatedComponent(); + this._updateRenderedComponentWithNextElement(transaction, context, nextRenderedElement, !1); + }, + _updateRenderedComponentWithNextElement: function(transaction, context, nextRenderedElement, safely) { + var prevComponentInstance = this._renderedComponent, prevRenderedElement = prevComponentInstance._currentElement, debugID = 0; + if (debugID = this._debugID, shouldUpdateReactComponent_1(prevRenderedElement, nextRenderedElement)) ReactReconciler_1.receiveComponent(prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context)); else { + var oldHostNode = ReactReconciler_1.getHostNode(prevComponentInstance); + ReactFeatureFlags_1.prepareNewChildrenBeforeUnmountInStack || ReactReconciler_1.unmountComponent(prevComponentInstance, safely, !1); + var nodeType = ReactNodeTypes_1.getType(nextRenderedElement); + this._renderedNodeType = nodeType; + var child = this._instantiateReactComponent(nextRenderedElement, nodeType !== ReactNodeTypes_1.EMPTY); + this._renderedComponent = child; + var nextMarkup = ReactReconciler_1.mountComponent(child, transaction, this._hostParent, this._hostContainerInfo, this._processChildContext(context), debugID); + if (ReactFeatureFlags_1.prepareNewChildrenBeforeUnmountInStack && ReactReconciler_1.unmountComponent(prevComponentInstance, safely, !1), + 0 !== debugID) { + var childDebugIDs = 0 !== child._debugID ? [ child._debugID ] : []; + ReactInstrumentation.debugTool.onSetChildren(debugID, childDebugIDs); + } + this._replaceNodeWithMarkup(oldHostNode, nextMarkup, prevComponentInstance); + } + }, + _replaceNodeWithMarkup: function(oldHostNode, nextMarkup, prevInstance) { + ReactComponentEnvironment_1.replaceNodeWithMarkup(oldHostNode, nextMarkup, prevInstance); + }, + _renderValidatedComponentWithoutOwnerOrContext: function() { + var renderedElement, inst = this._instance; + return renderedElement = measureLifeCyclePerf(function() { + return inst.render(); + }, this._debugID, "render"), void 0 === renderedElement && inst.render._isMockFunction && (renderedElement = null), + renderedElement; + }, + _renderValidatedComponent: function() { + var renderedElement; + if (0 && this._compositeType === ReactCompositeComponentTypes$1.StatelessFunctional) renderedElement = this._renderValidatedComponentWithoutOwnerOrContext(); else { + ReactCurrentOwner$1.current = this; + try { + renderedElement = this._renderValidatedComponentWithoutOwnerOrContext(); + } finally { + ReactCurrentOwner$1.current = null; + } + } + return invariant(null === renderedElement || !1 === renderedElement || React.isValidElement(renderedElement), "%s.render(): A valid React element (or null) must be returned. You may have " + "returned undefined, an array or some other invalid object.", this.getName() || "ReactCompositeComponent"), + renderedElement; + }, + attachRef: function(ref, component) { + var inst = this.getPublicInstance(); + invariant(null != inst, "Stateless function components cannot have refs."); + var publicComponentInstance = component.getPublicInstance(); + (inst.refs === emptyObject ? inst.refs = {} : inst.refs)[ref] = publicComponentInstance; + }, + detachRef: function(ref) { + delete this.getPublicInstance().refs[ref]; + }, + getName: function() { + var type = this._currentElement.type, constructor = this._instance && this._instance.constructor; + return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null; + }, + getPublicInstance: function() { + var inst = this._instance; + return this._compositeType === ReactCompositeComponentTypes$1.StatelessFunctional ? null : inst; + }, + _instantiateReactComponent: null +}, ReactCompositeComponent_1 = ReactCompositeComponent, emptyComponentFactory, ReactEmptyComponentInjection = { + injectEmptyComponentFactory: function(factory) { + emptyComponentFactory = factory; + } +}, ReactEmptyComponent = { + create: function(instantiate) { + return emptyComponentFactory(instantiate); + } +}; + +ReactEmptyComponent.injection = ReactEmptyComponentInjection; + +var ReactEmptyComponent_1 = ReactEmptyComponent, genericComponentClass = null, textComponentClass = null, ReactHostComponentInjection = { + injectGenericComponentClass: function(componentClass) { + genericComponentClass = componentClass; + }, + injectTextComponentClass: function(componentClass) { + textComponentClass = componentClass; + } +}; + +function createInternalComponent(element) { + return invariant(genericComponentClass, "There is no registered component for the tag %s", element.type), + new genericComponentClass(element); +} + +function createInstanceForText(text) { + return new textComponentClass(text); +} + +function isTextComponent(component) { + return component instanceof textComponentClass; +} + +var ReactHostComponent = { + createInternalComponent: createInternalComponent, + createInstanceForText: createInstanceForText, + isTextComponent: isTextComponent, + injection: ReactHostComponentInjection +}, ReactHostComponent_1 = ReactHostComponent, nextDebugID = 1; + +function getNextDebugID() { + return nextDebugID++; +} + +var getNextDebugID_1 = getNextDebugID, ReactCompositeComponentWrapper = function(element) { + this.construct(element); +}; + +function getDeclarationErrorAddendum(owner) { + if (owner) { + var name = owner.getName(); + if (name) return "\n\nCheck the render method of `" + name + "`."; + } + return ""; +} + +function isInternalComponentType(type) { + return "function" == typeof type && void 0 !== type.prototype && "function" == typeof type.prototype.mountComponent && "function" == typeof type.prototype.receiveComponent; +} + +function instantiateReactComponent(node, shouldHaveDebugID) { + var instance; + if (null === node || !1 === node) instance = ReactEmptyComponent_1.create(instantiateReactComponent); else if ("object" == typeof node) { + var element = node, type = element.type; + if ("function" != typeof type && "string" != typeof type) { + var info = ""; + (void 0 === type || "object" == typeof type && null !== type && 0 === Object.keys(type).length) && (info += " You likely forgot to export your component from the file " + "it's defined in."), + info += getDeclarationErrorAddendum(element._owner), invariant(!1, "Element type is invalid: expected a string (for built-in components) " + "or a class/function (for composite components) but got: %s.%s", null == type ? type : typeof type, info); + } + "string" == typeof element.type ? instance = ReactHostComponent_1.createInternalComponent(element) : isInternalComponentType(element.type) ? (instance = new element.type(element), + instance.getHostNode || (instance.getHostNode = instance.getNativeNode)) : instance = new ReactCompositeComponentWrapper(element); + } else "string" == typeof node || "number" == typeof node ? instance = ReactHostComponent_1.createInstanceForText(node) : invariant(!1, "Encountered invalid React node of type %s", typeof node); + return warning("function" == typeof instance.mountComponent && "function" == typeof instance.receiveComponent && "function" == typeof instance.getHostNode && "function" == typeof instance.unmountComponent, "Only React Components can be mounted."), + instance._mountIndex = 0, instance._mountImage = null, instance._debugID = shouldHaveDebugID ? getNextDebugID_1() : 0, + Object.preventExtensions && Object.preventExtensions(instance), instance; +} + +Object.assign(ReactCompositeComponentWrapper.prototype, ReactCompositeComponent_1, { + _instantiateReactComponent: instantiateReactComponent +}); + +var instantiateReactComponent_1 = instantiateReactComponent, DevOnlyStubShim = null, ReactNativeFeatureFlags$2 = { + useFiber: !1 +}, ReactNativeFeatureFlags_1 = ReactNativeFeatureFlags$2, ReactNativeFeatureFlags$3 = Object.freeze({ + default: ReactNativeFeatureFlags_1, + __moduleExports: ReactNativeFeatureFlags_1 +}), ReactNativeFeatureFlags$1 = ReactNativeFeatureFlags$3 && ReactNativeFeatureFlags_1 || ReactNativeFeatureFlags$3, ReactCurrentOwner$2 = ReactGlobalSharedState_1.ReactCurrentOwner, injectedFindNode = ReactNativeFeatureFlags$1.useFiber ? function(fiber) { + return DevOnlyStubShim.findHostInstance(fiber); +} : function(instance) { + return instance; +}; + +function findNodeHandle(componentOrHandle) { + var owner = ReactCurrentOwner$2.current; + if (null !== owner && (warning(owner._warnedAboutRefsInRender, "%s is accessing findNodeHandle inside its render(). " + "render() should be a pure function of props and state. It should " + "never access something that requires stale data from the previous " + "render, such as refs. Move this logic to componentDidMount and " + "componentDidUpdate instead.", owner.getName() || "A component"), + owner._warnedAboutRefsInRender = !0), null == componentOrHandle) return null; + if ("number" == typeof componentOrHandle) return componentOrHandle; + var component = componentOrHandle, internalInstance = ReactInstanceMap_1.get(component); + return internalInstance ? injectedFindNode(internalInstance) : component || (invariant("object" == typeof component && ("_rootNodeID" in component || "_nativeTag" in component) || null != component.render && "function" == typeof component.render, "findNodeHandle(...): Argument is not a component " + "(type: %s, keys: %s)", typeof component, Object.keys(component)), + void invariant(!1, "findNodeHandle(...): Unable to find node handle for unmounted " + "component.")); +} + +var findNodeHandle_1 = findNodeHandle, TopLevelWrapper = function() {}; + +TopLevelWrapper.prototype.isReactComponent = {}, TopLevelWrapper.displayName = "TopLevelWrapper", +TopLevelWrapper.prototype.render = function() { + return this.props.child; +}, TopLevelWrapper.isReactTopLevelWrapper = !0; + +function mountComponentIntoNode(componentInstance, containerTag, transaction) { + var markup = ReactReconciler_1.mountComponent(componentInstance, transaction, null, ReactNativeContainerInfo_1(containerTag), emptyObject, 0); + componentInstance._renderedComponent._topLevelWrapper = componentInstance, ReactNativeMount._mountImageIntoNode(markup, containerTag); +} + +function batchedMountComponentIntoNode(componentInstance, containerTag) { + var transaction = ReactUpdates_1.ReactReconcileTransaction.getPooled(); + transaction.perform(mountComponentIntoNode, null, componentInstance, containerTag, transaction), + ReactUpdates_1.ReactReconcileTransaction.release(transaction); +} + +var ReactNativeMount = { + _instancesByContainerID: {}, + findNodeHandle: findNodeHandle_1, + renderComponent: function(nextElement, containerTag, callback) { + var nextWrappedElement = React.createElement(TopLevelWrapper, { + child: nextElement + }), topRootNodeID = containerTag, prevComponent = ReactNativeMount._instancesByContainerID[topRootNodeID]; + if (prevComponent) { + var prevWrappedElement = prevComponent._currentElement, prevElement = prevWrappedElement.props.child; + if (shouldUpdateReactComponent_1(prevElement, nextElement)) return ReactUpdateQueue_1.enqueueElementInternal(prevComponent, nextWrappedElement, emptyObject), + callback && ReactUpdateQueue_1.enqueueCallbackInternal(prevComponent, callback), + prevComponent; + ReactNativeMount.unmountComponentAtNode(containerTag); + } + if (!ReactNativeTagHandles_1.reactTagIsNativeTopRootID(containerTag)) return console.error("You cannot render into anything but a top root"), + null; + ReactNativeTagHandles_1.assertRootTag(containerTag); + var instance = instantiateReactComponent_1(nextWrappedElement, !1); + if (ReactNativeMount._instancesByContainerID[containerTag] = instance, callback) { + var nonNullCallback = callback; + instance._pendingCallbacks = [ function() { + nonNullCallback.call(instance._renderedComponent.getPublicInstance()); + } ]; + } + return ReactUpdates_1.batchedUpdates(batchedMountComponentIntoNode, instance, containerTag), + instance._renderedComponent.getPublicInstance(); + }, + _mountImageIntoNode: function(mountImage, containerID) { + var childTag = mountImage; + UIManager.setChildren(containerID, [ childTag ]); + }, + unmountComponentAtNodeAndRemoveContainer: function(containerTag) { + ReactNativeMount.unmountComponentAtNode(containerTag), UIManager.removeRootView(containerTag); + }, + unmountComponentAtNode: function(containerTag) { + if (!ReactNativeTagHandles_1.reactTagIsNativeTopRootID(containerTag)) return console.error("You cannot render into anything but a top root"), + !1; + var instance = ReactNativeMount._instancesByContainerID[containerTag]; + return !!instance && (ReactInstrumentation.debugTool.onBeginFlush(), ReactNativeMount.unmountComponentFromNode(instance, containerTag), + delete ReactNativeMount._instancesByContainerID[containerTag], ReactInstrumentation.debugTool.onEndFlush(), + !0); + }, + unmountComponentFromNode: function(instance, containerID) { + ReactReconciler_1.unmountComponent(instance), UIManager.removeSubviewsFromContainerWithID(containerID); + } +}, ReactNativeMount_1 = ReactNativeMount, RESET_BATCHED_UPDATES = { + initialize: emptyFunction, + close: function() { + ReactDefaultBatchingStrategy.isBatchingUpdates = !1; + } +}, FLUSH_BATCHED_UPDATES = { + initialize: emptyFunction, + close: ReactUpdates_1.flushBatchedUpdates.bind(ReactUpdates_1) +}, TRANSACTION_WRAPPERS$1 = [ FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES ]; + +function ReactDefaultBatchingStrategyTransaction() { + this.reinitializeTransaction(); +} + +Object.assign(ReactDefaultBatchingStrategyTransaction.prototype, Transaction, { + getTransactionWrappers: function() { + return TRANSACTION_WRAPPERS$1; + } +}); + +var transaction = new ReactDefaultBatchingStrategyTransaction(), ReactDefaultBatchingStrategy = { + isBatchingUpdates: !1, + batchedUpdates: function(callback, a, b, c, d, e) { + var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; + return ReactDefaultBatchingStrategy.isBatchingUpdates = !0, alreadyBatchingUpdates ? callback(a, b, c, d, e) : transaction.perform(callback, null, a, b, c, d, e); + } +}, ReactDefaultBatchingStrategy_1 = ReactDefaultBatchingStrategy, dangerouslyProcessChildrenUpdates = function(inst, childrenUpdates) { + if (childrenUpdates.length) { + for (var moveFromIndices, moveToIndices, addChildTags, addAtIndices, removeAtIndices, containerTag = ReactNativeComponentTree_1.getNodeFromInstance(inst), i = 0; i < childrenUpdates.length; i++) { + var update = childrenUpdates[i]; + if ("MOVE_EXISTING" === update.type) (moveFromIndices || (moveFromIndices = [])).push(update.fromIndex), + (moveToIndices || (moveToIndices = [])).push(update.toIndex); else if ("REMOVE_NODE" === update.type) (removeAtIndices || (removeAtIndices = [])).push(update.fromIndex); else if ("INSERT_MARKUP" === update.type) { + var mountImage = update.content, tag = mountImage; + (addAtIndices || (addAtIndices = [])).push(update.toIndex), (addChildTags || (addChildTags = [])).push(tag); + } + } + UIManager.manageChildren(containerTag, moveFromIndices, moveToIndices, addChildTags, addAtIndices, removeAtIndices); + } +}, ReactNativeDOMIDOperations = { + dangerouslyProcessChildrenUpdates: dangerouslyProcessChildrenUpdates, + dangerouslyReplaceNodeWithMarkupByID: function(id, mountImage) { + var oldTag = id; + UIManager.replaceExistingNonRootView(oldTag, mountImage); + } +}, ReactNativeDOMIDOperations_1 = ReactNativeDOMIDOperations; + +function validateCallback(callback) { + invariant(!callback || "function" == typeof callback, "Invalid argument passed as callback. Expected a function. Instead " + "received: %s", callback); +} + +var validateCallback_1 = validateCallback; + +function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); +} + +var CallbackQueue = function() { + function CallbackQueue(arg) { + _classCallCheck(this, CallbackQueue), this._callbacks = null, this._contexts = null, + this._arg = arg; + } + return CallbackQueue.prototype.enqueue = function(callback, context) { + this._callbacks = this._callbacks || [], this._callbacks.push(callback), this._contexts = this._contexts || [], + this._contexts.push(context); + }, CallbackQueue.prototype.notifyAll = function() { + var callbacks = this._callbacks, contexts = this._contexts, arg = this._arg; + if (callbacks && contexts) { + invariant(callbacks.length === contexts.length, "Mismatched list of contexts in callback queue"), + this._callbacks = null, this._contexts = null; + for (var i = 0; i < callbacks.length; i++) validateCallback_1(callbacks[i]), callbacks[i].call(contexts[i], arg); + callbacks.length = 0, contexts.length = 0; + } + }, CallbackQueue.prototype.checkpoint = function() { + return this._callbacks ? this._callbacks.length : 0; + }, CallbackQueue.prototype.rollback = function(len) { + this._callbacks && this._contexts && (this._callbacks.length = len, this._contexts.length = len); + }, CallbackQueue.prototype.reset = function() { + this._callbacks = null, this._contexts = null; + }, CallbackQueue.prototype.destructor = function() { + this.reset(); + }, CallbackQueue; +}(), CallbackQueue_1 = PooledClass_1.addPoolingTo(CallbackQueue), ON_DOM_READY_QUEUEING = { + initialize: function() { + this.reactMountReady.reset(); + }, + close: function() { + this.reactMountReady.notifyAll(); + } +}, TRANSACTION_WRAPPERS$2 = [ ON_DOM_READY_QUEUEING ]; + +TRANSACTION_WRAPPERS$2.push({ + initialize: ReactInstrumentation.debugTool.onBeginFlush, + close: ReactInstrumentation.debugTool.onEndFlush +}); + +function ReactNativeReconcileTransaction() { + this.reinitializeTransaction(), this.reactMountReady = CallbackQueue_1.getPooled(null); +} + +var Mixin = { + getTransactionWrappers: function() { + return TRANSACTION_WRAPPERS$2; + }, + getReactMountReady: function() { + return this.reactMountReady; + }, + getUpdateQueue: function() { + return ReactUpdateQueue_1; + }, + checkpoint: function() { + return this.reactMountReady.checkpoint(); + }, + rollback: function(checkpoint) { + this.reactMountReady.rollback(checkpoint); + }, + destructor: function() { + CallbackQueue_1.release(this.reactMountReady), this.reactMountReady = null; + } +}; + +Object.assign(ReactNativeReconcileTransaction.prototype, Transaction, ReactNativeReconcileTransaction, Mixin), +PooledClass_1.addPoolingTo(ReactNativeReconcileTransaction); + +var ReactNativeReconcileTransaction_1 = ReactNativeReconcileTransaction, ReactNativeComponentEnvironment = { + processChildrenUpdates: ReactNativeDOMIDOperations_1.dangerouslyProcessChildrenUpdates, + replaceNodeWithMarkup: ReactNativeDOMIDOperations_1.dangerouslyReplaceNodeWithMarkupByID, + clearNode: function() {}, + ReactReconcileTransaction: ReactNativeReconcileTransaction_1 +}, ReactNativeComponentEnvironment_1 = ReactNativeComponentEnvironment, ReactNativeTextComponent = function(text) { + this._currentElement = text, this._stringText = "" + text, this._hostParent = null, + this._rootNodeID = 0; +}; + +Object.assign(ReactNativeTextComponent.prototype, { + mountComponent: function(transaction, hostParent, hostContainerInfo, context) { + invariant(context.isInAParentText, 'RawText "%s" must be wrapped in an explicit component.', this._stringText), + this._hostParent = hostParent; + var tag = ReactNativeTagHandles_1.allocateTag(); + this._rootNodeID = tag; + var nativeTopRootTag = hostContainerInfo._tag; + return UIManager.createView(tag, "RCTRawText", nativeTopRootTag, { + text: this._stringText + }), ReactNativeComponentTree_1.precacheNode(this, tag), tag; + }, + getHostNode: function() { + return this._rootNodeID; + }, + receiveComponent: function(nextText, transaction, context) { + if (nextText !== this._currentElement) { + this._currentElement = nextText; + var nextStringText = "" + nextText; + nextStringText !== this._stringText && (this._stringText = nextStringText, UIManager.updateView(this._rootNodeID, "RCTRawText", { + text: this._stringText + })); + } + }, + unmountComponent: function() { + ReactNativeComponentTree_1.uncacheNode(this), this._currentElement = null, this._stringText = null, + this._rootNodeID = 0; + } +}); + +var ReactNativeTextComponent_1 = ReactNativeTextComponent, ReactSimpleEmptyComponent = function(placeholderElement, instantiate) { + this._currentElement = null, this._renderedComponent = instantiate(placeholderElement); +}; + +Object.assign(ReactSimpleEmptyComponent.prototype, { + mountComponent: function(transaction, hostParent, hostContainerInfo, context, parentDebugID) { + return ReactReconciler_1.mountComponent(this._renderedComponent, transaction, hostParent, hostContainerInfo, context, parentDebugID); + }, + receiveComponent: function() {}, + getHostNode: function() { + return ReactReconciler_1.getHostNode(this._renderedComponent); + }, + unmountComponent: function(safely, skipLifecycle) { + ReactReconciler_1.unmountComponent(this._renderedComponent, safely, skipLifecycle), + this._renderedComponent = null; + } +}); + +var ReactSimpleEmptyComponent_1 = ReactSimpleEmptyComponent; + +function inject$1() { + ReactGenericBatching_1.injection.injectStackBatchedUpdates(ReactUpdates_1.batchedUpdates), + ReactUpdates_1.injection.injectReconcileTransaction(ReactNativeComponentEnvironment_1.ReactReconcileTransaction), + ReactUpdates_1.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy_1), + ReactComponentEnvironment_1.injection.injectEnvironment(ReactNativeComponentEnvironment_1); + var EmptyComponent = function(instantiate) { + var View = require("View"); + return new ReactSimpleEmptyComponent_1(React.createElement(View, { + collapsable: !0, + style: { + position: "absolute" + } + }), instantiate); + }; + ReactEmptyComponent_1.injection.injectEmptyComponentFactory(EmptyComponent), ReactHostComponent_1.injection.injectTextComponentClass(ReactNativeTextComponent_1), + ReactHostComponent_1.injection.injectGenericComponentClass(function(tag) { + var info = ""; + "string" == typeof tag && /^[a-z]/.test(tag) && (info += " Each component name should start with an uppercase letter."), + invariant(!1, "Expected a component class, got %s.%s", tag, info); + }); +} + +var ReactNativeStackInjection = { + inject: inject$1 +}; + +function getComponentName(instanceOrFiber) { + if ("function" == typeof instanceOrFiber.getName) { + return instanceOrFiber.getName(); + } + if ("number" == typeof instanceOrFiber.tag) { + var fiber = instanceOrFiber, type = fiber.type; + if ("string" == typeof type) return type; + if ("function" == typeof type) return type.displayName || type.name; + } + return null; +} + +var getComponentName_1 = getComponentName, getInspectorDataForViewTag = void 0, traverseOwnerTreeUp = function(hierarchy, instance) { + instance && (hierarchy.unshift(instance), traverseOwnerTreeUp(hierarchy, instance._currentElement._owner)); +}, getOwnerHierarchy = function(instance) { + var hierarchy = []; + return traverseOwnerTreeUp(hierarchy, instance), hierarchy; +}, lastNotNativeInstance = function(hierarchy) { + for (var i = hierarchy.length - 1; i > 1; i--) { + var instance = hierarchy[i]; + if (!instance.viewConfig) return instance; + } + return hierarchy[0]; +}, getHostProps = function(component) { + var instance = component._instance; + return instance ? instance.props || emptyObject : emptyObject; +}, createHierarchy = function(componentHierarchy) { + return componentHierarchy.map(function(component) { + return { + name: getComponentName_1(component), + getInspectorData: function() { + return { + measure: function(callback) { + return UIManager.measure(component.getHostNode(), callback); + }, + props: getHostProps(component), + source: component._currentElement && component._currentElement._source + }; + } + }; + }); +}; + +getInspectorDataForViewTag = function(viewTag) { + var component = ReactNativeComponentTree_1.getClosestInstanceFromNode(viewTag), componentHierarchy = getOwnerHierarchy(component), instance = lastNotNativeInstance(componentHierarchy), hierarchy = createHierarchy(componentHierarchy), props = getHostProps(instance), source = instance._currentElement && instance._currentElement._source; + return { + hierarchy: hierarchy, + instance: instance, + props: props, + selection: componentHierarchy.indexOf(instance), + source: source + }; +}; + +var ReactNativeStackInspector = { + getInspectorDataForViewTag: getInspectorDataForViewTag +}, findNumericNodeHandleStack = function(componentOrHandle) { + var nodeHandle = findNodeHandle_1(componentOrHandle); + return null == nodeHandle || "number" == typeof nodeHandle ? nodeHandle : nodeHandle.getHostNode(); +}; + +function _classCallCheck$1(instance, Constructor) { + if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); +} + +var objects = {}, uniqueID = 1, emptyObject$3 = {}, ReactNativePropRegistry = function() { + function ReactNativePropRegistry() { + _classCallCheck$1(this, ReactNativePropRegistry); + } + return ReactNativePropRegistry.register = function(object) { + var id = ++uniqueID; + return Object.freeze(object), objects[id] = object, id; + }, ReactNativePropRegistry.getByID = function(id) { + if (!id) return emptyObject$3; + var object = objects[id]; + return object || (console.warn("Invalid style with id `" + id + "`. Skipping ..."), + emptyObject$3); + }, ReactNativePropRegistry; +}(), ReactNativePropRegistry_1 = ReactNativePropRegistry, emptyObject$2 = {}, removedKeys = null, removedKeyCount = 0; + +function defaultDiffer(prevProp, nextProp) { + return "object" != typeof nextProp || null === nextProp || deepDiffer(prevProp, nextProp); +} + +function resolveObject(idOrObject) { + return "number" == typeof idOrObject ? ReactNativePropRegistry_1.getByID(idOrObject) : idOrObject; +} + +function restoreDeletedValuesInNestedArray(updatePayload, node, validAttributes) { + if (Array.isArray(node)) for (var i = node.length; i-- && removedKeyCount > 0; ) restoreDeletedValuesInNestedArray(updatePayload, node[i], validAttributes); else if (node && removedKeyCount > 0) { + var obj = resolveObject(node); + for (var propKey in removedKeys) if (removedKeys[propKey]) { + var nextProp = obj[propKey]; + if (void 0 !== nextProp) { + var attributeConfig = validAttributes[propKey]; + if (attributeConfig) { + if ("function" == typeof nextProp && (nextProp = !0), void 0 === nextProp && (nextProp = null), + "object" != typeof attributeConfig) updatePayload[propKey] = nextProp; else if ("function" == typeof attributeConfig.diff || "function" == typeof attributeConfig.process) { + var nextValue = "function" == typeof attributeConfig.process ? attributeConfig.process(nextProp) : nextProp; + updatePayload[propKey] = nextValue; + } + removedKeys[propKey] = !1, removedKeyCount--; + } + } + } + } +} + +function diffNestedArrayProperty(updatePayload, prevArray, nextArray, validAttributes) { + var i, minLength = prevArray.length < nextArray.length ? prevArray.length : nextArray.length; + for (i = 0; i < minLength; i++) updatePayload = diffNestedProperty(updatePayload, prevArray[i], nextArray[i], validAttributes); + for (;i < prevArray.length; i++) updatePayload = clearNestedProperty(updatePayload, prevArray[i], validAttributes); + for (;i < nextArray.length; i++) updatePayload = addNestedProperty(updatePayload, nextArray[i], validAttributes); + return updatePayload; +} + +function diffNestedProperty(updatePayload, prevProp, nextProp, validAttributes) { + return updatePayload || prevProp !== nextProp ? prevProp && nextProp ? Array.isArray(prevProp) || Array.isArray(nextProp) ? Array.isArray(prevProp) && Array.isArray(nextProp) ? diffNestedArrayProperty(updatePayload, prevProp, nextProp, validAttributes) : Array.isArray(prevProp) ? diffProperties(updatePayload, flattenStyle(prevProp), resolveObject(nextProp), validAttributes) : diffProperties(updatePayload, resolveObject(prevProp), flattenStyle(nextProp), validAttributes) : diffProperties(updatePayload, resolveObject(prevProp), resolveObject(nextProp), validAttributes) : nextProp ? addNestedProperty(updatePayload, nextProp, validAttributes) : prevProp ? clearNestedProperty(updatePayload, prevProp, validAttributes) : updatePayload : updatePayload; +} + +function addNestedProperty(updatePayload, nextProp, validAttributes) { + if (!nextProp) return updatePayload; + if (!Array.isArray(nextProp)) return addProperties(updatePayload, resolveObject(nextProp), validAttributes); + for (var i = 0; i < nextProp.length; i++) updatePayload = addNestedProperty(updatePayload, nextProp[i], validAttributes); + return updatePayload; +} + +function clearNestedProperty(updatePayload, prevProp, validAttributes) { + if (!prevProp) return updatePayload; + if (!Array.isArray(prevProp)) return clearProperties(updatePayload, resolveObject(prevProp), validAttributes); + for (var i = 0; i < prevProp.length; i++) updatePayload = clearNestedProperty(updatePayload, prevProp[i], validAttributes); + return updatePayload; +} + +function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { + var attributeConfig, nextProp, prevProp; + for (var propKey in nextProps) if (attributeConfig = validAttributes[propKey]) if (prevProp = prevProps[propKey], + nextProp = nextProps[propKey], "function" == typeof nextProp && (nextProp = !0, + "function" == typeof prevProp && (prevProp = !0)), void 0 === nextProp && (nextProp = null, + void 0 === prevProp && (prevProp = null)), removedKeys && (removedKeys[propKey] = !1), + updatePayload && void 0 !== updatePayload[propKey]) { + if ("object" != typeof attributeConfig) updatePayload[propKey] = nextProp; else if ("function" == typeof attributeConfig.diff || "function" == typeof attributeConfig.process) { + var nextValue = "function" == typeof attributeConfig.process ? attributeConfig.process(nextProp) : nextProp; + updatePayload[propKey] = nextValue; + } + } else if (prevProp !== nextProp) if ("object" != typeof attributeConfig) defaultDiffer(prevProp, nextProp) && ((updatePayload || (updatePayload = {}))[propKey] = nextProp); else if ("function" == typeof attributeConfig.diff || "function" == typeof attributeConfig.process) { + var shouldUpdate = void 0 === prevProp || ("function" == typeof attributeConfig.diff ? attributeConfig.diff(prevProp, nextProp) : defaultDiffer(prevProp, nextProp)); + shouldUpdate && (nextValue = "function" == typeof attributeConfig.process ? attributeConfig.process(nextProp) : nextProp, + (updatePayload || (updatePayload = {}))[propKey] = nextValue); + } else removedKeys = null, removedKeyCount = 0, updatePayload = diffNestedProperty(updatePayload, prevProp, nextProp, attributeConfig), + removedKeyCount > 0 && updatePayload && (restoreDeletedValuesInNestedArray(updatePayload, nextProp, attributeConfig), + removedKeys = null); + for (propKey in prevProps) void 0 === nextProps[propKey] && (attributeConfig = validAttributes[propKey]) && (updatePayload && void 0 !== updatePayload[propKey] || void 0 !== (prevProp = prevProps[propKey]) && ("object" != typeof attributeConfig || "function" == typeof attributeConfig.diff || "function" == typeof attributeConfig.process ? ((updatePayload || (updatePayload = {}))[propKey] = null, + removedKeys || (removedKeys = {}), removedKeys[propKey] || (removedKeys[propKey] = !0, + removedKeyCount++)) : updatePayload = clearNestedProperty(updatePayload, prevProp, attributeConfig))); + return updatePayload; +} + +function addProperties(updatePayload, props, validAttributes) { + return diffProperties(updatePayload, emptyObject$2, props, validAttributes); +} + +function clearProperties(updatePayload, prevProps, validAttributes) { + return diffProperties(updatePayload, prevProps, emptyObject$2, validAttributes); +} + +var ReactNativeAttributePayload = { + create: function(props, validAttributes) { + return addProperties(null, props, validAttributes); + }, + diff: function(prevProps, nextProps, validAttributes) { + return diffProperties(null, prevProps, nextProps, validAttributes); + } +}, ReactNativeAttributePayload_1 = ReactNativeAttributePayload; + +function mountSafeCallback$1(context, callback) { + return function() { + if (callback) { + if ("boolean" == typeof context.__isMounted) { + if (!context.__isMounted) return; + } else if ("function" == typeof context.isMounted && !context.isMounted()) return; + return callback.apply(context, arguments); + } + }; +} + +function throwOnStylesProp$1(component, props) { + if (void 0 !== props.styles) { + var owner = component._owner || null, name = component.constructor.displayName, msg = "`styles` is not a supported property of `" + name + "`, did " + "you mean `style` (singular)?"; + throw owner && owner.constructor && owner.constructor.displayName && (msg += "\n\nCheck the `" + owner.constructor.displayName + "` parent " + " component."), + new Error(msg); + } +} + +function warnForStyleProps$1(props, validAttributes) { + for (var key in validAttributes.style) validAttributes[key] || void 0 === props[key] || console.error("You are setting the style `{ " + key + ": ... }` as a prop. You " + "should nest it in a style object. " + "E.g. `{ style: { " + key + ": ... } }`"); +} + +var NativeMethodsMixinUtils = { + mountSafeCallback: mountSafeCallback$1, + throwOnStylesProp: throwOnStylesProp$1, + warnForStyleProps: warnForStyleProps$1 +}, mountSafeCallback = NativeMethodsMixinUtils.mountSafeCallback, throwOnStylesProp = NativeMethodsMixinUtils.throwOnStylesProp, warnForStyleProps = NativeMethodsMixinUtils.warnForStyleProps, findNumericNodeHandle = ReactNativeFeatureFlags$1.useFiber ? DevOnlyStubShim : findNumericNodeHandleStack, NativeMethodsMixin = { + measure: function(callback) { + UIManager.measure(findNumericNodeHandle(this), mountSafeCallback(this, callback)); + }, + measureInWindow: function(callback) { + UIManager.measureInWindow(findNumericNodeHandle(this), mountSafeCallback(this, callback)); + }, + measureLayout: function(relativeToNativeNode, onSuccess, onFail) { + UIManager.measureLayout(findNumericNodeHandle(this), relativeToNativeNode, mountSafeCallback(this, onFail), mountSafeCallback(this, onSuccess)); + }, + setNativeProps: function(nativeProps) { + injectedSetNativeProps(this, nativeProps); + }, + focus: function() { + TextInputState.focusTextInput(findNumericNodeHandle(this)); + }, + blur: function() { + TextInputState.blurTextInput(findNumericNodeHandle(this)); + } +}; + +function setNativePropsFiber(componentOrHandle, nativeProps) { + var maybeInstance = void 0; + try { + maybeInstance = findNodeHandle_1(componentOrHandle); + } catch (error) {} + if (null != maybeInstance) { + var viewConfig = maybeInstance.viewConfig; + warnForStyleProps(nativeProps, viewConfig.validAttributes); + var updatePayload = ReactNativeAttributePayload_1.create(nativeProps, viewConfig.validAttributes); + UIManager.updateView(maybeInstance._nativeTag, viewConfig.uiViewClassName, updatePayload); + } +} + +function setNativePropsStack(componentOrHandle, nativeProps) { + var maybeInstance = findNodeHandle_1(componentOrHandle); + if (null != maybeInstance) { + var viewConfig = void 0; + if (void 0 !== maybeInstance.viewConfig) viewConfig = maybeInstance.viewConfig; else if (void 0 !== maybeInstance._instance && void 0 !== maybeInstance._instance.viewConfig) viewConfig = maybeInstance._instance.viewConfig; else { + for (;void 0 !== maybeInstance._renderedComponent; ) maybeInstance = maybeInstance._renderedComponent; + viewConfig = maybeInstance.viewConfig; + } + var tag = "function" == typeof maybeInstance.getHostNode ? maybeInstance.getHostNode() : maybeInstance._rootNodeID; + warnForStyleProps(nativeProps, viewConfig.validAttributes); + var updatePayload = ReactNativeAttributePayload_1.create(nativeProps, viewConfig.validAttributes); + UIManager.updateView(tag, viewConfig.uiViewClassName, updatePayload); + } +} + +var injectedSetNativeProps = void 0; + +injectedSetNativeProps = ReactNativeFeatureFlags$1.useFiber ? setNativePropsFiber : setNativePropsStack; + +var NativeMethodsMixin_DEV = NativeMethodsMixin; + +invariant(!NativeMethodsMixin_DEV.componentWillMount && !NativeMethodsMixin_DEV.componentWillReceiveProps, "Do not override existing functions."), +NativeMethodsMixin_DEV.componentWillMount = function() { + throwOnStylesProp(this, this.props); +}, NativeMethodsMixin_DEV.componentWillReceiveProps = function(newProps) { + throwOnStylesProp(this, newProps); +}; + +var NativeMethodsMixin_1 = NativeMethodsMixin, TouchHistoryMath = { + centroidDimension: function(touchHistory, touchesChangedAfter, isXAxis, ofCurrent) { + var touchBank = touchHistory.touchBank, total = 0, count = 0, oneTouchData = 1 === touchHistory.numberActiveTouches ? touchHistory.touchBank[touchHistory.indexOfSingleActiveTouch] : null; + if (null !== oneTouchData) oneTouchData.touchActive && oneTouchData.currentTimeStamp > touchesChangedAfter && (total += ofCurrent && isXAxis ? oneTouchData.currentPageX : ofCurrent && !isXAxis ? oneTouchData.currentPageY : !ofCurrent && isXAxis ? oneTouchData.previousPageX : oneTouchData.previousPageY, + count = 1); else for (var i = 0; i < touchBank.length; i++) { + var touchTrack = touchBank[i]; + if (null !== touchTrack && void 0 !== touchTrack && touchTrack.touchActive && touchTrack.currentTimeStamp >= touchesChangedAfter) { + var toAdd; + toAdd = ofCurrent && isXAxis ? touchTrack.currentPageX : ofCurrent && !isXAxis ? touchTrack.currentPageY : !ofCurrent && isXAxis ? touchTrack.previousPageX : touchTrack.previousPageY, + total += toAdd, count++; + } + } + return count > 0 ? total / count : TouchHistoryMath.noCentroid; + }, + currentCentroidXOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) { + return TouchHistoryMath.centroidDimension(touchHistory, touchesChangedAfter, !0, !0); + }, + currentCentroidYOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) { + return TouchHistoryMath.centroidDimension(touchHistory, touchesChangedAfter, !1, !0); + }, + previousCentroidXOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) { + return TouchHistoryMath.centroidDimension(touchHistory, touchesChangedAfter, !0, !1); + }, + previousCentroidYOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) { + return TouchHistoryMath.centroidDimension(touchHistory, touchesChangedAfter, !1, !1); + }, + currentCentroidX: function(touchHistory) { + return TouchHistoryMath.centroidDimension(touchHistory, 0, !0, !0); + }, + currentCentroidY: function(touchHistory) { + return TouchHistoryMath.centroidDimension(touchHistory, 0, !1, !0); + }, + noCentroid: -1 +}, TouchHistoryMath_1 = TouchHistoryMath; + +function escape(key) { + var escaperLookup = { + "=": "=0", + ":": "=2" + }; + return "$" + ("" + key).replace(/[=:]/g, function(match) { + return escaperLookup[match]; + }); +} + +function unescape(key) { + var unescapeRegex = /(=0|=2)/g, unescaperLookup = { + "=0": "=", + "=2": ":" + }; + return ("" + ("." === key[0] && "$" === key[1] ? key.substring(2) : key.substring(1))).replace(unescapeRegex, function(match) { + return unescaperLookup[match]; + }); +} + +var KeyEscapeUtils = { + escape: escape, + unescape: unescape +}, KeyEscapeUtils_1 = KeyEscapeUtils, REACT_ELEMENT_TYPE = "function" == typeof Symbol && Symbol.for && Symbol.for("react.element") || 60103, ReactElementSymbol = REACT_ELEMENT_TYPE, ITERATOR_SYMBOL = "function" == typeof Symbol && Symbol.iterator, FAUX_ITERATOR_SYMBOL = "@@iterator"; + +function getIteratorFn(maybeIterable) { + var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); + if ("function" == typeof iteratorFn) return iteratorFn; +} + +var getIteratorFn_1 = getIteratorFn, getCurrentStackAddendum = ReactGlobalSharedState_1.ReactComponentTreeHook.getCurrentStackAddendum, SEPARATOR = ".", SUBSEPARATOR = ":", didWarnAboutMaps = !1; + +function getComponentKey(component, index) { + return component && "object" == typeof component && null != component.key ? KeyEscapeUtils_1.escape(component.key) : index.toString(36); +} + +function traverseStackChildrenImpl(children, nameSoFar, callback, traverseContext) { + var type = typeof children; + if ("undefined" !== type && "boolean" !== type || (children = null), null === children || "string" === type || "number" === type || "object" === type && children.$$typeof === ReactElementSymbol) return callback(traverseContext, children, "" === nameSoFar ? SEPARATOR + getComponentKey(children, 0) : nameSoFar), + 1; + var child, nextName, subtreeCount = 0, nextNamePrefix = "" === nameSoFar ? SEPARATOR : nameSoFar + SUBSEPARATOR; + if (Array.isArray(children)) for (var i = 0; i < children.length; i++) child = children[i], + nextName = nextNamePrefix + getComponentKey(child, i), subtreeCount += traverseStackChildrenImpl(child, nextName, callback, traverseContext); else { + var iteratorFn = getIteratorFn_1(children); + if (iteratorFn) { + iteratorFn === children.entries && (warning(didWarnAboutMaps, "Using Maps as children is unsupported and will likely yield " + "unexpected results. Convert it to a sequence/iterable of keyed " + "ReactElements instead.%s", getCurrentStackAddendum()), + didWarnAboutMaps = !0); + for (var step, iterator = iteratorFn.call(children), ii = 0; !(step = iterator.next()).done; ) child = step.value, + nextName = nextNamePrefix + getComponentKey(child, ii++), subtreeCount += traverseStackChildrenImpl(child, nextName, callback, traverseContext); + } else if ("object" === type) { + var addendum = ""; + addendum = " If you meant to render a collection of children, use an array " + "instead." + getCurrentStackAddendum(); + var childrenString = "" + children; + invariant(!1, "Objects are not valid as a React child (found: %s).%s", "[object Object]" === childrenString ? "object with keys {" + Object.keys(children).join(", ") + "}" : childrenString, addendum); + } + } + return subtreeCount; +} + +function traverseStackChildren(children, callback, traverseContext) { + return null == children ? 0 : traverseStackChildrenImpl(children, "", callback, traverseContext); +} + +var traverseStackChildren_1 = traverseStackChildren, ReactComponentTreeHook$2; + +"undefined" != typeof process && process.env && "development" == "test" && (ReactComponentTreeHook$2 = ReactGlobalSharedState_1.ReactComponentTreeHook); + +function instantiateChild(childInstances, child, name, selfDebugID) { + var keyUnique = void 0 === childInstances[name]; + ReactComponentTreeHook$2 || (ReactComponentTreeHook$2 = ReactGlobalSharedState_1.ReactComponentTreeHook), + keyUnique || warning(!1, "flattenChildren(...): Encountered two children with the same key, " + "`%s`. Child keys must be unique; when two children share a key, only " + "the first child will be used.%s", KeyEscapeUtils_1.unescape(name), ReactComponentTreeHook$2.getStackAddendumByID(selfDebugID)), + null != child && keyUnique && (childInstances[name] = instantiateReactComponent_1(child, !0)); +} + +var ReactChildReconciler = { + instantiateChildren: function(nestedChildNodes, transaction, context, selfDebugID) { + if (null == nestedChildNodes) return null; + var childInstances = {}; + return traverseStackChildren_1(nestedChildNodes, function(childInsts, child, name) { + return instantiateChild(childInsts, child, name, selfDebugID); + }, childInstances), childInstances; + }, + updateChildren: function(prevChildren, nextChildren, mountImages, removedNodes, transaction, hostParent, hostContainerInfo, context, selfDebugID) { + if (nextChildren || prevChildren) { + var name, prevChild; + for (name in nextChildren) if (nextChildren.hasOwnProperty(name)) { + prevChild = prevChildren && prevChildren[name]; + var prevElement = prevChild && prevChild._currentElement, nextElement = nextChildren[name]; + if (null != prevChild && shouldUpdateReactComponent_1(prevElement, nextElement)) ReactReconciler_1.receiveComponent(prevChild, nextElement, transaction, context), + nextChildren[name] = prevChild; else { + !ReactFeatureFlags_1.prepareNewChildrenBeforeUnmountInStack && prevChild && (removedNodes[name] = ReactReconciler_1.getHostNode(prevChild), + ReactReconciler_1.unmountComponent(prevChild, !1, !1)); + var nextChildInstance = instantiateReactComponent_1(nextElement, !0); + nextChildren[name] = nextChildInstance; + var nextChildMountImage = ReactReconciler_1.mountComponent(nextChildInstance, transaction, hostParent, hostContainerInfo, context, selfDebugID); + mountImages.push(nextChildMountImage), ReactFeatureFlags_1.prepareNewChildrenBeforeUnmountInStack && prevChild && (removedNodes[name] = ReactReconciler_1.getHostNode(prevChild), + ReactReconciler_1.unmountComponent(prevChild, !1, !1)); + } + } + for (name in prevChildren) !prevChildren.hasOwnProperty(name) || nextChildren && nextChildren.hasOwnProperty(name) || (prevChild = prevChildren[name], + removedNodes[name] = ReactReconciler_1.getHostNode(prevChild), ReactReconciler_1.unmountComponent(prevChild, !1, !1)); + } + }, + unmountChildren: function(renderedChildren, safely, skipLifecycle) { + for (var name in renderedChildren) if (renderedChildren.hasOwnProperty(name)) { + var renderedChild = renderedChildren[name]; + ReactReconciler_1.unmountComponent(renderedChild, safely, skipLifecycle); + } + } +}, ReactChildReconciler_1 = ReactChildReconciler, ReactComponentTreeHook$3; + +"undefined" != typeof process && process.env && "development" == "test" && (ReactComponentTreeHook$3 = ReactGlobalSharedState_1.ReactComponentTreeHook); + +function flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID) { + if (traverseContext && "object" == typeof traverseContext) { + var result = traverseContext, keyUnique = void 0 === result[name]; + ReactComponentTreeHook$3 || (ReactComponentTreeHook$3 = ReactGlobalSharedState_1.ReactComponentTreeHook), + keyUnique || warning(!1, "flattenChildren(...): Encountered two children with the same key, " + "`%s`. Child keys must be unique; when two children share a key, only " + "the first child will be used.%s", KeyEscapeUtils_1.unescape(name), ReactComponentTreeHook$3.getStackAddendumByID(selfDebugID)), + keyUnique && null != child && (result[name] = child); + } +} + +function flattenStackChildren(children, selfDebugID) { + if (null == children) return children; + var result = {}; + return traverseStackChildren_1(children, function(traverseContext, child, name) { + return flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID); + }, result), result; +} + +var flattenStackChildren_1 = flattenStackChildren, ReactCurrentOwner$3 = ReactGlobalSharedState_1.ReactCurrentOwner; + +function makeInsertMarkup(markup, afterNode, toIndex) { + return { + type: "INSERT_MARKUP", + content: markup, + fromIndex: null, + fromNode: null, + toIndex: toIndex, + afterNode: afterNode + }; +} + +function makeMove(child, afterNode, toIndex) { + return { + type: "MOVE_EXISTING", + content: null, + fromIndex: child._mountIndex, + fromNode: ReactReconciler_1.getHostNode(child), + toIndex: toIndex, + afterNode: afterNode + }; +} + +function makeRemove(child, node) { + return { + type: "REMOVE_NODE", + content: null, + fromIndex: child._mountIndex, + fromNode: node, + toIndex: null, + afterNode: null + }; +} + +function makeSetMarkup(markup) { + return { + type: "SET_MARKUP", + content: markup, + fromIndex: null, + fromNode: null, + toIndex: null, + afterNode: null + }; +} + +function makeTextContent(textContent) { + return { + type: "TEXT_CONTENT", + content: textContent, + fromIndex: null, + fromNode: null, + toIndex: null, + afterNode: null + }; +} + +function enqueue(queue, update) { + return update && (queue = queue || [], queue.push(update)), queue; +} + +function processQueue(inst, updateQueue) { + ReactComponentEnvironment_1.processChildrenUpdates(inst, updateQueue); +} + +var setChildrenForInstrumentation = emptyFunction, getDebugID = function(inst) { + if (!inst._debugID) { + var internal; + (internal = ReactInstanceMap_1.get(inst)) && (inst = internal); + } + return inst._debugID; +}; + +setChildrenForInstrumentation = function(children) { + var debugID = getDebugID(this); + 0 !== debugID && ReactInstrumentation.debugTool.onSetChildren(debugID, children ? Object.keys(children).map(function(key) { + return children[key]._debugID; + }) : []); +}; + +var ReactMultiChild = { + _reconcilerInstantiateChildren: function(nestedChildren, transaction, context) { + var selfDebugID = getDebugID(this); + if (this._currentElement) try { + return ReactCurrentOwner$3.current = this._currentElement._owner, ReactChildReconciler_1.instantiateChildren(nestedChildren, transaction, context, selfDebugID); + } finally { + ReactCurrentOwner$3.current = null; + } + return ReactChildReconciler_1.instantiateChildren(nestedChildren, transaction, context); + }, + _reconcilerUpdateChildren: function(prevChildren, nextNestedChildrenElements, mountImages, removedNodes, transaction, context) { + var nextChildren, selfDebugID = 0; + if (selfDebugID = getDebugID(this), this._currentElement) { + try { + ReactCurrentOwner$3.current = this._currentElement._owner, nextChildren = flattenStackChildren_1(nextNestedChildrenElements, selfDebugID); + } finally { + ReactCurrentOwner$3.current = null; + } + return ReactChildReconciler_1.updateChildren(prevChildren, nextChildren, mountImages, removedNodes, transaction, this, this._hostContainerInfo, context, selfDebugID), + nextChildren; + } + return nextChildren = flattenStackChildren_1(nextNestedChildrenElements, selfDebugID), + ReactChildReconciler_1.updateChildren(prevChildren, nextChildren, mountImages, removedNodes, transaction, this, this._hostContainerInfo, context, selfDebugID), + nextChildren; + }, + mountChildren: function(nestedChildren, transaction, context) { + var children = this._reconcilerInstantiateChildren(nestedChildren, transaction, context); + this._renderedChildren = children; + var mountImages = [], index = 0; + for (var name in children) if (children.hasOwnProperty(name)) { + var child = children[name], selfDebugID = 0; + selfDebugID = getDebugID(this); + var mountImage = ReactReconciler_1.mountComponent(child, transaction, this, this._hostContainerInfo, context, selfDebugID); + child._mountIndex = index++, mountImages.push(mountImage); + } + return setChildrenForInstrumentation.call(this, children), mountImages; + }, + updateTextContent: function(nextContent) { + var prevChildren = this._renderedChildren; + ReactChildReconciler_1.unmountChildren(prevChildren, !1, !1); + for (var name in prevChildren) prevChildren.hasOwnProperty(name) && invariant(!1, "updateTextContent called on non-empty component."); + processQueue(this, [ makeTextContent(nextContent) ]); + }, + updateMarkup: function(nextMarkup) { + var prevChildren = this._renderedChildren; + ReactChildReconciler_1.unmountChildren(prevChildren, !1, !1); + for (var name in prevChildren) prevChildren.hasOwnProperty(name) && invariant(!1, "updateTextContent called on non-empty component."); + processQueue(this, [ makeSetMarkup(nextMarkup) ]); + }, + updateChildren: function(nextNestedChildrenElements, transaction, context) { + this._updateChildren(nextNestedChildrenElements, transaction, context); + }, + _updateChildren: function(nextNestedChildrenElements, transaction, context) { + var prevChildren = this._renderedChildren, removedNodes = {}, mountImages = [], nextChildren = this._reconcilerUpdateChildren(prevChildren, nextNestedChildrenElements, mountImages, removedNodes, transaction, context); + if (nextChildren || prevChildren) { + var name, updates = null, nextIndex = 0, lastIndex = 0, nextMountIndex = 0, lastPlacedNode = null; + for (name in nextChildren) if (nextChildren.hasOwnProperty(name)) { + var prevChild = prevChildren && prevChildren[name], nextChild = nextChildren[name]; + prevChild === nextChild ? (updates = enqueue(updates, this.moveChild(prevChild, lastPlacedNode, nextIndex, lastIndex)), + lastIndex = Math.max(prevChild._mountIndex, lastIndex), prevChild._mountIndex = nextIndex) : (prevChild && (lastIndex = Math.max(prevChild._mountIndex, lastIndex)), + updates = enqueue(updates, this._mountChildAtIndex(nextChild, mountImages[nextMountIndex], lastPlacedNode, nextIndex, transaction, context)), + nextMountIndex++), nextIndex++, lastPlacedNode = ReactReconciler_1.getHostNode(nextChild); + } + for (name in removedNodes) removedNodes.hasOwnProperty(name) && (updates = enqueue(updates, this._unmountChild(prevChildren[name], removedNodes[name]))); + updates && processQueue(this, updates), this._renderedChildren = nextChildren, setChildrenForInstrumentation.call(this, nextChildren); + } + }, + unmountChildren: function(safely, skipLifecycle) { + var renderedChildren = this._renderedChildren; + ReactChildReconciler_1.unmountChildren(renderedChildren, safely, skipLifecycle), + this._renderedChildren = null; + }, + moveChild: function(child, afterNode, toIndex, lastIndex) { + if (child._mountIndex < lastIndex) return makeMove(child, afterNode, toIndex); + }, + createChild: function(child, afterNode, mountImage) { + return makeInsertMarkup(mountImage, afterNode, child._mountIndex); + }, + removeChild: function(child, node) { + return makeRemove(child, node); + }, + _mountChildAtIndex: function(child, mountImage, afterNode, index, transaction, context) { + return child._mountIndex = index, this.createChild(child, afterNode, mountImage); + }, + _unmountChild: function(child, node) { + var update = this.removeChild(child, node); + return child._mountIndex = null, update; + } +}, ReactMultiChild_1 = ReactMultiChild, ReactNativeBaseComponent = function(viewConfig) { + this.viewConfig = viewConfig; +}; + +ReactNativeBaseComponent.Mixin = { + getPublicInstance: function() { + return this; + }, + unmountComponent: function(safely, skipLifecycle) { + ReactNativeComponentTree_1.uncacheNode(this), this.unmountChildren(safely, skipLifecycle), + this._rootNodeID = 0; + }, + initializeChildren: function(children, containerTag, transaction, context) { + var mountImages = this.mountChildren(children, transaction, context); + if (mountImages.length) { + for (var createdTags = [], i = 0, l = mountImages.length; i < l; i++) { + var mountImage = mountImages[i], childTag = mountImage; + createdTags[i] = childTag; + } + UIManager.setChildren(containerTag, createdTags); + } + }, + receiveComponent: function(nextElement, transaction, context) { + var prevElement = this._currentElement; + this._currentElement = nextElement; + for (var key in this.viewConfig.validAttributes) nextElement.props.hasOwnProperty(key) && deepFreezeAndThrowOnMutationInDev(nextElement.props[key]); + var updatePayload = ReactNativeAttributePayload_1.diff(prevElement.props, nextElement.props, this.viewConfig.validAttributes); + updatePayload && UIManager.updateView(this._rootNodeID, this.viewConfig.uiViewClassName, updatePayload), + this.updateChildren(nextElement.props.children, transaction, context); + }, + getHostNode: function() { + return this._rootNodeID; + }, + mountComponent: function(transaction, hostParent, hostContainerInfo, context) { + var tag = ReactNativeTagHandles_1.allocateTag(); + this._rootNodeID = tag, this._hostParent = hostParent, this._hostContainerInfo = hostContainerInfo; + for (var key in this.viewConfig.validAttributes) this._currentElement.props.hasOwnProperty(key) && deepFreezeAndThrowOnMutationInDev(this._currentElement.props[key]); + var updatePayload = ReactNativeAttributePayload_1.create(this._currentElement.props, this.viewConfig.validAttributes), nativeTopRootTag = hostContainerInfo._tag; + return UIManager.createView(tag, this.viewConfig.uiViewClassName, nativeTopRootTag, updatePayload), + ReactNativeComponentTree_1.precacheNode(this, tag), this.initializeChildren(this._currentElement.props.children, tag, transaction, context), + tag; + } +}, Object.assign(ReactNativeBaseComponent.prototype, ReactMultiChild_1, ReactNativeBaseComponent.Mixin, NativeMethodsMixin_1); + +var ReactNativeBaseComponent_1 = ReactNativeBaseComponent, createReactNativeComponentClassStack = function(viewConfig) { + var Constructor = function(element) { + this._currentElement = element, this._topLevelWrapper = null, this._hostParent = null, + this._hostContainerInfo = null, this._rootNodeID = 0, this._renderedChildren = null; + }; + return Constructor.displayName = viewConfig.uiViewClassName, Constructor.viewConfig = viewConfig, + Constructor.propTypes = viewConfig.propTypes, Constructor.prototype = new ReactNativeBaseComponent_1(viewConfig), + Constructor.prototype.constructor = Constructor, Constructor; +}, createReactNativeComponentClassStack_1 = createReactNativeComponentClassStack, createReactNativeComponentClass = ReactNativeFeatureFlags$1.useFiber ? DevOnlyStubShim : createReactNativeComponentClassStack_1, findNumericNodeHandle$1 = ReactNativeFeatureFlags$1.useFiber ? DevOnlyStubShim : findNumericNodeHandleStack; + +function takeSnapshot(view, options) { + return "number" != typeof view && "window" !== view && (view = findNumericNodeHandle$1(view) || "window"), + UIManager.__takeSnapshot(view, options); +} + +var takeSnapshot_1 = takeSnapshot, lowPriorityWarning = function() {}, printWarning = function(format) { + for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) args[_key - 1] = arguments[_key]; + var argIndex = 0, message = "Warning: " + format.replace(/%s/g, function() { + return args[argIndex++]; + }); + "undefined" != typeof console && console.warn(message); + try { + throw new Error(message); + } catch (x) {} +}; + +lowPriorityWarning = function(condition, format) { + if (void 0 === format) throw new Error("`warning(condition, format, ...args)` requires a warning " + "message argument"); + if (!condition) { + for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) args[_key2 - 2] = arguments[_key2]; + printWarning.apply(void 0, [ format ].concat(args)); + } +}; + +var lowPriorityWarning_1 = lowPriorityWarning, _extends$2 = Object.assign || function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]); + } + return target; +}; + +function roundFloat(val) { + var base = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 2, n = Math.pow(10, base); + return Math.floor(val * n) / n; +} + +function consoleTable(table) { + console.table(table); +} + +function getLastMeasurements() { + return ReactDebugTool_1.getFlushHistory(); +} + +function getExclusive() { + var flushHistory = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : getLastMeasurements(), aggregatedStats = {}, affectedIDs = {}; + function updateAggregatedStats(treeSnapshot, instanceID, timerType, applyUpdate) { + var displayName = treeSnapshot[instanceID].displayName, key = displayName, stats = aggregatedStats[key]; + stats || (affectedIDs[key] = {}, stats = aggregatedStats[key] = { + key: key, + instanceCount: 0, + counts: {}, + durations: {}, + totalDuration: 0 + }), stats.durations[timerType] || (stats.durations[timerType] = 0), stats.counts[timerType] || (stats.counts[timerType] = 0), + affectedIDs[key][instanceID] = !0, applyUpdate(stats); + } + return flushHistory.forEach(function(flush) { + var measurements = flush.measurements, treeSnapshot = flush.treeSnapshot; + measurements.forEach(function(measurement) { + var duration = measurement.duration, instanceID = measurement.instanceID, timerType = measurement.timerType; + updateAggregatedStats(treeSnapshot, instanceID, timerType, function(stats) { + stats.totalDuration += duration, stats.durations[timerType] += duration, stats.counts[timerType]++; + }); + }); + }), Object.keys(aggregatedStats).map(function(key) { + return _extends$2({}, aggregatedStats[key], { + instanceCount: Object.keys(affectedIDs[key]).length + }); + }).sort(function(a, b) { + return b.totalDuration - a.totalDuration; + }); +} + +function getInclusive() { + var flushHistory = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : getLastMeasurements(), aggregatedStats = {}, affectedIDs = {}; + function updateAggregatedStats(treeSnapshot, instanceID, applyUpdate) { + var _treeSnapshot$instanc = treeSnapshot[instanceID], displayName = _treeSnapshot$instanc.displayName, ownerID = _treeSnapshot$instanc.ownerID, owner = treeSnapshot[ownerID], key = (owner ? owner.displayName + " > " : "") + displayName, stats = aggregatedStats[key]; + stats || (affectedIDs[key] = {}, stats = aggregatedStats[key] = { + key: key, + instanceCount: 0, + inclusiveRenderDuration: 0, + renderCount: 0 + }), affectedIDs[key][instanceID] = !0, applyUpdate(stats); + } + var isCompositeByID = {}; + return flushHistory.forEach(function(flush) { + flush.measurements.forEach(function(measurement) { + var instanceID = measurement.instanceID; + "render" === measurement.timerType && (isCompositeByID[instanceID] = !0); + }); + }), flushHistory.forEach(function(flush) { + var measurements = flush.measurements, treeSnapshot = flush.treeSnapshot; + measurements.forEach(function(measurement) { + var duration = measurement.duration, instanceID = measurement.instanceID; + if ("render" === measurement.timerType) { + updateAggregatedStats(treeSnapshot, instanceID, function(stats) { + stats.renderCount++; + }); + for (var nextParentID = instanceID; nextParentID; ) isCompositeByID[nextParentID] && updateAggregatedStats(treeSnapshot, nextParentID, function(stats) { + stats.inclusiveRenderDuration += duration; + }), nextParentID = treeSnapshot[nextParentID].parentID; + } + }); + }), Object.keys(aggregatedStats).map(function(key) { + return _extends$2({}, aggregatedStats[key], { + instanceCount: Object.keys(affectedIDs[key]).length + }); + }).sort(function(a, b) { + return b.inclusiveRenderDuration - a.inclusiveRenderDuration; + }); +} + +function getWasted() { + var flushHistory = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : getLastMeasurements(), aggregatedStats = {}, affectedIDs = {}; + function updateAggregatedStats(treeSnapshot, instanceID, applyUpdate) { + var _treeSnapshot$instanc2 = treeSnapshot[instanceID], displayName = _treeSnapshot$instanc2.displayName, ownerID = _treeSnapshot$instanc2.ownerID, owner = treeSnapshot[ownerID], key = (owner ? owner.displayName + " > " : "") + displayName, stats = aggregatedStats[key]; + stats || (affectedIDs[key] = {}, stats = aggregatedStats[key] = { + key: key, + instanceCount: 0, + inclusiveRenderDuration: 0, + renderCount: 0 + }), affectedIDs[key][instanceID] = !0, applyUpdate(stats); + } + return flushHistory.forEach(function(flush) { + var measurements = flush.measurements, treeSnapshot = flush.treeSnapshot, operations = flush.operations, isDefinitelyNotWastedByID = {}; + operations.forEach(function(operation) { + for (var instanceID = operation.instanceID, nextParentID = instanceID; nextParentID; ) isDefinitelyNotWastedByID[nextParentID] = !0, + nextParentID = treeSnapshot[nextParentID].parentID; + }); + var renderedCompositeIDs = {}; + measurements.forEach(function(measurement) { + var instanceID = measurement.instanceID; + "render" === measurement.timerType && (renderedCompositeIDs[instanceID] = !0); + }), measurements.forEach(function(measurement) { + var duration = measurement.duration, instanceID = measurement.instanceID; + if ("render" === measurement.timerType) { + var updateCount = treeSnapshot[instanceID].updateCount; + if (!isDefinitelyNotWastedByID[instanceID] && 0 !== updateCount) { + updateAggregatedStats(treeSnapshot, instanceID, function(stats) { + stats.renderCount++; + }); + for (var nextParentID = instanceID; nextParentID; ) renderedCompositeIDs[nextParentID] && !isDefinitelyNotWastedByID[nextParentID] && updateAggregatedStats(treeSnapshot, nextParentID, function(stats) { + stats.inclusiveRenderDuration += duration; + }), nextParentID = treeSnapshot[nextParentID].parentID; + } + } + }); + }), Object.keys(aggregatedStats).map(function(key) { + return _extends$2({}, aggregatedStats[key], { + instanceCount: Object.keys(affectedIDs[key]).length + }); + }).sort(function(a, b) { + return b.inclusiveRenderDuration - a.inclusiveRenderDuration; + }); +} + +function getOperations() { + var flushHistory = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : getLastMeasurements(), stats = []; + return flushHistory.forEach(function(flush, flushIndex) { + var operations = flush.operations, treeSnapshot = flush.treeSnapshot; + operations.forEach(function(operation) { + var instanceID = operation.instanceID, type = operation.type, payload = operation.payload, _treeSnapshot$instanc3 = treeSnapshot[instanceID], displayName = _treeSnapshot$instanc3.displayName, ownerID = _treeSnapshot$instanc3.ownerID, owner = treeSnapshot[ownerID], key = (owner ? owner.displayName + " > " : "") + displayName; + stats.push({ + flushIndex: flushIndex, + instanceID: instanceID, + key: key, + type: type, + ownerID: ownerID, + payload: payload + }); + }); + }), stats; +} + +function printExclusive(flushHistory) { + consoleTable(getExclusive(flushHistory).map(function(item) { + var key = item.key, instanceCount = item.instanceCount, totalDuration = item.totalDuration, renderCount = item.counts.render || 0, renderDuration = item.durations.render || 0; + return { + Component: key, + "Total time (ms)": roundFloat(totalDuration), + "Instance count": instanceCount, + "Total render time (ms)": roundFloat(renderDuration), + "Average render time (ms)": renderCount ? roundFloat(renderDuration / renderCount) : void 0, + "Render count": renderCount, + "Total lifecycle time (ms)": roundFloat(totalDuration - renderDuration) + }; + })); +} + +function printInclusive(flushHistory) { + consoleTable(getInclusive(flushHistory).map(function(item) { + var key = item.key, instanceCount = item.instanceCount, inclusiveRenderDuration = item.inclusiveRenderDuration, renderCount = item.renderCount; + return { + "Owner > Component": key, + "Inclusive render time (ms)": roundFloat(inclusiveRenderDuration), + "Instance count": instanceCount, + "Render count": renderCount + }; + })); +} + +function printWasted(flushHistory) { + consoleTable(getWasted(flushHistory).map(function(item) { + var key = item.key, instanceCount = item.instanceCount, inclusiveRenderDuration = item.inclusiveRenderDuration, renderCount = item.renderCount; + return { + "Owner > Component": key, + "Inclusive wasted time (ms)": roundFloat(inclusiveRenderDuration), + "Instance count": instanceCount, + "Render count": renderCount + }; + })); +} + +function printOperations(flushHistory) { + consoleTable(getOperations(flushHistory).map(function(stat) { + return { + "Owner > Node": stat.key, + Operation: stat.type, + Payload: "object" == typeof stat.payload ? JSON.stringify(stat.payload) : stat.payload, + "Flush index": stat.flushIndex, + "Owner Component ID": stat.ownerID, + "DOM Component ID": stat.instanceID + }; + })); +} + +var warnedAboutPrintDOM = !1; + +function printDOM(measurements) { + return lowPriorityWarning_1(warnedAboutPrintDOM, "`ReactPerf.printDOM(...)` is deprecated. Use " + "`ReactPerf.printOperations(...)` instead."), + warnedAboutPrintDOM = !0, printOperations(measurements); +} + +var warnedAboutGetMeasurementsSummaryMap = !1; + +function getMeasurementsSummaryMap(measurements) { + return lowPriorityWarning_1(warnedAboutGetMeasurementsSummaryMap, "`ReactPerf.getMeasurementsSummaryMap(...)` is deprecated. Use " + "`ReactPerf.getWasted(...)` instead."), + warnedAboutGetMeasurementsSummaryMap = !0, getWasted(measurements); +} + +function start() { + ReactDebugTool_1.beginProfiling(); +} + +function stop() { + ReactDebugTool_1.endProfiling(); +} + +function isRunning() { + return ReactDebugTool_1.isProfiling(); +} + +var ReactPerfAnalysis = { + getLastMeasurements: getLastMeasurements, + getExclusive: getExclusive, + getInclusive: getInclusive, + getWasted: getWasted, + getOperations: getOperations, + printExclusive: printExclusive, + printInclusive: printInclusive, + printWasted: printWasted, + printOperations: printOperations, + start: start, + stop: stop, + isRunning: isRunning, + printDOM: printDOM, + getMeasurementsSummaryMap: getMeasurementsSummaryMap +}, ReactPerf = ReactPerfAnalysis; + +ReactNativeInjection.inject(), ReactNativeStackInjection.inject(); + +var render = function(element, mountInto, callback) { + return ReactNativeMount_1.renderComponent(element, mountInto, callback); +}, ReactNative = { + hasReactNativeInitialized: !1, + findNodeHandle: findNumericNodeHandleStack, + render: render, + unmountComponentAtNode: ReactNativeMount_1.unmountComponentAtNode, + unstable_batchedUpdates: ReactUpdates_1.batchedUpdates, + unmountComponentAtNodeAndRemoveContainer: ReactNativeMount_1.unmountComponentAtNodeAndRemoveContainer, + __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: { + NativeMethodsMixin: NativeMethodsMixin_1, + ReactGlobalSharedState: ReactGlobalSharedState_1, + ReactNativeComponentTree: ReactNativeComponentTree_1, + ReactNativePropRegistry: ReactNativePropRegistry_1, + TouchHistoryMath: TouchHistoryMath_1, + createReactNativeComponentClass: createReactNativeComponentClass, + takeSnapshot: takeSnapshot_1 + } +}; + +Object.assign(ReactNative.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, { + ReactDebugTool: ReactDebugTool_1, + ReactPerf: ReactPerf +}), "undefined" != typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" == typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject && __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ + ComponentTree: { + getClosestInstanceFromNode: function(node) { + return ReactNativeComponentTree_1.getClosestInstanceFromNode(node); + }, + getNodeFromInstance: function(inst) { + for (;inst._renderedComponent; ) inst = inst._renderedComponent; + return inst ? ReactNativeComponentTree_1.getNodeFromInstance(inst) : null; + } + }, + Mount: ReactNativeMount_1, + Reconciler: ReactReconciler_1, + getInspectorDataForViewTag: ReactNativeStackInspector.getInspectorDataForViewTag +}); + +var ReactNativeStack = ReactNative; + +module.exports = ReactNativeStack; diff --git a/Libraries/Renderer/ReactNativeStack-prod.js b/Libraries/Renderer/ReactNativeStack-prod.js new file mode 100644 index 0000000000..b2105ce0db --- /dev/null +++ b/Libraries/Renderer/ReactNativeStack-prod.js @@ -0,0 +1,2478 @@ +/** + * Copyright 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @noflow + * @providesModule ReactNativeStack-prod + */ +"use strict"; + +var invariant = require("fbjs/lib/invariant"); + +require("InitializeCore"); + +var warning = require("fbjs/lib/warning"), RCTEventEmitter = require("RCTEventEmitter"), emptyFunction = require("fbjs/lib/emptyFunction"), UIManager = require("UIManager"), React = require("react"), emptyObject = require("fbjs/lib/emptyObject"); + +require("prop-types/checkPropTypes"); + +var shallowEqual = require("fbjs/lib/shallowEqual"); + +require("ReactNativeFeatureFlags"); + +var deepDiffer = require("deepDiffer"), flattenStyle = require("flattenStyle"), TextInputState = require("TextInputState"); + +require("deepFreezeAndThrowOnMutationInDev"); + +var instanceCache = {}, instanceProps = {}; + +function getRenderedHostOrTextFromComponent(component) { + for (var rendered; rendered = component._renderedComponent; ) component = rendered; + return component; +} + +function precacheNode(inst, tag) { + var nativeInst = getRenderedHostOrTextFromComponent(inst); + instanceCache[tag] = nativeInst; +} + +function precacheFiberNode(hostInst, tag) { + instanceCache[tag] = hostInst; +} + +function uncacheNode(inst) { + var tag = inst._rootNodeID; + tag && delete instanceCache[tag]; +} + +function uncacheFiberNode(tag) { + delete instanceCache[tag], delete instanceProps[tag]; +} + +function getInstanceFromTag(tag) { + return instanceCache[tag] || null; +} + +function getTagFromInstance(inst) { + var tag = "number" != typeof inst.tag ? inst._rootNodeID : inst.stateNode._nativeTag; + return invariant(tag, "All native instances should have a tag."), tag; +} + +function getFiberCurrentPropsFromNode(stateNode) { + return instanceProps[stateNode._nativeTag] || null; +} + +function updateFiberProps(tag, props) { + instanceProps[tag] = props; +} + +var ReactNativeComponentTree = { + getClosestInstanceFromNode: getInstanceFromTag, + getInstanceFromNode: getInstanceFromTag, + getNodeFromInstance: getTagFromInstance, + precacheFiberNode: precacheFiberNode, + precacheNode: precacheNode, + uncacheFiberNode: uncacheFiberNode, + uncacheNode: uncacheNode, + getFiberCurrentPropsFromNode: getFiberCurrentPropsFromNode, + updateFiberProps: updateFiberProps +}, ReactNativeComponentTree_1 = ReactNativeComponentTree, eventPluginOrder = null, namesToPlugins = {}; + +function recomputePluginOrdering() { + if (eventPluginOrder) for (var pluginName in namesToPlugins) { + var pluginModule = namesToPlugins[pluginName], pluginIndex = eventPluginOrder.indexOf(pluginName); + if (invariant(pluginIndex > -1, "EventPluginRegistry: Cannot inject event plugins that do not exist in " + "the plugin ordering, `%s`.", pluginName), + !EventPluginRegistry.plugins[pluginIndex]) { + invariant(pluginModule.extractEvents, "EventPluginRegistry: Event plugins must implement an `extractEvents` " + "method, but `%s` does not.", pluginName), + EventPluginRegistry.plugins[pluginIndex] = pluginModule; + var publishedEvents = pluginModule.eventTypes; + for (var eventName in publishedEvents) invariant(publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName), "EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.", eventName, pluginName); + } + } +} + +function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { + invariant(!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName), "EventPluginHub: More than one plugin attempted to publish the same " + "event name, `%s`.", eventName), + EventPluginRegistry.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 !0; + } + return !!dispatchConfig.registrationName && (publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName), + !0); +} + +function publishRegistrationName(registrationName, pluginModule, eventName) { + invariant(!EventPluginRegistry.registrationNameModules[registrationName], "EventPluginHub: More than one plugin attempted to publish the same " + "registration name, `%s`.", registrationName), + EventPluginRegistry.registrationNameModules[registrationName] = pluginModule, EventPluginRegistry.registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies; +} + +var EventPluginRegistry = { + plugins: [], + eventNameDispatchConfigs: {}, + registrationNameModules: {}, + registrationNameDependencies: {}, + possibleRegistrationNames: null, + injectEventPluginOrder: function(injectedEventPluginOrder) { + invariant(!eventPluginOrder, "EventPluginRegistry: Cannot inject event plugin ordering more than " + "once. You are likely trying to load more than one copy of React."), + eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder), recomputePluginOrdering(); + }, + injectEventPluginsByName: function(injectedNamesToPlugins) { + var isOrderingDirty = !1; + for (var pluginName in injectedNamesToPlugins) if (injectedNamesToPlugins.hasOwnProperty(pluginName)) { + var pluginModule = injectedNamesToPlugins[pluginName]; + namesToPlugins.hasOwnProperty(pluginName) && namesToPlugins[pluginName] === pluginModule || (invariant(!namesToPlugins[pluginName], "EventPluginRegistry: Cannot inject two different event plugins " + "using the same name, `%s`.", pluginName), + namesToPlugins[pluginName] = pluginModule, isOrderingDirty = !0); + } + isOrderingDirty && recomputePluginOrdering(); + } +}, EventPluginRegistry_1 = EventPluginRegistry, caughtError = null, invokeGuardedCallback = 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) { + return error; + } + return null; +}, rethrowCaughtError = function() { + if (caughtError) { + var error = caughtError; + throw caughtError = null, error; + } +}, ReactErrorUtils = { + injection: { + injectErrorUtils: function(injectedErrorUtils) { + invariant("function" == typeof injectedErrorUtils.invokeGuardedCallback, "Injected invokeGuardedCallback() must be a function."), + invokeGuardedCallback = injectedErrorUtils.invokeGuardedCallback; + } + }, + invokeGuardedCallback: function(name, func, context, a, b, c, d, e, f) { + return invokeGuardedCallback.apply(this, arguments); + }, + invokeGuardedCallbackAndCatchFirstError: function(name, func, context, a, b, c, d, e, f) { + var error = ReactErrorUtils.invokeGuardedCallback.apply(this, arguments); + null !== error && null === caughtError && (caughtError = error); + }, + rethrowCaughtError: function() { + return rethrowCaughtError.apply(this, arguments); + } +}, ReactErrorUtils_1 = ReactErrorUtils, ComponentTree, injection = { + injectComponentTree: function(Injected) { + ComponentTree = Injected; + } +}; + +function isEndish(topLevelType) { + return "topMouseUp" === topLevelType || "topTouchEnd" === topLevelType || "topTouchCancel" === topLevelType; +} + +function isMoveish(topLevelType) { + return "topMouseMove" === topLevelType || "topTouchMove" === topLevelType; +} + +function isStartish(topLevelType) { + return "topMouseDown" === topLevelType || "topTouchStart" === topLevelType; +} + +function executeDispatch(event, simulated, listener, inst) { + var type = event.type || "unknown-event"; + event.currentTarget = EventPluginUtils.getNodeFromInstance(inst), ReactErrorUtils_1.invokeGuardedCallbackAndCatchFirstError(type, listener, void 0, event), + event.currentTarget = null; +} + +function executeDispatchesInOrder(event, simulated) { + var dispatchListeners = event._dispatchListeners, dispatchInstances = event._dispatchInstances; + if (Array.isArray(dispatchListeners)) for (var i = 0; i < dispatchListeners.length && !event.isPropagationStopped(); i++) executeDispatch(event, simulated, dispatchListeners[i], dispatchInstances[i]); else dispatchListeners && executeDispatch(event, simulated, dispatchListeners, dispatchInstances); + event._dispatchListeners = null, event._dispatchInstances = null; +} + +function executeDispatchesInOrderStopAtTrueImpl(event) { + var dispatchListeners = event._dispatchListeners, dispatchInstances = event._dispatchInstances; + if (Array.isArray(dispatchListeners)) { + for (var i = 0; i < dispatchListeners.length && !event.isPropagationStopped(); i++) if (dispatchListeners[i](event, dispatchInstances[i])) return dispatchInstances[i]; + } else if (dispatchListeners && dispatchListeners(event, dispatchInstances)) return dispatchInstances; + return null; +} + +function executeDispatchesInOrderStopAtTrue(event) { + var ret = executeDispatchesInOrderStopAtTrueImpl(event); + return event._dispatchInstances = null, event._dispatchListeners = null, ret; +} + +function executeDirectDispatch(event) { + var dispatchListener = event._dispatchListeners, dispatchInstance = event._dispatchInstances; + invariant(!Array.isArray(dispatchListener), "executeDirectDispatch(...): Invalid `event`."), + event.currentTarget = dispatchListener ? EventPluginUtils.getNodeFromInstance(dispatchInstance) : null; + var res = dispatchListener ? dispatchListener(event) : null; + return event.currentTarget = null, event._dispatchListeners = null, event._dispatchInstances = null, + res; +} + +function hasDispatches(event) { + return !!event._dispatchListeners; +} + +var EventPluginUtils = { + isEndish: isEndish, + isMoveish: isMoveish, + isStartish: isStartish, + executeDirectDispatch: executeDirectDispatch, + executeDispatchesInOrder: executeDispatchesInOrder, + executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue, + hasDispatches: hasDispatches, + getFiberCurrentPropsFromNode: function(node) { + return ComponentTree.getFiberCurrentPropsFromNode(node); + }, + getInstanceFromNode: function(node) { + return ComponentTree.getInstanceFromNode(node); + }, + getNodeFromInstance: function(node) { + return ComponentTree.getNodeFromInstance(node); + }, + injection: injection +}, EventPluginUtils_1 = EventPluginUtils; + +function accumulateInto(current, next) { + return invariant(null != next, "accumulateInto(...): Accumulated items must not be null or undefined."), + null == current ? next : Array.isArray(current) ? Array.isArray(next) ? (current.push.apply(current, next), + current) : (current.push(next), current) : Array.isArray(next) ? [ current ].concat(next) : [ current, next ]; +} + +var accumulateInto_1 = accumulateInto; + +function forEachAccumulated(arr, cb, scope) { + Array.isArray(arr) ? arr.forEach(cb, scope) : arr && cb.call(scope, arr); +} + +var forEachAccumulated_1 = forEachAccumulated, eventQueue = null, executeDispatchesAndRelease = function(event, simulated) { + event && (EventPluginUtils_1.executeDispatchesInOrder(event, simulated), event.isPersistent() || event.constructor.release(event)); +}, executeDispatchesAndReleaseSimulated = function(e) { + return executeDispatchesAndRelease(e, !0); +}, executeDispatchesAndReleaseTopLevel = function(e) { + return executeDispatchesAndRelease(e, !1); +}; + +function isInteractive(tag) { + return "button" === tag || "input" === tag || "select" === tag || "textarea" === tag; +} + +function shouldPreventMouseEvent(name, type, props) { + switch (name) { + case "onClick": + case "onClickCapture": + case "onDoubleClick": + case "onDoubleClickCapture": + case "onMouseDown": + case "onMouseDownCapture": + case "onMouseMove": + case "onMouseMoveCapture": + case "onMouseUp": + case "onMouseUpCapture": + return !(!props.disabled || !isInteractive(type)); + + default: + return !1; + } +} + +var EventPluginHub = { + injection: { + injectEventPluginOrder: EventPluginRegistry_1.injectEventPluginOrder, + injectEventPluginsByName: EventPluginRegistry_1.injectEventPluginsByName + }, + getListener: function(inst, registrationName) { + var listener; + if ("number" == typeof inst.tag) { + var stateNode = inst.stateNode; + if (!stateNode) return null; + var props = EventPluginUtils_1.getFiberCurrentPropsFromNode(stateNode); + if (!props) return null; + if (listener = props[registrationName], shouldPreventMouseEvent(registrationName, inst.type, props)) return null; + } else { + var currentElement = inst._currentElement; + if ("string" == typeof currentElement || "number" == typeof currentElement) return null; + if (!inst._rootNodeID) return null; + var _props = currentElement.props; + if (listener = _props[registrationName], shouldPreventMouseEvent(registrationName, currentElement.type, _props)) return null; + } + return invariant(!listener || "function" == typeof listener, "Expected %s listener to be a function, instead got type %s", registrationName, typeof listener), + listener; + }, + extractEvents: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) { + for (var events, plugins = EventPluginRegistry_1.plugins, i = 0; i < plugins.length; i++) { + var possiblePlugin = plugins[i]; + if (possiblePlugin) { + var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); + extractedEvents && (events = accumulateInto_1(events, extractedEvents)); + } + } + return events; + }, + enqueueEvents: function(events) { + events && (eventQueue = accumulateInto_1(eventQueue, events)); + }, + processEventQueue: function(simulated) { + var processingEventQueue = eventQueue; + eventQueue = null, simulated ? forEachAccumulated_1(processingEventQueue, executeDispatchesAndReleaseSimulated) : forEachAccumulated_1(processingEventQueue, executeDispatchesAndReleaseTopLevel), + invariant(!eventQueue, "processEventQueue(): Additional events were enqueued while processing " + "an event queue. Support for this has not yet been implemented."), + ReactErrorUtils_1.rethrowCaughtError(); + } +}, EventPluginHub_1 = EventPluginHub, ReactTypeOfWork = { + IndeterminateComponent: 0, + FunctionalComponent: 1, + ClassComponent: 2, + HostRoot: 3, + HostPortal: 4, + HostComponent: 5, + HostText: 6, + CoroutineComponent: 7, + CoroutineHandlerPhase: 8, + YieldComponent: 9, + Fragment: 10 +}, HostComponent = ReactTypeOfWork.HostComponent; + +function getParent(inst) { + if (void 0 !== inst._hostParent) return inst._hostParent; + if ("number" == typeof inst.tag) { + do { + inst = inst.return; + } while (inst && inst.tag !== HostComponent); + if (inst) return inst; + } + return null; +} + +function getLowestCommonAncestor(instA, instB) { + for (var depthA = 0, tempA = instA; tempA; tempA = getParent(tempA)) depthA++; + for (var depthB = 0, tempB = instB; tempB; tempB = getParent(tempB)) depthB++; + for (;depthA - depthB > 0; ) instA = getParent(instA), depthA--; + for (;depthB - depthA > 0; ) instB = getParent(instB), depthB--; + for (var depth = depthA; depth--; ) { + if (instA === instB || instA === instB.alternate) return instA; + instA = getParent(instA), instB = getParent(instB); + } + return null; +} + +function isAncestor(instA, instB) { + for (;instB; ) { + if (instA === instB || instA === instB.alternate) return !0; + instB = getParent(instB); + } + return !1; +} + +function getParentInstance(inst) { + return getParent(inst); +} + +function traverseTwoPhase(inst, fn, arg) { + for (var path = []; inst; ) path.push(inst), inst = getParent(inst); + var i; + for (i = path.length; i-- > 0; ) fn(path[i], "captured", arg); + for (i = 0; i < path.length; i++) fn(path[i], "bubbled", arg); +} + +function traverseEnterLeave(from, to, fn, argFrom, argTo) { + for (var common = from && to ? getLowestCommonAncestor(from, to) : null, pathFrom = []; from && from !== common; ) pathFrom.push(from), + from = getParent(from); + for (var pathTo = []; to && to !== common; ) pathTo.push(to), to = getParent(to); + var i; + for (i = 0; i < pathFrom.length; i++) fn(pathFrom[i], "bubbled", argFrom); + for (i = pathTo.length; i-- > 0; ) fn(pathTo[i], "captured", argTo); +} + +var ReactTreeTraversal = { + isAncestor: isAncestor, + getLowestCommonAncestor: getLowestCommonAncestor, + getParentInstance: getParentInstance, + traverseTwoPhase: traverseTwoPhase, + traverseEnterLeave: traverseEnterLeave +}, getListener = EventPluginHub_1.getListener; + +function listenerAtPhase(inst, event, propagationPhase) { + var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; + return getListener(inst, registrationName); +} + +function accumulateDirectionalDispatches(inst, phase, event) { + var listener = listenerAtPhase(inst, event, phase); + listener && (event._dispatchListeners = accumulateInto_1(event._dispatchListeners, listener), + event._dispatchInstances = accumulateInto_1(event._dispatchInstances, inst)); +} + +function accumulateTwoPhaseDispatchesSingle(event) { + event && event.dispatchConfig.phasedRegistrationNames && ReactTreeTraversal.traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event); +} + +function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { + if (event && event.dispatchConfig.phasedRegistrationNames) { + var targetInst = event._targetInst, parentInst = targetInst ? ReactTreeTraversal.getParentInstance(targetInst) : null; + ReactTreeTraversal.traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event); + } +} + +function accumulateDispatches(inst, ignoredDirection, event) { + if (inst && event && event.dispatchConfig.registrationName) { + var registrationName = event.dispatchConfig.registrationName, listener = getListener(inst, registrationName); + listener && (event._dispatchListeners = accumulateInto_1(event._dispatchListeners, listener), + event._dispatchInstances = accumulateInto_1(event._dispatchInstances, inst)); + } +} + +function accumulateDirectDispatchesSingle(event) { + event && event.dispatchConfig.registrationName && accumulateDispatches(event._targetInst, null, event); +} + +function accumulateTwoPhaseDispatches(events) { + forEachAccumulated_1(events, accumulateTwoPhaseDispatchesSingle); +} + +function accumulateTwoPhaseDispatchesSkipTarget(events) { + forEachAccumulated_1(events, accumulateTwoPhaseDispatchesSingleSkipTarget); +} + +function accumulateEnterLeaveDispatches(leave, enter, from, to) { + ReactTreeTraversal.traverseEnterLeave(from, to, accumulateDispatches, leave, enter); +} + +function accumulateDirectDispatches(events) { + forEachAccumulated_1(events, accumulateDirectDispatchesSingle); +} + +var EventPropagators = { + accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches, + accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget, + accumulateDirectDispatches: accumulateDirectDispatches, + accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches +}, EventPropagators_1 = EventPropagators, oneArgumentPooler = function(copyFieldsFrom) { + var Klass = this; + if (Klass.instancePool.length) { + var instance = Klass.instancePool.pop(); + return Klass.call(instance, copyFieldsFrom), instance; + } + return new Klass(copyFieldsFrom); +}, twoArgumentPooler = function(a1, a2) { + var Klass = this; + if (Klass.instancePool.length) { + var instance = Klass.instancePool.pop(); + return Klass.call(instance, a1, a2), instance; + } + return new Klass(a1, a2); +}, threeArgumentPooler = function(a1, a2, a3) { + var Klass = this; + if (Klass.instancePool.length) { + var instance = Klass.instancePool.pop(); + return Klass.call(instance, a1, a2, a3), instance; + } + return new Klass(a1, a2, a3); +}, fourArgumentPooler = function(a1, a2, a3, a4) { + var Klass = this; + if (Klass.instancePool.length) { + var instance = Klass.instancePool.pop(); + return Klass.call(instance, a1, a2, a3, a4), instance; + } + return new Klass(a1, a2, a3, a4); +}, standardReleaser = function(instance) { + var Klass = this; + invariant(instance instanceof Klass, "Trying to release an instance into a pool of a different type."), + instance.destructor(), Klass.instancePool.length < Klass.poolSize && Klass.instancePool.push(instance); +}, DEFAULT_POOL_SIZE = 10, DEFAULT_POOLER = oneArgumentPooler, addPoolingTo = function(CopyConstructor, pooler) { + var NewKlass = CopyConstructor; + return NewKlass.instancePool = [], NewKlass.getPooled = pooler || DEFAULT_POOLER, + NewKlass.poolSize || (NewKlass.poolSize = DEFAULT_POOL_SIZE), NewKlass.release = standardReleaser, + NewKlass; +}, PooledClass = { + addPoolingTo: addPoolingTo, + oneArgumentPooler: oneArgumentPooler, + twoArgumentPooler: twoArgumentPooler, + threeArgumentPooler: threeArgumentPooler, + fourArgumentPooler: fourArgumentPooler +}, PooledClass_1 = PooledClass, shouldBeReleasedProperties = [ "dispatchConfig", "_targetInst", "nativeEvent", "isDefaultPrevented", "isPropagationStopped", "_dispatchListeners", "_dispatchInstances" ], EventInterface = { + type: null, + target: null, + currentTarget: emptyFunction.thatReturnsNull, + eventPhase: null, + bubbles: null, + cancelable: null, + timeStamp: function(event) { + return event.timeStamp || Date.now(); + }, + defaultPrevented: null, + isTrusted: null +}; + +function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) { + this.dispatchConfig = dispatchConfig, this._targetInst = targetInst, this.nativeEvent = nativeEvent; + var Interface = this.constructor.Interface; + for (var propName in Interface) if (Interface.hasOwnProperty(propName)) { + var normalize = Interface[propName]; + normalize ? this[propName] = normalize(nativeEvent) : "target" === propName ? this.target = nativeEventTarget : this[propName] = nativeEvent[propName]; + } + var defaultPrevented = null != nativeEvent.defaultPrevented ? nativeEvent.defaultPrevented : !1 === nativeEvent.returnValue; + return this.isDefaultPrevented = defaultPrevented ? emptyFunction.thatReturnsTrue : emptyFunction.thatReturnsFalse, + this.isPropagationStopped = emptyFunction.thatReturnsFalse, this; +} + +Object.assign(SyntheticEvent.prototype, { + preventDefault: function() { + this.defaultPrevented = !0; + var event = this.nativeEvent; + event && (event.preventDefault ? event.preventDefault() : "unknown" != typeof event.returnValue && (event.returnValue = !1), + this.isDefaultPrevented = emptyFunction.thatReturnsTrue); + }, + stopPropagation: function() { + var event = this.nativeEvent; + event && (event.stopPropagation ? event.stopPropagation() : "unknown" != typeof event.cancelBubble && (event.cancelBubble = !0), + this.isPropagationStopped = emptyFunction.thatReturnsTrue); + }, + persist: function() { + this.isPersistent = emptyFunction.thatReturnsTrue; + }, + isPersistent: emptyFunction.thatReturnsFalse, + destructor: function() { + var Interface = this.constructor.Interface; + for (var propName in Interface) this[propName] = null; + for (var i = 0; i < shouldBeReleasedProperties.length; i++) this[shouldBeReleasedProperties[i]] = null; + } +}), SyntheticEvent.Interface = EventInterface, SyntheticEvent.augmentClass = function(Class, Interface) { + var Super = this, E = function() {}; + E.prototype = Super.prototype; + var prototype = new E(); + Object.assign(prototype, Class.prototype), Class.prototype = prototype, Class.prototype.constructor = Class, + Class.Interface = Object.assign({}, Super.Interface, Interface), Class.augmentClass = Super.augmentClass, + PooledClass_1.addPoolingTo(Class, PooledClass_1.fourArgumentPooler); +}, PooledClass_1.addPoolingTo(SyntheticEvent, PooledClass_1.fourArgumentPooler); + +var SyntheticEvent_1 = SyntheticEvent, _extends = Object.assign || function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]); + } + return target; +}, customBubblingEventTypes = UIManager.customBubblingEventTypes, customDirectEventTypes = UIManager.customDirectEventTypes, allTypesByEventName = {}; + +for (var bubblingTypeName in customBubblingEventTypes) allTypesByEventName[bubblingTypeName] = customBubblingEventTypes[bubblingTypeName]; + +for (var directTypeName in customDirectEventTypes) warning(!customBubblingEventTypes[directTypeName], "Event cannot be both direct and bubbling: %s", directTypeName), +allTypesByEventName[directTypeName] = customDirectEventTypes[directTypeName]; + +var ReactNativeBridgeEventPlugin = { + eventTypes: _extends({}, customBubblingEventTypes, customDirectEventTypes), + extractEvents: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) { + var bubbleDispatchConfig = customBubblingEventTypes[topLevelType], directDispatchConfig = customDirectEventTypes[topLevelType], event = SyntheticEvent_1.getPooled(bubbleDispatchConfig || directDispatchConfig, targetInst, nativeEvent, nativeEventTarget); + if (bubbleDispatchConfig) EventPropagators_1.accumulateTwoPhaseDispatches(event); else { + if (!directDispatchConfig) return null; + EventPropagators_1.accumulateDirectDispatches(event); + } + return event; + } +}, ReactNativeBridgeEventPlugin_1 = ReactNativeBridgeEventPlugin; + +function runEventQueueInBatch(events) { + EventPluginHub_1.enqueueEvents(events), EventPluginHub_1.processEventQueue(!1); +} + +var ReactEventEmitterMixin = { + handleTopLevel: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) { + runEventQueueInBatch(EventPluginHub_1.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget)); + } +}, ReactEventEmitterMixin_1 = ReactEventEmitterMixin, INITIAL_TAG_COUNT = 1, ReactNativeTagHandles = { + tagsStartAt: INITIAL_TAG_COUNT, + tagCount: INITIAL_TAG_COUNT, + allocateTag: function() { + for (;this.reactTagIsNativeTopRootID(ReactNativeTagHandles.tagCount); ) ReactNativeTagHandles.tagCount++; + var tag = ReactNativeTagHandles.tagCount; + return ReactNativeTagHandles.tagCount++, tag; + }, + assertRootTag: function(tag) { + invariant(this.reactTagIsNativeTopRootID(tag), "Expect a native root tag, instead got %s", tag); + }, + reactTagIsNativeTopRootID: function(reactTag) { + return reactTag % 10 == 1; + } +}, ReactNativeTagHandles_1 = ReactNativeTagHandles, fiberHostComponent = null, ReactControlledComponentInjection = { + injectFiberControlledHostComponent: function(hostComponentImpl) { + fiberHostComponent = hostComponentImpl; + } +}, restoreTarget = null, restoreQueue = null; + +function restoreStateOfTarget(target) { + var internalInstance = EventPluginUtils_1.getInstanceFromNode(target); + if (internalInstance) { + if ("number" == typeof internalInstance.tag) { + invariant(fiberHostComponent && "function" == typeof fiberHostComponent.restoreControlledState, "Fiber needs to be injected to handle a fiber target for controlled " + "events."); + var props = EventPluginUtils_1.getFiberCurrentPropsFromNode(internalInstance.stateNode); + return void fiberHostComponent.restoreControlledState(internalInstance.stateNode, internalInstance.type, props); + } + invariant("function" == typeof internalInstance.restoreControlledState, "The internal instance must be a React host component."), + internalInstance.restoreControlledState(); + } +} + +var ReactControlledComponent = { + injection: ReactControlledComponentInjection, + enqueueStateRestore: function(target) { + restoreTarget ? restoreQueue ? restoreQueue.push(target) : restoreQueue = [ target ] : restoreTarget = target; + }, + restoreStateIfNeeded: function() { + if (restoreTarget) { + var target = restoreTarget, queuedTargets = restoreQueue; + if (restoreTarget = null, restoreQueue = null, restoreStateOfTarget(target), queuedTargets) for (var i = 0; i < queuedTargets.length; i++) restoreStateOfTarget(queuedTargets[i]); + } + } +}, ReactControlledComponent_1 = ReactControlledComponent, stackBatchedUpdates = function(fn, a, b, c, d, e) { + return fn(a, b, c, d, e); +}, fiberBatchedUpdates = function(fn, bookkeeping) { + return fn(bookkeeping); +}; + +function performFiberBatchedUpdates(fn, bookkeeping) { + return fiberBatchedUpdates(fn, bookkeeping); +} + +function batchedUpdates(fn, bookkeeping) { + return stackBatchedUpdates(performFiberBatchedUpdates, fn, bookkeeping); +} + +var isNestingBatched = !1; + +function batchedUpdatesWithControlledComponents(fn, bookkeeping) { + if (isNestingBatched) return batchedUpdates(fn, bookkeeping); + isNestingBatched = !0; + try { + return batchedUpdates(fn, bookkeeping); + } finally { + isNestingBatched = !1, ReactControlledComponent_1.restoreStateIfNeeded(); + } +} + +var ReactGenericBatchingInjection = { + injectStackBatchedUpdates: function(_batchedUpdates) { + stackBatchedUpdates = _batchedUpdates; + }, + injectFiberBatchedUpdates: function(_batchedUpdates) { + fiberBatchedUpdates = _batchedUpdates; + } +}, ReactGenericBatching = { + batchedUpdates: batchedUpdatesWithControlledComponents, + injection: ReactGenericBatchingInjection +}, ReactGenericBatching_1 = ReactGenericBatching, _extends$1 = Object.assign || function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]); + } + return target; +}, EMPTY_NATIVE_EVENT = {}, touchSubsequence = function(touches, indices) { + for (var ret = [], i = 0; i < indices.length; i++) ret.push(touches[indices[i]]); + return ret; +}, removeTouchesAtIndices = function(touches, indices) { + for (var rippedOut = [], temp = touches, i = 0; i < indices.length; i++) { + var index = indices[i]; + rippedOut.push(touches[index]), temp[index] = null; + } + for (var fillAt = 0, j = 0; j < temp.length; j++) { + var cur = temp[j]; + null !== cur && (temp[fillAt++] = cur); + } + return temp.length = fillAt, rippedOut; +}, ReactNativeEventEmitter = _extends$1({}, ReactEventEmitterMixin_1, { + registrationNames: EventPluginRegistry_1.registrationNameModules, + getListener: EventPluginHub_1.getListener, + _receiveRootNodeIDEvent: function(rootNodeID, topLevelType, nativeEventParam) { + var nativeEvent = nativeEventParam || EMPTY_NATIVE_EVENT, inst = ReactNativeComponentTree_1.getInstanceFromNode(rootNodeID); + ReactGenericBatching_1.batchedUpdates(function() { + ReactNativeEventEmitter.handleTopLevel(topLevelType, inst, nativeEvent, nativeEvent.target); + }); + }, + receiveEvent: function(tag, topLevelType, nativeEventParam) { + var rootNodeID = tag; + ReactNativeEventEmitter._receiveRootNodeIDEvent(rootNodeID, topLevelType, nativeEventParam); + }, + receiveTouches: function(eventTopLevelType, touches, changedIndices) { + for (var changedTouches = "topTouchEnd" === eventTopLevelType || "topTouchCancel" === eventTopLevelType ? removeTouchesAtIndices(touches, changedIndices) : touchSubsequence(touches, changedIndices), jj = 0; jj < changedTouches.length; jj++) { + var touch = changedTouches[jj]; + touch.changedTouches = changedTouches, touch.touches = touches; + var nativeEvent = touch, rootNodeID = null, target = nativeEvent.target; + null !== target && void 0 !== target && (target < ReactNativeTagHandles_1.tagsStartAt || (rootNodeID = target)), + ReactNativeEventEmitter._receiveRootNodeIDEvent(rootNodeID, eventTopLevelType, nativeEvent); + } + } +}), ReactNativeEventEmitter_1 = ReactNativeEventEmitter, ReactNativeEventPluginOrder = [ "ResponderEventPlugin", "ReactNativeBridgeEventPlugin" ], ReactNativeEventPluginOrder_1 = ReactNativeEventPluginOrder, ReactNativeGlobalResponderHandler = { + onChange: function(from, to, blockNativeResponder) { + if (null !== to) { + var tag = "number" != typeof to.tag ? to._rootNodeID : to.stateNode._nativeTag; + UIManager.setJSResponder(tag, blockNativeResponder); + } else UIManager.clearJSResponder(); + } +}, ReactNativeGlobalResponderHandler_1 = ReactNativeGlobalResponderHandler, ResponderEventInterface = { + touchHistory: function(nativeEvent) { + return null; + } +}; + +function ResponderSyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { + return SyntheticEvent_1.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); +} + +SyntheticEvent_1.augmentClass(ResponderSyntheticEvent, ResponderEventInterface); + +var ResponderSyntheticEvent_1 = ResponderSyntheticEvent, isEndish$2 = EventPluginUtils_1.isEndish, isMoveish$2 = EventPluginUtils_1.isMoveish, isStartish$2 = EventPluginUtils_1.isStartish, MAX_TOUCH_BANK = 20, touchBank = [], touchHistory = { + touchBank: touchBank, + numberActiveTouches: 0, + indexOfSingleActiveTouch: -1, + mostRecentTimeStamp: 0 +}; + +function timestampForTouch(touch) { + return touch.timeStamp || touch.timestamp; +} + +function createTouchRecord(touch) { + return { + touchActive: !0, + startPageX: touch.pageX, + startPageY: touch.pageY, + startTimeStamp: timestampForTouch(touch), + currentPageX: touch.pageX, + currentPageY: touch.pageY, + currentTimeStamp: timestampForTouch(touch), + previousPageX: touch.pageX, + previousPageY: touch.pageY, + previousTimeStamp: timestampForTouch(touch) + }; +} + +function resetTouchRecord(touchRecord, touch) { + touchRecord.touchActive = !0, touchRecord.startPageX = touch.pageX, touchRecord.startPageY = touch.pageY, + touchRecord.startTimeStamp = timestampForTouch(touch), touchRecord.currentPageX = touch.pageX, + touchRecord.currentPageY = touch.pageY, touchRecord.currentTimeStamp = timestampForTouch(touch), + touchRecord.previousPageX = touch.pageX, touchRecord.previousPageY = touch.pageY, + touchRecord.previousTimeStamp = timestampForTouch(touch); +} + +function getTouchIdentifier(_ref) { + var identifier = _ref.identifier; + return invariant(null != identifier, "Touch object is missing identifier."), warning(identifier <= MAX_TOUCH_BANK, "Touch identifier %s is greater than maximum supported %s which causes " + "performance issues backfilling array locations for all of the indices.", identifier, MAX_TOUCH_BANK), + identifier; +} + +function recordTouchStart(touch) { + var identifier = getTouchIdentifier(touch), touchRecord = touchBank[identifier]; + touchRecord ? resetTouchRecord(touchRecord, touch) : touchBank[identifier] = createTouchRecord(touch), + touchHistory.mostRecentTimeStamp = timestampForTouch(touch); +} + +function recordTouchMove(touch) { + var touchRecord = touchBank[getTouchIdentifier(touch)]; + touchRecord ? (touchRecord.touchActive = !0, touchRecord.previousPageX = touchRecord.currentPageX, + touchRecord.previousPageY = touchRecord.currentPageY, touchRecord.previousTimeStamp = touchRecord.currentTimeStamp, + touchRecord.currentPageX = touch.pageX, touchRecord.currentPageY = touch.pageY, + touchRecord.currentTimeStamp = timestampForTouch(touch), touchHistory.mostRecentTimeStamp = timestampForTouch(touch)) : console.error("Cannot record touch move without a touch start.\n" + "Touch Move: %s\n", "Touch Bank: %s", printTouch(touch), printTouchBank()); +} + +function recordTouchEnd(touch) { + var touchRecord = touchBank[getTouchIdentifier(touch)]; + touchRecord ? (touchRecord.touchActive = !1, touchRecord.previousPageX = touchRecord.currentPageX, + touchRecord.previousPageY = touchRecord.currentPageY, touchRecord.previousTimeStamp = touchRecord.currentTimeStamp, + touchRecord.currentPageX = touch.pageX, touchRecord.currentPageY = touch.pageY, + touchRecord.currentTimeStamp = timestampForTouch(touch), touchHistory.mostRecentTimeStamp = timestampForTouch(touch)) : console.error("Cannot record touch end without a touch start.\n" + "Touch End: %s\n", "Touch Bank: %s", printTouch(touch), printTouchBank()); +} + +function printTouch(touch) { + return JSON.stringify({ + identifier: touch.identifier, + pageX: touch.pageX, + pageY: touch.pageY, + timestamp: timestampForTouch(touch) + }); +} + +function printTouchBank() { + var printed = JSON.stringify(touchBank.slice(0, MAX_TOUCH_BANK)); + return touchBank.length > MAX_TOUCH_BANK && (printed += " (original size: " + touchBank.length + ")"), + printed; +} + +var ResponderTouchHistoryStore = { + recordTouchTrack: function(topLevelType, nativeEvent) { + if (isMoveish$2(topLevelType)) nativeEvent.changedTouches.forEach(recordTouchMove); else if (isStartish$2(topLevelType)) nativeEvent.changedTouches.forEach(recordTouchStart), + touchHistory.numberActiveTouches = nativeEvent.touches.length, 1 === touchHistory.numberActiveTouches && (touchHistory.indexOfSingleActiveTouch = nativeEvent.touches[0].identifier); else if (isEndish$2(topLevelType) && (nativeEvent.changedTouches.forEach(recordTouchEnd), + touchHistory.numberActiveTouches = nativeEvent.touches.length, 1 === touchHistory.numberActiveTouches)) for (var i = 0; i < touchBank.length; i++) { + var touchTrackToCheck = touchBank[i]; + if (null != touchTrackToCheck && touchTrackToCheck.touchActive) { + touchHistory.indexOfSingleActiveTouch = i; + break; + } + } + }, + touchHistory: touchHistory +}, ResponderTouchHistoryStore_1 = ResponderTouchHistoryStore; + +function accumulate(current, next) { + return invariant(null != next, "accumulate(...): Accumulated items must be not be null or undefined."), + null == current ? next : Array.isArray(current) ? current.concat(next) : Array.isArray(next) ? [ current ].concat(next) : [ current, next ]; +} + +var accumulate_1 = accumulate, isStartish$1 = EventPluginUtils_1.isStartish, isMoveish$1 = EventPluginUtils_1.isMoveish, isEndish$1 = EventPluginUtils_1.isEndish, executeDirectDispatch$1 = EventPluginUtils_1.executeDirectDispatch, hasDispatches$1 = EventPluginUtils_1.hasDispatches, executeDispatchesInOrderStopAtTrue$1 = EventPluginUtils_1.executeDispatchesInOrderStopAtTrue, responderInst = null, trackedTouchCount = 0, previousActiveTouches = 0, changeResponder = function(nextResponderInst, blockHostResponder) { + var oldResponderInst = responderInst; + responderInst = nextResponderInst, null !== ResponderEventPlugin.GlobalResponderHandler && ResponderEventPlugin.GlobalResponderHandler.onChange(oldResponderInst, nextResponderInst, blockHostResponder); +}, eventTypes = { + startShouldSetResponder: { + phasedRegistrationNames: { + bubbled: "onStartShouldSetResponder", + captured: "onStartShouldSetResponderCapture" + } + }, + scrollShouldSetResponder: { + phasedRegistrationNames: { + bubbled: "onScrollShouldSetResponder", + captured: "onScrollShouldSetResponderCapture" + } + }, + selectionChangeShouldSetResponder: { + phasedRegistrationNames: { + bubbled: "onSelectionChangeShouldSetResponder", + captured: "onSelectionChangeShouldSetResponderCapture" + } + }, + moveShouldSetResponder: { + phasedRegistrationNames: { + bubbled: "onMoveShouldSetResponder", + captured: "onMoveShouldSetResponderCapture" + } + }, + responderStart: { + registrationName: "onResponderStart" + }, + responderMove: { + registrationName: "onResponderMove" + }, + responderEnd: { + registrationName: "onResponderEnd" + }, + responderRelease: { + registrationName: "onResponderRelease" + }, + responderTerminationRequest: { + registrationName: "onResponderTerminationRequest" + }, + responderGrant: { + registrationName: "onResponderGrant" + }, + responderReject: { + registrationName: "onResponderReject" + }, + responderTerminate: { + registrationName: "onResponderTerminate" + } +}; + +function setResponderAndExtractTransfer(topLevelType, targetInst, nativeEvent, nativeEventTarget) { + var shouldSetEventType = isStartish$1(topLevelType) ? eventTypes.startShouldSetResponder : isMoveish$1(topLevelType) ? eventTypes.moveShouldSetResponder : "topSelectionChange" === topLevelType ? eventTypes.selectionChangeShouldSetResponder : eventTypes.scrollShouldSetResponder, bubbleShouldSetFrom = responderInst ? ReactTreeTraversal.getLowestCommonAncestor(responderInst, targetInst) : targetInst, skipOverBubbleShouldSetFrom = bubbleShouldSetFrom === responderInst, shouldSetEvent = ResponderSyntheticEvent_1.getPooled(shouldSetEventType, bubbleShouldSetFrom, nativeEvent, nativeEventTarget); + shouldSetEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, skipOverBubbleShouldSetFrom ? EventPropagators_1.accumulateTwoPhaseDispatchesSkipTarget(shouldSetEvent) : EventPropagators_1.accumulateTwoPhaseDispatches(shouldSetEvent); + var wantsResponderInst = executeDispatchesInOrderStopAtTrue$1(shouldSetEvent); + if (shouldSetEvent.isPersistent() || shouldSetEvent.constructor.release(shouldSetEvent), + !wantsResponderInst || wantsResponderInst === responderInst) return null; + var extracted, grantEvent = ResponderSyntheticEvent_1.getPooled(eventTypes.responderGrant, wantsResponderInst, nativeEvent, nativeEventTarget); + grantEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, EventPropagators_1.accumulateDirectDispatches(grantEvent); + var blockHostResponder = !0 === executeDirectDispatch$1(grantEvent); + if (responderInst) { + var terminationRequestEvent = ResponderSyntheticEvent_1.getPooled(eventTypes.responderTerminationRequest, responderInst, nativeEvent, nativeEventTarget); + terminationRequestEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, + EventPropagators_1.accumulateDirectDispatches(terminationRequestEvent); + var shouldSwitch = !hasDispatches$1(terminationRequestEvent) || executeDirectDispatch$1(terminationRequestEvent); + if (terminationRequestEvent.isPersistent() || terminationRequestEvent.constructor.release(terminationRequestEvent), + shouldSwitch) { + var terminateEvent = ResponderSyntheticEvent_1.getPooled(eventTypes.responderTerminate, responderInst, nativeEvent, nativeEventTarget); + terminateEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, EventPropagators_1.accumulateDirectDispatches(terminateEvent), + extracted = accumulate_1(extracted, [ grantEvent, terminateEvent ]), changeResponder(wantsResponderInst, blockHostResponder); + } else { + var rejectEvent = ResponderSyntheticEvent_1.getPooled(eventTypes.responderReject, wantsResponderInst, nativeEvent, nativeEventTarget); + rejectEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, EventPropagators_1.accumulateDirectDispatches(rejectEvent), + extracted = accumulate_1(extracted, rejectEvent); + } + } else extracted = accumulate_1(extracted, grantEvent), changeResponder(wantsResponderInst, blockHostResponder); + return extracted; +} + +function canTriggerTransfer(topLevelType, topLevelInst, nativeEvent) { + return topLevelInst && ("topScroll" === topLevelType && !nativeEvent.responderIgnoreScroll || trackedTouchCount > 0 && "topSelectionChange" === topLevelType || isStartish$1(topLevelType) || isMoveish$1(topLevelType)); +} + +function noResponderTouches(nativeEvent) { + var touches = nativeEvent.touches; + if (!touches || 0 === touches.length) return !0; + for (var i = 0; i < touches.length; i++) { + var activeTouch = touches[i], target = activeTouch.target; + if (null !== target && void 0 !== target && 0 !== target) { + var targetInst = EventPluginUtils_1.getInstanceFromNode(target); + if (ReactTreeTraversal.isAncestor(responderInst, targetInst)) return !1; + } + } + return !0; +} + +var ResponderEventPlugin = { + _getResponder: function() { + return responderInst; + }, + eventTypes: eventTypes, + extractEvents: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) { + if (isStartish$1(topLevelType)) trackedTouchCount += 1; else if (isEndish$1(topLevelType)) { + if (!(trackedTouchCount >= 0)) return console.error("Ended a touch event which was not counted in `trackedTouchCount`."), + null; + trackedTouchCount -= 1; + } + ResponderTouchHistoryStore_1.recordTouchTrack(topLevelType, nativeEvent); + var extracted = canTriggerTransfer(topLevelType, targetInst, nativeEvent) ? setResponderAndExtractTransfer(topLevelType, targetInst, nativeEvent, nativeEventTarget) : null, isResponderTouchStart = responderInst && isStartish$1(topLevelType), isResponderTouchMove = responderInst && isMoveish$1(topLevelType), isResponderTouchEnd = responderInst && isEndish$1(topLevelType), incrementalTouch = isResponderTouchStart ? eventTypes.responderStart : isResponderTouchMove ? eventTypes.responderMove : isResponderTouchEnd ? eventTypes.responderEnd : null; + if (incrementalTouch) { + var gesture = ResponderSyntheticEvent_1.getPooled(incrementalTouch, responderInst, nativeEvent, nativeEventTarget); + gesture.touchHistory = ResponderTouchHistoryStore_1.touchHistory, EventPropagators_1.accumulateDirectDispatches(gesture), + extracted = accumulate_1(extracted, gesture); + } + var isResponderTerminate = responderInst && "topTouchCancel" === topLevelType, isResponderRelease = responderInst && !isResponderTerminate && isEndish$1(topLevelType) && noResponderTouches(nativeEvent), finalTouch = isResponderTerminate ? eventTypes.responderTerminate : isResponderRelease ? eventTypes.responderRelease : null; + if (finalTouch) { + var finalEvent = ResponderSyntheticEvent_1.getPooled(finalTouch, responderInst, nativeEvent, nativeEventTarget); + finalEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, EventPropagators_1.accumulateDirectDispatches(finalEvent), + extracted = accumulate_1(extracted, finalEvent), changeResponder(null); + } + var numberActiveTouches = ResponderTouchHistoryStore_1.touchHistory.numberActiveTouches; + return ResponderEventPlugin.GlobalInteractionHandler && numberActiveTouches !== previousActiveTouches && ResponderEventPlugin.GlobalInteractionHandler.onChange(numberActiveTouches), + previousActiveTouches = numberActiveTouches, extracted; + }, + GlobalResponderHandler: null, + GlobalInteractionHandler: null, + injection: { + injectGlobalResponderHandler: function(GlobalResponderHandler) { + ResponderEventPlugin.GlobalResponderHandler = GlobalResponderHandler; + }, + injectGlobalInteractionHandler: function(GlobalInteractionHandler) { + ResponderEventPlugin.GlobalInteractionHandler = GlobalInteractionHandler; + } + } +}, ResponderEventPlugin_1 = ResponderEventPlugin; + +function inject() { + RCTEventEmitter.register(ReactNativeEventEmitter_1), EventPluginHub_1.injection.injectEventPluginOrder(ReactNativeEventPluginOrder_1), + EventPluginUtils_1.injection.injectComponentTree(ReactNativeComponentTree_1), ResponderEventPlugin_1.injection.injectGlobalResponderHandler(ReactNativeGlobalResponderHandler_1), + EventPluginHub_1.injection.injectEventPluginsByName({ + ResponderEventPlugin: ResponderEventPlugin_1, + ReactNativeBridgeEventPlugin: ReactNativeBridgeEventPlugin_1 + }); +} + +var ReactNativeInjection = { + inject: inject +}; + +function ReactNativeContainerInfo(tag) { + return { + _tag: tag + }; +} + +var ReactNativeContainerInfo_1 = ReactNativeContainerInfo, ClassComponent = ReactTypeOfWork.ClassComponent; + +function isValidOwner(object) { + return !(!object || "function" != typeof object.attachRef || "function" != typeof object.detachRef); +} + +var ReactOwner = { + addComponentAsRefTo: function(component, ref, owner) { + if (owner && owner.tag === ClassComponent) { + var inst = owner.stateNode; + (inst.refs === emptyObject ? inst.refs = {} : inst.refs)[ref] = component.getPublicInstance(); + } else invariant(isValidOwner(owner), "addComponentAsRefTo(...): Only a ReactOwner can have refs. You might " + "be adding a ref to a component that was not created inside a component's " + "`render` method, or you have multiple copies of React loaded " + "(details: https://fb.me/react-refs-must-have-owner)."), + owner.attachRef(ref, component); + }, + removeComponentAsRefFrom: function(component, ref, owner) { + if (owner && owner.tag === ClassComponent) { + var inst = owner.stateNode; + inst && inst.refs[ref] === component.getPublicInstance() && delete inst.refs[ref]; + } else { + invariant(isValidOwner(owner), "removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might " + "be removing a ref to a component that was not created inside a component's " + "`render` method, or you have multiple copies of React loaded " + "(details: https://fb.me/react-refs-must-have-owner)."); + var ownerPublicInstance = owner.getPublicInstance(); + ownerPublicInstance && ownerPublicInstance.refs[ref] === component.getPublicInstance() && owner.detachRef(ref); + } + } +}, ReactOwner_1 = ReactOwner, ReactRef = {}; + +function attachRef(ref, component, owner) { + "function" == typeof ref ? ref(component.getPublicInstance()) : ReactOwner_1.addComponentAsRefTo(component, ref, owner); +} + +function detachRef(ref, component, owner) { + "function" == typeof ref ? ref(null) : ReactOwner_1.removeComponentAsRefFrom(component, ref, owner); +} + +ReactRef.attachRefs = function(instance, element) { + if (null !== element && "object" == typeof element) { + var ref = element.ref; + null != ref && attachRef(ref, instance, element._owner); + } +}, ReactRef.shouldUpdateRefs = function(prevElement, nextElement) { + var prevRef = null, prevOwner = null; + null !== prevElement && "object" == typeof prevElement && (prevRef = prevElement.ref, + prevOwner = prevElement._owner); + var nextRef = null, nextOwner = null; + return null !== nextElement && "object" == typeof nextElement && (nextRef = nextElement.ref, + nextOwner = nextElement._owner), prevRef !== nextRef || "string" == typeof nextRef && nextOwner !== prevOwner; +}, ReactRef.detachRefs = function(instance, element) { + if (null !== element && "object" == typeof element) { + var ref = element.ref; + null != ref && detachRef(ref, instance, element._owner); + } +}; + +var ReactRef_1 = ReactRef; + +function attachRefs() { + ReactRef_1.attachRefs(this, this._currentElement); +} + +var ReactReconciler = { + mountComponent: function(internalInstance, transaction, hostParent, hostContainerInfo, context, parentDebugID) { + var markup = internalInstance.mountComponent(transaction, hostParent, hostContainerInfo, context, parentDebugID); + return internalInstance._currentElement && null != internalInstance._currentElement.ref && transaction.getReactMountReady().enqueue(attachRefs, internalInstance), + markup; + }, + getHostNode: function(internalInstance) { + return internalInstance.getHostNode(); + }, + unmountComponent: function(internalInstance, safely, skipLifecycle) { + ReactRef_1.detachRefs(internalInstance, internalInstance._currentElement), internalInstance.unmountComponent(safely, skipLifecycle); + }, + receiveComponent: function(internalInstance, nextElement, transaction, context) { + var prevElement = internalInstance._currentElement; + if (nextElement !== prevElement || context !== internalInstance._context) { + var refsChanged = ReactRef_1.shouldUpdateRefs(prevElement, nextElement); + refsChanged && ReactRef_1.detachRefs(internalInstance, prevElement), internalInstance.receiveComponent(nextElement, transaction, context), + refsChanged && internalInstance._currentElement && null != internalInstance._currentElement.ref && transaction.getReactMountReady().enqueue(attachRefs, internalInstance); + } + }, + performUpdateIfNecessary: function(internalInstance, transaction, updateBatchNumber) { + if (internalInstance._updateBatchNumber !== updateBatchNumber) return void warning(null == internalInstance._updateBatchNumber || internalInstance._updateBatchNumber === updateBatchNumber + 1, "performUpdateIfNecessary: Unexpected batch number (current %s, " + "pending %s)", updateBatchNumber, internalInstance._updateBatchNumber); + internalInstance.performUpdateIfNecessary(transaction); + } +}, ReactReconciler_1 = ReactReconciler, ReactInstanceMap = { + remove: function(key) { + key._reactInternalInstance = void 0; + }, + get: function(key) { + return key._reactInternalInstance; + }, + has: function(key) { + return void 0 !== key._reactInternalInstance; + }, + set: function(key, value) { + key._reactInternalInstance = value; + } +}, ReactInstanceMap_1 = ReactInstanceMap, ReactFeatureFlags = { + logTopLevelRenders: !1, + prepareNewChildrenBeforeUnmountInStack: !0, + disableNewFiberFeatures: !1, + enableAsyncSubtreeAPI: !1 +}, ReactFeatureFlags_1 = ReactFeatureFlags, OBSERVED_ERROR = {}, TransactionImpl = { + reinitializeTransaction: function() { + this.transactionWrappers = this.getTransactionWrappers(), this.wrapperInitData ? this.wrapperInitData.length = 0 : this.wrapperInitData = [], + this._isInTransaction = !1; + }, + _isInTransaction: !1, + getTransactionWrappers: null, + isInTransaction: function() { + return !!this._isInTransaction; + }, + perform: function(method, scope, a, b, c, d, e, f) { + invariant(!this.isInTransaction(), "Transaction.perform(...): Cannot initialize a transaction when there " + "is already an outstanding transaction."); + var errorThrown, ret; + try { + this._isInTransaction = !0, errorThrown = !0, this.initializeAll(0), ret = method.call(scope, a, b, c, d, e, f), + errorThrown = !1; + } finally { + try { + if (errorThrown) try { + this.closeAll(0); + } catch (err) {} else this.closeAll(0); + } finally { + this._isInTransaction = !1; + } + } + return ret; + }, + initializeAll: function(startIndex) { + for (var transactionWrappers = this.transactionWrappers, i = startIndex; i < transactionWrappers.length; i++) { + var wrapper = transactionWrappers[i]; + try { + this.wrapperInitData[i] = OBSERVED_ERROR, this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null; + } finally { + if (this.wrapperInitData[i] === OBSERVED_ERROR) try { + this.initializeAll(i + 1); + } catch (err) {} + } + } + }, + closeAll: function(startIndex) { + invariant(this.isInTransaction(), "Transaction.closeAll(): Cannot close transaction when none are open."); + for (var transactionWrappers = this.transactionWrappers, i = startIndex; i < transactionWrappers.length; i++) { + var errorThrown, wrapper = transactionWrappers[i], initData = this.wrapperInitData[i]; + try { + errorThrown = !0, initData !== OBSERVED_ERROR && wrapper.close && wrapper.close.call(this, initData), + errorThrown = !1; + } finally { + if (errorThrown) try { + this.closeAll(i + 1); + } catch (e) {} + } + } + this.wrapperInitData.length = 0; + } +}, Transaction = TransactionImpl, dirtyComponents = [], updateBatchNumber = 0, batchingStrategy = null; + +function ensureInjected() { + invariant(ReactUpdates.ReactReconcileTransaction && batchingStrategy, "ReactUpdates: must inject a reconcile transaction class and batching " + "strategy"); +} + +var NESTED_UPDATES = { + initialize: function() { + this.dirtyComponentsLength = dirtyComponents.length; + }, + close: function() { + this.dirtyComponentsLength !== dirtyComponents.length ? (dirtyComponents.splice(0, this.dirtyComponentsLength), + flushBatchedUpdates()) : dirtyComponents.length = 0; + } +}, TRANSACTION_WRAPPERS = [ NESTED_UPDATES ]; + +function ReactUpdatesFlushTransaction() { + this.reinitializeTransaction(), this.dirtyComponentsLength = null, this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled(!0); +} + +Object.assign(ReactUpdatesFlushTransaction.prototype, Transaction, { + getTransactionWrappers: function() { + return TRANSACTION_WRAPPERS; + }, + destructor: function() { + this.dirtyComponentsLength = null, ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction), + this.reconcileTransaction = null; + }, + perform: function(method, scope, a) { + return Transaction.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a); + } +}), PooledClass_1.addPoolingTo(ReactUpdatesFlushTransaction); + +function batchedUpdates$1(callback, a, b, c, d, e) { + return ensureInjected(), batchingStrategy.batchedUpdates(callback, a, b, c, d, e); +} + +function mountOrderComparator(c1, c2) { + return c1._mountOrder - c2._mountOrder; +} + +function runBatchedUpdates(transaction) { + var len = transaction.dirtyComponentsLength; + invariant(len === dirtyComponents.length, "Expected flush transaction's stored dirty-components length (%s) to " + "match dirty-components array length (%s).", len, dirtyComponents.length), + dirtyComponents.sort(mountOrderComparator), updateBatchNumber++; + for (var i = 0; i < len; i++) { + var markerName, component = dirtyComponents[i]; + if (ReactFeatureFlags_1.logTopLevelRenders) { + var namedComponent = component; + component._currentElement.type.isReactTopLevelWrapper && (namedComponent = component._renderedComponent), + markerName = "React update: " + namedComponent.getName(), console.time(markerName); + } + ReactReconciler_1.performUpdateIfNecessary(component, transaction.reconcileTransaction, updateBatchNumber), + markerName && console.timeEnd(markerName); + } +} + +var flushBatchedUpdates = function() { + for (;dirtyComponents.length; ) { + var transaction = ReactUpdatesFlushTransaction.getPooled(); + transaction.perform(runBatchedUpdates, null, transaction), ReactUpdatesFlushTransaction.release(transaction); + } +}; + +function enqueueUpdate$1(component) { + if (ensureInjected(), !batchingStrategy.isBatchingUpdates) return void batchingStrategy.batchedUpdates(enqueueUpdate$1, component); + dirtyComponents.push(component), null == component._updateBatchNumber && (component._updateBatchNumber = updateBatchNumber + 1); +} + +var ReactUpdatesInjection = { + injectReconcileTransaction: function(ReconcileTransaction) { + invariant(ReconcileTransaction, "ReactUpdates: must provide a reconcile transaction class"), + ReactUpdates.ReactReconcileTransaction = ReconcileTransaction; + }, + injectBatchingStrategy: function(_batchingStrategy) { + invariant(_batchingStrategy, "ReactUpdates: must provide a batching strategy"), + invariant("function" == typeof _batchingStrategy.batchedUpdates, "ReactUpdates: must provide a batchedUpdates() function"), + invariant("boolean" == typeof _batchingStrategy.isBatchingUpdates, "ReactUpdates: must provide an isBatchingUpdates boolean attribute"), + batchingStrategy = _batchingStrategy; + }, + getBatchingStrategy: function() { + return batchingStrategy; + } +}, ReactUpdates = { + ReactReconcileTransaction: null, + batchedUpdates: batchedUpdates$1, + enqueueUpdate: enqueueUpdate$1, + flushBatchedUpdates: flushBatchedUpdates, + injection: ReactUpdatesInjection +}, ReactUpdates_1 = ReactUpdates, ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, ReactGlobalSharedState = { + ReactCurrentOwner: ReactInternals.ReactCurrentOwner +}, ReactGlobalSharedState_1 = ReactGlobalSharedState; + +function enqueueUpdate(internalInstance) { + ReactUpdates_1.enqueueUpdate(internalInstance); +} + +function getInternalInstanceReadyForUpdate(publicInstance, callerName) { + var internalInstance = ReactInstanceMap_1.get(publicInstance); + return internalInstance || null; +} + +var ReactUpdateQueue = { + isMounted: function(publicInstance) { + var internalInstance = ReactInstanceMap_1.get(publicInstance); + return !!internalInstance && !!internalInstance._renderedComponent; + }, + enqueueCallbackInternal: function(internalInstance, callback) { + internalInstance._pendingCallbacks ? internalInstance._pendingCallbacks.push(callback) : internalInstance._pendingCallbacks = [ callback ], + enqueueUpdate(internalInstance); + }, + enqueueForceUpdate: function(publicInstance, callback, callerName) { + var internalInstance = getInternalInstanceReadyForUpdate(publicInstance); + internalInstance && (callback = void 0 === callback ? null : callback, null !== callback && (internalInstance._pendingCallbacks ? internalInstance._pendingCallbacks.push(callback) : internalInstance._pendingCallbacks = [ callback ]), + internalInstance._pendingForceUpdate = !0, enqueueUpdate(internalInstance)); + }, + enqueueReplaceState: function(publicInstance, completeState, callback, callerName) { + var internalInstance = getInternalInstanceReadyForUpdate(publicInstance); + internalInstance && (internalInstance._pendingStateQueue = [ completeState ], internalInstance._pendingReplaceState = !0, + callback = void 0 === callback ? null : callback, null !== callback && (internalInstance._pendingCallbacks ? internalInstance._pendingCallbacks.push(callback) : internalInstance._pendingCallbacks = [ callback ]), + enqueueUpdate(internalInstance)); + }, + enqueueSetState: function(publicInstance, partialState, callback, callerName) { + var internalInstance = getInternalInstanceReadyForUpdate(publicInstance); + if (internalInstance) { + (internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = [])).push(partialState), + callback = void 0 === callback ? null : callback, null !== callback && (internalInstance._pendingCallbacks ? internalInstance._pendingCallbacks.push(callback) : internalInstance._pendingCallbacks = [ callback ]), + enqueueUpdate(internalInstance); + } + }, + enqueueElementInternal: function(internalInstance, nextElement, nextContext) { + internalInstance._pendingElement = nextElement, internalInstance._context = nextContext, + enqueueUpdate(internalInstance); + } +}, ReactUpdateQueue_1 = ReactUpdateQueue, injected = !1, ReactComponentEnvironment = { + replaceNodeWithMarkup: null, + processChildrenUpdates: null, + injection: { + injectEnvironment: function(environment) { + invariant(!injected, "ReactCompositeComponent: injectEnvironment() can only be called once."), + ReactComponentEnvironment.replaceNodeWithMarkup = environment.replaceNodeWithMarkup, + ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates, + injected = !0; + } + } +}, ReactComponentEnvironment_1 = ReactComponentEnvironment, ReactCompositeComponentTypes$1 = { + ImpureClass: 0, + PureClass: 1, + StatelessFunctional: 2 +}, ReactNodeTypes = { + HOST: 0, + COMPOSITE: 1, + EMPTY: 2, + getType: function(node) { + return null === node || !1 === node ? ReactNodeTypes.EMPTY : React.isValidElement(node) ? "function" == typeof node.type ? ReactNodeTypes.COMPOSITE : ReactNodeTypes.HOST : void invariant(!1, "Unexpected node: %s", node); + } +}, ReactNodeTypes_1 = ReactNodeTypes; + +function shouldUpdateReactComponent(prevElement, nextElement) { + var prevEmpty = null === prevElement || !1 === prevElement, nextEmpty = null === nextElement || !1 === nextElement; + if (prevEmpty || nextEmpty) return prevEmpty === nextEmpty; + var prevType = typeof prevElement, nextType = typeof nextElement; + return "string" === prevType || "number" === prevType ? "string" === nextType || "number" === nextType : "object" === nextType && prevElement.type === nextElement.type && prevElement.key === nextElement.key; +} + +var shouldUpdateReactComponent_1 = shouldUpdateReactComponent, ReactCurrentOwner$1 = ReactGlobalSharedState_1.ReactCurrentOwner; + +function StatelessComponent(Component) {} + +StatelessComponent.prototype.render = function() { + return (0, ReactInstanceMap_1.get(this)._currentElement.type)(this.props, this.context, this.updater); +}; + +function shouldConstruct(Component) { + return !(!Component.prototype || !Component.prototype.isReactComponent); +} + +function isPureComponent(Component) { + return !(!Component.prototype || !Component.prototype.isPureReactComponent); +} + +var nextMountID = 1, ReactCompositeComponent = { + construct: function(element) { + this._currentElement = element, this._rootNodeID = 0, this._compositeType = null, + this._instance = null, this._hostParent = null, this._hostContainerInfo = null, + this._updateBatchNumber = null, this._pendingElement = null, this._pendingStateQueue = null, + this._pendingReplaceState = !1, this._pendingForceUpdate = !1, this._renderedNodeType = null, + this._renderedComponent = null, this._context = null, this._mountOrder = 0, this._topLevelWrapper = null, + this._pendingCallbacks = null, this._calledComponentWillUnmount = !1; + }, + mountComponent: function(transaction, hostParent, hostContainerInfo, context) { + this._context = context, this._mountOrder = nextMountID++, this._hostParent = hostParent, + this._hostContainerInfo = hostContainerInfo; + var renderedElement, publicProps = this._currentElement.props, publicContext = this._processContext(context), Component = this._currentElement.type, updateQueue = transaction.getUpdateQueue(), doConstruct = shouldConstruct(Component), inst = this._constructComponent(doConstruct, publicProps, publicContext, updateQueue); + doConstruct || null != inst && null != inst.render ? isPureComponent(Component) ? this._compositeType = ReactCompositeComponentTypes$1.PureClass : this._compositeType = ReactCompositeComponentTypes$1.ImpureClass : (renderedElement = inst, + invariant(null === inst || !1 === inst || React.isValidElement(inst), "%s(...): A valid React element (or null) must be returned. You may have " + "returned undefined, an array or some other invalid object.", Component.displayName || Component.name || "Component"), + inst = new StatelessComponent(Component), this._compositeType = ReactCompositeComponentTypes$1.StatelessFunctional), + inst.props = publicProps, inst.context = publicContext, inst.refs = emptyObject, + inst.updater = updateQueue, this._instance = inst, ReactInstanceMap_1.set(inst, this); + var initialState = inst.state; + void 0 === initialState && (inst.state = initialState = null), invariant("object" == typeof initialState && !Array.isArray(initialState), "%s.state: must be set to an object or null", this.getName() || "ReactCompositeComponent"), + this._pendingStateQueue = null, this._pendingReplaceState = !1, this._pendingForceUpdate = !1, + inst.componentWillMount && (inst.componentWillMount(), this._pendingStateQueue && (inst.state = this._processPendingState(inst.props, inst.context))); + var markup; + markup = inst.unstable_handleError ? this.performInitialMountWithErrorHandling(renderedElement, hostParent, hostContainerInfo, transaction, context) : this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context), + inst.componentDidMount && transaction.getReactMountReady().enqueue(inst.componentDidMount, inst); + var callbacks = this._pendingCallbacks; + if (callbacks) { + this._pendingCallbacks = null; + for (var i = 0; i < callbacks.length; i++) transaction.getReactMountReady().enqueue(callbacks[i], inst); + } + return markup; + }, + _constructComponent: function(doConstruct, publicProps, publicContext, updateQueue) { + return this._constructComponentWithoutOwner(doConstruct, publicProps, publicContext, updateQueue); + }, + _constructComponentWithoutOwner: function(doConstruct, publicProps, publicContext, updateQueue) { + var Component = this._currentElement.type; + return doConstruct ? new Component(publicProps, publicContext, updateQueue) : Component(publicProps, publicContext, updateQueue); + }, + performInitialMountWithErrorHandling: function(renderedElement, hostParent, hostContainerInfo, transaction, context) { + var markup, checkpoint = transaction.checkpoint(); + try { + markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context); + } catch (e) { + transaction.rollback(checkpoint), this._instance.unstable_handleError(e), this._pendingStateQueue && (this._instance.state = this._processPendingState(this._instance.props, this._instance.context)), + checkpoint = transaction.checkpoint(), this._renderedComponent.unmountComponent(!0, !0), + transaction.rollback(checkpoint), markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context); + } + return markup; + }, + performInitialMount: function(renderedElement, hostParent, hostContainerInfo, transaction, context) { + void 0 === renderedElement && (renderedElement = this._renderValidatedComponent()); + var nodeType = ReactNodeTypes_1.getType(renderedElement); + this._renderedNodeType = nodeType; + var child = this._instantiateReactComponent(renderedElement, nodeType !== ReactNodeTypes_1.EMPTY); + return this._renderedComponent = child, ReactReconciler_1.mountComponent(child, transaction, hostParent, hostContainerInfo, this._processChildContext(context), 0); + }, + getHostNode: function() { + return ReactReconciler_1.getHostNode(this._renderedComponent); + }, + unmountComponent: function(safely, skipLifecycle) { + if (this._renderedComponent) { + var inst = this._instance; + if (inst.componentWillUnmount && !inst._calledComponentWillUnmount) if (inst._calledComponentWillUnmount = !0, + safely) { + if (!skipLifecycle) { + var name = this.getName() + ".componentWillUnmount()"; + ReactErrorUtils_1.invokeGuardedCallbackAndCatchFirstError(name, inst.componentWillUnmount, inst); + } + } else inst.componentWillUnmount(); + this._renderedComponent && (ReactReconciler_1.unmountComponent(this._renderedComponent, safely, skipLifecycle), + this._renderedNodeType = null, this._renderedComponent = null, this._instance = null), + this._pendingStateQueue = null, this._pendingReplaceState = !1, this._pendingForceUpdate = !1, + this._pendingCallbacks = null, this._pendingElement = null, this._context = null, + this._rootNodeID = 0, this._topLevelWrapper = null, ReactInstanceMap_1.remove(inst); + } + }, + _maskContext: function(context) { + var Component = this._currentElement.type, contextTypes = Component.contextTypes; + if (!contextTypes) return emptyObject; + var maskedContext = {}; + for (var contextName in contextTypes) maskedContext[contextName] = context[contextName]; + return maskedContext; + }, + _processContext: function(context) { + return this._maskContext(context); + }, + _processChildContext: function(currentContext) { + var childContext, Component = this._currentElement.type, inst = this._instance; + if ("function" == typeof inst.getChildContext) { + childContext = inst.getChildContext(), invariant("object" == typeof Component.childContextTypes, "%s.getChildContext(): childContextTypes must be defined in order to " + "use getChildContext().", this.getName() || "ReactCompositeComponent"); + for (var name in childContext) invariant(name in Component.childContextTypes, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || "ReactCompositeComponent", name); + return Object.assign({}, currentContext, childContext); + } + return currentContext; + }, + _checkContextTypes: function(typeSpecs, values, location) {}, + receiveComponent: function(nextElement, transaction, nextContext) { + var prevElement = this._currentElement, prevContext = this._context; + this._pendingElement = null, this.updateComponent(transaction, prevElement, nextElement, prevContext, nextContext); + }, + performUpdateIfNecessary: function(transaction) { + if (null != this._pendingElement) ReactReconciler_1.receiveComponent(this, this._pendingElement, transaction, this._context); else if (null !== this._pendingStateQueue || this._pendingForceUpdate) this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context); else { + var callbacks = this._pendingCallbacks; + if (this._pendingCallbacks = null, callbacks) for (var j = 0; j < callbacks.length; j++) transaction.getReactMountReady().enqueue(callbacks[j], this.getPublicInstance()); + this._updateBatchNumber = null; + } + }, + updateComponent: function(transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext) { + var inst = this._instance; + invariant(null != inst, "Attempted to update component `%s` that has already been unmounted " + "(or failed to mount).", this.getName() || "ReactCompositeComponent"); + var nextContext, willReceive = !1; + this._context === nextUnmaskedContext ? nextContext = inst.context : (nextContext = this._processContext(nextUnmaskedContext), + willReceive = !0); + var prevProps = prevParentElement.props, nextProps = nextParentElement.props; + if (prevParentElement !== nextParentElement && (willReceive = !0), willReceive && inst.componentWillReceiveProps) { + var beforeState = inst.state; + inst.componentWillReceiveProps(nextProps, nextContext); + var afterState = inst.state; + beforeState !== afterState && (inst.state = beforeState, inst.updater.enqueueReplaceState(inst, afterState)); + } + var callbacks = this._pendingCallbacks; + this._pendingCallbacks = null; + var nextState = this._processPendingState(nextProps, nextContext), shouldUpdate = !0; + if (!this._pendingForceUpdate) { + var prevState = inst.state; + shouldUpdate = willReceive || nextState !== prevState, inst.shouldComponentUpdate ? shouldUpdate = inst.shouldComponentUpdate(nextProps, nextState, nextContext) : this._compositeType === ReactCompositeComponentTypes$1.PureClass && (shouldUpdate = !shallowEqual(prevProps, nextProps) || !shallowEqual(inst.state, nextState)); + } + if (this._updateBatchNumber = null, shouldUpdate ? (this._pendingForceUpdate = !1, + this._performComponentUpdate(nextParentElement, nextProps, nextState, nextContext, transaction, nextUnmaskedContext)) : (this._currentElement = nextParentElement, + this._context = nextUnmaskedContext, inst.props = nextProps, inst.state = nextState, + inst.context = nextContext), callbacks) for (var j = 0; j < callbacks.length; j++) transaction.getReactMountReady().enqueue(callbacks[j], this.getPublicInstance()); + }, + _processPendingState: function(props, context) { + var inst = this._instance, queue = this._pendingStateQueue, replace = this._pendingReplaceState; + if (this._pendingReplaceState = !1, this._pendingStateQueue = null, !queue) return inst.state; + if (replace && 1 === queue.length) return queue[0]; + for (var nextState = replace ? queue[0] : inst.state, dontMutate = !0, i = replace ? 1 : 0; i < queue.length; i++) { + var partial = queue[i], partialState = "function" == typeof partial ? partial.call(inst, nextState, props, context) : partial; + partialState && (dontMutate ? (dontMutate = !1, nextState = Object.assign({}, nextState, partialState)) : Object.assign(nextState, partialState)); + } + return nextState; + }, + _performComponentUpdate: function(nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext) { + var prevProps, prevState, inst = this._instance, hasComponentDidUpdate = !!inst.componentDidUpdate; + hasComponentDidUpdate && (prevProps = inst.props, prevState = inst.state), inst.componentWillUpdate && inst.componentWillUpdate(nextProps, nextState, nextContext), + this._currentElement = nextElement, this._context = unmaskedContext, inst.props = nextProps, + inst.state = nextState, inst.context = nextContext, inst.unstable_handleError ? this._updateRenderedComponentWithErrorHandling(transaction, unmaskedContext) : this._updateRenderedComponent(transaction, unmaskedContext), + hasComponentDidUpdate && transaction.getReactMountReady().enqueue(inst.componentDidUpdate.bind(inst, prevProps, prevState), inst); + }, + _updateRenderedComponentWithErrorHandling: function(transaction, context) { + var checkpoint = transaction.checkpoint(); + try { + this._updateRenderedComponent(transaction, context); + } catch (e) { + transaction.rollback(checkpoint), this._instance.unstable_handleError(e), this._pendingStateQueue && (this._instance.state = this._processPendingState(this._instance.props, this._instance.context)), + checkpoint = transaction.checkpoint(), this._updateRenderedComponentWithNextElement(transaction, context, null, !0), + this._updateRenderedComponent(transaction, context); + } + }, + _updateRenderedComponent: function(transaction, context) { + var nextRenderedElement = this._renderValidatedComponent(); + this._updateRenderedComponentWithNextElement(transaction, context, nextRenderedElement, !1); + }, + _updateRenderedComponentWithNextElement: function(transaction, context, nextRenderedElement, safely) { + var prevComponentInstance = this._renderedComponent, prevRenderedElement = prevComponentInstance._currentElement; + if (shouldUpdateReactComponent_1(prevRenderedElement, nextRenderedElement)) ReactReconciler_1.receiveComponent(prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context)); else { + var oldHostNode = ReactReconciler_1.getHostNode(prevComponentInstance); + ReactFeatureFlags_1.prepareNewChildrenBeforeUnmountInStack || ReactReconciler_1.unmountComponent(prevComponentInstance, safely, !1); + var nodeType = ReactNodeTypes_1.getType(nextRenderedElement); + this._renderedNodeType = nodeType; + var child = this._instantiateReactComponent(nextRenderedElement, nodeType !== ReactNodeTypes_1.EMPTY); + this._renderedComponent = child; + var nextMarkup = ReactReconciler_1.mountComponent(child, transaction, this._hostParent, this._hostContainerInfo, this._processChildContext(context), 0); + ReactFeatureFlags_1.prepareNewChildrenBeforeUnmountInStack && ReactReconciler_1.unmountComponent(prevComponentInstance, safely, !1), + this._replaceNodeWithMarkup(oldHostNode, nextMarkup, prevComponentInstance); + } + }, + _replaceNodeWithMarkup: function(oldHostNode, nextMarkup, prevInstance) { + ReactComponentEnvironment_1.replaceNodeWithMarkup(oldHostNode, nextMarkup, prevInstance); + }, + _renderValidatedComponentWithoutOwnerOrContext: function() { + var inst = this._instance; + return inst.render(); + }, + _renderValidatedComponent: function() { + var renderedElement; + if (1 && this._compositeType === ReactCompositeComponentTypes$1.StatelessFunctional) renderedElement = this._renderValidatedComponentWithoutOwnerOrContext(); else { + ReactCurrentOwner$1.current = this; + try { + renderedElement = this._renderValidatedComponentWithoutOwnerOrContext(); + } finally { + ReactCurrentOwner$1.current = null; + } + } + return invariant(null === renderedElement || !1 === renderedElement || React.isValidElement(renderedElement), "%s.render(): A valid React element (or null) must be returned. You may have " + "returned undefined, an array or some other invalid object.", this.getName() || "ReactCompositeComponent"), + renderedElement; + }, + attachRef: function(ref, component) { + var inst = this.getPublicInstance(); + invariant(null != inst, "Stateless function components cannot have refs."); + var publicComponentInstance = component.getPublicInstance(); + (inst.refs === emptyObject ? inst.refs = {} : inst.refs)[ref] = publicComponentInstance; + }, + detachRef: function(ref) { + delete this.getPublicInstance().refs[ref]; + }, + getName: function() { + var type = this._currentElement.type, constructor = this._instance && this._instance.constructor; + return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null; + }, + getPublicInstance: function() { + var inst = this._instance; + return this._compositeType === ReactCompositeComponentTypes$1.StatelessFunctional ? null : inst; + }, + _instantiateReactComponent: null +}, ReactCompositeComponent_1 = ReactCompositeComponent, emptyComponentFactory, ReactEmptyComponentInjection = { + injectEmptyComponentFactory: function(factory) { + emptyComponentFactory = factory; + } +}, ReactEmptyComponent = { + create: function(instantiate) { + return emptyComponentFactory(instantiate); + } +}; + +ReactEmptyComponent.injection = ReactEmptyComponentInjection; + +var ReactEmptyComponent_1 = ReactEmptyComponent, genericComponentClass = null, textComponentClass = null, ReactHostComponentInjection = { + injectGenericComponentClass: function(componentClass) { + genericComponentClass = componentClass; + }, + injectTextComponentClass: function(componentClass) { + textComponentClass = componentClass; + } +}; + +function createInternalComponent(element) { + return invariant(genericComponentClass, "There is no registered component for the tag %s", element.type), + new genericComponentClass(element); +} + +function createInstanceForText(text) { + return new textComponentClass(text); +} + +function isTextComponent(component) { + return component instanceof textComponentClass; +} + +var ReactHostComponent = { + createInternalComponent: createInternalComponent, + createInstanceForText: createInstanceForText, + isTextComponent: isTextComponent, + injection: ReactHostComponentInjection +}, ReactHostComponent_1 = ReactHostComponent, ReactCompositeComponentWrapper = function(element) { + this.construct(element); +}; + +function getDeclarationErrorAddendum(owner) { + if (owner) { + var name = owner.getName(); + if (name) return "\n\nCheck the render method of `" + name + "`."; + } + return ""; +} + +function isInternalComponentType(type) { + return "function" == typeof type && void 0 !== type.prototype && "function" == typeof type.prototype.mountComponent && "function" == typeof type.prototype.receiveComponent; +} + +function instantiateReactComponent(node, shouldHaveDebugID) { + var instance; + if (null === node || !1 === node) instance = ReactEmptyComponent_1.create(instantiateReactComponent); else if ("object" == typeof node) { + var element = node, type = element.type; + if ("function" != typeof type && "string" != typeof type) { + var info = ""; + info += getDeclarationErrorAddendum(element._owner), invariant(!1, "Element type is invalid: expected a string (for built-in components) " + "or a class/function (for composite components) but got: %s.%s", null == type ? type : typeof type, info); + } + "string" == typeof element.type ? instance = ReactHostComponent_1.createInternalComponent(element) : isInternalComponentType(element.type) ? (instance = new element.type(element), + instance.getHostNode || (instance.getHostNode = instance.getNativeNode)) : instance = new ReactCompositeComponentWrapper(element); + } else "string" == typeof node || "number" == typeof node ? instance = ReactHostComponent_1.createInstanceForText(node) : invariant(!1, "Encountered invalid React node of type %s", typeof node); + return instance._mountIndex = 0, instance._mountImage = null, instance; +} + +Object.assign(ReactCompositeComponentWrapper.prototype, ReactCompositeComponent_1, { + _instantiateReactComponent: instantiateReactComponent +}); + +var instantiateReactComponent_1 = instantiateReactComponent, DevOnlyStubShim = null, ReactNativeFeatureFlags$2 = { + useFiber: !1 +}, ReactNativeFeatureFlags_1 = ReactNativeFeatureFlags$2, ReactNativeFeatureFlags$3 = Object.freeze({ + default: ReactNativeFeatureFlags_1, + __moduleExports: ReactNativeFeatureFlags_1 +}), ReactNativeFeatureFlags$1 = ReactNativeFeatureFlags$3 && ReactNativeFeatureFlags_1 || ReactNativeFeatureFlags$3, injectedFindNode = ReactNativeFeatureFlags$1.useFiber ? function(fiber) { + return DevOnlyStubShim.findHostInstance(fiber); +} : function(instance) { + return instance; +}; + +function findNodeHandle(componentOrHandle) { + if (null == componentOrHandle) return null; + if ("number" == typeof componentOrHandle) return componentOrHandle; + var component = componentOrHandle, internalInstance = ReactInstanceMap_1.get(component); + return internalInstance ? injectedFindNode(internalInstance) : component || (invariant("object" == typeof component && ("_rootNodeID" in component || "_nativeTag" in component) || null != component.render && "function" == typeof component.render, "findNodeHandle(...): Argument is not a component " + "(type: %s, keys: %s)", typeof component, Object.keys(component)), + void invariant(!1, "findNodeHandle(...): Unable to find node handle for unmounted " + "component.")); +} + +var findNodeHandle_1 = findNodeHandle, TopLevelWrapper = function() {}; + +TopLevelWrapper.prototype.isReactComponent = {}, TopLevelWrapper.prototype.render = function() { + return this.props.child; +}, TopLevelWrapper.isReactTopLevelWrapper = !0; + +function mountComponentIntoNode(componentInstance, containerTag, transaction) { + var markup = ReactReconciler_1.mountComponent(componentInstance, transaction, null, ReactNativeContainerInfo_1(containerTag), emptyObject, 0); + componentInstance._renderedComponent._topLevelWrapper = componentInstance, ReactNativeMount._mountImageIntoNode(markup, containerTag); +} + +function batchedMountComponentIntoNode(componentInstance, containerTag) { + var transaction = ReactUpdates_1.ReactReconcileTransaction.getPooled(); + transaction.perform(mountComponentIntoNode, null, componentInstance, containerTag, transaction), + ReactUpdates_1.ReactReconcileTransaction.release(transaction); +} + +var ReactNativeMount = { + _instancesByContainerID: {}, + findNodeHandle: findNodeHandle_1, + renderComponent: function(nextElement, containerTag, callback) { + var nextWrappedElement = React.createElement(TopLevelWrapper, { + child: nextElement + }), topRootNodeID = containerTag, prevComponent = ReactNativeMount._instancesByContainerID[topRootNodeID]; + if (prevComponent) { + var prevWrappedElement = prevComponent._currentElement, prevElement = prevWrappedElement.props.child; + if (shouldUpdateReactComponent_1(prevElement, nextElement)) return ReactUpdateQueue_1.enqueueElementInternal(prevComponent, nextWrappedElement, emptyObject), + callback && ReactUpdateQueue_1.enqueueCallbackInternal(prevComponent, callback), + prevComponent; + ReactNativeMount.unmountComponentAtNode(containerTag); + } + if (!ReactNativeTagHandles_1.reactTagIsNativeTopRootID(containerTag)) return console.error("You cannot render into anything but a top root"), + null; + ReactNativeTagHandles_1.assertRootTag(containerTag); + var instance = instantiateReactComponent_1(nextWrappedElement, !1); + if (ReactNativeMount._instancesByContainerID[containerTag] = instance, callback) { + var nonNullCallback = callback; + instance._pendingCallbacks = [ function() { + nonNullCallback.call(instance._renderedComponent.getPublicInstance()); + } ]; + } + return ReactUpdates_1.batchedUpdates(batchedMountComponentIntoNode, instance, containerTag), + instance._renderedComponent.getPublicInstance(); + }, + _mountImageIntoNode: function(mountImage, containerID) { + var childTag = mountImage; + UIManager.setChildren(containerID, [ childTag ]); + }, + unmountComponentAtNodeAndRemoveContainer: function(containerTag) { + ReactNativeMount.unmountComponentAtNode(containerTag), UIManager.removeRootView(containerTag); + }, + unmountComponentAtNode: function(containerTag) { + if (!ReactNativeTagHandles_1.reactTagIsNativeTopRootID(containerTag)) return console.error("You cannot render into anything but a top root"), + !1; + var instance = ReactNativeMount._instancesByContainerID[containerTag]; + return !!instance && (ReactNativeMount.unmountComponentFromNode(instance, containerTag), + delete ReactNativeMount._instancesByContainerID[containerTag], !0); + }, + unmountComponentFromNode: function(instance, containerID) { + ReactReconciler_1.unmountComponent(instance), UIManager.removeSubviewsFromContainerWithID(containerID); + } +}, ReactNativeMount_1 = ReactNativeMount, RESET_BATCHED_UPDATES = { + initialize: emptyFunction, + close: function() { + ReactDefaultBatchingStrategy.isBatchingUpdates = !1; + } +}, FLUSH_BATCHED_UPDATES = { + initialize: emptyFunction, + close: ReactUpdates_1.flushBatchedUpdates.bind(ReactUpdates_1) +}, TRANSACTION_WRAPPERS$1 = [ FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES ]; + +function ReactDefaultBatchingStrategyTransaction() { + this.reinitializeTransaction(); +} + +Object.assign(ReactDefaultBatchingStrategyTransaction.prototype, Transaction, { + getTransactionWrappers: function() { + return TRANSACTION_WRAPPERS$1; + } +}); + +var transaction = new ReactDefaultBatchingStrategyTransaction(), ReactDefaultBatchingStrategy = { + isBatchingUpdates: !1, + batchedUpdates: function(callback, a, b, c, d, e) { + var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; + return ReactDefaultBatchingStrategy.isBatchingUpdates = !0, alreadyBatchingUpdates ? callback(a, b, c, d, e) : transaction.perform(callback, null, a, b, c, d, e); + } +}, ReactDefaultBatchingStrategy_1 = ReactDefaultBatchingStrategy, dangerouslyProcessChildrenUpdates = function(inst, childrenUpdates) { + if (childrenUpdates.length) { + for (var moveFromIndices, moveToIndices, addChildTags, addAtIndices, removeAtIndices, containerTag = ReactNativeComponentTree_1.getNodeFromInstance(inst), i = 0; i < childrenUpdates.length; i++) { + var update = childrenUpdates[i]; + if ("MOVE_EXISTING" === update.type) (moveFromIndices || (moveFromIndices = [])).push(update.fromIndex), + (moveToIndices || (moveToIndices = [])).push(update.toIndex); else if ("REMOVE_NODE" === update.type) (removeAtIndices || (removeAtIndices = [])).push(update.fromIndex); else if ("INSERT_MARKUP" === update.type) { + var mountImage = update.content, tag = mountImage; + (addAtIndices || (addAtIndices = [])).push(update.toIndex), (addChildTags || (addChildTags = [])).push(tag); + } + } + UIManager.manageChildren(containerTag, moveFromIndices, moveToIndices, addChildTags, addAtIndices, removeAtIndices); + } +}, ReactNativeDOMIDOperations = { + dangerouslyProcessChildrenUpdates: dangerouslyProcessChildrenUpdates, + dangerouslyReplaceNodeWithMarkupByID: function(id, mountImage) { + var oldTag = id; + UIManager.replaceExistingNonRootView(oldTag, mountImage); + } +}, ReactNativeDOMIDOperations_1 = ReactNativeDOMIDOperations; + +function validateCallback(callback) { + invariant(!callback || "function" == typeof callback, "Invalid argument passed as callback. Expected a function. Instead " + "received: %s", callback); +} + +var validateCallback_1 = validateCallback; + +function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); +} + +var CallbackQueue = function() { + function CallbackQueue(arg) { + _classCallCheck(this, CallbackQueue), this._callbacks = null, this._contexts = null, + this._arg = arg; + } + return CallbackQueue.prototype.enqueue = function(callback, context) { + this._callbacks = this._callbacks || [], this._callbacks.push(callback), this._contexts = this._contexts || [], + this._contexts.push(context); + }, CallbackQueue.prototype.notifyAll = function() { + var callbacks = this._callbacks, contexts = this._contexts, arg = this._arg; + if (callbacks && contexts) { + invariant(callbacks.length === contexts.length, "Mismatched list of contexts in callback queue"), + this._callbacks = null, this._contexts = null; + for (var i = 0; i < callbacks.length; i++) validateCallback_1(callbacks[i]), callbacks[i].call(contexts[i], arg); + callbacks.length = 0, contexts.length = 0; + } + }, CallbackQueue.prototype.checkpoint = function() { + return this._callbacks ? this._callbacks.length : 0; + }, CallbackQueue.prototype.rollback = function(len) { + this._callbacks && this._contexts && (this._callbacks.length = len, this._contexts.length = len); + }, CallbackQueue.prototype.reset = function() { + this._callbacks = null, this._contexts = null; + }, CallbackQueue.prototype.destructor = function() { + this.reset(); + }, CallbackQueue; +}(), CallbackQueue_1 = PooledClass_1.addPoolingTo(CallbackQueue), ON_DOM_READY_QUEUEING = { + initialize: function() { + this.reactMountReady.reset(); + }, + close: function() { + this.reactMountReady.notifyAll(); + } +}, TRANSACTION_WRAPPERS$2 = [ ON_DOM_READY_QUEUEING ]; + +function ReactNativeReconcileTransaction() { + this.reinitializeTransaction(), this.reactMountReady = CallbackQueue_1.getPooled(null); +} + +var Mixin = { + getTransactionWrappers: function() { + return TRANSACTION_WRAPPERS$2; + }, + getReactMountReady: function() { + return this.reactMountReady; + }, + getUpdateQueue: function() { + return ReactUpdateQueue_1; + }, + checkpoint: function() { + return this.reactMountReady.checkpoint(); + }, + rollback: function(checkpoint) { + this.reactMountReady.rollback(checkpoint); + }, + destructor: function() { + CallbackQueue_1.release(this.reactMountReady), this.reactMountReady = null; + } +}; + +Object.assign(ReactNativeReconcileTransaction.prototype, Transaction, ReactNativeReconcileTransaction, Mixin), +PooledClass_1.addPoolingTo(ReactNativeReconcileTransaction); + +var ReactNativeReconcileTransaction_1 = ReactNativeReconcileTransaction, ReactNativeComponentEnvironment = { + processChildrenUpdates: ReactNativeDOMIDOperations_1.dangerouslyProcessChildrenUpdates, + replaceNodeWithMarkup: ReactNativeDOMIDOperations_1.dangerouslyReplaceNodeWithMarkupByID, + clearNode: function() {}, + ReactReconcileTransaction: ReactNativeReconcileTransaction_1 +}, ReactNativeComponentEnvironment_1 = ReactNativeComponentEnvironment, ReactNativeTextComponent = function(text) { + this._currentElement = text, this._stringText = "" + text, this._hostParent = null, + this._rootNodeID = 0; +}; + +Object.assign(ReactNativeTextComponent.prototype, { + mountComponent: function(transaction, hostParent, hostContainerInfo, context) { + invariant(context.isInAParentText, 'RawText "%s" must be wrapped in an explicit component.', this._stringText), + this._hostParent = hostParent; + var tag = ReactNativeTagHandles_1.allocateTag(); + this._rootNodeID = tag; + var nativeTopRootTag = hostContainerInfo._tag; + return UIManager.createView(tag, "RCTRawText", nativeTopRootTag, { + text: this._stringText + }), ReactNativeComponentTree_1.precacheNode(this, tag), tag; + }, + getHostNode: function() { + return this._rootNodeID; + }, + receiveComponent: function(nextText, transaction, context) { + if (nextText !== this._currentElement) { + this._currentElement = nextText; + var nextStringText = "" + nextText; + nextStringText !== this._stringText && (this._stringText = nextStringText, UIManager.updateView(this._rootNodeID, "RCTRawText", { + text: this._stringText + })); + } + }, + unmountComponent: function() { + ReactNativeComponentTree_1.uncacheNode(this), this._currentElement = null, this._stringText = null, + this._rootNodeID = 0; + } +}); + +var ReactNativeTextComponent_1 = ReactNativeTextComponent, ReactSimpleEmptyComponent = function(placeholderElement, instantiate) { + this._currentElement = null, this._renderedComponent = instantiate(placeholderElement); +}; + +Object.assign(ReactSimpleEmptyComponent.prototype, { + mountComponent: function(transaction, hostParent, hostContainerInfo, context, parentDebugID) { + return ReactReconciler_1.mountComponent(this._renderedComponent, transaction, hostParent, hostContainerInfo, context, parentDebugID); + }, + receiveComponent: function() {}, + getHostNode: function() { + return ReactReconciler_1.getHostNode(this._renderedComponent); + }, + unmountComponent: function(safely, skipLifecycle) { + ReactReconciler_1.unmountComponent(this._renderedComponent, safely, skipLifecycle), + this._renderedComponent = null; + } +}); + +var ReactSimpleEmptyComponent_1 = ReactSimpleEmptyComponent; + +function inject$1() { + ReactGenericBatching_1.injection.injectStackBatchedUpdates(ReactUpdates_1.batchedUpdates), + ReactUpdates_1.injection.injectReconcileTransaction(ReactNativeComponentEnvironment_1.ReactReconcileTransaction), + ReactUpdates_1.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy_1), + ReactComponentEnvironment_1.injection.injectEnvironment(ReactNativeComponentEnvironment_1); + var EmptyComponent = function(instantiate) { + var View = require("View"); + return new ReactSimpleEmptyComponent_1(React.createElement(View, { + collapsable: !0, + style: { + position: "absolute" + } + }), instantiate); + }; + ReactEmptyComponent_1.injection.injectEmptyComponentFactory(EmptyComponent), ReactHostComponent_1.injection.injectTextComponentClass(ReactNativeTextComponent_1), + ReactHostComponent_1.injection.injectGenericComponentClass(function(tag) { + var info = ""; + "string" == typeof tag && /^[a-z]/.test(tag) && (info += " Each component name should start with an uppercase letter."), + invariant(!1, "Expected a component class, got %s.%s", tag, info); + }); +} + +var ReactNativeStackInjection = { + inject: inject$1 +}, getInspectorDataForViewTag = void 0; + +getInspectorDataForViewTag = function() { + invariant(!1, "getInspectorDataForViewTag() is not available in production"); +}; + +var ReactNativeStackInspector = { + getInspectorDataForViewTag: getInspectorDataForViewTag +}, findNumericNodeHandleStack = function(componentOrHandle) { + var nodeHandle = findNodeHandle_1(componentOrHandle); + return null == nodeHandle || "number" == typeof nodeHandle ? nodeHandle : nodeHandle.getHostNode(); +}; + +function _classCallCheck$1(instance, Constructor) { + if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); +} + +var objects = {}, uniqueID = 1, emptyObject$3 = {}, ReactNativePropRegistry = function() { + function ReactNativePropRegistry() { + _classCallCheck$1(this, ReactNativePropRegistry); + } + return ReactNativePropRegistry.register = function(object) { + var id = ++uniqueID; + return objects[id] = object, id; + }, ReactNativePropRegistry.getByID = function(id) { + if (!id) return emptyObject$3; + var object = objects[id]; + return object || (console.warn("Invalid style with id `" + id + "`. Skipping ..."), + emptyObject$3); + }, ReactNativePropRegistry; +}(), ReactNativePropRegistry_1 = ReactNativePropRegistry, emptyObject$2 = {}, removedKeys = null, removedKeyCount = 0; + +function defaultDiffer(prevProp, nextProp) { + return "object" != typeof nextProp || null === nextProp || deepDiffer(prevProp, nextProp); +} + +function resolveObject(idOrObject) { + return "number" == typeof idOrObject ? ReactNativePropRegistry_1.getByID(idOrObject) : idOrObject; +} + +function restoreDeletedValuesInNestedArray(updatePayload, node, validAttributes) { + if (Array.isArray(node)) for (var i = node.length; i-- && removedKeyCount > 0; ) restoreDeletedValuesInNestedArray(updatePayload, node[i], validAttributes); else if (node && removedKeyCount > 0) { + var obj = resolveObject(node); + for (var propKey in removedKeys) if (removedKeys[propKey]) { + var nextProp = obj[propKey]; + if (void 0 !== nextProp) { + var attributeConfig = validAttributes[propKey]; + if (attributeConfig) { + if ("function" == typeof nextProp && (nextProp = !0), void 0 === nextProp && (nextProp = null), + "object" != typeof attributeConfig) updatePayload[propKey] = nextProp; else if ("function" == typeof attributeConfig.diff || "function" == typeof attributeConfig.process) { + var nextValue = "function" == typeof attributeConfig.process ? attributeConfig.process(nextProp) : nextProp; + updatePayload[propKey] = nextValue; + } + removedKeys[propKey] = !1, removedKeyCount--; + } + } + } + } +} + +function diffNestedArrayProperty(updatePayload, prevArray, nextArray, validAttributes) { + var i, minLength = prevArray.length < nextArray.length ? prevArray.length : nextArray.length; + for (i = 0; i < minLength; i++) updatePayload = diffNestedProperty(updatePayload, prevArray[i], nextArray[i], validAttributes); + for (;i < prevArray.length; i++) updatePayload = clearNestedProperty(updatePayload, prevArray[i], validAttributes); + for (;i < nextArray.length; i++) updatePayload = addNestedProperty(updatePayload, nextArray[i], validAttributes); + return updatePayload; +} + +function diffNestedProperty(updatePayload, prevProp, nextProp, validAttributes) { + return updatePayload || prevProp !== nextProp ? prevProp && nextProp ? Array.isArray(prevProp) || Array.isArray(nextProp) ? Array.isArray(prevProp) && Array.isArray(nextProp) ? diffNestedArrayProperty(updatePayload, prevProp, nextProp, validAttributes) : Array.isArray(prevProp) ? diffProperties(updatePayload, flattenStyle(prevProp), resolveObject(nextProp), validAttributes) : diffProperties(updatePayload, resolveObject(prevProp), flattenStyle(nextProp), validAttributes) : diffProperties(updatePayload, resolveObject(prevProp), resolveObject(nextProp), validAttributes) : nextProp ? addNestedProperty(updatePayload, nextProp, validAttributes) : prevProp ? clearNestedProperty(updatePayload, prevProp, validAttributes) : updatePayload : updatePayload; +} + +function addNestedProperty(updatePayload, nextProp, validAttributes) { + if (!nextProp) return updatePayload; + if (!Array.isArray(nextProp)) return addProperties(updatePayload, resolveObject(nextProp), validAttributes); + for (var i = 0; i < nextProp.length; i++) updatePayload = addNestedProperty(updatePayload, nextProp[i], validAttributes); + return updatePayload; +} + +function clearNestedProperty(updatePayload, prevProp, validAttributes) { + if (!prevProp) return updatePayload; + if (!Array.isArray(prevProp)) return clearProperties(updatePayload, resolveObject(prevProp), validAttributes); + for (var i = 0; i < prevProp.length; i++) updatePayload = clearNestedProperty(updatePayload, prevProp[i], validAttributes); + return updatePayload; +} + +function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { + var attributeConfig, nextProp, prevProp; + for (var propKey in nextProps) if (attributeConfig = validAttributes[propKey]) if (prevProp = prevProps[propKey], + nextProp = nextProps[propKey], "function" == typeof nextProp && (nextProp = !0, + "function" == typeof prevProp && (prevProp = !0)), void 0 === nextProp && (nextProp = null, + void 0 === prevProp && (prevProp = null)), removedKeys && (removedKeys[propKey] = !1), + updatePayload && void 0 !== updatePayload[propKey]) { + if ("object" != typeof attributeConfig) updatePayload[propKey] = nextProp; else if ("function" == typeof attributeConfig.diff || "function" == typeof attributeConfig.process) { + var nextValue = "function" == typeof attributeConfig.process ? attributeConfig.process(nextProp) : nextProp; + updatePayload[propKey] = nextValue; + } + } else if (prevProp !== nextProp) if ("object" != typeof attributeConfig) defaultDiffer(prevProp, nextProp) && ((updatePayload || (updatePayload = {}))[propKey] = nextProp); else if ("function" == typeof attributeConfig.diff || "function" == typeof attributeConfig.process) { + var shouldUpdate = void 0 === prevProp || ("function" == typeof attributeConfig.diff ? attributeConfig.diff(prevProp, nextProp) : defaultDiffer(prevProp, nextProp)); + shouldUpdate && (nextValue = "function" == typeof attributeConfig.process ? attributeConfig.process(nextProp) : nextProp, + (updatePayload || (updatePayload = {}))[propKey] = nextValue); + } else removedKeys = null, removedKeyCount = 0, updatePayload = diffNestedProperty(updatePayload, prevProp, nextProp, attributeConfig), + removedKeyCount > 0 && updatePayload && (restoreDeletedValuesInNestedArray(updatePayload, nextProp, attributeConfig), + removedKeys = null); + for (propKey in prevProps) void 0 === nextProps[propKey] && (attributeConfig = validAttributes[propKey]) && (updatePayload && void 0 !== updatePayload[propKey] || void 0 !== (prevProp = prevProps[propKey]) && ("object" != typeof attributeConfig || "function" == typeof attributeConfig.diff || "function" == typeof attributeConfig.process ? ((updatePayload || (updatePayload = {}))[propKey] = null, + removedKeys || (removedKeys = {}), removedKeys[propKey] || (removedKeys[propKey] = !0, + removedKeyCount++)) : updatePayload = clearNestedProperty(updatePayload, prevProp, attributeConfig))); + return updatePayload; +} + +function addProperties(updatePayload, props, validAttributes) { + return diffProperties(updatePayload, emptyObject$2, props, validAttributes); +} + +function clearProperties(updatePayload, prevProps, validAttributes) { + return diffProperties(updatePayload, prevProps, emptyObject$2, validAttributes); +} + +var ReactNativeAttributePayload = { + create: function(props, validAttributes) { + return addProperties(null, props, validAttributes); + }, + diff: function(prevProps, nextProps, validAttributes) { + return diffProperties(null, prevProps, nextProps, validAttributes); + } +}, ReactNativeAttributePayload_1 = ReactNativeAttributePayload; + +function mountSafeCallback$1(context, callback) { + return function() { + if (callback) { + if ("boolean" == typeof context.__isMounted) { + if (!context.__isMounted) return; + } else if ("function" == typeof context.isMounted && !context.isMounted()) return; + return callback.apply(context, arguments); + } + }; +} + +function throwOnStylesProp$1(component, props) { + if (void 0 !== props.styles) { + var owner = component._owner || null, name = component.constructor.displayName, msg = "`styles` is not a supported property of `" + name + "`, did " + "you mean `style` (singular)?"; + throw owner && owner.constructor && owner.constructor.displayName && (msg += "\n\nCheck the `" + owner.constructor.displayName + "` parent " + " component."), + new Error(msg); + } +} + +function warnForStyleProps$1(props, validAttributes) { + for (var key in validAttributes.style) validAttributes[key] || void 0 === props[key] || console.error("You are setting the style `{ " + key + ": ... }` as a prop. You " + "should nest it in a style object. " + "E.g. `{ style: { " + key + ": ... } }`"); +} + +var NativeMethodsMixinUtils = { + mountSafeCallback: mountSafeCallback$1, + throwOnStylesProp: throwOnStylesProp$1, + warnForStyleProps: warnForStyleProps$1 +}, mountSafeCallback = NativeMethodsMixinUtils.mountSafeCallback, findNumericNodeHandle = ReactNativeFeatureFlags$1.useFiber ? DevOnlyStubShim : findNumericNodeHandleStack, NativeMethodsMixin = { + measure: function(callback) { + UIManager.measure(findNumericNodeHandle(this), mountSafeCallback(this, callback)); + }, + measureInWindow: function(callback) { + UIManager.measureInWindow(findNumericNodeHandle(this), mountSafeCallback(this, callback)); + }, + measureLayout: function(relativeToNativeNode, onSuccess, onFail) { + UIManager.measureLayout(findNumericNodeHandle(this), relativeToNativeNode, mountSafeCallback(this, onFail), mountSafeCallback(this, onSuccess)); + }, + setNativeProps: function(nativeProps) { + injectedSetNativeProps(this, nativeProps); + }, + focus: function() { + TextInputState.focusTextInput(findNumericNodeHandle(this)); + }, + blur: function() { + TextInputState.blurTextInput(findNumericNodeHandle(this)); + } +}; + +function setNativePropsFiber(componentOrHandle, nativeProps) { + var maybeInstance = void 0; + try { + maybeInstance = findNodeHandle_1(componentOrHandle); + } catch (error) {} + if (null != maybeInstance) { + var viewConfig = maybeInstance.viewConfig, updatePayload = ReactNativeAttributePayload_1.create(nativeProps, viewConfig.validAttributes); + UIManager.updateView(maybeInstance._nativeTag, viewConfig.uiViewClassName, updatePayload); + } +} + +function setNativePropsStack(componentOrHandle, nativeProps) { + var maybeInstance = findNodeHandle_1(componentOrHandle); + if (null != maybeInstance) { + var viewConfig = void 0; + if (void 0 !== maybeInstance.viewConfig) viewConfig = maybeInstance.viewConfig; else if (void 0 !== maybeInstance._instance && void 0 !== maybeInstance._instance.viewConfig) viewConfig = maybeInstance._instance.viewConfig; else { + for (;void 0 !== maybeInstance._renderedComponent; ) maybeInstance = maybeInstance._renderedComponent; + viewConfig = maybeInstance.viewConfig; + } + var tag = "function" == typeof maybeInstance.getHostNode ? maybeInstance.getHostNode() : maybeInstance._rootNodeID, updatePayload = ReactNativeAttributePayload_1.create(nativeProps, viewConfig.validAttributes); + UIManager.updateView(tag, viewConfig.uiViewClassName, updatePayload); + } +} + +var injectedSetNativeProps = void 0; + +injectedSetNativeProps = ReactNativeFeatureFlags$1.useFiber ? setNativePropsFiber : setNativePropsStack; + +var NativeMethodsMixin_1 = NativeMethodsMixin, TouchHistoryMath = { + centroidDimension: function(touchHistory, touchesChangedAfter, isXAxis, ofCurrent) { + var touchBank = touchHistory.touchBank, total = 0, count = 0, oneTouchData = 1 === touchHistory.numberActiveTouches ? touchHistory.touchBank[touchHistory.indexOfSingleActiveTouch] : null; + if (null !== oneTouchData) oneTouchData.touchActive && oneTouchData.currentTimeStamp > touchesChangedAfter && (total += ofCurrent && isXAxis ? oneTouchData.currentPageX : ofCurrent && !isXAxis ? oneTouchData.currentPageY : !ofCurrent && isXAxis ? oneTouchData.previousPageX : oneTouchData.previousPageY, + count = 1); else for (var i = 0; i < touchBank.length; i++) { + var touchTrack = touchBank[i]; + if (null !== touchTrack && void 0 !== touchTrack && touchTrack.touchActive && touchTrack.currentTimeStamp >= touchesChangedAfter) { + var toAdd; + toAdd = ofCurrent && isXAxis ? touchTrack.currentPageX : ofCurrent && !isXAxis ? touchTrack.currentPageY : !ofCurrent && isXAxis ? touchTrack.previousPageX : touchTrack.previousPageY, + total += toAdd, count++; + } + } + return count > 0 ? total / count : TouchHistoryMath.noCentroid; + }, + currentCentroidXOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) { + return TouchHistoryMath.centroidDimension(touchHistory, touchesChangedAfter, !0, !0); + }, + currentCentroidYOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) { + return TouchHistoryMath.centroidDimension(touchHistory, touchesChangedAfter, !1, !0); + }, + previousCentroidXOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) { + return TouchHistoryMath.centroidDimension(touchHistory, touchesChangedAfter, !0, !1); + }, + previousCentroidYOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) { + return TouchHistoryMath.centroidDimension(touchHistory, touchesChangedAfter, !1, !1); + }, + currentCentroidX: function(touchHistory) { + return TouchHistoryMath.centroidDimension(touchHistory, 0, !0, !0); + }, + currentCentroidY: function(touchHistory) { + return TouchHistoryMath.centroidDimension(touchHistory, 0, !1, !0); + }, + noCentroid: -1 +}, TouchHistoryMath_1 = TouchHistoryMath; + +function escape(key) { + var escaperLookup = { + "=": "=0", + ":": "=2" + }; + return "$" + ("" + key).replace(/[=:]/g, function(match) { + return escaperLookup[match]; + }); +} + +function unescape(key) { + var unescapeRegex = /(=0|=2)/g, unescaperLookup = { + "=0": "=", + "=2": ":" + }; + return ("" + ("." === key[0] && "$" === key[1] ? key.substring(2) : key.substring(1))).replace(unescapeRegex, function(match) { + return unescaperLookup[match]; + }); +} + +var KeyEscapeUtils = { + escape: escape, + unescape: unescape +}, KeyEscapeUtils_1 = KeyEscapeUtils, REACT_ELEMENT_TYPE = "function" == typeof Symbol && Symbol.for && Symbol.for("react.element") || 60103, ReactElementSymbol = REACT_ELEMENT_TYPE, ITERATOR_SYMBOL = "function" == typeof Symbol && Symbol.iterator, FAUX_ITERATOR_SYMBOL = "@@iterator"; + +function getIteratorFn(maybeIterable) { + var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); + if ("function" == typeof iteratorFn) return iteratorFn; +} + +var getIteratorFn_1 = getIteratorFn, SEPARATOR = ".", SUBSEPARATOR = ":"; + +function getComponentKey(component, index) { + return component && "object" == typeof component && null != component.key ? KeyEscapeUtils_1.escape(component.key) : index.toString(36); +} + +function traverseStackChildrenImpl(children, nameSoFar, callback, traverseContext) { + var type = typeof children; + if ("undefined" !== type && "boolean" !== type || (children = null), null === children || "string" === type || "number" === type || "object" === type && children.$$typeof === ReactElementSymbol) return callback(traverseContext, children, "" === nameSoFar ? SEPARATOR + getComponentKey(children, 0) : nameSoFar), + 1; + var child, nextName, subtreeCount = 0, nextNamePrefix = "" === nameSoFar ? SEPARATOR : nameSoFar + SUBSEPARATOR; + if (Array.isArray(children)) for (var i = 0; i < children.length; i++) child = children[i], + nextName = nextNamePrefix + getComponentKey(child, i), subtreeCount += traverseStackChildrenImpl(child, nextName, callback, traverseContext); else { + var iteratorFn = getIteratorFn_1(children); + if (iteratorFn) for (var step, iterator = iteratorFn.call(children), ii = 0; !(step = iterator.next()).done; ) child = step.value, + nextName = nextNamePrefix + getComponentKey(child, ii++), subtreeCount += traverseStackChildrenImpl(child, nextName, callback, traverseContext); else if ("object" === type) { + var addendum = "", childrenString = "" + children; + invariant(!1, "Objects are not valid as a React child (found: %s).%s", "[object Object]" === childrenString ? "object with keys {" + Object.keys(children).join(", ") + "}" : childrenString, addendum); + } + } + return subtreeCount; +} + +function traverseStackChildren(children, callback, traverseContext) { + return null == children ? 0 : traverseStackChildrenImpl(children, "", callback, traverseContext); +} + +var traverseStackChildren_1 = traverseStackChildren, ReactComponentTreeHook$1; + +"undefined" != typeof process && process.env && "production" == "test" && (ReactComponentTreeHook$1 = ReactGlobalSharedState_1.ReactComponentTreeHook); + +function instantiateChild(childInstances, child, name, selfDebugID) { + var keyUnique = void 0 === childInstances[name]; + null != child && keyUnique && (childInstances[name] = instantiateReactComponent_1(child, !0)); +} + +var ReactChildReconciler = { + instantiateChildren: function(nestedChildNodes, transaction, context, selfDebugID) { + if (null == nestedChildNodes) return null; + var childInstances = {}; + return traverseStackChildren_1(nestedChildNodes, instantiateChild, childInstances), + childInstances; + }, + updateChildren: function(prevChildren, nextChildren, mountImages, removedNodes, transaction, hostParent, hostContainerInfo, context, selfDebugID) { + if (nextChildren || prevChildren) { + var name, prevChild; + for (name in nextChildren) if (nextChildren.hasOwnProperty(name)) { + prevChild = prevChildren && prevChildren[name]; + var prevElement = prevChild && prevChild._currentElement, nextElement = nextChildren[name]; + if (null != prevChild && shouldUpdateReactComponent_1(prevElement, nextElement)) ReactReconciler_1.receiveComponent(prevChild, nextElement, transaction, context), + nextChildren[name] = prevChild; else { + !ReactFeatureFlags_1.prepareNewChildrenBeforeUnmountInStack && prevChild && (removedNodes[name] = ReactReconciler_1.getHostNode(prevChild), + ReactReconciler_1.unmountComponent(prevChild, !1, !1)); + var nextChildInstance = instantiateReactComponent_1(nextElement, !0); + nextChildren[name] = nextChildInstance; + var nextChildMountImage = ReactReconciler_1.mountComponent(nextChildInstance, transaction, hostParent, hostContainerInfo, context, selfDebugID); + mountImages.push(nextChildMountImage), ReactFeatureFlags_1.prepareNewChildrenBeforeUnmountInStack && prevChild && (removedNodes[name] = ReactReconciler_1.getHostNode(prevChild), + ReactReconciler_1.unmountComponent(prevChild, !1, !1)); + } + } + for (name in prevChildren) !prevChildren.hasOwnProperty(name) || nextChildren && nextChildren.hasOwnProperty(name) || (prevChild = prevChildren[name], + removedNodes[name] = ReactReconciler_1.getHostNode(prevChild), ReactReconciler_1.unmountComponent(prevChild, !1, !1)); + } + }, + unmountChildren: function(renderedChildren, safely, skipLifecycle) { + for (var name in renderedChildren) if (renderedChildren.hasOwnProperty(name)) { + var renderedChild = renderedChildren[name]; + ReactReconciler_1.unmountComponent(renderedChild, safely, skipLifecycle); + } + } +}, ReactChildReconciler_1 = ReactChildReconciler, ReactComponentTreeHook$2; + +"undefined" != typeof process && process.env && "production" == "test" && (ReactComponentTreeHook$2 = ReactGlobalSharedState_1.ReactComponentTreeHook); + +function flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID) { + if (traverseContext && "object" == typeof traverseContext) { + var result = traverseContext; + void 0 === result[name] && null != child && (result[name] = child); + } +} + +function flattenStackChildren(children, selfDebugID) { + if (null == children) return children; + var result = {}; + return traverseStackChildren_1(children, flattenSingleChildIntoContext, result), + result; +} + +var flattenStackChildren_1 = flattenStackChildren; + +function makeInsertMarkup(markup, afterNode, toIndex) { + return { + type: "INSERT_MARKUP", + content: markup, + fromIndex: null, + fromNode: null, + toIndex: toIndex, + afterNode: afterNode + }; +} + +function makeMove(child, afterNode, toIndex) { + return { + type: "MOVE_EXISTING", + content: null, + fromIndex: child._mountIndex, + fromNode: ReactReconciler_1.getHostNode(child), + toIndex: toIndex, + afterNode: afterNode + }; +} + +function makeRemove(child, node) { + return { + type: "REMOVE_NODE", + content: null, + fromIndex: child._mountIndex, + fromNode: node, + toIndex: null, + afterNode: null + }; +} + +function makeSetMarkup(markup) { + return { + type: "SET_MARKUP", + content: markup, + fromIndex: null, + fromNode: null, + toIndex: null, + afterNode: null + }; +} + +function makeTextContent(textContent) { + return { + type: "TEXT_CONTENT", + content: textContent, + fromIndex: null, + fromNode: null, + toIndex: null, + afterNode: null + }; +} + +function enqueue(queue, update) { + return update && (queue = queue || [], queue.push(update)), queue; +} + +function processQueue(inst, updateQueue) { + ReactComponentEnvironment_1.processChildrenUpdates(inst, updateQueue); +} + +var ReactMultiChild = { + _reconcilerInstantiateChildren: function(nestedChildren, transaction, context) { + return ReactChildReconciler_1.instantiateChildren(nestedChildren, transaction, context); + }, + _reconcilerUpdateChildren: function(prevChildren, nextNestedChildrenElements, mountImages, removedNodes, transaction, context) { + var nextChildren, selfDebugID = 0; + return nextChildren = flattenStackChildren_1(nextNestedChildrenElements, selfDebugID), + ReactChildReconciler_1.updateChildren(prevChildren, nextChildren, mountImages, removedNodes, transaction, this, this._hostContainerInfo, context, selfDebugID), + nextChildren; + }, + mountChildren: function(nestedChildren, transaction, context) { + var children = this._reconcilerInstantiateChildren(nestedChildren, transaction, context); + this._renderedChildren = children; + var mountImages = [], index = 0; + for (var name in children) if (children.hasOwnProperty(name)) { + var child = children[name], selfDebugID = 0, mountImage = ReactReconciler_1.mountComponent(child, transaction, this, this._hostContainerInfo, context, selfDebugID); + child._mountIndex = index++, mountImages.push(mountImage); + } + return mountImages; + }, + updateTextContent: function(nextContent) { + var prevChildren = this._renderedChildren; + ReactChildReconciler_1.unmountChildren(prevChildren, !1, !1); + for (var name in prevChildren) prevChildren.hasOwnProperty(name) && invariant(!1, "updateTextContent called on non-empty component."); + processQueue(this, [ makeTextContent(nextContent) ]); + }, + updateMarkup: function(nextMarkup) { + var prevChildren = this._renderedChildren; + ReactChildReconciler_1.unmountChildren(prevChildren, !1, !1); + for (var name in prevChildren) prevChildren.hasOwnProperty(name) && invariant(!1, "updateTextContent called on non-empty component."); + processQueue(this, [ makeSetMarkup(nextMarkup) ]); + }, + updateChildren: function(nextNestedChildrenElements, transaction, context) { + this._updateChildren(nextNestedChildrenElements, transaction, context); + }, + _updateChildren: function(nextNestedChildrenElements, transaction, context) { + var prevChildren = this._renderedChildren, removedNodes = {}, mountImages = [], nextChildren = this._reconcilerUpdateChildren(prevChildren, nextNestedChildrenElements, mountImages, removedNodes, transaction, context); + if (nextChildren || prevChildren) { + var name, updates = null, nextIndex = 0, lastIndex = 0, nextMountIndex = 0, lastPlacedNode = null; + for (name in nextChildren) if (nextChildren.hasOwnProperty(name)) { + var prevChild = prevChildren && prevChildren[name], nextChild = nextChildren[name]; + prevChild === nextChild ? (updates = enqueue(updates, this.moveChild(prevChild, lastPlacedNode, nextIndex, lastIndex)), + lastIndex = Math.max(prevChild._mountIndex, lastIndex), prevChild._mountIndex = nextIndex) : (prevChild && (lastIndex = Math.max(prevChild._mountIndex, lastIndex)), + updates = enqueue(updates, this._mountChildAtIndex(nextChild, mountImages[nextMountIndex], lastPlacedNode, nextIndex, transaction, context)), + nextMountIndex++), nextIndex++, lastPlacedNode = ReactReconciler_1.getHostNode(nextChild); + } + for (name in removedNodes) removedNodes.hasOwnProperty(name) && (updates = enqueue(updates, this._unmountChild(prevChildren[name], removedNodes[name]))); + updates && processQueue(this, updates), this._renderedChildren = nextChildren; + } + }, + unmountChildren: function(safely, skipLifecycle) { + var renderedChildren = this._renderedChildren; + ReactChildReconciler_1.unmountChildren(renderedChildren, safely, skipLifecycle), + this._renderedChildren = null; + }, + moveChild: function(child, afterNode, toIndex, lastIndex) { + if (child._mountIndex < lastIndex) return makeMove(child, afterNode, toIndex); + }, + createChild: function(child, afterNode, mountImage) { + return makeInsertMarkup(mountImage, afterNode, child._mountIndex); + }, + removeChild: function(child, node) { + return makeRemove(child, node); + }, + _mountChildAtIndex: function(child, mountImage, afterNode, index, transaction, context) { + return child._mountIndex = index, this.createChild(child, afterNode, mountImage); + }, + _unmountChild: function(child, node) { + var update = this.removeChild(child, node); + return child._mountIndex = null, update; + } +}, ReactMultiChild_1 = ReactMultiChild, ReactNativeBaseComponent = function(viewConfig) { + this.viewConfig = viewConfig; +}; + +ReactNativeBaseComponent.Mixin = { + getPublicInstance: function() { + return this; + }, + unmountComponent: function(safely, skipLifecycle) { + ReactNativeComponentTree_1.uncacheNode(this), this.unmountChildren(safely, skipLifecycle), + this._rootNodeID = 0; + }, + initializeChildren: function(children, containerTag, transaction, context) { + var mountImages = this.mountChildren(children, transaction, context); + if (mountImages.length) { + for (var createdTags = [], i = 0, l = mountImages.length; i < l; i++) { + var mountImage = mountImages[i], childTag = mountImage; + createdTags[i] = childTag; + } + UIManager.setChildren(containerTag, createdTags); + } + }, + receiveComponent: function(nextElement, transaction, context) { + var prevElement = this._currentElement; + this._currentElement = nextElement; + var updatePayload = ReactNativeAttributePayload_1.diff(prevElement.props, nextElement.props, this.viewConfig.validAttributes); + updatePayload && UIManager.updateView(this._rootNodeID, this.viewConfig.uiViewClassName, updatePayload), + this.updateChildren(nextElement.props.children, transaction, context); + }, + getHostNode: function() { + return this._rootNodeID; + }, + mountComponent: function(transaction, hostParent, hostContainerInfo, context) { + var tag = ReactNativeTagHandles_1.allocateTag(); + this._rootNodeID = tag, this._hostParent = hostParent, this._hostContainerInfo = hostContainerInfo; + var updatePayload = ReactNativeAttributePayload_1.create(this._currentElement.props, this.viewConfig.validAttributes), nativeTopRootTag = hostContainerInfo._tag; + return UIManager.createView(tag, this.viewConfig.uiViewClassName, nativeTopRootTag, updatePayload), + ReactNativeComponentTree_1.precacheNode(this, tag), this.initializeChildren(this._currentElement.props.children, tag, transaction, context), + tag; + } +}, Object.assign(ReactNativeBaseComponent.prototype, ReactMultiChild_1, ReactNativeBaseComponent.Mixin, NativeMethodsMixin_1); + +var ReactNativeBaseComponent_1 = ReactNativeBaseComponent, createReactNativeComponentClassStack = function(viewConfig) { + var Constructor = function(element) { + this._currentElement = element, this._topLevelWrapper = null, this._hostParent = null, + this._hostContainerInfo = null, this._rootNodeID = 0, this._renderedChildren = null; + }; + return Constructor.displayName = viewConfig.uiViewClassName, Constructor.viewConfig = viewConfig, + Constructor.propTypes = viewConfig.propTypes, Constructor.prototype = new ReactNativeBaseComponent_1(viewConfig), + Constructor.prototype.constructor = Constructor, Constructor; +}, createReactNativeComponentClassStack_1 = createReactNativeComponentClassStack, createReactNativeComponentClass = ReactNativeFeatureFlags$1.useFiber ? DevOnlyStubShim : createReactNativeComponentClassStack_1, findNumericNodeHandle$1 = ReactNativeFeatureFlags$1.useFiber ? DevOnlyStubShim : findNumericNodeHandleStack; + +function takeSnapshot(view, options) { + return "number" != typeof view && "window" !== view && (view = findNumericNodeHandle$1(view) || "window"), + UIManager.__takeSnapshot(view, options); +} + +var takeSnapshot_1 = takeSnapshot; + +ReactNativeInjection.inject(), ReactNativeStackInjection.inject(); + +var render = function(element, mountInto, callback) { + return ReactNativeMount_1.renderComponent(element, mountInto, callback); +}, ReactNative = { + hasReactNativeInitialized: !1, + findNodeHandle: findNumericNodeHandleStack, + render: render, + unmountComponentAtNode: ReactNativeMount_1.unmountComponentAtNode, + unstable_batchedUpdates: ReactUpdates_1.batchedUpdates, + unmountComponentAtNodeAndRemoveContainer: ReactNativeMount_1.unmountComponentAtNodeAndRemoveContainer, + __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: { + NativeMethodsMixin: NativeMethodsMixin_1, + ReactGlobalSharedState: ReactGlobalSharedState_1, + ReactNativeComponentTree: ReactNativeComponentTree_1, + ReactNativePropRegistry: ReactNativePropRegistry_1, + TouchHistoryMath: TouchHistoryMath_1, + createReactNativeComponentClass: createReactNativeComponentClass, + takeSnapshot: takeSnapshot_1 + } +}; + +"undefined" != typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" == typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject && __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ + ComponentTree: { + getClosestInstanceFromNode: function(node) { + return ReactNativeComponentTree_1.getClosestInstanceFromNode(node); + }, + getNodeFromInstance: function(inst) { + for (;inst._renderedComponent; ) inst = inst._renderedComponent; + return inst ? ReactNativeComponentTree_1.getNodeFromInstance(inst) : null; + } + }, + Mount: ReactNativeMount_1, + Reconciler: ReactReconciler_1, + getInspectorDataForViewTag: ReactNativeStackInspector.getInspectorDataForViewTag +}); + +var ReactNativeStack = ReactNative; + +module.exports = ReactNativeStack; diff --git a/Libraries/Renderer/shims/NativeMethodsMixin.js b/Libraries/Renderer/shims/NativeMethodsMixin.js new file mode 100644 index 0000000000..085c653bfe --- /dev/null +++ b/Libraries/Renderer/shims/NativeMethodsMixin.js @@ -0,0 +1,23 @@ +/** + * Copyright 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule NativeMethodsMixin + * @flow + */ + +'use strict'; + +const { + __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, +} = require('ReactNative'); + +import type {NativeMethodsMixinType} from 'ReactNativeTypes'; + +const {NativeMethodsMixin} = __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +module.exports = ((NativeMethodsMixin: any): $Exact); diff --git a/Libraries/Renderer/src/shared/utils/PooledClass.js b/Libraries/Renderer/shims/PooledClass.js similarity index 96% rename from Libraries/Renderer/src/shared/utils/PooledClass.js rename to Libraries/Renderer/shims/PooledClass.js index 9055f43740..a89b9e1a7f 100644 --- a/Libraries/Renderer/src/shared/utils/PooledClass.js +++ b/Libraries/Renderer/shims/PooledClass.js @@ -95,8 +95,8 @@ var addPoolingTo = function( CopyConstructor: Class, pooler: Pooler, ): Class & { - getPooled(...args: $ReadOnlyArray): /* arguments of the constructor */ T, - release(instance: mixed): void, + getPooled(): /* arguments of the constructor */ T, + release(): void, } { // Casting as any so that flow ignores the actual implementation and trusts // it to match the type we declared diff --git a/Libraries/Renderer/src/shared/types/ReactPropTypesSecret.js b/Libraries/Renderer/shims/ReactDebugTool.js similarity index 60% rename from Libraries/Renderer/src/shared/types/ReactPropTypesSecret.js rename to Libraries/Renderer/shims/ReactDebugTool.js index 0f47ff2afb..c532f4bbe9 100644 --- a/Libraries/Renderer/src/shared/types/ReactPropTypesSecret.js +++ b/Libraries/Renderer/shims/ReactDebugTool.js @@ -6,12 +6,14 @@ * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * - * @flow - * @providesModule ReactPropTypesSecret + * @providesModule ReactDebugTool */ 'use strict'; -const ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; +const { + __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, +} = require('ReactNative'); -module.exports = ReactPropTypesSecret; +module.exports = + __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactDebugTool; diff --git a/Libraries/Renderer/shims/ReactGlobalSharedState.js b/Libraries/Renderer/shims/ReactGlobalSharedState.js new file mode 100644 index 0000000000..a2b5840201 --- /dev/null +++ b/Libraries/Renderer/shims/ReactGlobalSharedState.js @@ -0,0 +1,19 @@ +/** + * Copyright 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactGlobalSharedState + */ + +'use strict'; + +const { + __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, +} = require('ReactNative'); + +module.exports = + __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactGlobalSharedState; diff --git a/Libraries/Renderer/src/renderers/native/ReactNative.js b/Libraries/Renderer/shims/ReactNative.js similarity index 51% rename from Libraries/Renderer/src/renderers/native/ReactNative.js rename to Libraries/Renderer/shims/ReactNative.js index 82b12de9a1..ed27f10253 100644 --- a/Libraries/Renderer/src/renderers/native/ReactNative.js +++ b/Libraries/Renderer/shims/ReactNative.js @@ -13,6 +13,18 @@ const ReactNativeFeatureFlags = require('ReactNativeFeatureFlags'); -module.exports = ReactNativeFeatureFlags.useFiber - ? require('ReactNativeFiber') - : require('ReactNativeStack'); +import type {ReactNativeType} from 'ReactNativeTypes'; + +let ReactNative; + +if (__DEV__) { + ReactNative = ReactNativeFeatureFlags.useFiber + ? require('ReactNativeFiber-dev') + : require('ReactNativeStack-dev'); +} else { + ReactNative = ReactNativeFeatureFlags.useFiber + ? require('ReactNativeFiber-prod') + : require('ReactNativeStack-prod'); +} + +module.exports = (ReactNative: ReactNativeType); diff --git a/Libraries/Renderer/shims/ReactNativeComponentTree.js b/Libraries/Renderer/shims/ReactNativeComponentTree.js new file mode 100644 index 0000000000..92672f3e8f --- /dev/null +++ b/Libraries/Renderer/shims/ReactNativeComponentTree.js @@ -0,0 +1,20 @@ +/** + * Copyright 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactNativeComponentTree + * @flow + */ + +'use strict'; + +const { + __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, +} = require('ReactNative'); + +module.exports = + __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactNativeComponentTree; diff --git a/Libraries/Renderer/src/renderers/native/ReactNativeFeatureFlags.js b/Libraries/Renderer/shims/ReactNativeFeatureFlags.js similarity index 100% rename from Libraries/Renderer/src/renderers/native/ReactNativeFeatureFlags.js rename to Libraries/Renderer/shims/ReactNativeFeatureFlags.js diff --git a/Libraries/Renderer/shims/ReactNativePropRegistry.js b/Libraries/Renderer/shims/ReactNativePropRegistry.js new file mode 100644 index 0000000000..d72d460183 --- /dev/null +++ b/Libraries/Renderer/shims/ReactNativePropRegistry.js @@ -0,0 +1,20 @@ +/** + * Copyright 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactNativePropRegistry + * @flow + */ + +'use strict'; + +const { + __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, +} = require('ReactNative'); + +module.exports = + __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactNativePropRegistry; diff --git a/Libraries/Renderer/shims/ReactNativeTypes.js b/Libraries/Renderer/shims/ReactNativeTypes.js new file mode 100644 index 0000000000..594b8ac5ae --- /dev/null +++ b/Libraries/Renderer/shims/ReactNativeTypes.js @@ -0,0 +1,89 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactNativeTypes + * @flow + */ +'use strict'; + +import type React from 'react'; + +export type MeasureOnSuccessCallback = ( + x: number, + y: number, + width: number, + height: number, + pageX: number, + pageY: number, +) => void; + +export type MeasureInWindowOnSuccessCallback = ( + x: number, + y: number, + width: number, + height: number, +) => void; + +export type MeasureLayoutOnSuccessCallback = ( + left: number, + top: number, + width: number, + height: number, +) => void; + +/** + * This type keeps ReactNativeFiberHostComponent and NativeMethodsMixin in sync. + * It can also provide types for ReactNative applications that use NMM or refs. + */ +export type NativeMethodsMixinType = { + blur(): void, + focus(): void, + measure(callback: MeasureOnSuccessCallback): void, + measureInWindow(callback: MeasureInWindowOnSuccessCallback): void, + measureLayout( + relativeToNativeNode: number, + onSuccess: MeasureLayoutOnSuccessCallback, + onFail: () => void, + ): void, + setNativeProps(nativeProps: Object): void, +}; + +type ReactNativeBaseComponentViewConfig = { + validAttributes: Object, + uiViewClassName: string, + propTypes?: Object, +}; + +type SecretInternalsType = { + NativeMethodsMixin: NativeMethodsMixinType, + createReactNativeComponentClass( + viewConfig: ReactNativeBaseComponentViewConfig, + ): any, + ReactNativeComponentTree: any, + ReactNativePropRegistry: any, + // TODO (bvaughn) Decide which additional types to expose here? + // And how much information to fill in for the above types. +}; + +/** + * Flat ReactNative renderer bundles are too big for Flow to parse effeciently. + * Provide minimal Flow typing for the high-level RN API and call it a day. + */ +export type ReactNativeType = { + findNodeHandle(componentOrHandle: any): ?number, + render( + element: React.Element, + containerTag: any, + callback: ?Function, + ): any, + unmountComponentAtNode(containerTag: number): any, + unmountComponentAtNodeAndRemoveContainer(containerTag: number): any, + unstable_batchedUpdates: any, // TODO (bvaughn) Add types + + __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: SecretInternalsType, +}; diff --git a/Libraries/Renderer/src/shared/utils/getNextDebugID.js b/Libraries/Renderer/shims/ReactPerf.js similarity index 62% rename from Libraries/Renderer/src/shared/utils/getNextDebugID.js rename to Libraries/Renderer/shims/ReactPerf.js index 6e7ecb43b8..e879d267a8 100644 --- a/Libraries/Renderer/src/shared/utils/getNextDebugID.js +++ b/Libraries/Renderer/shims/ReactPerf.js @@ -6,16 +6,13 @@ * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * - * @providesModule getNextDebugID - * @flow + * @providesModule ReactPerf */ 'use strict'; -var nextDebugID = 1; +const { + __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, +} = require('ReactNative'); -function getNextDebugID(): number { - return nextDebugID++; -} - -module.exports = getNextDebugID; +module.exports = __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactPerf; diff --git a/Libraries/Renderer/src/renderers/shared/fiber/isomorphic/ReactTypes.js b/Libraries/Renderer/shims/ReactTypes.js similarity index 56% rename from Libraries/Renderer/src/renderers/shared/fiber/isomorphic/ReactTypes.js rename to Libraries/Renderer/shims/ReactTypes.js index 2a3c05a1f5..f63948d403 100644 --- a/Libraries/Renderer/src/renderers/shared/fiber/isomorphic/ReactTypes.js +++ b/Libraries/Renderer/shims/ReactTypes.js @@ -12,9 +12,6 @@ 'use strict'; -import type {ReactCoroutine, ReactYield} from 'ReactCoroutine'; -import type {ReactPortal} from 'ReactPortal'; - export type ReactNode = | ReactElement | ReactCoroutine @@ -30,3 +27,26 @@ export type ReactNodeList = ReactEmpty | ReactNode; export type ReactText = string | number; export type ReactEmpty = null | void | boolean; + +export type ReactCoroutine = { + $$typeof: Symbol | number, + key: null | string, + children: any, + // This should be a more specific CoroutineHandler + handler: (props: any, yields: Array) => ReactNodeList, + props: any, +}; + +export type ReactYield = { + $$typeof: Symbol | number, + value: mixed, +}; + +export type ReactPortal = { + $$typeof: Symbol | number, + key: null | string, + containerInfo: any, + children: ReactNodeList, + // TODO: figure out the API for cross-renderer implementation. + implementation: any, +}; diff --git a/Libraries/Renderer/src/ReactVersion.js b/Libraries/Renderer/shims/TouchHistoryMath.js similarity index 60% rename from Libraries/Renderer/src/ReactVersion.js rename to Libraries/Renderer/shims/TouchHistoryMath.js index 68f9d541cc..339bfe03f9 100644 --- a/Libraries/Renderer/src/ReactVersion.js +++ b/Libraries/Renderer/shims/TouchHistoryMath.js @@ -6,9 +6,14 @@ * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * - * @providesModule ReactVersion + * @providesModule TouchHistoryMath */ 'use strict'; -module.exports = '16.0.0-alpha.12'; +const { + __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, +} = require('ReactNative'); + +module.exports = + __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.TouchHistoryMath; diff --git a/Libraries/Renderer/shims/createReactNativeComponentClass.js b/Libraries/Renderer/shims/createReactNativeComponentClass.js new file mode 100644 index 0000000000..6934beb791 --- /dev/null +++ b/Libraries/Renderer/shims/createReactNativeComponentClass.js @@ -0,0 +1,20 @@ +/** + * Copyright 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule createReactNativeComponentClass + * @flow + */ + +'use strict'; + +const { + __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, +} = require('ReactNative'); + +module.exports = + __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.createReactNativeComponentClass; diff --git a/Libraries/Renderer/src/renderers/shared/fiber/ReactTypeOfInternalContext.js b/Libraries/Renderer/shims/takeSnapshot.js similarity index 61% rename from Libraries/Renderer/src/renderers/shared/fiber/ReactTypeOfInternalContext.js rename to Libraries/Renderer/shims/takeSnapshot.js index 89a3d2938d..e594b97837 100644 --- a/Libraries/Renderer/src/renderers/shared/fiber/ReactTypeOfInternalContext.js +++ b/Libraries/Renderer/shims/takeSnapshot.js @@ -6,15 +6,14 @@ * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * - * @providesModule ReactTypeOfInternalContext - * @flow + * @providesModule takeSnapshot */ 'use strict'; -export type TypeOfInternalContext = number; +const { + __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, +} = require('ReactNative'); -module.exports = { - NoContext: 0, - AsyncUpdates: 1, -}; +module.exports = + __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.takeSnapshot; diff --git a/Libraries/Renderer/src/renderers/native/NativeMethodsMixin.js b/Libraries/Renderer/src/renderers/native/NativeMethodsMixin.js deleted file mode 100644 index 44b5dcc238..0000000000 --- a/Libraries/Renderer/src/renderers/native/NativeMethodsMixin.js +++ /dev/null @@ -1,282 +0,0 @@ -/** - * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule NativeMethodsMixin - * @flow - */ -'use strict'; - -var ReactNative = require('ReactNative'); -var ReactNativeFeatureFlags = require('ReactNativeFeatureFlags'); -var ReactNativeAttributePayload = require('ReactNativeAttributePayload'); -var TextInputState = require('TextInputState'); -var UIManager = require('UIManager'); - -var invariant = require('fbjs/lib/invariant'); -var findNodeHandle = require('findNodeHandle'); - -var { - mountSafeCallback, - throwOnStylesProp, - warnForStyleProps, -} = require('NativeMethodsMixinUtils'); - -import type { - MeasureInWindowOnSuccessCallback, - MeasureLayoutOnSuccessCallback, - MeasureOnSuccessCallback, -} from 'NativeMethodsMixinUtils'; -import type { - ReactNativeBaseComponentViewConfig, -} from 'ReactNativeViewConfigRegistry'; - -/** - * `NativeMethodsMixin` provides methods to access the underlying native - * component directly. This can be useful in cases when you want to focus - * a view or measure its on-screen dimensions, for example. - * - * The methods described here are available on most of the default components - * provided by React Native. Note, however, that they are *not* available on - * composite components that aren't directly backed by a native view. This will - * generally include most components that you define in your own app. For more - * information, see [Direct - * Manipulation](docs/direct-manipulation.html). - */ -// TODO (bvaughn) Figure out how to use the NativeMethodsInterface type to- -// ensure that these mixins and ReactNativeFiberHostComponent stay in sync. -// Unfortunately, using it causes Flow to complain WRT createClass mixins: -// "call of method `createClass`. Expected an exact object instead of ..." -var NativeMethodsMixin = { - /** - * Determines the location on screen, width, and height of the given view and - * returns the values via an async callback. If successful, the callback will - * be called with the following arguments: - * - * - x - * - y - * - width - * - height - * - pageX - * - pageY - * - * Note that these measurements are not available until after the rendering - * has been completed in native. If you need the measurements as soon as - * possible, consider using the [`onLayout` - * prop](docs/view.html#onlayout) instead. - */ - measure: function(callback: MeasureOnSuccessCallback) { - UIManager.measure( - ReactNative.findNodeHandle(this), - mountSafeCallback(this, callback), - ); - }, - - /** - * Determines the location of the given view in the window and returns the - * values via an async callback. If the React root view is embedded in - * another native view, this will give you the absolute coordinates. If - * successful, the callback will be called with the following - * arguments: - * - * - x - * - y - * - width - * - height - * - * Note that these measurements are not available until after the rendering - * has been completed in native. - */ - measureInWindow: function(callback: MeasureInWindowOnSuccessCallback) { - UIManager.measureInWindow( - ReactNative.findNodeHandle(this), - mountSafeCallback(this, callback), - ); - }, - - /** - * Like [`measure()`](#measure), but measures the view relative an ancestor, - * specified as `relativeToNativeNode`. This means that the returned x, y - * are relative to the origin x, y of the ancestor view. - * - * As always, to obtain a native node handle for a component, you can use - * `ReactNative.findNodeHandle(component)`. - */ - measureLayout: function( - relativeToNativeNode: number, - onSuccess: MeasureLayoutOnSuccessCallback, - onFail: () => void /* currently unused */, - ) { - UIManager.measureLayout( - ReactNative.findNodeHandle(this), - relativeToNativeNode, - mountSafeCallback(this, onFail), - mountSafeCallback(this, onSuccess), - ); - }, - - /** - * This function sends props straight to native. They will not participate in - * future diff process - this means that if you do not include them in the - * next render, they will remain active (see [Direct - * Manipulation](docs/direct-manipulation.html)). - */ - setNativeProps: function(nativeProps: Object) { - // Ensure ReactNative factory function has configured findNodeHandle. - // Requiring it won't execute the factory function until first referenced. - // It's possible for tests that use ReactTestRenderer to reach this point, - // Without having executed ReactNative. - // Defer the factory function until now to avoid a cycle with UIManager. - // TODO (bvaughn) Remove this once ReactNativeStack is dropped. - require('ReactNative'); - - injectedSetNativeProps(this, nativeProps); - }, - - /** - * Requests focus for the given input or view. The exact behavior triggered - * will depend on the platform and type of view. - */ - focus: function() { - TextInputState.focusTextInput(ReactNative.findNodeHandle(this)); - }, - - /** - * Removes focus from an input or view. This is the opposite of `focus()`. - */ - blur: function() { - TextInputState.blurTextInput(ReactNative.findNodeHandle(this)); - }, -}; - -// TODO (bvaughn) Inline this once ReactNativeStack is dropped. -function setNativePropsFiber(componentOrHandle: any, nativeProps: Object) { - // Class components don't have viewConfig -> validateAttributes. - // Nor does it make sense to set native props on a non-native component. - // Instead, find the nearest host component and set props on it. - // Use findNodeHandle() rather than ReactNative.findNodeHandle() because - // We want the instance/wrapper (not the native tag). - let maybeInstance; - - // Fiber errors if findNodeHandle is called for an umounted component. - // Tests using ReactTestRenderer will trigger this case indirectly. - // Mimicking stack behavior, we should silently ignore this case. - // TODO Fix ReactTestRenderer so we can remove this try/catch. - try { - maybeInstance = findNodeHandle(componentOrHandle); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. - // This is not an error; it could mean a class component rendered null. - if (maybeInstance == null) { - return; - } - - const viewConfig: ReactNativeBaseComponentViewConfig = - maybeInstance.viewConfig; - - if (__DEV__) { - warnForStyleProps(nativeProps, viewConfig.validAttributes); - } - - var updatePayload = ReactNativeAttributePayload.create( - nativeProps, - viewConfig.validAttributes, - ); - - UIManager.updateView( - maybeInstance._nativeTag, - viewConfig.uiViewClassName, - updatePayload, - ); -} - -// TODO (bvaughn) Remove this once ReactNativeStack is dropped. -function setNativePropsStack(componentOrHandle: any, nativeProps: Object) { - // Class components don't have viewConfig -> validateAttributes. - // Nor does it make sense to set native props on a non-native component. - // Instead, find the nearest host component and set props on it. - // Use findNodeHandle() rather than ReactNative.findNodeHandle() because - // We want the instance/wrapper (not the native tag). - let maybeInstance = findNodeHandle(componentOrHandle); - - // If there is no host component beneath this we should fail silently. - // This is not an error; it could mean a class component rendered null. - if (maybeInstance == null) { - return; - } - - let viewConfig: ReactNativeBaseComponentViewConfig; - if (maybeInstance.viewConfig !== undefined) { - // ReactNativeBaseComponent - viewConfig = maybeInstance.viewConfig; - } else if ( - maybeInstance._instance !== undefined && - maybeInstance._instance.viewConfig !== undefined - ) { - // ReactCompositeComponentWrapper - // Some instances (eg Text) define their own viewConfig - viewConfig = maybeInstance._instance.viewConfig; - } else { - // ReactCompositeComponentWrapper - // Other instances (eg TextInput) defer to their children's viewConfig - while (maybeInstance._renderedComponent !== undefined) { - maybeInstance = maybeInstance._renderedComponent; - } - viewConfig = maybeInstance.viewConfig; - } - - const tag: number = typeof maybeInstance.getHostNode === 'function' - ? maybeInstance.getHostNode() - : maybeInstance._rootNodeID; - - if (__DEV__) { - warnForStyleProps(nativeProps, viewConfig.validAttributes); - } - - var updatePayload = ReactNativeAttributePayload.create( - nativeProps, - viewConfig.validAttributes, - ); - - UIManager.updateView(tag, viewConfig.uiViewClassName, updatePayload); -} - -// Switching based on fiber vs stack to avoid a lot of inline checks at runtime. -// HACK Normally this injection would be done by the renderer, but in this case -// that would result in a cycle between ReactNative and NativeMethodsMixin. -// We avoid requiring additional code for this injection so it's probably ok? -// TODO (bvaughn) Remove this once ReactNativeStack is gone. -let injectedSetNativeProps: ( - componentOrHandle: any, - nativeProps: Object, -) => void; -if (ReactNativeFeatureFlags.useFiber) { - injectedSetNativeProps = setNativePropsFiber; -} else { - injectedSetNativeProps = setNativePropsStack; -} - -if (__DEV__) { - // hide this from Flow since we can't define these properties outside of - // __DEV__ without actually implementing them (setting them to undefined - // isn't allowed by ReactClass) - var NativeMethodsMixin_DEV = (NativeMethodsMixin: any); - invariant( - !NativeMethodsMixin_DEV.componentWillMount && - !NativeMethodsMixin_DEV.componentWillReceiveProps, - 'Do not override existing functions.', - ); - NativeMethodsMixin_DEV.componentWillMount = function() { - throwOnStylesProp(this, this.props); - }; - NativeMethodsMixin_DEV.componentWillReceiveProps = function(newProps) { - throwOnStylesProp(this, newProps); - }; -} - -module.exports = NativeMethodsMixin; diff --git a/Libraries/Renderer/src/renderers/native/NativeMethodsMixinUtils.js b/Libraries/Renderer/src/renderers/native/NativeMethodsMixinUtils.js deleted file mode 100644 index 81a0c55cae..0000000000 --- a/Libraries/Renderer/src/renderers/native/NativeMethodsMixinUtils.js +++ /dev/null @@ -1,122 +0,0 @@ -/** - * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule NativeMethodsMixinUtils - * @flow - */ -'use strict'; - -export type MeasureOnSuccessCallback = ( - x: number, - y: number, - width: number, - height: number, - pageX: number, - pageY: number, -) => void; - -export type MeasureInWindowOnSuccessCallback = ( - x: number, - y: number, - width: number, - height: number, -) => void; - -export type MeasureLayoutOnSuccessCallback = ( - left: number, - top: number, - width: number, - height: number, -) => void; - -/** - * Shared between ReactNativeFiberHostComponent and NativeMethodsMixin to keep - * API in sync. - */ -export interface NativeMethodsInterface { - blur(): void, - focus(): void, - measure(callback: MeasureOnSuccessCallback): void, - measureInWindow(callback: MeasureInWindowOnSuccessCallback): void, - measureLayout( - relativeToNativeNode: number, - onSuccess: MeasureLayoutOnSuccessCallback, - onFail: () => void, - ): void, - setNativeProps(nativeProps: Object): void, -} - -/** - * In the future, we should cleanup callbacks by cancelling them instead of - * using this. - */ -function mountSafeCallback(context: any, callback: ?Function): any { - return function() { - if (!callback) { - return undefined; - } - if (typeof context.__isMounted === 'boolean') { - // TODO(gaearon): this is gross and should be removed. - // It is currently necessary because View uses createClass, - // and so any measure() calls on View (which are done by React - // DevTools) trigger the isMounted() deprecation warning. - if (!context.__isMounted) { - return undefined; - } - // The else branch is important so that we don't - // trigger the deprecation warning by calling isMounted. - } else if (typeof context.isMounted === 'function') { - if (!context.isMounted()) { - return undefined; - } - } - return callback.apply(context, arguments); - }; -} - -function throwOnStylesProp(component: any, props: any) { - if (props.styles !== undefined) { - var owner = component._owner || null; - var name = component.constructor.displayName; - var msg = - '`styles` is not a supported property of `' + - name + - '`, did ' + - 'you mean `style` (singular)?'; - if (owner && owner.constructor && owner.constructor.displayName) { - msg += - '\n\nCheck the `' + - owner.constructor.displayName + - '` parent ' + - ' component.'; - } - throw new Error(msg); - } -} - -function warnForStyleProps(props: any, validAttributes: any) { - for (var key in validAttributes.style) { - if (!(validAttributes[key] || props[key] === undefined)) { - console.error( - 'You are setting the style `{ ' + - key + - ': ... }` as a prop. You ' + - 'should nest it in a style object. ' + - 'E.g. `{ style: { ' + - key + - ': ... } }`', - ); - } - } -} - -module.exports = { - mountSafeCallback, - throwOnStylesProp, - warnForStyleProps, -}; diff --git a/Libraries/Renderer/src/renderers/native/ReactNativeAttributePayload.js b/Libraries/Renderer/src/renderers/native/ReactNativeAttributePayload.js deleted file mode 100644 index 07dd2058de..0000000000 --- a/Libraries/Renderer/src/renderers/native/ReactNativeAttributePayload.js +++ /dev/null @@ -1,516 +0,0 @@ -/** - * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactNativeAttributePayload - * @flow - */ -'use strict'; - -var ReactNativePropRegistry = require('ReactNativePropRegistry'); - -var deepDiffer = require('deepDiffer'); -var flattenStyle = require('flattenStyle'); - -var emptyObject = {}; - -/** - * Create a payload that contains all the updates between two sets of props. - * - * These helpers are all encapsulated into a single module, because they use - * mutation as a performance optimization which leads to subtle shared - * dependencies between the code paths. To avoid this mutable state leaking - * across modules, I've kept them isolated to this module. - */ - -type AttributeDiffer = (prevProp: mixed, nextProp: mixed) => boolean; -type AttributePreprocessor = (nextProp: mixed) => mixed; - -type CustomAttributeConfiguration = - | {diff: AttributeDiffer, process: AttributePreprocessor} - | {diff: AttributeDiffer} - | {process: AttributePreprocessor}; - -type AttributeConfiguration = { - [key: string]: - | CustomAttributeConfiguration - | AttributeConfiguration /*| boolean*/, -}; - -type NestedNode = Array | Object | number; - -// Tracks removed keys -var removedKeys = null; -var removedKeyCount = 0; - -function defaultDiffer(prevProp: mixed, nextProp: mixed): boolean { - if (typeof nextProp !== 'object' || nextProp === null) { - // Scalars have already been checked for equality - return true; - } else { - // For objects and arrays, the default diffing algorithm is a deep compare - return deepDiffer(prevProp, nextProp); - } -} - -function resolveObject(idOrObject: number | Object): Object { - if (typeof idOrObject === 'number') { - return ReactNativePropRegistry.getByID(idOrObject); - } - return idOrObject; -} - -function restoreDeletedValuesInNestedArray( - updatePayload: Object, - node: NestedNode, - validAttributes: AttributeConfiguration, -) { - if (Array.isArray(node)) { - var i = node.length; - while (i-- && removedKeyCount > 0) { - restoreDeletedValuesInNestedArray( - updatePayload, - node[i], - validAttributes, - ); - } - } else if (node && removedKeyCount > 0) { - var obj = resolveObject(node); - for (var propKey in removedKeys) { - if (!removedKeys[propKey]) { - continue; - } - var nextProp = obj[propKey]; - if (nextProp === undefined) { - continue; - } - - var attributeConfig = validAttributes[propKey]; - if (!attributeConfig) { - continue; // not a valid native prop - } - - if (typeof nextProp === 'function') { - nextProp = true; - } - if (typeof nextProp === 'undefined') { - nextProp = null; - } - - if (typeof attributeConfig !== 'object') { - // case: !Object is the default case - updatePayload[propKey] = nextProp; - } else if ( - typeof attributeConfig.diff === 'function' || - typeof attributeConfig.process === 'function' - ) { - // case: CustomAttributeConfiguration - var nextValue = typeof attributeConfig.process === 'function' - ? attributeConfig.process(nextProp) - : nextProp; - updatePayload[propKey] = nextValue; - } - removedKeys[propKey] = false; - removedKeyCount--; - } - } -} - -function diffNestedArrayProperty( - updatePayload: ?Object, - prevArray: Array, - nextArray: Array, - validAttributes: AttributeConfiguration, -): ?Object { - var minLength = prevArray.length < nextArray.length - ? prevArray.length - : nextArray.length; - var i; - for (i = 0; i < minLength; i++) { - // Diff any items in the array in the forward direction. Repeated keys - // will be overwritten by later values. - updatePayload = diffNestedProperty( - updatePayload, - prevArray[i], - nextArray[i], - validAttributes, - ); - } - for (; i < prevArray.length; i++) { - // Clear out all remaining properties. - updatePayload = clearNestedProperty( - updatePayload, - prevArray[i], - validAttributes, - ); - } - for (; i < nextArray.length; i++) { - // Add all remaining properties. - updatePayload = addNestedProperty( - updatePayload, - nextArray[i], - validAttributes, - ); - } - return updatePayload; -} - -function diffNestedProperty( - updatePayload: ?Object, - prevProp: NestedNode, - nextProp: NestedNode, - validAttributes: AttributeConfiguration, -): ?Object { - if (!updatePayload && prevProp === nextProp) { - // If no properties have been added, then we can bail out quickly on object - // equality. - return updatePayload; - } - - if (!prevProp || !nextProp) { - if (nextProp) { - return addNestedProperty(updatePayload, nextProp, validAttributes); - } - if (prevProp) { - return clearNestedProperty(updatePayload, prevProp, validAttributes); - } - return updatePayload; - } - - if (!Array.isArray(prevProp) && !Array.isArray(nextProp)) { - // Both are leaves, we can diff the leaves. - return diffProperties( - updatePayload, - resolveObject(prevProp), - resolveObject(nextProp), - validAttributes, - ); - } - - if (Array.isArray(prevProp) && Array.isArray(nextProp)) { - // Both are arrays, we can diff the arrays. - return diffNestedArrayProperty( - updatePayload, - prevProp, - nextProp, - validAttributes, - ); - } - - if (Array.isArray(prevProp)) { - return diffProperties( - updatePayload, - // $FlowFixMe - We know that this is always an object when the input is. - flattenStyle(prevProp), - // $FlowFixMe - We know that this isn't an array because of above flow. - resolveObject(nextProp), - validAttributes, - ); - } - - return diffProperties( - updatePayload, - resolveObject(prevProp), - // $FlowFixMe - We know that this is always an object when the input is. - flattenStyle(nextProp), - validAttributes, - ); -} - -/** - * addNestedProperty takes a single set of props and valid attribute - * attribute configurations. It processes each prop and adds it to the - * updatePayload. - */ -function addNestedProperty( - updatePayload: ?Object, - nextProp: NestedNode, - validAttributes: AttributeConfiguration, -) { - if (!nextProp) { - return updatePayload; - } - - if (!Array.isArray(nextProp)) { - // Add each property of the leaf. - return addProperties( - updatePayload, - resolveObject(nextProp), - validAttributes, - ); - } - - for (var i = 0; i < nextProp.length; i++) { - // Add all the properties of the array. - updatePayload = addNestedProperty( - updatePayload, - nextProp[i], - validAttributes, - ); - } - - return updatePayload; -} - -/** - * clearNestedProperty takes a single set of props and valid attributes. It - * adds a null sentinel to the updatePayload, for each prop key. - */ -function clearNestedProperty( - updatePayload: ?Object, - prevProp: NestedNode, - validAttributes: AttributeConfiguration, -): ?Object { - if (!prevProp) { - return updatePayload; - } - - if (!Array.isArray(prevProp)) { - // Add each property of the leaf. - return clearProperties( - updatePayload, - resolveObject(prevProp), - validAttributes, - ); - } - - for (var i = 0; i < prevProp.length; i++) { - // Add all the properties of the array. - updatePayload = clearNestedProperty( - updatePayload, - prevProp[i], - validAttributes, - ); - } - return updatePayload; -} - -/** - * diffProperties takes two sets of props and a set of valid attributes - * and write to updatePayload the values that changed or were deleted. - * If no updatePayload is provided, a new one is created and returned if - * anything changed. - */ -function diffProperties( - updatePayload: ?Object, - prevProps: Object, - nextProps: Object, - validAttributes: AttributeConfiguration, -): ?Object { - var attributeConfig: ?(CustomAttributeConfiguration | AttributeConfiguration); - var nextProp; - var prevProp; - - for (var propKey in nextProps) { - attributeConfig = validAttributes[propKey]; - if (!attributeConfig) { - continue; // not a valid native prop - } - - prevProp = prevProps[propKey]; - nextProp = nextProps[propKey]; - - // functions are converted to booleans as markers that the associated - // events should be sent from native. - if (typeof nextProp === 'function') { - nextProp = (true: any); - // If nextProp is not a function, then don't bother changing prevProp - // since nextProp will win and go into the updatePayload regardless. - if (typeof prevProp === 'function') { - prevProp = (true: any); - } - } - - // An explicit value of undefined is treated as a null because it overrides - // any other preceding value. - if (typeof nextProp === 'undefined') { - nextProp = (null: any); - if (typeof prevProp === 'undefined') { - prevProp = (null: any); - } - } - - if (removedKeys) { - removedKeys[propKey] = false; - } - - if (updatePayload && updatePayload[propKey] !== undefined) { - // Something else already triggered an update to this key because another - // value diffed. Since we're now later in the nested arrays our value is - // more important so we need to calculate it and override the existing - // value. It doesn't matter if nothing changed, we'll set it anyway. - - // Pattern match on: attributeConfig - if (typeof attributeConfig !== 'object') { - // case: !Object is the default case - updatePayload[propKey] = nextProp; - } else if ( - typeof attributeConfig.diff === 'function' || - typeof attributeConfig.process === 'function' - ) { - // case: CustomAttributeConfiguration - var nextValue = typeof attributeConfig.process === 'function' - ? attributeConfig.process(nextProp) - : nextProp; - updatePayload[propKey] = nextValue; - } - continue; - } - - if (prevProp === nextProp) { - continue; // nothing changed - } - - // Pattern match on: attributeConfig - if (typeof attributeConfig !== 'object') { - // case: !Object is the default case - if (defaultDiffer(prevProp, nextProp)) { - // a normal leaf has changed - (updatePayload || (updatePayload = {}))[propKey] = nextProp; - } - } else if ( - typeof attributeConfig.diff === 'function' || - typeof attributeConfig.process === 'function' - ) { - // case: CustomAttributeConfiguration - var shouldUpdate = - prevProp === undefined || - (typeof attributeConfig.diff === 'function' - ? attributeConfig.diff(prevProp, nextProp) - : defaultDiffer(prevProp, nextProp)); - if (shouldUpdate) { - nextValue = typeof attributeConfig.process === 'function' - ? attributeConfig.process(nextProp) - : nextProp; - (updatePayload || (updatePayload = {}))[propKey] = nextValue; - } - } else { - // default: fallthrough case when nested properties are defined - removedKeys = null; - removedKeyCount = 0; - // We think that attributeConfig is not CustomAttributeConfiguration at - // this point so we assume it must be AttributeConfiguration. - updatePayload = diffNestedProperty( - updatePayload, - prevProp, - nextProp, - ((attributeConfig: any): AttributeConfiguration), - ); - if (removedKeyCount > 0 && updatePayload) { - restoreDeletedValuesInNestedArray( - updatePayload, - nextProp, - ((attributeConfig: any): AttributeConfiguration), - ); - removedKeys = null; - } - } - } - - // Also iterate through all the previous props to catch any that have been - // removed and make sure native gets the signal so it can reset them to the - // default. - for (propKey in prevProps) { - if (nextProps[propKey] !== undefined) { - continue; // we've already covered this key in the previous pass - } - attributeConfig = validAttributes[propKey]; - if (!attributeConfig) { - continue; // not a valid native prop - } - - if (updatePayload && updatePayload[propKey] !== undefined) { - // This was already updated to a diff result earlier. - continue; - } - - prevProp = prevProps[propKey]; - if (prevProp === undefined) { - continue; // was already empty anyway - } - // Pattern match on: attributeConfig - if ( - typeof attributeConfig !== 'object' || - typeof attributeConfig.diff === 'function' || - typeof attributeConfig.process === 'function' - ) { - // case: CustomAttributeConfiguration | !Object - // Flag the leaf property for removal by sending a sentinel. - (updatePayload || (updatePayload = {}))[propKey] = null; - if (!removedKeys) { - removedKeys = {}; - } - if (!removedKeys[propKey]) { - removedKeys[propKey] = true; - removedKeyCount++; - } - } else { - // default: - // This is a nested attribute configuration where all the properties - // were removed so we need to go through and clear out all of them. - updatePayload = clearNestedProperty( - updatePayload, - prevProp, - ((attributeConfig: any): AttributeConfiguration), - ); - } - } - return updatePayload; -} - -/** - * addProperties adds all the valid props to the payload after being processed. - */ -function addProperties( - updatePayload: ?Object, - props: Object, - validAttributes: AttributeConfiguration, -): ?Object { - // TODO: Fast path - return diffProperties(updatePayload, emptyObject, props, validAttributes); -} - -/** - * clearProperties clears all the previous props by adding a null sentinel - * to the payload for each valid key. - */ -function clearProperties( - updatePayload: ?Object, - prevProps: Object, - validAttributes: AttributeConfiguration, -): ?Object { - // TODO: Fast path - return diffProperties(updatePayload, prevProps, emptyObject, validAttributes); -} - -var ReactNativeAttributePayload = { - create: function( - props: Object, - validAttributes: AttributeConfiguration, - ): ?Object { - return addProperties( - null, // updatePayload - props, - validAttributes, - ); - }, - - diff: function( - prevProps: Object, - nextProps: Object, - validAttributes: AttributeConfiguration, - ): ?Object { - return diffProperties( - null, // updatePayload - prevProps, - nextProps, - validAttributes, - ); - }, -}; - -module.exports = ReactNativeAttributePayload; diff --git a/Libraries/Renderer/src/renderers/native/ReactNativeBaseComponent.js b/Libraries/Renderer/src/renderers/native/ReactNativeBaseComponent.js deleted file mode 100644 index fba2116e86..0000000000 --- a/Libraries/Renderer/src/renderers/native/ReactNativeBaseComponent.js +++ /dev/null @@ -1,194 +0,0 @@ -/** - * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactNativeBaseComponent - * @flow - */ - -'use strict'; - -var NativeMethodsMixin = require('NativeMethodsMixin'); -var ReactNativeAttributePayload = require('ReactNativeAttributePayload'); -var ReactNativeComponentTree = require('ReactNativeComponentTree'); -var ReactNativeTagHandles = require('ReactNativeTagHandles'); -var ReactMultiChild = require('ReactMultiChild'); -var UIManager = require('UIManager'); - -var deepFreezeAndThrowOnMutationInDev = require('deepFreezeAndThrowOnMutationInDev'); - -type ReactNativeBaseComponentViewConfig = { - validAttributes: Object, - uiViewClassName: string, -}; - -// require('UIManagerStatTracker').install(); // uncomment to enable - -/** - * @constructor ReactNativeBaseComponent - * @extends ReactComponent - * @extends ReactMultiChild - * @param {!object} UIKit View Configuration. - */ -var ReactNativeBaseComponent = function( - viewConfig: ReactNativeBaseComponentViewConfig, -) { - this.viewConfig = viewConfig; -}; - -/** - * Mixin for containers that contain UIViews. NOTE: markup is rendered markup - * which is a `viewID` ... see the return value for `mountComponent` ! - */ -ReactNativeBaseComponent.Mixin = { - getPublicInstance: function() { - // TODO: This should probably use a composite wrapper - return this; - }, - - unmountComponent: function(safely, skipLifecycle) { - ReactNativeComponentTree.uncacheNode(this); - this.unmountChildren(safely, skipLifecycle); - this._rootNodeID = 0; - }, - - /** - * Every native component is responsible for allocating its own `tag`, and - * issuing the native `createView` command. But it is not responsible for - * recording the fact that its own `rootNodeID` is associated with a - * `nodeHandle`. Only the code that actually adds its `nodeHandle` (`tag`) as - * a child of a container can confidently record that in - * `ReactNativeTagHandles`. - */ - initializeChildren: function(children, containerTag, transaction, context) { - var mountImages = this.mountChildren(children, transaction, context); - // In a well balanced tree, half of the nodes are in the bottom row and have - // no children - let's avoid calling out to the native bridge for a large - // portion of the children. - if (mountImages.length) { - // TODO: Pool these per platform view class. Reusing the `mountImages` - // array would likely be a jit deopt. - var createdTags = []; - for (var i = 0, l = mountImages.length; i < l; i++) { - var mountImage = mountImages[i]; - var childTag = mountImage; - createdTags[i] = childTag; - } - UIManager.setChildren(containerTag, createdTags); - } - }, - - /** - * Updates the component's currently mounted representation. - * - * @param {object} nextElement - * @param {ReactReconcileTransaction} transaction - * @param {object} context - * @internal - */ - receiveComponent: function(nextElement, transaction, context) { - var prevElement = this._currentElement; - this._currentElement = nextElement; - - if (__DEV__) { - for (var key in this.viewConfig.validAttributes) { - if (nextElement.props.hasOwnProperty(key)) { - deepFreezeAndThrowOnMutationInDev(nextElement.props[key]); - } - } - } - - var updatePayload = ReactNativeAttributePayload.diff( - prevElement.props, - nextElement.props, - this.viewConfig.validAttributes, - ); - - if (updatePayload) { - UIManager.updateView( - this._rootNodeID, - this.viewConfig.uiViewClassName, - updatePayload, - ); - } - - this.updateChildren(nextElement.props.children, transaction, context); - }, - - /** - * Currently this still uses IDs for reconciliation so this can return null. - * - * @return {null} Null. - */ - getHostNode: function() { - return this._rootNodeID; - }, - - /** - * @param {ReactNativeReconcileTransaction} transaction - * @param {?ReactNativeBaseComponent} the parent component instance - * @param {?object} info about the host container - * @param {object} context - * @return {string} Unique iOS view tag. - */ - mountComponent: function( - transaction, - hostParent, - hostContainerInfo, - context, - ) { - var tag = ReactNativeTagHandles.allocateTag(); - - this._rootNodeID = tag; - this._hostParent = hostParent; - this._hostContainerInfo = hostContainerInfo; - - if (__DEV__) { - for (var key in this.viewConfig.validAttributes) { - if (this._currentElement.props.hasOwnProperty(key)) { - deepFreezeAndThrowOnMutationInDev(this._currentElement.props[key]); - } - } - } - - var updatePayload = ReactNativeAttributePayload.create( - this._currentElement.props, - this.viewConfig.validAttributes, - ); - - var nativeTopRootTag = hostContainerInfo._tag; - UIManager.createView( - tag, - this.viewConfig.uiViewClassName, - nativeTopRootTag, - updatePayload, - ); - - ReactNativeComponentTree.precacheNode(this, tag); - - this.initializeChildren( - this._currentElement.props.children, - tag, - transaction, - context, - ); - return tag; - }, -}; - -/** - * Order of mixins is important. ReactNativeBaseComponent overrides methods in - * ReactMultiChild. - */ -Object.assign( - ReactNativeBaseComponent.prototype, - ReactMultiChild, - ReactNativeBaseComponent.Mixin, - NativeMethodsMixin, -); - -module.exports = ReactNativeBaseComponent; diff --git a/Libraries/Renderer/src/renderers/native/ReactNativeBridgeEventPlugin.js b/Libraries/Renderer/src/renderers/native/ReactNativeBridgeEventPlugin.js deleted file mode 100644 index 628b9e0d0f..0000000000 --- a/Libraries/Renderer/src/renderers/native/ReactNativeBridgeEventPlugin.js +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactNativeBridgeEventPlugin - * @flow - */ -'use strict'; - -var EventPropagators = require('EventPropagators'); -var SyntheticEvent = require('SyntheticEvent'); -var UIManager = require('UIManager'); - -var warning = require('fbjs/lib/warning'); - -var customBubblingEventTypes = UIManager.customBubblingEventTypes; -var customDirectEventTypes = UIManager.customDirectEventTypes; - -var allTypesByEventName = {}; - -for (var bubblingTypeName in customBubblingEventTypes) { - allTypesByEventName[bubblingTypeName] = - customBubblingEventTypes[bubblingTypeName]; -} - -for (var directTypeName in customDirectEventTypes) { - warning( - !customBubblingEventTypes[directTypeName], - 'Event cannot be both direct and bubbling: %s', - directTypeName, - ); - allTypesByEventName[directTypeName] = customDirectEventTypes[directTypeName]; -} - -var ReactNativeBridgeEventPlugin = { - eventTypes: {...customBubblingEventTypes, ...customDirectEventTypes}, - - /** - * @see {EventPluginHub.extractEvents} - */ - extractEvents: function( - topLevelType: string, - targetInst: Object, - nativeEvent: Event, - nativeEventTarget: Object, - ): ?Object { - var bubbleDispatchConfig = customBubblingEventTypes[topLevelType]; - var directDispatchConfig = customDirectEventTypes[topLevelType]; - var event = SyntheticEvent.getPooled( - bubbleDispatchConfig || directDispatchConfig, - targetInst, - nativeEvent, - nativeEventTarget, - ); - if (bubbleDispatchConfig) { - EventPropagators.accumulateTwoPhaseDispatches(event); - } else if (directDispatchConfig) { - EventPropagators.accumulateDirectDispatches(event); - } else { - return null; - } - return event; - }, -}; - -module.exports = ReactNativeBridgeEventPlugin; diff --git a/Libraries/Renderer/src/renderers/native/ReactNativeComponentEnvironment.js b/Libraries/Renderer/src/renderers/native/ReactNativeComponentEnvironment.js deleted file mode 100644 index 0e1a3f5826..0000000000 --- a/Libraries/Renderer/src/renderers/native/ReactNativeComponentEnvironment.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactNativeComponentEnvironment - * @flow - */ -'use strict'; - -var ReactNativeDOMIDOperations = require('ReactNativeDOMIDOperations'); -var ReactNativeReconcileTransaction = require('ReactNativeReconcileTransaction'); - -var ReactNativeComponentEnvironment = { - processChildrenUpdates: ReactNativeDOMIDOperations.dangerouslyProcessChildrenUpdates, - - replaceNodeWithMarkup: ReactNativeDOMIDOperations.dangerouslyReplaceNodeWithMarkupByID, - - /** - * @param {DOMElement} Element to clear. - */ - clearNode: function(/*containerView*/) {}, - - ReactReconcileTransaction: ReactNativeReconcileTransaction, -}; - -module.exports = ReactNativeComponentEnvironment; diff --git a/Libraries/Renderer/src/renderers/native/ReactNativeComponentTree.js b/Libraries/Renderer/src/renderers/native/ReactNativeComponentTree.js deleted file mode 100644 index e091667789..0000000000 --- a/Libraries/Renderer/src/renderers/native/ReactNativeComponentTree.js +++ /dev/null @@ -1,92 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactNativeComponentTree - */ - -'use strict'; - -var invariant = require('fbjs/lib/invariant'); - -var instanceCache = {}; -var instanceProps = {}; - -/** - * Drill down (through composites and empty components) until we get a host or - * host text component. - * - * This is pretty polymorphic but unavoidable with the current structure we have - * for `_renderedChildren`. - */ -function getRenderedHostOrTextFromComponent(component) { - var rendered; - while ((rendered = component._renderedComponent)) { - component = rendered; - } - return component; -} - -/** - * Populate `_hostNode` on the rendered host/text component with the given - * DOM node. The passed `inst` can be a composite. - */ -function precacheNode(inst, tag) { - var nativeInst = getRenderedHostOrTextFromComponent(inst); - instanceCache[tag] = nativeInst; -} - -function precacheFiberNode(hostInst, tag) { - instanceCache[tag] = hostInst; -} - -function uncacheNode(inst) { - var tag = inst._rootNodeID; - if (tag) { - delete instanceCache[tag]; - } -} - -function uncacheFiberNode(tag) { - delete instanceCache[tag]; - delete instanceProps[tag]; -} - -function getInstanceFromTag(tag) { - return instanceCache[tag] || null; -} - -function getTagFromInstance(inst) { - // TODO (bvaughn) Clean up once Stack is deprecated - var tag = typeof inst.tag !== 'number' - ? inst._rootNodeID - : inst.stateNode._nativeTag; - invariant(tag, 'All native instances should have a tag.'); - return tag; -} - -function getFiberCurrentPropsFromNode(stateNode) { - return instanceProps[stateNode._nativeTag] || null; -} - -function updateFiberProps(tag, props) { - instanceProps[tag] = props; -} - -var ReactNativeComponentTree = { - getClosestInstanceFromNode: getInstanceFromTag, - getInstanceFromNode: getInstanceFromTag, - getNodeFromInstance: getTagFromInstance, - precacheFiberNode, - precacheNode, - uncacheFiberNode, - uncacheNode, - getFiberCurrentPropsFromNode, - updateFiberProps, -}; - -module.exports = ReactNativeComponentTree; diff --git a/Libraries/Renderer/src/renderers/native/ReactNativeContainerInfo.js b/Libraries/Renderer/src/renderers/native/ReactNativeContainerInfo.js deleted file mode 100644 index 6d24f4c751..0000000000 --- a/Libraries/Renderer/src/renderers/native/ReactNativeContainerInfo.js +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactNativeContainerInfo - * @flow - */ -'use strict'; - -function ReactNativeContainerInfo(tag: number) { - var info = { - _tag: tag, - }; - return info; -} - -module.exports = ReactNativeContainerInfo; diff --git a/Libraries/Renderer/src/renderers/native/ReactNativeDOMIDOperations.js b/Libraries/Renderer/src/renderers/native/ReactNativeDOMIDOperations.js deleted file mode 100644 index c008373f66..0000000000 --- a/Libraries/Renderer/src/renderers/native/ReactNativeDOMIDOperations.js +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactNativeDOMIDOperations - */ -'use strict'; - -var ReactNativeComponentTree = require('ReactNativeComponentTree'); -var UIManager = require('UIManager'); - -/** - * Updates a component's children by processing a series of updates. - * For each of the update/create commands, the `fromIndex` refers to the index - * that the item existed at *before* any of the updates are applied, and the - * `toIndex` refers to the index after *all* of the updates are applied - * (including deletes/moves). TODO: refactor so this can be shared with - * DOMChildrenOperations. - * - * @param {ReactNativeBaseComponent} updates List of update configurations. - * @param {array} markup List of markup strings - in the case of React - * IOS, the ids of new components assumed to be already created. - */ -var dangerouslyProcessChildrenUpdates = function(inst, childrenUpdates) { - if (!childrenUpdates.length) { - return; - } - - var containerTag = ReactNativeComponentTree.getNodeFromInstance(inst); - - var moveFromIndices; - var moveToIndices; - var addChildTags; - var addAtIndices; - var removeAtIndices; - - for (var i = 0; i < childrenUpdates.length; i++) { - var update = childrenUpdates[i]; - if (update.type === 'MOVE_EXISTING') { - (moveFromIndices || (moveFromIndices = [])).push(update.fromIndex); - (moveToIndices || (moveToIndices = [])).push(update.toIndex); - } else if (update.type === 'REMOVE_NODE') { - (removeAtIndices || (removeAtIndices = [])).push(update.fromIndex); - } else if (update.type === 'INSERT_MARKUP') { - var mountImage = update.content; - var tag = mountImage; - (addAtIndices || (addAtIndices = [])).push(update.toIndex); - (addChildTags || (addChildTags = [])).push(tag); - } - } - - UIManager.manageChildren( - containerTag, - moveFromIndices, - moveToIndices, - addChildTags, - addAtIndices, - removeAtIndices, - ); -}; - -/** - * Operations used to process updates to DOM nodes. This is made injectable via - * `ReactComponent.DOMIDOperations`. - */ -var ReactNativeDOMIDOperations = { - dangerouslyProcessChildrenUpdates, - - /** - * Replaces a view that exists in the document with markup. - * - * @param {string} id ID of child to be replaced. - * @param {string} markup Mount image to replace child with id. - */ - dangerouslyReplaceNodeWithMarkupByID: function(id, mountImage) { - var oldTag = id; - UIManager.replaceExistingNonRootView(oldTag, mountImage); - }, -}; - -module.exports = ReactNativeDOMIDOperations; diff --git a/Libraries/Renderer/src/renderers/native/ReactNativeEventEmitter.js b/Libraries/Renderer/src/renderers/native/ReactNativeEventEmitter.js deleted file mode 100644 index 42b69aa150..0000000000 --- a/Libraries/Renderer/src/renderers/native/ReactNativeEventEmitter.js +++ /dev/null @@ -1,201 +0,0 @@ -/** - * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactNativeEventEmitter - * @flow - */ -'use strict'; - -var EventPluginHub = require('EventPluginHub'); -var EventPluginRegistry = require('EventPluginRegistry'); -var ReactEventEmitterMixin = require('ReactEventEmitterMixin'); -var ReactNativeComponentTree = require('ReactNativeComponentTree'); -var ReactNativeTagHandles = require('ReactNativeTagHandles'); -var ReactGenericBatching = require('ReactGenericBatching'); - -var warning = require('fbjs/lib/warning'); - -/** - * Version of `ReactBrowserEventEmitter` that works on the receiving side of a - * serialized worker boundary. - */ - -// Shared default empty native event - conserve memory. -var EMPTY_NATIVE_EVENT = {}; - -/** - * Selects a subsequence of `Touch`es, without destroying `touches`. - * - * @param {Array} touches Deserialized touch objects. - * @param {Array} indices Indices by which to pull subsequence. - * @return {Array} Subsequence of touch objects. - */ -var touchSubsequence = function(touches, indices) { - var ret = []; - for (var i = 0; i < indices.length; i++) { - ret.push(touches[indices[i]]); - } - return ret; -}; - -/** - * TODO: Pool all of this. - * - * Destroys `touches` by removing touch objects at indices `indices`. This is - * to maintain compatibility with W3C touch "end" events, where the active - * touches don't include the set that has just been "ended". - * - * @param {Array} touches Deserialized touch objects. - * @param {Array} indices Indices to remove from `touches`. - * @return {Array} Subsequence of removed touch objects. - */ -var removeTouchesAtIndices = function( - touches: Array, - indices: Array, -): Array { - var rippedOut = []; - // use an unsafe downcast to alias to nullable elements, - // so we can delete and then compact. - var temp: Array = (touches: Array); - for (var i = 0; i < indices.length; i++) { - var index = indices[i]; - rippedOut.push(touches[index]); - temp[index] = null; - } - var fillAt = 0; - for (var j = 0; j < temp.length; j++) { - var cur = temp[j]; - if (cur !== null) { - temp[fillAt++] = cur; - } - } - temp.length = fillAt; - return rippedOut; -}; - -var ReactNativeEventEmitter = { - ...ReactEventEmitterMixin, - - registrationNames: EventPluginRegistry.registrationNameModules, - - getListener: EventPluginHub.getListener, - - /** - * Internal version of `receiveEvent` in terms of normalized (non-tag) - * `rootNodeID`. - * - * @see receiveEvent. - * - * @param {rootNodeID} rootNodeID React root node ID that event occurred on. - * @param {TopLevelType} topLevelType Top level type of event. - * @param {object} nativeEventParam Object passed from native. - */ - _receiveRootNodeIDEvent: function( - rootNodeID: number, - topLevelType: string, - nativeEventParam: Object, - ) { - var nativeEvent = nativeEventParam || EMPTY_NATIVE_EVENT; - var inst = ReactNativeComponentTree.getInstanceFromNode(rootNodeID); - ReactGenericBatching.batchedUpdates(function() { - ReactNativeEventEmitter.handleTopLevel( - topLevelType, - inst, - nativeEvent, - nativeEvent.target, - ); - }); - // React Native doesn't use ReactControlledComponent but if it did, here's - // where it would do it. - }, - - /** - * Publicly exposed method on module for native objc to invoke when a top - * level event is extracted. - * @param {rootNodeID} rootNodeID React root node ID that event occurred on. - * @param {TopLevelType} topLevelType Top level type of event. - * @param {object} nativeEventParam Object passed from native. - */ - receiveEvent: function( - tag: number, - topLevelType: string, - nativeEventParam: Object, - ) { - var rootNodeID = tag; - ReactNativeEventEmitter._receiveRootNodeIDEvent( - rootNodeID, - topLevelType, - nativeEventParam, - ); - }, - - /** - * Simple multi-wrapper around `receiveEvent` that is intended to receive an - * efficient representation of `Touch` objects, and other information that - * can be used to construct W3C compliant `Event` and `Touch` lists. - * - * This may create dispatch behavior that differs than web touch handling. We - * loop through each of the changed touches and receive it as a single event. - * So two `touchStart`/`touchMove`s that occur simultaneously are received as - * two separate touch event dispatches - when they arguably should be one. - * - * This implementation reuses the `Touch` objects themselves as the `Event`s - * since we dispatch an event for each touch (though that might not be spec - * compliant). The main purpose of reusing them is to save allocations. - * - * TODO: Dispatch multiple changed touches in one event. The bubble path - * could be the first common ancestor of all the `changedTouches`. - * - * One difference between this behavior and W3C spec: cancelled touches will - * not appear in `.touches`, or in any future `.touches`, though they may - * still be "actively touching the surface". - * - * Web desktop polyfills only need to construct a fake touch event with - * identifier 0, also abandoning traditional click handlers. - */ - receiveTouches: function( - eventTopLevelType: string, - touches: Array, - changedIndices: Array, - ) { - var changedTouches = eventTopLevelType === 'topTouchEnd' || - eventTopLevelType === 'topTouchCancel' - ? removeTouchesAtIndices(touches, changedIndices) - : touchSubsequence(touches, changedIndices); - - for (var jj = 0; jj < changedTouches.length; jj++) { - var touch = changedTouches[jj]; - // Touch objects can fulfill the role of `DOM` `Event` objects if we set - // the `changedTouches`/`touches`. This saves allocations. - touch.changedTouches = changedTouches; - touch.touches = touches; - var nativeEvent = touch; - var rootNodeID = null; - var target = nativeEvent.target; - if (target !== null && target !== undefined) { - if (target < ReactNativeTagHandles.tagsStartAt) { - if (__DEV__) { - warning( - false, - 'A view is reporting that a touch occurred on tag zero.', - ); - } - } else { - rootNodeID = target; - } - } - ReactNativeEventEmitter._receiveRootNodeIDEvent( - rootNodeID, - eventTopLevelType, - nativeEvent, - ); - } - }, -}; - -module.exports = ReactNativeEventEmitter; diff --git a/Libraries/Renderer/src/renderers/native/ReactNativeEventPluginOrder.js b/Libraries/Renderer/src/renderers/native/ReactNativeEventPluginOrder.js deleted file mode 100644 index b1b5f66d11..0000000000 --- a/Libraries/Renderer/src/renderers/native/ReactNativeEventPluginOrder.js +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactNativeEventPluginOrder - * @flow - */ -'use strict'; - -var ReactNativeEventPluginOrder = [ - 'ResponderEventPlugin', - 'ReactNativeBridgeEventPlugin', -]; - -module.exports = ReactNativeEventPluginOrder; diff --git a/Libraries/Renderer/src/renderers/native/ReactNativeFiber.js b/Libraries/Renderer/src/renderers/native/ReactNativeFiber.js deleted file mode 100644 index 79a4acac18..0000000000 --- a/Libraries/Renderer/src/renderers/native/ReactNativeFiber.js +++ /dev/null @@ -1,474 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactNativeFiber - * @flow - */ - -'use strict'; - -const ReactFiberErrorLogger = require('ReactFiberErrorLogger'); -const ReactFiberReconciler = require('ReactFiberReconciler'); -const ReactGenericBatching = require('ReactGenericBatching'); -const ReactNativeAttributePayload = require('ReactNativeAttributePayload'); -const ReactNativeComponentTree = require('ReactNativeComponentTree'); -const ReactNativeFiberErrorDialog = require('ReactNativeFiberErrorDialog'); -const ReactNativeFiberHostComponent = require('ReactNativeFiberHostComponent'); -const ReactNativeInjection = require('ReactNativeInjection'); -const ReactNativeTagHandles = require('ReactNativeTagHandles'); -const ReactNativeViewConfigRegistry = require('ReactNativeViewConfigRegistry'); -const ReactPortal = require('ReactPortal'); -const ReactVersion = require('ReactVersion'); -const UIManager = require('UIManager'); - -const deepFreezeAndThrowOnMutationInDev = require('deepFreezeAndThrowOnMutationInDev'); -const emptyObject = require('fbjs/lib/emptyObject'); -const findNodeHandle = require('findNodeHandle'); -const invariant = require('fbjs/lib/invariant'); - -const {injectInternals} = require('ReactFiberDevToolsHook'); - -import type {Element} from 'React'; -import type {Fiber} from 'ReactFiber'; -import type { - ReactNativeBaseComponentViewConfig, -} from 'ReactNativeViewConfigRegistry'; -import type {ReactNodeList} from 'ReactTypes'; -const { - precacheFiberNode, - uncacheFiberNode, - updateFiberProps, -} = ReactNativeComponentTree; - -ReactNativeInjection.inject(); - -type Container = number; -export type Instance = { - _children: Array, - _nativeTag: number, - viewConfig: ReactNativeBaseComponentViewConfig, -}; -type Props = Object; -type TextInstance = number; - -function recursivelyUncacheFiberNode(node: Instance | TextInstance) { - if (typeof node === 'number') { - // Leaf node (eg text) - uncacheFiberNode(node); - } else { - uncacheFiberNode((node: any)._nativeTag); - - (node: any)._children.forEach(recursivelyUncacheFiberNode); - } -} - -const NativeRenderer = ReactFiberReconciler({ - appendChild( - parentInstance: Instance | Container, - child: Instance | TextInstance, - ): void { - const childTag = typeof child === 'number' ? child : child._nativeTag; - - if (typeof parentInstance === 'number') { - // Root container - UIManager.setChildren( - parentInstance, // containerTag - [childTag], // reactTags - ); - } else { - const children = parentInstance._children; - - const index = children.indexOf(child); - - if (index >= 0) { - children.splice(index, 1); - children.push(child); - - UIManager.manageChildren( - parentInstance._nativeTag, // containerTag - [index], // moveFromIndices - [children.length - 1], // moveToIndices - [], // addChildReactTags - [], // addAtIndices - [], // removeAtIndices - ); - } else { - children.push(child); - - UIManager.manageChildren( - parentInstance._nativeTag, // containerTag - [], // moveFromIndices - [], // moveToIndices - [childTag], // addChildReactTags - [children.length - 1], // addAtIndices - [], // removeAtIndices - ); - } - } - }, - - appendInitialChild( - parentInstance: Instance, - child: Instance | TextInstance, - ): void { - parentInstance._children.push(child); - }, - - commitTextUpdate( - textInstance: TextInstance, - oldText: string, - newText: string, - ): void { - UIManager.updateView( - textInstance, // reactTag - 'RCTRawText', // viewName - {text: newText}, // props - ); - }, - - commitMount( - instance: Instance, - type: string, - newProps: Props, - internalInstanceHandle: Object, - ): void { - // Noop - }, - - commitUpdate( - instance: Instance, - updatePayloadTODO: Object, - type: string, - oldProps: Props, - newProps: Props, - internalInstanceHandle: Object, - ): void { - const viewConfig = instance.viewConfig; - - updateFiberProps(instance._nativeTag, newProps); - - const updatePayload = ReactNativeAttributePayload.diff( - oldProps, - newProps, - viewConfig.validAttributes, - ); - - UIManager.updateView( - instance._nativeTag, // reactTag - viewConfig.uiViewClassName, // viewName - updatePayload, // props - ); - }, - - createInstance( - type: string, - props: Props, - rootContainerInstance: Container, - hostContext: {}, - internalInstanceHandle: Object, - ): Instance { - const tag = ReactNativeTagHandles.allocateTag(); - const viewConfig = ReactNativeViewConfigRegistry.get(type); - - if (__DEV__) { - for (const key in viewConfig.validAttributes) { - if (props.hasOwnProperty(key)) { - deepFreezeAndThrowOnMutationInDev(props[key]); - } - } - } - - const updatePayload = ReactNativeAttributePayload.create( - props, - viewConfig.validAttributes, - ); - - UIManager.createView( - tag, // reactTag - viewConfig.uiViewClassName, // viewName - rootContainerInstance, // rootTag - updatePayload, // props - ); - - const component = new ReactNativeFiberHostComponent(tag, viewConfig); - - precacheFiberNode(internalInstanceHandle, tag); - updateFiberProps(tag, props); - - // Not sure how to avoid this cast. Flow is okay if the component is defined - // in the same file but if it's external it can't see the types. - return ((component: any): Instance); - }, - - createTextInstance( - text: string, - rootContainerInstance: Container, - hostContext: {}, - internalInstanceHandle: Object, - ): TextInstance { - const tag = ReactNativeTagHandles.allocateTag(); - - UIManager.createView( - tag, // reactTag - 'RCTRawText', // viewName - rootContainerInstance, // rootTag - {text: text}, // props - ); - - precacheFiberNode(internalInstanceHandle, tag); - - return tag; - }, - - finalizeInitialChildren( - parentInstance: Instance, - type: string, - props: Props, - rootContainerInstance: Container, - ): boolean { - // Don't send a no-op message over the bridge. - if (parentInstance._children.length === 0) { - return false; - } - - // Map from child objects to native tags. - // Either way we need to pass a copy of the Array to prevent it from being frozen. - const nativeTags = parentInstance._children.map( - child => - (typeof child === 'number' - ? child // Leaf node (eg text) - : child._nativeTag), - ); - - UIManager.setChildren( - parentInstance._nativeTag, // containerTag - nativeTags, // reactTags - ); - - return false; - }, - - getRootHostContext(): {} { - return emptyObject; - }, - - getChildHostContext(): {} { - return emptyObject; - }, - - getPublicInstance(instance) { - return instance; - }, - - insertBefore( - parentInstance: Instance | Container, - child: Instance | TextInstance, - beforeChild: Instance | TextInstance, - ): void { - // TODO (bvaughn): Remove this check when... - // We create a wrapper object for the container in ReactNative render() - // Or we refactor to remove wrapper objects entirely. - // For more info on pros/cons see PR #8560 description. - invariant( - typeof parentInstance !== 'number', - 'Container does not support insertBefore operation', - ); - - const children = (parentInstance: any)._children; - - const index = children.indexOf(child); - - // Move existing child or add new child? - if (index >= 0) { - children.splice(index, 1); - const beforeChildIndex = children.indexOf(beforeChild); - children.splice(beforeChildIndex, 0, child); - - UIManager.manageChildren( - (parentInstance: any)._nativeTag, // containerID - [index], // moveFromIndices - [beforeChildIndex], // moveToIndices - [], // addChildReactTags - [], // addAtIndices - [], // removeAtIndices - ); - } else { - const beforeChildIndex = children.indexOf(beforeChild); - children.splice(beforeChildIndex, 0, child); - - const childTag = typeof child === 'number' ? child : child._nativeTag; - - UIManager.manageChildren( - (parentInstance: any)._nativeTag, // containerID - [], // moveFromIndices - [], // moveToIndices - [childTag], // addChildReactTags - [beforeChildIndex], // addAtIndices - [], // removeAtIndices - ); - } - }, - - prepareForCommit(): void { - // Noop - }, - - prepareUpdate( - instance: Instance, - type: string, - oldProps: Props, - newProps: Props, - rootContainerInstance: Container, - hostContext: {}, - ): null | Object { - return emptyObject; - }, - - removeChild( - parentInstance: Instance | Container, - child: Instance | TextInstance, - ): void { - recursivelyUncacheFiberNode(child); - - if (typeof parentInstance === 'number') { - UIManager.manageChildren( - parentInstance, // containerID - [], // moveFromIndices - [], // moveToIndices - [], // addChildReactTags - [], // addAtIndices - [0], // removeAtIndices - ); - } else { - const children = parentInstance._children; - const index = children.indexOf(child); - - children.splice(index, 1); - - UIManager.manageChildren( - parentInstance._nativeTag, // containerID - [], // moveFromIndices - [], // moveToIndices - [], // addChildReactTags - [], // addAtIndices - [index], // removeAtIndices - ); - } - }, - - resetAfterCommit(): void { - // Noop - }, - - resetTextContent(instance: Instance): void { - // Noop - }, - - shouldDeprioritizeSubtree(type: string, props: Props): boolean { - return false; - }, - - scheduleAnimationCallback: global.requestAnimationFrame, - - scheduleDeferredCallback: global.requestIdleCallback, - - shouldSetTextContent(props: Props): boolean { - // TODO (bvaughn) Revisit this decision. - // Always returning false simplifies the createInstance() implementation, - // But creates an additional child Fiber for raw text children. - // No additional native views are created though. - // It's not clear to me which is better so I'm deferring for now. - // More context @ github.com/facebook/react/pull/8560#discussion_r92111303 - return false; - }, - - useSyncScheduling: true, -}); - -ReactGenericBatching.injection.injectFiberBatchedUpdates( - NativeRenderer.batchedUpdates, -); - -const roots = new Map(); - -findNodeHandle.injection.injectFindNode((fiber: Fiber) => - NativeRenderer.findHostInstance(fiber), -); -findNodeHandle.injection.injectFindRootNodeID(instance => instance); - -// Intercept lifecycle errors and ensure they are shown with the correct stack -// trace within the native redbox component. -ReactFiberErrorLogger.injection.injectDialog( - ReactNativeFiberErrorDialog.showDialog, -); - -const ReactNative = { - // External users of findNodeHandle() expect the host tag number return type. - // The injected findNodeHandle() strategy returns the instance wrapper though. - // See NativeMethodsMixin#setNativeProps for more info on why this is done. - findNodeHandle(componentOrHandle: any): ?number { - const instance: any = findNodeHandle(componentOrHandle); - if (instance == null || typeof instance === 'number') { - return instance; - } - return instance._nativeTag; - }, - - render(element: Element, containerTag: any, callback: ?Function) { - let root = roots.get(containerTag); - - if (!root) { - // TODO (bvaughn): If we decide to keep the wrapper component, - // We could create a wrapper for containerTag as well to reduce special casing. - root = NativeRenderer.createContainer(containerTag); - roots.set(containerTag, root); - } - NativeRenderer.updateContainer(element, root, null, callback); - - return NativeRenderer.getPublicRootInstance(root); - }, - - unmountComponentAtNode(containerTag: number) { - const root = roots.get(containerTag); - if (root) { - // TODO: Is it safe to reset this now or should I wait since this unmount could be deferred? - NativeRenderer.updateContainer(null, root, null, () => { - roots.delete(containerTag); - }); - } - }, - - unmountComponentAtNodeAndRemoveContainer(containerTag: number) { - ReactNative.unmountComponentAtNode(containerTag); - - // Call back into native to remove all of the subviews from this container - UIManager.removeRootView(containerTag); - }, - - unstable_createPortal( - children: ReactNodeList, - containerTag: number, - key: ?string = null, - ) { - return ReactPortal.createPortal(children, containerTag, null, key); - }, - - unstable_batchedUpdates: ReactGenericBatching.batchedUpdates, -}; - -if (typeof injectInternals === 'function') { - injectInternals({ - findFiberByHostInstance: ReactNativeComponentTree.getClosestInstanceFromNode, - findHostInstanceByFiber: NativeRenderer.findHostInstance, - // This is an enum because we may add more (e.g. profiler build) - bundleType: __DEV__ ? 1 : 0, - version: ReactVersion, - }); -} - -module.exports = ReactNative; diff --git a/Libraries/Renderer/src/renderers/native/ReactNativeFiberErrorDialog.js b/Libraries/Renderer/src/renderers/native/ReactNativeFiberErrorDialog.js deleted file mode 100644 index 3d65ac4663..0000000000 --- a/Libraries/Renderer/src/renderers/native/ReactNativeFiberErrorDialog.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactNativeFiberErrorDialog - * @flow - */ - -'use strict'; - -const ExceptionsManager = require('ExceptionsManager'); - -import type {CapturedError} from 'ReactFiberScheduler'; - -/** - * Intercept lifecycle errors and ensure they are shown with the correct stack - * trace within the native redbox component. - */ -function ReactNativeFiberErrorDialog(capturedError: CapturedError): boolean { - const {componentStack, error} = capturedError; - - let errorMessage: string; - let errorStack: string; - let errorType: Class; - - // Typically Errors are thrown but eg strings or null can be thrown as well. - if (error && typeof error === 'object') { - const {message, name} = error; - - const summary = message ? `${name}: ${message}` : name; - - errorMessage = `${summary}\n\nThis error is located at:${componentStack}`; - errorStack = error.stack; - errorType = error.constructor; - } else { - errorMessage = `Unspecified error at:${componentStack}`; - errorStack = ''; - errorType = Error; - } - - const newError = new errorType(errorMessage); - newError.stack = errorStack; - - ExceptionsManager.handleException(newError, false); - - // Return false here to prevent ReactFiberErrorLogger default behavior of - // logging error details to console.error. Calls to console.error are - // automatically routed to the native redbox controller, which we've already - // done above by calling ExceptionsManager. - return false; -} - -module.exports.showDialog = ReactNativeFiberErrorDialog; diff --git a/Libraries/Renderer/src/renderers/native/ReactNativeFiberHostComponent.js b/Libraries/Renderer/src/renderers/native/ReactNativeFiberHostComponent.js deleted file mode 100644 index 017f08b847..0000000000 --- a/Libraries/Renderer/src/renderers/native/ReactNativeFiberHostComponent.js +++ /dev/null @@ -1,101 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactNativeFiberHostComponent - * @flow - * @preventMunge - */ - -'use strict'; - -var ReactNativeAttributePayload = require('ReactNativeAttributePayload'); -var TextInputState = require('TextInputState'); -var UIManager = require('UIManager'); - -var {mountSafeCallback, warnForStyleProps} = require('NativeMethodsMixinUtils'); - -import type { - MeasureInWindowOnSuccessCallback, - MeasureLayoutOnSuccessCallback, - MeasureOnSuccessCallback, - NativeMethodsInterface, -} from 'NativeMethodsMixinUtils'; -import type {Instance} from 'ReactNativeFiber'; -import type { - ReactNativeBaseComponentViewConfig, -} from 'ReactNativeViewConfigRegistry'; - -/** - * This component defines the same methods as NativeMethodsMixin but without the - * findNodeHandle wrapper. This wrapper is unnecessary for HostComponent views - * and would also result in a circular require.js dependency (since - * ReactNativeFiber depends on this component and NativeMethodsMixin depends on - * ReactNativeFiber). - */ -class ReactNativeFiberHostComponent implements NativeMethodsInterface { - _children: Array; - _nativeTag: number; - viewConfig: ReactNativeBaseComponentViewConfig; - - constructor(tag: number, viewConfig: ReactNativeBaseComponentViewConfig) { - this._nativeTag = tag; - this._children = []; - this.viewConfig = viewConfig; - } - - blur() { - TextInputState.blurTextInput(this._nativeTag); - } - - focus() { - TextInputState.focusTextInput(this._nativeTag); - } - - measure(callback: MeasureOnSuccessCallback) { - UIManager.measure(this._nativeTag, mountSafeCallback(this, callback)); - } - - measureInWindow(callback: MeasureInWindowOnSuccessCallback) { - UIManager.measureInWindow( - this._nativeTag, - mountSafeCallback(this, callback), - ); - } - - measureLayout( - relativeToNativeNode: number, - onSuccess: MeasureLayoutOnSuccessCallback, - onFail: () => void /* currently unused */, - ) { - UIManager.measureLayout( - this._nativeTag, - relativeToNativeNode, - mountSafeCallback(this, onFail), - mountSafeCallback(this, onSuccess), - ); - } - - setNativeProps(nativeProps: Object) { - if (__DEV__) { - warnForStyleProps(nativeProps, this.viewConfig.validAttributes); - } - - var updatePayload = ReactNativeAttributePayload.create( - nativeProps, - this.viewConfig.validAttributes, - ); - - UIManager.updateView( - this._nativeTag, - this.viewConfig.uiViewClassName, - updatePayload, - ); - } -} - -module.exports = ReactNativeFiberHostComponent; diff --git a/Libraries/Renderer/src/renderers/native/ReactNativeGlobalResponderHandler.js b/Libraries/Renderer/src/renderers/native/ReactNativeGlobalResponderHandler.js deleted file mode 100644 index 73bfe04720..0000000000 --- a/Libraries/Renderer/src/renderers/native/ReactNativeGlobalResponderHandler.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactNativeGlobalResponderHandler - */ -'use strict'; - -var UIManager = require('UIManager'); - -var ReactNativeGlobalResponderHandler = { - onChange: function(from, to, blockNativeResponder) { - if (to !== null) { - // TODO (bvaughn) Clean up once Stack is deprecated - var tag = typeof to.tag !== 'number' - ? to._rootNodeID - : to.stateNode._nativeTag; - UIManager.setJSResponder(tag, blockNativeResponder); - } else { - UIManager.clearJSResponder(); - } - }, -}; - -module.exports = ReactNativeGlobalResponderHandler; diff --git a/Libraries/Renderer/src/renderers/native/ReactNativeInjection.js b/Libraries/Renderer/src/renderers/native/ReactNativeInjection.js deleted file mode 100644 index 116948d7bd..0000000000 --- a/Libraries/Renderer/src/renderers/native/ReactNativeInjection.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactNativeInjection - * @flow - */ -'use strict'; - -/** - * Make sure essential globals are available and are patched correctly. Please don't remove this - * line. Bundles created by react-packager `require` it before executing any application code. This - * ensures it exists in the dependency graph and can be `require`d. - * TODO: require this in packager, not in React #10932517 - */ -require('InitializeCore'); - -var EventPluginHub = require('EventPluginHub'); -var EventPluginUtils = require('EventPluginUtils'); -var RCTEventEmitter = require('RCTEventEmitter'); -var ReactNativeBridgeEventPlugin = require('ReactNativeBridgeEventPlugin'); -var ReactNativeComponentTree = require('ReactNativeComponentTree'); -var ReactNativeEventEmitter = require('ReactNativeEventEmitter'); -var ReactNativeEventPluginOrder = require('ReactNativeEventPluginOrder'); -var ReactNativeGlobalResponderHandler = require('ReactNativeGlobalResponderHandler'); -var ResponderEventPlugin = require('ResponderEventPlugin'); - -function inject() { - /** - * Register the event emitter with the native bridge - */ - RCTEventEmitter.register(ReactNativeEventEmitter); - - /** - * Inject module for resolving DOM hierarchy and plugin ordering. - */ - EventPluginHub.injection.injectEventPluginOrder(ReactNativeEventPluginOrder); - EventPluginUtils.injection.injectComponentTree(ReactNativeComponentTree); - - ResponderEventPlugin.injection.injectGlobalResponderHandler( - ReactNativeGlobalResponderHandler, - ); - - /** - * Some important event plugins included by default (without having to require - * them). - */ - EventPluginHub.injection.injectEventPluginsByName({ - ResponderEventPlugin: ResponderEventPlugin, - ReactNativeBridgeEventPlugin: ReactNativeBridgeEventPlugin, - }); -} - -module.exports = { - inject: inject, -}; diff --git a/Libraries/Renderer/src/renderers/native/ReactNativeMount.js b/Libraries/Renderer/src/renderers/native/ReactNativeMount.js deleted file mode 100644 index ee4a28f45a..0000000000 --- a/Libraries/Renderer/src/renderers/native/ReactNativeMount.js +++ /dev/null @@ -1,227 +0,0 @@ -/** - * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactNativeMount - * @flow - */ -'use strict'; - -var React = require('react'); -var ReactInstrumentation = require('ReactInstrumentation'); -var ReactNativeContainerInfo = require('ReactNativeContainerInfo'); -var ReactNativeTagHandles = require('ReactNativeTagHandles'); -var ReactReconciler = require('ReactReconciler'); -var ReactUpdateQueue = require('ReactUpdateQueue'); -var ReactUpdates = require('ReactUpdates'); -var UIManager = require('UIManager'); - -var emptyObject = require('fbjs/lib/emptyObject'); -var instantiateReactComponent = require('instantiateReactComponent'); -var shouldUpdateReactComponent = require('shouldUpdateReactComponent'); - -/** - * Temporary (?) hack so that we can store all top-level pending updates on - * composites instead of having to worry about different types of components - * here. - */ -var TopLevelWrapper = function() {}; -TopLevelWrapper.prototype.isReactComponent = {}; -if (__DEV__) { - TopLevelWrapper.displayName = 'TopLevelWrapper'; -} -TopLevelWrapper.prototype.render = function() { - return this.props.child; -}; -TopLevelWrapper.isReactTopLevelWrapper = true; - -/** - * Mounts this component and inserts it into the DOM. - * - * @param {ReactComponent} componentInstance The instance to mount. - * @param {number} rootID ID of the root node. - * @param {number} containerTag container element to mount into. - * @param {ReactReconcileTransaction} transaction - */ -function mountComponentIntoNode(componentInstance, containerTag, transaction) { - var markup = ReactReconciler.mountComponent( - componentInstance, - transaction, - null, - ReactNativeContainerInfo(containerTag), - emptyObject, - 0 /* parentDebugID */, - ); - componentInstance._renderedComponent._topLevelWrapper = componentInstance; - ReactNativeMount._mountImageIntoNode(markup, containerTag); -} - -/** - * Batched mount. - * - * @param {ReactComponent} componentInstance The instance to mount. - * @param {number} rootID ID of the root node. - * @param {number} containerTag container element to mount into. - */ -function batchedMountComponentIntoNode(componentInstance, containerTag) { - var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(); - transaction.perform( - mountComponentIntoNode, - null, - componentInstance, - containerTag, - transaction, - ); - ReactUpdates.ReactReconcileTransaction.release(transaction); -} - -/** - * As soon as `ReactMount` is refactored to not rely on the DOM, we can share - * code between the two. For now, we'll hard code the ID logic. - */ -var ReactNativeMount = { - _instancesByContainerID: {}, - - // these two functions are needed by React Devtools - findNodeHandle: require('findNodeHandle'), - - /** - * @param {ReactComponent} instance Instance to render. - * @param {containerTag} containerView Handle to native view tag - */ - renderComponent: function( - nextElement: ReactElement<*>, - containerTag: number, - callback?: ?() => void, - ): ?ReactComponent { - var nextWrappedElement = React.createElement(TopLevelWrapper, { - child: nextElement, - }); - - var topRootNodeID = containerTag; - var prevComponent = ReactNativeMount._instancesByContainerID[topRootNodeID]; - if (prevComponent) { - var prevWrappedElement = prevComponent._currentElement; - var prevElement = prevWrappedElement.props.child; - if (shouldUpdateReactComponent(prevElement, nextElement)) { - ReactUpdateQueue.enqueueElementInternal( - prevComponent, - nextWrappedElement, - emptyObject, - ); - if (callback) { - ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback); - } - return prevComponent; - } else { - ReactNativeMount.unmountComponentAtNode(containerTag); - } - } - - if (!ReactNativeTagHandles.reactTagIsNativeTopRootID(containerTag)) { - console.error('You cannot render into anything but a top root'); - return null; - } - - ReactNativeTagHandles.assertRootTag(containerTag); - - var instance = instantiateReactComponent(nextWrappedElement, false); - ReactNativeMount._instancesByContainerID[containerTag] = instance; - - if (callback) { - var nonNullCallback = callback; - instance._pendingCallbacks = [ - function() { - nonNullCallback.call(instance._renderedComponent.getPublicInstance()); - }, - ]; - } - - // The initial render is synchronous but any updates that happen during - // rendering, in componentWillMount or componentDidMount, will be batched - // according to the current batching strategy. - - ReactUpdates.batchedUpdates( - batchedMountComponentIntoNode, - instance, - containerTag, - ); - var component = instance._renderedComponent.getPublicInstance(); - return component; - }, - - /** - * @param {View} view View tree image. - * @param {number} containerViewID View to insert sub-view into. - */ - _mountImageIntoNode: function(mountImage: number, containerID: number) { - // Since we now know that the `mountImage` has been mounted, we can - // mark it as such. - var childTag = mountImage; - UIManager.setChildren(containerID, [childTag]); - }, - - /** - * Standard unmounting of the component that is rendered into `containerID`, - * but will also execute a command to remove the actual container view - * itself. This is useful when a client is cleaning up a React tree, and also - * knows that the container will no longer be needed. When executing - * asynchronously, it's easier to just have this method be the one that calls - * for removal of the view. - */ - unmountComponentAtNodeAndRemoveContainer: function(containerTag: number) { - ReactNativeMount.unmountComponentAtNode(containerTag); - // call back into native to remove all of the subviews from this container - UIManager.removeRootView(containerTag); - }, - - /** - * Unmount component at container ID by iterating through each child component - * that has been rendered and unmounting it. There should just be one child - * component at this time. - */ - unmountComponentAtNode: function(containerTag: number): boolean { - if (!ReactNativeTagHandles.reactTagIsNativeTopRootID(containerTag)) { - console.error('You cannot render into anything but a top root'); - return false; - } - - var instance = ReactNativeMount._instancesByContainerID[containerTag]; - if (!instance) { - return false; - } - if (__DEV__) { - ReactInstrumentation.debugTool.onBeginFlush(); - } - ReactNativeMount.unmountComponentFromNode(instance, containerTag); - delete ReactNativeMount._instancesByContainerID[containerTag]; - if (__DEV__) { - ReactInstrumentation.debugTool.onEndFlush(); - } - return true; - }, - - /** - * Unmounts a component and sends messages back to iOS to remove its subviews. - * - * @param {ReactComponent} instance React component instance. - * @param {string} containerID ID of container we're removing from. - * @final - * @internal - * @see {ReactNativeMount.unmountComponentAtNode} - */ - unmountComponentFromNode: function( - instance: ReactComponent, - containerID: number, - ) { - // Call back into native to remove all of the subviews from this container - ReactReconciler.unmountComponent(instance); - UIManager.removeSubviewsFromContainerWithID(containerID); - }, -}; - -module.exports = ReactNativeMount; diff --git a/Libraries/Renderer/src/renderers/native/ReactNativePropRegistry.js b/Libraries/Renderer/src/renderers/native/ReactNativePropRegistry.js deleted file mode 100644 index 3cffb9acf3..0000000000 --- a/Libraries/Renderer/src/renderers/native/ReactNativePropRegistry.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactNativePropRegistry - * @flow - */ -'use strict'; - -var objects = {}; -var uniqueID = 1; -var emptyObject = {}; - -class ReactNativePropRegistry { - static register(object: Object): number { - var id = ++uniqueID; - if (__DEV__) { - Object.freeze(object); - } - objects[id] = object; - return id; - } - - static getByID(id: number): Object { - if (!id) { - // Used in the style={[condition && id]} pattern, - // we want it to be a no-op when the value is false or null - return emptyObject; - } - - var object = objects[id]; - if (!object) { - console.warn('Invalid style with id `' + id + '`. Skipping ...'); - return emptyObject; - } - return object; - } -} - -module.exports = ReactNativePropRegistry; diff --git a/Libraries/Renderer/src/renderers/native/ReactNativeReconcileTransaction.js b/Libraries/Renderer/src/renderers/native/ReactNativeReconcileTransaction.js deleted file mode 100644 index 9ee4fc9815..0000000000 --- a/Libraries/Renderer/src/renderers/native/ReactNativeReconcileTransaction.js +++ /dev/null @@ -1,132 +0,0 @@ -/** - * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactNativeReconcileTransaction - * @flow - */ -'use strict'; - -var CallbackQueue = require('CallbackQueue'); -var PooledClass = require('PooledClass'); -var Transaction = require('Transaction'); -var ReactInstrumentation = require('ReactInstrumentation'); -var ReactUpdateQueue = require('ReactUpdateQueue'); - -/** - * Provides a `CallbackQueue` queue for collecting `onDOMReady` callbacks during - * the performing of the transaction. - */ -var ON_DOM_READY_QUEUEING = { - /** - * Initializes the internal `onDOMReady` queue. - */ - initialize: function() { - this.reactMountReady.reset(); - }, - - /** - * After DOM is flushed, invoke all registered `onDOMReady` callbacks. - */ - close: function() { - this.reactMountReady.notifyAll(); - }, -}; - -/** - * Executed within the scope of the `Transaction` instance. Consider these as - * being member methods, but with an implied ordering while being isolated from - * each other. - */ -var TRANSACTION_WRAPPERS = [ON_DOM_READY_QUEUEING]; - -if (__DEV__) { - TRANSACTION_WRAPPERS.push({ - initialize: ReactInstrumentation.debugTool.onBeginFlush, - close: ReactInstrumentation.debugTool.onEndFlush, - }); -} - -/** - * Currently: - * - The order that these are listed in the transaction is critical: - * - Suppresses events. - * - Restores selection range. - * - * Future: - * - Restore document/overflow scroll positions that were unintentionally - * modified via DOM insertions above the top viewport boundary. - * - Implement/integrate with customized constraint based layout system and keep - * track of which dimensions must be remeasured. - * - * @class ReactNativeReconcileTransaction - */ -function ReactNativeReconcileTransaction() { - this.reinitializeTransaction(); - this.reactMountReady = CallbackQueue.getPooled(null); -} - -var Mixin = { - /** - * @see Transaction - * @abstract - * @final - * @return {array} List of operation wrap procedures. - * TODO: convert to array - */ - getTransactionWrappers: function() { - return TRANSACTION_WRAPPERS; - }, - - /** - * @return {object} The queue to collect `onDOMReady` callbacks with. - * TODO: convert to ReactMountReady - */ - getReactMountReady: function() { - return this.reactMountReady; - }, - - /** - * @return {object} The queue to collect React async events. - */ - getUpdateQueue: function() { - return ReactUpdateQueue; - }, - - /** - * Save current transaction state -- if the return value from this method is - * passed to `rollback`, the transaction will be reset to that state. - */ - checkpoint: function() { - // reactMountReady is the our only stateful wrapper - return this.reactMountReady.checkpoint(); - }, - - rollback: function(checkpoint) { - this.reactMountReady.rollback(checkpoint); - }, - - /** - * `PooledClass` looks for this, and will invoke this before allowing this - * instance to be reused. - */ - destructor: function() { - CallbackQueue.release(this.reactMountReady); - this.reactMountReady = null; - }, -}; - -Object.assign( - ReactNativeReconcileTransaction.prototype, - Transaction, - ReactNativeReconcileTransaction, - Mixin, -); - -PooledClass.addPoolingTo(ReactNativeReconcileTransaction); - -module.exports = ReactNativeReconcileTransaction; diff --git a/Libraries/Renderer/src/renderers/native/ReactNativeStack.js b/Libraries/Renderer/src/renderers/native/ReactNativeStack.js deleted file mode 100644 index a9fa118cf2..0000000000 --- a/Libraries/Renderer/src/renderers/native/ReactNativeStack.js +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactNativeStack - * @flow - */ -'use strict'; - -var ReactNativeComponentTree = require('ReactNativeComponentTree'); -var ReactNativeInjection = require('ReactNativeInjection'); -var ReactNativeMount = require('ReactNativeMount'); -var ReactNativeStackInjection = require('ReactNativeStackInjection'); -var ReactUpdates = require('ReactUpdates'); - -var findNodeHandle = require('findNodeHandle'); - -ReactNativeInjection.inject(); -ReactNativeStackInjection.inject(); - -var render = function( - element: ReactElement, - mountInto: number, - callback?: ?() => void, -): ?ReactComponent { - return ReactNativeMount.renderComponent(element, mountInto, callback); -}; - -var ReactNative = { - hasReactNativeInitialized: false, - - // External users of findNodeHandle() expect the host tag number return type. - // The injected findNodeHandle() strategy returns the instance wrapper though. - // See NativeMethodsMixin#setNativeProps for more info on why this is done. - findNodeHandle(componentOrHandle: any): ?number { - const nodeHandle = findNodeHandle(componentOrHandle); - if (nodeHandle == null || typeof nodeHandle === 'number') { - return nodeHandle; - } - return nodeHandle.getHostNode(); - }, - - render: render, - - unmountComponentAtNode: ReactNativeMount.unmountComponentAtNode, - - /* eslint-disable camelcase */ - unstable_batchedUpdates: ReactUpdates.batchedUpdates, - /* eslint-enable camelcase */ - - unmountComponentAtNodeAndRemoveContainer: ReactNativeMount.unmountComponentAtNodeAndRemoveContainer, -}; - -// Inject the runtime into a devtools global hook regardless of browser. -// Allows for debugging when the hook is injected on the page. -/* globals __REACT_DEVTOOLS_GLOBAL_HOOK__ */ -if ( - typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && - typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function' -) { - __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ - ComponentTree: { - getClosestInstanceFromNode: function(node) { - return ReactNativeComponentTree.getClosestInstanceFromNode(node); - }, - getNodeFromInstance: function(inst) { - // inst is an internal instance (but could be a composite) - while (inst._renderedComponent) { - inst = inst._renderedComponent; - } - if (inst) { - return ReactNativeComponentTree.getNodeFromInstance(inst); - } else { - return null; - } - }, - }, - Mount: ReactNativeMount, - Reconciler: require('ReactReconciler'), - }); -} - -module.exports = ReactNative; diff --git a/Libraries/Renderer/src/renderers/native/ReactNativeStackInjection.js b/Libraries/Renderer/src/renderers/native/ReactNativeStackInjection.js deleted file mode 100644 index 5aa3d3d879..0000000000 --- a/Libraries/Renderer/src/renderers/native/ReactNativeStackInjection.js +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactNativeStackInjection - * @flow - */ -'use strict'; - -/** - * Make sure essential globals are available and are patched correctly. Please don't remove this - * line. Bundles created by react-packager `require` it before executing any application code. This - * ensures it exists in the dependency graph and can be `require`d. - * TODO: require this in packager, not in React #10932517 - */ -require('InitializeCore'); - -var React = require('react'); -var ReactComponentEnvironment = require('ReactComponentEnvironment'); -var ReactDefaultBatchingStrategy = require('ReactDefaultBatchingStrategy'); -var ReactEmptyComponent = require('ReactEmptyComponent'); -var ReactGenericBatching = require('ReactGenericBatching'); -var ReactHostComponent = require('ReactHostComponent'); -var ReactNativeComponentEnvironment = require('ReactNativeComponentEnvironment'); -var ReactNativeTextComponent = require('ReactNativeTextComponent'); -var ReactSimpleEmptyComponent = require('ReactSimpleEmptyComponent'); -var ReactUpdates = require('ReactUpdates'); - -var findNodeHandle = require('findNodeHandle'); -var invariant = require('fbjs/lib/invariant'); - -function inject() { - ReactGenericBatching.injection.injectStackBatchedUpdates( - ReactUpdates.batchedUpdates, - ); - - ReactUpdates.injection.injectReconcileTransaction( - ReactNativeComponentEnvironment.ReactReconcileTransaction, - ); - - ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy); - - ReactComponentEnvironment.injection.injectEnvironment( - ReactNativeComponentEnvironment, - ); - - var EmptyComponent = instantiate => { - // Can't import View at the top because it depends on React to make its composite - var View = require('View'); - return new ReactSimpleEmptyComponent( - React.createElement(View, { - collapsable: true, - style: {position: 'absolute'}, - }), - instantiate, - ); - }; - - findNodeHandle.injection.injectFindNode(instance => instance); - findNodeHandle.injection.injectFindRootNodeID(instance => instance); - - ReactEmptyComponent.injection.injectEmptyComponentFactory(EmptyComponent); - - ReactHostComponent.injection.injectTextComponentClass( - ReactNativeTextComponent, - ); - ReactHostComponent.injection.injectGenericComponentClass(function(tag) { - // Show a nicer error message for non-function tags - var info = ''; - if (typeof tag === 'string' && /^[a-z]/.test(tag)) { - info += ' Each component name should start with an uppercase letter.'; - } - invariant(false, 'Expected a component class, got %s.%s', tag, info); - }); -} - -module.exports = { - inject: inject, -}; diff --git a/Libraries/Renderer/src/renderers/native/ReactNativeTagHandles.js b/Libraries/Renderer/src/renderers/native/ReactNativeTagHandles.js deleted file mode 100644 index 51e54d4033..0000000000 --- a/Libraries/Renderer/src/renderers/native/ReactNativeTagHandles.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactNativeTagHandles - * @flow - */ -'use strict'; - -var invariant = require('fbjs/lib/invariant'); - -/** - * Keeps track of allocating and associating native "tags" which are numeric, - * unique view IDs. All the native tags are negative numbers, to avoid - * collisions, but in the JS we keep track of them as positive integers to store - * them effectively in Arrays. So we must refer to them as "inverses" of the - * native tags (that are * normally negative). - * - * It *must* be the case that every `rootNodeID` always maps to the exact same - * `tag` forever. The easiest way to accomplish this is to never delete - * anything from this table. - * Why: Because `dangerouslyReplaceNodeWithMarkupByID` relies on being able to - * unmount a component with a `rootNodeID`, then mount a new one in its place, - */ -var INITIAL_TAG_COUNT = 1; -var ReactNativeTagHandles = { - tagsStartAt: INITIAL_TAG_COUNT, - tagCount: INITIAL_TAG_COUNT, - - allocateTag: function(): number { - // Skip over root IDs as those are reserved for native - while (this.reactTagIsNativeTopRootID(ReactNativeTagHandles.tagCount)) { - ReactNativeTagHandles.tagCount++; - } - var tag = ReactNativeTagHandles.tagCount; - ReactNativeTagHandles.tagCount++; - return tag; - }, - - assertRootTag: function(tag: number): void { - invariant( - this.reactTagIsNativeTopRootID(tag), - 'Expect a native root tag, instead got %s', - tag, - ); - }, - - reactTagIsNativeTopRootID: function(reactTag: number): boolean { - // We reserve all tags that are 1 mod 10 for native root views - return reactTag % 10 === 1; - }, -}; - -module.exports = ReactNativeTagHandles; diff --git a/Libraries/Renderer/src/renderers/native/ReactNativeTextComponent.js b/Libraries/Renderer/src/renderers/native/ReactNativeTextComponent.js deleted file mode 100644 index 6f7988403a..0000000000 --- a/Libraries/Renderer/src/renderers/native/ReactNativeTextComponent.js +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactNativeTextComponent - */ - -'use strict'; - -var ReactNativeComponentTree = require('ReactNativeComponentTree'); -var ReactNativeTagHandles = require('ReactNativeTagHandles'); -var UIManager = require('UIManager'); - -var invariant = require('fbjs/lib/invariant'); - -var ReactNativeTextComponent = function(text) { - // This is really a ReactText (ReactNode), not a ReactElement - this._currentElement = text; - this._stringText = '' + text; - this._hostParent = null; - this._rootNodeID = 0; -}; - -Object.assign(ReactNativeTextComponent.prototype, { - mountComponent: function( - transaction, - hostParent, - hostContainerInfo, - context, - ) { - // TODO: hostParent should have this context already. Stop abusing context. - invariant( - context.isInAParentText, - 'RawText "%s" must be wrapped in an explicit component.', - this._stringText, - ); - this._hostParent = hostParent; - var tag = ReactNativeTagHandles.allocateTag(); - this._rootNodeID = tag; - var nativeTopRootTag = hostContainerInfo._tag; - UIManager.createView(tag, 'RCTRawText', nativeTopRootTag, { - text: this._stringText, - }); - - ReactNativeComponentTree.precacheNode(this, tag); - - return tag; - }, - - getHostNode: function() { - return this._rootNodeID; - }, - - receiveComponent: function(nextText, transaction, context) { - if (nextText !== this._currentElement) { - this._currentElement = nextText; - var nextStringText = '' + nextText; - if (nextStringText !== this._stringText) { - this._stringText = nextStringText; - UIManager.updateView(this._rootNodeID, 'RCTRawText', { - text: this._stringText, - }); - } - } - }, - - unmountComponent: function() { - ReactNativeComponentTree.uncacheNode(this); - this._currentElement = null; - this._stringText = null; - this._rootNodeID = 0; - }, -}); - -module.exports = ReactNativeTextComponent; diff --git a/Libraries/Renderer/src/renderers/native/ReactNativeViewConfigRegistry.js b/Libraries/Renderer/src/renderers/native/ReactNativeViewConfigRegistry.js deleted file mode 100644 index 23a783cb31..0000000000 --- a/Libraries/Renderer/src/renderers/native/ReactNativeViewConfigRegistry.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactNativeViewConfigRegistry - * @flow - */ - -'use strict'; - -const invariant = require('fbjs/lib/invariant'); - -export type ReactNativeBaseComponentViewConfig = { - validAttributes: Object, - uiViewClassName: string, - propTypes?: Object, -}; - -const viewConfigs = new Map(); - -const prefix = 'topsecret-'; - -const ReactNativeViewConfigRegistry = { - register(viewConfig: ReactNativeBaseComponentViewConfig) { - const name = viewConfig.uiViewClassName; - invariant( - !viewConfigs.has(name), - 'Tried to register two views with the same name %s', - name, - ); - const secretName = prefix + name; - viewConfigs.set(secretName, viewConfig); - return secretName; - }, - get(secretName: string) { - const config = viewConfigs.get(secretName); - invariant(config, 'View config not found for name %s', secretName); - return config; - }, -}; - -module.exports = ReactNativeViewConfigRegistry; diff --git a/Libraries/Renderer/src/renderers/native/__mocks__/ReactNative.js b/Libraries/Renderer/src/renderers/native/__mocks__/ReactNative.js deleted file mode 100644 index ce5f605038..0000000000 --- a/Libraries/Renderer/src/renderers/native/__mocks__/ReactNative.js +++ /dev/null @@ -1,16 +0,0 @@ -/** - * Copyright 2013-2015, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - */ - -'use strict'; - -const ReactNativeFeatureFlags = require('ReactNativeFeatureFlags'); - -module.exports = ReactNativeFeatureFlags.useFiber - ? require('ReactNativeFiber') - : require('ReactNativeStack'); diff --git a/Libraries/Renderer/src/renderers/native/__tests__/ReactNativeAttributePayload-test.js b/Libraries/Renderer/src/renderers/native/__tests__/ReactNativeAttributePayload-test.js deleted file mode 100644 index 77c8ae799c..0000000000 --- a/Libraries/Renderer/src/renderers/native/__tests__/ReactNativeAttributePayload-test.js +++ /dev/null @@ -1,236 +0,0 @@ -/** - * Copyright (c) 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - */ -'use strict'; - -var ReactNativeAttributePayload = require('ReactNativeAttributePayload'); -var ReactNativePropRegistry = require('ReactNativePropRegistry'); - -var diff = ReactNativeAttributePayload.diff; - -describe('ReactNativeAttributePayload', () => { - it('should work with simple example', () => { - expect(diff({a: 1, c: 3}, {b: 2, c: 3}, {a: true, b: true})).toEqual({ - a: null, - b: 2, - }); - }); - - it('should skip fields that are equal', () => { - expect( - diff( - {a: 1, b: 'two', c: true, d: false, e: undefined, f: 0}, - {a: 1, b: 'two', c: true, d: false, e: undefined, f: 0}, - {a: true, b: true, c: true, d: true, e: true, f: true}, - ), - ).toEqual(null); - }); - - it('should remove fields', () => { - expect(diff({a: 1}, {}, {a: true})).toEqual({a: null}); - }); - - it('should remove fields that are set to undefined', () => { - expect(diff({a: 1}, {a: undefined}, {a: true})).toEqual({a: null}); - }); - - it('should ignore invalid fields', () => { - expect(diff({a: 1}, {b: 2}, {})).toEqual(null); - }); - - it('should use the diff attribute', () => { - var diffA = jest.fn((a, b) => true); - var diffB = jest.fn((a, b) => false); - expect( - diff( - {a: [1], b: [3]}, - {a: [2], b: [4]}, - {a: {diff: diffA}, b: {diff: diffB}}, - ), - ).toEqual({a: [2]}); - expect(diffA).toBeCalledWith([1], [2]); - expect(diffB).toBeCalledWith([3], [4]); - }); - - it('should not use the diff attribute on addition/removal', () => { - var diffA = jest.fn(); - var diffB = jest.fn(); - expect( - diff({a: [1]}, {b: [2]}, {a: {diff: diffA}, b: {diff: diffB}}), - ).toEqual({a: null, b: [2]}); - expect(diffA).not.toBeCalled(); - expect(diffB).not.toBeCalled(); - }); - - it('should do deep diffs of Objects by default', () => { - expect( - diff( - {a: [1], b: {k: [3, 4]}, c: {k: [4, 4]}}, - {a: [2], b: {k: [3, 4]}, c: {k: [4, 5]}}, - {a: true, b: true, c: true}, - ), - ).toEqual({a: [2], c: {k: [4, 5]}}); - }); - - it('should work with undefined styles', () => { - expect( - diff( - {style: {a: '#ffffff', b: 1}}, - {style: undefined}, - {style: {b: true}}, - ), - ).toEqual({b: null}); - expect( - diff( - {style: undefined}, - {style: {a: '#ffffff', b: 1}}, - {style: {b: true}}, - ), - ).toEqual({b: 1}); - expect( - diff({style: undefined}, {style: undefined}, {style: {b: true}}), - ).toEqual(null); - }); - - it('should work with empty styles', () => { - expect(diff({a: 1, c: 3}, {}, {a: true, b: true})).toEqual({a: null}); - expect(diff({}, {a: 1, c: 3}, {a: true, b: true})).toEqual({a: 1}); - expect(diff({}, {}, {a: true, b: true})).toEqual(null); - }); - - it('should flatten nested styles and predefined styles', () => { - var validStyleAttribute = {someStyle: {foo: true, bar: true}}; - - expect( - diff({}, {someStyle: [{foo: 1}, {bar: 2}]}, validStyleAttribute), - ).toEqual({foo: 1, bar: 2}); - - expect( - diff({someStyle: [{foo: 1}, {bar: 2}]}, {}, validStyleAttribute), - ).toEqual({foo: null, bar: null}); - - var barStyle = ReactNativePropRegistry.register({ - bar: 3, - }); - - expect( - diff( - {}, - {someStyle: [[{foo: 1}, {foo: 2}], barStyle]}, - validStyleAttribute, - ), - ).toEqual({foo: 2, bar: 3}); - }); - - it('should reset a value to a previous if it is removed', () => { - var validStyleAttribute = {someStyle: {foo: true, bar: true}}; - - expect( - diff( - {someStyle: [{foo: 1}, {foo: 3}]}, - {someStyle: [{foo: 1}, {bar: 2}]}, - validStyleAttribute, - ), - ).toEqual({foo: 1, bar: 2}); - }); - - it('should not clear removed props if they are still in another slot', () => { - var validStyleAttribute = {someStyle: {foo: true, bar: true}}; - - expect( - diff( - {someStyle: [{}, {foo: 3, bar: 2}]}, - {someStyle: [{foo: 3}, {bar: 2}]}, - validStyleAttribute, - ), - ).toEqual({foo: 3}); // this should ideally be null. heuristic tradeoff. - - expect( - diff( - {someStyle: [{}, {foo: 3, bar: 2}]}, - {someStyle: [{foo: 1, bar: 1}, {bar: 2}]}, - validStyleAttribute, - ), - ).toEqual({bar: 2, foo: 1}); - }); - - it('should clear a prop if a later style is explicit null/undefined', () => { - var validStyleAttribute = {someStyle: {foo: true, bar: true}}; - expect( - diff( - {someStyle: [{}, {foo: 3, bar: 2}]}, - {someStyle: [{foo: 1}, {bar: 2, foo: null}]}, - validStyleAttribute, - ), - ).toEqual({foo: null}); - - expect( - diff( - {someStyle: [{foo: 3}, {foo: null, bar: 2}]}, - {someStyle: [{foo: null}, {bar: 2}]}, - validStyleAttribute, - ), - ).toEqual({foo: null}); - - expect( - diff( - {someStyle: [{foo: 1}, {foo: null}]}, - {someStyle: [{foo: 2}, {foo: null}]}, - validStyleAttribute, - ), - ).toEqual({foo: null}); // this should ideally be null. heuristic. - - // Test the same case with object equality because an early bailout doesn't - // work in this case. - var fooObj = {foo: 3}; - expect( - diff( - {someStyle: [{foo: 1}, fooObj]}, - {someStyle: [{foo: 2}, fooObj]}, - validStyleAttribute, - ), - ).toEqual({foo: 3}); // this should ideally be null. heuristic. - - expect( - diff( - {someStyle: [{foo: 1}, {foo: 3}]}, - {someStyle: [{foo: 2}, {foo: undefined}]}, - validStyleAttribute, - ), - ).toEqual({foo: null}); // this should ideally be null. heuristic. - }); - - // Function properties are just markers to native that events should be sent. - it('should convert functions to booleans', () => { - // Note that if the property changes from one function to another, we don't - // need to send an update. - expect( - diff( - { - a: function() { - return 1; - }, - b: function() { - return 2; - }, - c: 3, - }, - { - b: function() { - return 9; - }, - c: function() { - return 3; - }, - }, - {a: true, b: true, c: true}, - ), - ).toEqual({a: null, c: true}); - }); -}); diff --git a/Libraries/Renderer/src/renderers/native/__tests__/ReactNativeEvents-test.js b/Libraries/Renderer/src/renderers/native/__tests__/ReactNativeEvents-test.js deleted file mode 100644 index 495f51338a..0000000000 --- a/Libraries/Renderer/src/renderers/native/__tests__/ReactNativeEvents-test.js +++ /dev/null @@ -1,366 +0,0 @@ -/** - * Copyright 2013-2015, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @emails react-core - */ - -'use strict'; - -var PropTypes; -var RCTEventEmitter; -var React; -var ReactNative; -var ResponderEventPlugin; -var UIManager; -var createReactNativeComponentClass; - -beforeEach(() => { - jest.resetModules(); - - PropTypes = require('prop-types'); - RCTEventEmitter = require('RCTEventEmitter'); - React = require('react'); - ReactNative = require('ReactNative'); - ResponderEventPlugin = require('ResponderEventPlugin'); - UIManager = require('UIManager'); - createReactNativeComponentClass = require('createReactNativeComponentClass'); -}); - -it('handles events', () => { - expect(RCTEventEmitter.register.mock.calls.length).toBe(1); - var EventEmitter = RCTEventEmitter.register.mock.calls[0][0]; - var View = createReactNativeComponentClass({ - validAttributes: {foo: true}, - uiViewClassName: 'View', - }); - - var log = []; - ReactNative.render( - log.push('outer touchend')} - onTouchEndCapture={() => log.push('outer touchend capture')} - onTouchStart={() => log.push('outer touchstart')} - onTouchStartCapture={() => log.push('outer touchstart capture')}> - log.push('inner touchend capture')} - onTouchEnd={() => log.push('inner touchend')} - onTouchStartCapture={() => log.push('inner touchstart capture')} - onTouchStart={() => log.push('inner touchstart')} - /> - , - 1, - ); - - expect(UIManager.__dumpHierarchyForJestTestsOnly()).toMatchSnapshot(); - expect(UIManager.createView.mock.calls.length).toBe(2); - - // Don't depend on the order of createView() calls. - // Stack creates views outside-in; fiber creates them inside-out. - var innerTag = UIManager.createView.mock.calls.find( - args => args[3].foo === 'inner', - )[0]; - - EventEmitter.receiveTouches( - 'topTouchStart', - [{target: innerTag, identifier: 17}], - [0], - ); - EventEmitter.receiveTouches( - 'topTouchEnd', - [{target: innerTag, identifier: 17}], - [0], - ); - - expect(log).toEqual([ - 'outer touchstart capture', - 'inner touchstart capture', - 'inner touchstart', - 'outer touchstart', - 'outer touchend capture', - 'inner touchend capture', - 'inner touchend', - 'outer touchend', - ]); -}); - -it('handles events on text nodes', () => { - expect(RCTEventEmitter.register.mock.calls.length).toBe(1); - var EventEmitter = RCTEventEmitter.register.mock.calls[0][0]; - - var Text = createReactNativeComponentClass({ - validAttributes: {foo: true}, - uiViewClassName: 'Text', - }); - - class ContextHack extends React.Component { - static childContextTypes = {isInAParentText: PropTypes.bool}; - getChildContext() { - return {isInAParentText: true}; - } - render() { - return this.props.children; - } - } - - var log = []; - ReactNative.render( - - - log.push('string touchend')} - onTouchEndCapture={() => log.push('string touchend capture')} - onTouchStart={() => log.push('string touchstart')} - onTouchStartCapture={() => log.push('string touchstart capture')}> - Text Content - - log.push('number touchend')} - onTouchEndCapture={() => log.push('number touchend capture')} - onTouchStart={() => log.push('number touchstart')} - onTouchStartCapture={() => log.push('number touchstart capture')}> - {123} - - - , - 1, - ); - - expect(UIManager.createView.mock.calls.length).toBe(5); - - // Don't depend on the order of createView() calls. - // Stack creates views outside-in; fiber creates them inside-out. - var innerTagString = UIManager.createView.mock.calls.find( - args => args[3] && args[3].text === 'Text Content', - )[0]; - var innerTagNumber = UIManager.createView.mock.calls.find( - args => args[3] && args[3].text === '123', - )[0]; - - EventEmitter.receiveTouches( - 'topTouchStart', - [{target: innerTagString, identifier: 17}], - [0], - ); - EventEmitter.receiveTouches( - 'topTouchEnd', - [{target: innerTagString, identifier: 17}], - [0], - ); - - EventEmitter.receiveTouches( - 'topTouchStart', - [{target: innerTagNumber, identifier: 18}], - [0], - ); - EventEmitter.receiveTouches( - 'topTouchEnd', - [{target: innerTagNumber, identifier: 18}], - [0], - ); - - expect(log).toEqual([ - 'string touchstart capture', - 'string touchstart', - 'string touchend capture', - 'string touchend', - 'number touchstart capture', - 'number touchstart', - 'number touchend capture', - 'number touchend', - ]); -}); - -it('handles when a responder is unmounted while a touch sequence is in progress', () => { - var EventEmitter = RCTEventEmitter.register.mock.calls[0][0]; - var View = createReactNativeComponentClass({ - validAttributes: {id: true}, - uiViewClassName: 'View', - }); - - function getViewById(id) { - return UIManager.createView.mock.calls.find( - args => args[3] && args[3].id === id, - )[0]; - } - - function getResponderId() { - const responder = ResponderEventPlugin._getResponder(); - if (responder === null) { - return null; - } - const props = typeof responder.tag === 'number' - ? responder.memoizedProps - : responder._currentElement.props; - return props ? props.id : null; - } - - var log = []; - ReactNative.render( - - - log.push('one responder end')} - onResponderStart={() => log.push('one responder start')} - onStartShouldSetResponder={() => true} - /> - - - log.push('two responder end')} - onResponderStart={() => log.push('two responder start')} - onStartShouldSetResponder={() => true} - /> - - , - 1, - ); - - EventEmitter.receiveTouches( - 'topTouchStart', - [{target: getViewById('one'), identifier: 17}], - [0], - ); - - expect(getResponderId()).toBe('one'); - expect(log).toEqual(['one responder start']); - log.splice(0); - - ReactNative.render( - - - log.push('two responder end')} - onResponderStart={() => log.push('two responder start')} - onStartShouldSetResponder={() => true} - /> - - , - 1, - ); - - // TODO Verify the onResponderEnd listener has been called (before the unmount) - // expect(log).toEqual(['one responder end']); - // log.splice(0); - - EventEmitter.receiveTouches( - 'topTouchEnd', - [{target: getViewById('two'), identifier: 17}], - [0], - ); - - expect(getResponderId()).toBeNull(); - expect(log).toEqual([]); - - EventEmitter.receiveTouches( - 'topTouchStart', - [{target: getViewById('two'), identifier: 17}], - [0], - ); - - expect(getResponderId()).toBe('two'); - expect(log).toEqual(['two responder start']); -}); - -it('handles events without target', () => { - var EventEmitter = RCTEventEmitter.register.mock.calls[0][0]; - var View = createReactNativeComponentClass({ - validAttributes: {id: true}, - uiViewClassName: 'View', - }); - - function getViewById(id) { - return UIManager.createView.mock.calls.find( - args => args[3] && args[3].id === id, - )[0]; - } - - function getResponderId() { - const responder = ResponderEventPlugin._getResponder(); - if (responder === null) { - return null; - } - const props = typeof responder.tag === 'number' - ? responder.memoizedProps - : responder._currentElement.props; - return props ? props.id : null; - } - - var log = []; - - function render(renderFirstComponent) { - ReactNative.render( - - - {renderFirstComponent - ? log.push('one responder end')} - onResponderStart={() => log.push('one responder start')} - onStartShouldSetResponder={() => true} - /> - : null} - - - log.push('two responder end')} - onResponderStart={() => log.push('two responder start')} - onStartShouldSetResponder={() => true} - /> - - , - 1, - ); - } - - render(true); - - EventEmitter.receiveTouches( - 'topTouchStart', - [{target: getViewById('one'), identifier: 17}], - [0], - ); - - // Unmounting component 'one'. - render(false); - - EventEmitter.receiveTouches( - 'topTouchEnd', - [{target: getViewById('one'), identifier: 17}], - [0], - ); - - expect(getResponderId()).toBe(null); - - EventEmitter.receiveTouches( - 'topTouchStart', - [{target: getViewById('two'), identifier: 18}], - [0], - ); - - expect(getResponderId()).toBe('two'); - - EventEmitter.receiveTouches( - 'topTouchEnd', - [{target: getViewById('two'), identifier: 18}], - [0], - ); - - expect(getResponderId()).toBe(null); - - expect(log).toEqual([ - 'one responder start', - 'two responder start', - 'two responder end', - ]); -}); diff --git a/Libraries/Renderer/src/renderers/native/__tests__/ReactNativeMount-test.js b/Libraries/Renderer/src/renderers/native/__tests__/ReactNativeMount-test.js deleted file mode 100644 index 2328b49065..0000000000 --- a/Libraries/Renderer/src/renderers/native/__tests__/ReactNativeMount-test.js +++ /dev/null @@ -1,111 +0,0 @@ -/** - * Copyright 2013-2015, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @emails react-core - */ - -'use strict'; - -var React; -var ReactNative; -var createReactNativeComponentClass; -var UIManager; - -describe('ReactNative', () => { - beforeEach(() => { - jest.resetModules(); - - React = require('react'); - ReactNative = require('ReactNative'); - UIManager = require('UIManager'); - createReactNativeComponentClass = require('createReactNativeComponentClass'); - }); - - it('should be able to create and render a native component', () => { - var View = createReactNativeComponentClass({ - validAttributes: {foo: true}, - uiViewClassName: 'View', - }); - - ReactNative.render(, 1); - expect(UIManager.createView).toBeCalled(); - expect(UIManager.setChildren).toBeCalled(); - expect(UIManager.manageChildren).not.toBeCalled(); - expect(UIManager.updateView).not.toBeCalled(); - }); - - it('should be able to create and update a native component', () => { - var View = createReactNativeComponentClass({ - validAttributes: {foo: true}, - uiViewClassName: 'View', - }); - - ReactNative.render(, 11); - - expect(UIManager.createView.mock.calls.length).toBe(1); - expect(UIManager.setChildren.mock.calls.length).toBe(1); - expect(UIManager.manageChildren).not.toBeCalled(); - expect(UIManager.updateView).not.toBeCalled(); - - ReactNative.render(, 11); - - expect(UIManager.createView.mock.calls.length).toBe(1); - expect(UIManager.setChildren.mock.calls.length).toBe(1); - expect(UIManager.manageChildren).not.toBeCalled(); - expect(UIManager.updateView).toBeCalledWith(2, 'View', {foo: 'bar'}); - }); - - it('returns the correct instance and calls it in the callback', () => { - var View = createReactNativeComponentClass({ - validAttributes: {foo: true}, - uiViewClassName: 'View', - }); - - var a; - var b; - var c = ReactNative.render( - (a = v)} />, - 11, - function() { - b = this; - }, - ); - - expect(a).toBeTruthy(); - expect(a).toBe(b); - expect(a).toBe(c); - }); - - it('renders and reorders children', () => { - var View = createReactNativeComponentClass({ - validAttributes: {title: true}, - uiViewClassName: 'View', - }); - - class Component extends React.Component { - render() { - var chars = this.props.chars.split(''); - return ( - - {chars.map(text => )} - - ); - } - } - - // Mini multi-child stress test: lots of reorders, some adds, some removes. - var before = 'abcdefghijklmnopqrst'; - var after = 'mxhpgwfralkeoivcstzy'; - - ReactNative.render(, 11); - expect(UIManager.__dumpHierarchyForJestTestsOnly()).toMatchSnapshot(); - - ReactNative.render(, 11); - expect(UIManager.__dumpHierarchyForJestTestsOnly()).toMatchSnapshot(); - }); -}); diff --git a/Libraries/Renderer/src/renderers/native/__tests__/__snapshots__/ReactNativeEvents-test.js.snap b/Libraries/Renderer/src/renderers/native/__tests__/__snapshots__/ReactNativeEvents-test.js.snap deleted file mode 100644 index b24c719f39..0000000000 --- a/Libraries/Renderer/src/renderers/native/__tests__/__snapshots__/ReactNativeEvents-test.js.snap +++ /dev/null @@ -1,7 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`handles events 1`] = ` -" {} - View {\\"foo\\":\\"outer\\"} - View {\\"foo\\":\\"inner\\"}" -`; diff --git a/Libraries/Renderer/src/renderers/native/__tests__/__snapshots__/ReactNativeMount-test.js.snap b/Libraries/Renderer/src/renderers/native/__tests__/__snapshots__/ReactNativeMount-test.js.snap deleted file mode 100644 index 5225479968..0000000000 --- a/Libraries/Renderer/src/renderers/native/__tests__/__snapshots__/ReactNativeMount-test.js.snap +++ /dev/null @@ -1,51 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`ReactNative renders and reorders children 1`] = ` -" {} - View null - View {\\"title\\":\\"a\\"} - View {\\"title\\":\\"b\\"} - View {\\"title\\":\\"c\\"} - View {\\"title\\":\\"d\\"} - View {\\"title\\":\\"e\\"} - View {\\"title\\":\\"f\\"} - View {\\"title\\":\\"g\\"} - View {\\"title\\":\\"h\\"} - View {\\"title\\":\\"i\\"} - View {\\"title\\":\\"j\\"} - View {\\"title\\":\\"k\\"} - View {\\"title\\":\\"l\\"} - View {\\"title\\":\\"m\\"} - View {\\"title\\":\\"n\\"} - View {\\"title\\":\\"o\\"} - View {\\"title\\":\\"p\\"} - View {\\"title\\":\\"q\\"} - View {\\"title\\":\\"r\\"} - View {\\"title\\":\\"s\\"} - View {\\"title\\":\\"t\\"}" -`; - -exports[`ReactNative renders and reorders children 2`] = ` -" {} - View null - View {\\"title\\":\\"m\\"} - View {\\"title\\":\\"x\\"} - View {\\"title\\":\\"h\\"} - View {\\"title\\":\\"p\\"} - View {\\"title\\":\\"g\\"} - View {\\"title\\":\\"w\\"} - View {\\"title\\":\\"f\\"} - View {\\"title\\":\\"r\\"} - View {\\"title\\":\\"a\\"} - View {\\"title\\":\\"l\\"} - View {\\"title\\":\\"k\\"} - View {\\"title\\":\\"e\\"} - View {\\"title\\":\\"o\\"} - View {\\"title\\":\\"i\\"} - View {\\"title\\":\\"v\\"} - View {\\"title\\":\\"c\\"} - View {\\"title\\":\\"s\\"} - View {\\"title\\":\\"t\\"} - View {\\"title\\":\\"z\\"} - View {\\"title\\":\\"y\\"}" -`; diff --git a/Libraries/Renderer/src/renderers/native/createReactNativeComponentClass.js b/Libraries/Renderer/src/renderers/native/createReactNativeComponentClass.js deleted file mode 100644 index f216325828..0000000000 --- a/Libraries/Renderer/src/renderers/native/createReactNativeComponentClass.js +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule createReactNativeComponentClass - * @flow - */ - -'use strict'; - -const ReactNativeBaseComponent = require('ReactNativeBaseComponent'); -const ReactNativeFeatureFlags = require('ReactNativeFeatureFlags'); -const ReactNativeViewConfigRegistry = require('ReactNativeViewConfigRegistry'); - -// See also ReactNativeBaseComponent -type ReactNativeBaseComponentViewConfig = { - validAttributes: Object, - uiViewClassName: string, - propTypes?: Object, -}; - -/** - * @param {string} config iOS View configuration. - * @private - */ -const createReactNativeFiberComponentClass = function( - viewConfig: ReactNativeBaseComponentViewConfig, -): string { - return ReactNativeViewConfigRegistry.register(viewConfig); -}; - -/** - * @param {string} config iOS View configuration. - * @private - */ -const createReactNativeComponentClass = function( - viewConfig: ReactNativeBaseComponentViewConfig, -): ReactClass { - const Constructor = function(element) { - this._currentElement = element; - this._topLevelWrapper = null; - this._hostParent = null; - this._hostContainerInfo = null; - this._rootNodeID = 0; - this._renderedChildren = null; - }; - Constructor.displayName = viewConfig.uiViewClassName; - Constructor.viewConfig = viewConfig; - Constructor.propTypes = viewConfig.propTypes; - Constructor.prototype = new ReactNativeBaseComponent(viewConfig); - Constructor.prototype.constructor = Constructor; - - return ((Constructor: any): ReactClass); -}; - -module.exports = ReactNativeFeatureFlags.useFiber - ? createReactNativeFiberComponentClass - : createReactNativeComponentClass; diff --git a/Libraries/Renderer/src/renderers/native/findNodeHandle.js b/Libraries/Renderer/src/renderers/native/findNodeHandle.js deleted file mode 100644 index 34c511b860..0000000000 --- a/Libraries/Renderer/src/renderers/native/findNodeHandle.js +++ /dev/null @@ -1,139 +0,0 @@ -/** - * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule findNodeHandle - * @flow - */ - -'use strict'; - -var ReactInstanceMap = require('ReactInstanceMap'); -var {ReactCurrentOwner} = require('ReactGlobalSharedState'); - -var getComponentName = require('getComponentName'); -var invariant = require('fbjs/lib/invariant'); -var warning = require('fbjs/lib/warning'); - -import type {Fiber} from 'ReactFiber'; -import type {ReactInstance} from 'ReactInstanceType'; - -/** - * ReactNative vs ReactWeb - * ----------------------- - * React treats some pieces of data opaquely. This means that the information - * is first class (it can be passed around), but cannot be inspected. This - * allows us to build infrastructure that reasons about resources, without - * making assumptions about the nature of those resources, and this allows that - * infra to be shared across multiple platforms, where the resources are very - * different. General infra (such as `ReactMultiChild`) reasons opaquely about - * the data, but platform specific code (such as `ReactNativeBaseComponent`) can - * make assumptions about the data. - * - * - * `rootNodeID`, uniquely identifies a position in the generated native view - * tree. Many layers of composite components (created with `React.createClass`) - * can all share the same `rootNodeID`. - * - * `nodeHandle`: A sufficiently unambiguous way to refer to a lower level - * resource (dom node, native view etc). The `rootNodeID` is sufficient for web - * `nodeHandle`s, because the position in a tree is always enough to uniquely - * identify a DOM node (we never have nodes in some bank outside of the - * document). The same would be true for `ReactNative`, but we must maintain a - * mapping that we can send efficiently serializable - * strings across native boundaries. - * - * Opaque name TodaysWebReact FutureWebWorkerReact ReactNative - * ---------------------------------------------------------------------------- - * nodeHandle N/A rootNodeID tag - */ - -let injectedFindNode; -let injectedFindRootNodeID; - -// TODO (bvaughn) Rename the findNodeHandle module to something more descriptive -// eg findInternalHostInstance. This will reduce the likelihood of someone -// accidentally deep-requiring this version. -function findNodeHandle(componentOrHandle: any): any { - if (__DEV__) { - var owner = - ((ReactCurrentOwner.current: any): ReactInstance | Fiber | null); - if (owner !== null) { - const isFiber = typeof (owner: any).tag === 'number'; - const warnedAboutRefsInRender = isFiber - ? ((owner: any): Fiber).stateNode._warnedAboutRefsInRender - : ((owner: any): ReactInstance)._warnedAboutRefsInRender; - - warning( - warnedAboutRefsInRender, - '%s is accessing findNodeHandle inside its render(). ' + - 'render() should be a pure function of props and state. It should ' + - 'never access something that requires stale data from the previous ' + - 'render, such as refs. Move this logic to componentDidMount and ' + - 'componentDidUpdate instead.', - getComponentName(owner) || 'A component', - ); - - if (isFiber) { - ((owner: any): Fiber).stateNode._warnedAboutRefsInRender = true; - } else { - ((owner: any): ReactInstance)._warnedAboutRefsInRender = true; - } - } - } - if (componentOrHandle == null) { - return null; - } - if (typeof componentOrHandle === 'number') { - // Already a node handle - return componentOrHandle; - } - - var component = componentOrHandle; - - // TODO (balpert): Wrap iOS native components in a composite wrapper, then - // ReactInstanceMap.get here will always succeed for mounted components - var internalInstance = ReactInstanceMap.get(component); - if (internalInstance) { - return injectedFindNode(internalInstance); - } else { - var rootNodeID = injectedFindRootNodeID(component); - if (rootNodeID) { - return rootNodeID; - } else { - invariant( - // Native - (typeof component === 'object' && - ('_rootNodeID' in component || // TODO (bvaughn) Clean up once Stack is deprecated - '_nativeTag' in component)) || - // Composite - (component.render != null && typeof component.render === 'function'), - 'findNodeHandle(...): Argument is not a component ' + - '(type: %s, keys: %s)', - typeof component, - Object.keys(component), - ); - invariant( - false, - 'findNodeHandle(...): Unable to find node handle for unmounted ' + - 'component.', - ); - } - } -} - -// Fiber and stack implementations differ; each must inject a strategy -findNodeHandle.injection = { - injectFindNode(findNode) { - injectedFindNode = findNode; - }, - injectFindRootNodeID(findRootNodeID) { - injectedFindRootNodeID = findRootNodeID; - }, -}; - -module.exports = findNodeHandle; diff --git a/Libraries/Renderer/src/renderers/native/takeSnapshot.js b/Libraries/Renderer/src/renderers/native/takeSnapshot.js deleted file mode 100644 index 98608c83e5..0000000000 --- a/Libraries/Renderer/src/renderers/native/takeSnapshot.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright (c) 2015-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule takeSnapshot - * @flow - */ -'use strict'; - -var ReactNative = require('ReactNative'); -var UIManager = require('UIManager'); - -import type {Element} from 'React'; - -/** - * Capture an image of the screen, window or an individual view. The image - * will be stored in a temporary file that will only exist for as long as the - * app is running. - * - * The `view` argument can be the literal string `window` if you want to - * capture the entire window, or it can be a reference to a specific - * React Native component. - * - * The `options` argument may include: - * - width/height (number) - the width and height of the image to capture. - * - format (string) - either 'png' or 'jpeg'. Defaults to 'png'. - * - quality (number) - the quality when using jpeg. 0.0 - 1.0 (default). - * - * Returns a Promise. - * @platform ios - */ -function takeSnapshot( - view?: 'window' | Element | number, - options?: { - width?: number, - height?: number, - format?: 'png' | 'jpeg', - quality?: number, - }, -): Promise { - if (typeof view !== 'number' && view !== 'window') { - view = ReactNative.findNodeHandle(view) || 'window'; - } - - // Call the hidden '__takeSnapshot' method; the main one throws an error to - // prevent accidental backwards-incompatible usage. - return UIManager.__takeSnapshot(view, options); -} - -module.exports = takeSnapshot; diff --git a/Libraries/Renderer/src/renderers/noop/ReactNoop.js b/Libraries/Renderer/src/renderers/noop/ReactNoop.js deleted file mode 100644 index d51b8b0980..0000000000 --- a/Libraries/Renderer/src/renderers/noop/ReactNoop.js +++ /dev/null @@ -1,391 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactNoop - * @flow - */ - -/** - * This is a renderer of React that doesn't have a render target output. - * It is useful to demonstrate the internals of the reconciler in isolation - * and for testing semantics of reconciliation separate from the host - * environment. - */ - -'use strict'; - -import type { Fiber } from 'ReactFiber'; -import type { UpdateQueue } from 'ReactFiberUpdateQueue'; - -var ReactFiberInstrumentation = require('ReactFiberInstrumentation'); -var ReactFiberReconciler = require('ReactFiberReconciler'); -var ReactInstanceMap = require('ReactInstanceMap'); -var { - AnimationPriority, -} = require('ReactPriorityLevel'); -var emptyObject = require('fbjs/lib/emptyObject'); - -const UPDATE_SIGNAL = {}; - -var scheduledAnimationCallback = null; -var scheduledDeferredCallback = null; - -type Container = { rootID: string, children: Array }; -type Props = { prop: any }; -type Instance = {| type: string, id: number, children: Array, prop: any |}; -type TextInstance = {| text: string, id: number |}; - -var instanceCounter = 0; - -var failInBeginPhase = false; - -var NoopRenderer = ReactFiberReconciler({ - - getRootHostContext() { - if (failInBeginPhase) { - throw new Error('Error in host config.'); - } - return emptyObject; - }, - - getChildHostContext() { - return emptyObject; - }, - - getPublicInstance(instance) { - return instance; - }, - - createInstance(type : string, props : Props) : Instance { - const inst = { - id: instanceCounter++, - type: type, - children: [], - prop: props.prop, - }; - // Hide from unit tests - Object.defineProperty(inst, 'id', { value: inst.id, enumerable: false }); - return inst; - }, - - appendInitialChild(parentInstance : Instance, child : Instance | TextInstance) : void { - parentInstance.children.push(child); - }, - - finalizeInitialChildren(domElement : Instance, type : string, props : Props) : boolean { - return false; - }, - - prepareUpdate(instance : Instance, type : string, oldProps : Props, newProps : Props) : null | {} { - return UPDATE_SIGNAL; - }, - - commitMount(instance : Instance, type : string, newProps : Props) : void { - // Noop - }, - - commitUpdate(instance : Instance, updatePayload : Object, type : string, oldProps : Props, newProps : Props) : void { - instance.prop = newProps.prop; - }, - - shouldSetTextContent(props : Props) : boolean { - return ( - typeof props.children === 'string' || - typeof props.children === 'number' - ); - }, - - resetTextContent(instance : Instance) : void {}, - - createTextInstance( - text : string, - rootContainerInstance : Container, - hostContext : Object, - internalInstanceHandle : Object - ) : TextInstance { - var inst = { text : text, id: instanceCounter++ }; - // Hide from unit tests - Object.defineProperty(inst, 'id', { value: inst.id, enumerable: false }); - return inst; - }, - - commitTextUpdate(textInstance : TextInstance, oldText : string, newText : string) : void { - textInstance.text = newText; - }, - - appendChild(parentInstance : Instance | Container, child : Instance | TextInstance) : void { - const index = parentInstance.children.indexOf(child); - if (index !== -1) { - parentInstance.children.splice(index, 1); - } - parentInstance.children.push(child); - }, - - insertBefore( - parentInstance : Instance | Container, - child : Instance | TextInstance, - beforeChild : Instance | TextInstance - ) : void { - const index = parentInstance.children.indexOf(child); - if (index !== -1) { - parentInstance.children.splice(index, 1); - } - const beforeIndex = parentInstance.children.indexOf(beforeChild); - if (beforeIndex === -1) { - throw new Error('This child does not exist.'); - } - parentInstance.children.splice(beforeIndex, 0, child); - }, - - removeChild(parentInstance : Instance | Container, child : Instance | TextInstance) : void { - const index = parentInstance.children.indexOf(child); - if (index === -1) { - throw new Error('This child does not exist.'); - } - parentInstance.children.splice(index, 1); - }, - - shouldDeprioritizeSubtree(type: string, props: Props): boolean { - return false; - }, - - scheduleAnimationCallback(callback) { - if (scheduledAnimationCallback) { - throw new Error( - 'Scheduling an animation callback twice is excessive. ' + - 'Instead, keep track of whether the callback has already been scheduled.' - ); - } - scheduledAnimationCallback = callback; - }, - - scheduleDeferredCallback(callback) { - if (scheduledDeferredCallback) { - throw new Error( - 'Scheduling deferred callback twice is excessive. ' + - 'Instead, keep track of whether the callback has already been scheduled.' - ); - } - scheduledDeferredCallback = callback; - }, - - prepareForCommit() : void { - }, - - resetAfterCommit() : void { - }, - -}); - -var rootContainers = new Map(); -var roots = new Map(); -var DEFAULT_ROOT_ID = ''; - -var ReactNoop = { - - getChildren(rootID : string = DEFAULT_ROOT_ID) { - const container = rootContainers.get(rootID); - if (container) { - return container.children; - } else { - return null; - } - }, - - // Shortcut for testing a single root - render(element : ReactElement, callback: ?Function) { - ReactNoop.renderToRootWithID(element, DEFAULT_ROOT_ID, callback); - }, - - renderToRootWithID(element : ReactElement, rootID : string, callback : ?Function) { - let root = roots.get(rootID); - if (!root) { - const container = { rootID: rootID, children: [] }; - rootContainers.set(rootID, container); - root = NoopRenderer.createContainer(container); - roots.set(rootID, root); - } - NoopRenderer.updateContainer(element, root, null, callback); - }, - - unmountRootWithID(rootID : string) { - const root = roots.get(rootID); - if (root) { - NoopRenderer.updateContainer(null, root, null, () => { - roots.delete(rootID); - rootContainers.delete(rootID); - }); - } - }, - - findInstance(componentOrElement : Element | ?ReactComponent) : null | Instance | TextInstance { - if (componentOrElement == null) { - return null; - } - // Unsound duck typing. - const component = (componentOrElement : any); - if (typeof component.id === 'number') { - return component; - } - const inst = ReactInstanceMap.get(component); - return inst ? NoopRenderer.findHostInstance(inst) : null; - }, - - flushAnimationPri() { - var cb = scheduledAnimationCallback; - if (cb === null) { - return; - } - scheduledAnimationCallback = null; - cb(); - }, - - flushDeferredPri(timeout : number = Infinity) { - var cb = scheduledDeferredCallback; - if (cb === null) { - return; - } - scheduledDeferredCallback = null; - var timeRemaining = timeout; - cb({ - timeRemaining() { - // Simulate a fix amount of time progressing between each call. - timeRemaining -= 5; - if (timeRemaining < 0) { - timeRemaining = 0; - } - return timeRemaining; - }, - }); - }, - - flush() { - ReactNoop.flushAnimationPri(); - ReactNoop.flushDeferredPri(); - }, - - performAnimationWork(fn: Function) { - NoopRenderer.performWithPriority(AnimationPriority, fn); - }, - - batchedUpdates: NoopRenderer.batchedUpdates, - - unbatchedUpdates: NoopRenderer.unbatchedUpdates, - - syncUpdates: NoopRenderer.syncUpdates, - - // Logs the current state of the tree. - dumpTree(rootID : string = DEFAULT_ROOT_ID) { - const root = roots.get(rootID); - const rootContainer = rootContainers.get(rootID); - if (!root || !rootContainer) { - console.log('Nothing rendered yet.'); - return; - } - - var bufferedLog = []; - function log(...args) { - bufferedLog.push(...args, '\n'); - } - - function logHostInstances(children: Array, depth) { - for (var i = 0; i < children.length; i++) { - var child = children[i]; - var indent = ' '.repeat(depth); - if (typeof child.text === 'string') { - log(indent + '- ' + child.text); - } else { - // $FlowFixMe - The child should've been refined now. - log(indent + '- ' + child.type + '#' + child.id); - // $FlowFixMe - The child should've been refined now. - logHostInstances(child.children, depth + 1); - } - } - } - function logContainer(container : Container, depth) { - log(' '.repeat(depth) + '- [root#' + container.rootID + ']'); - logHostInstances(container.children, depth + 1); - } - - function logUpdateQueue(updateQueue : UpdateQueue, depth) { - log( - ' '.repeat(depth + 1) + 'QUEUED UPDATES' - ); - const firstUpdate = updateQueue.first; - if (!firstUpdate) { - return; - } - - log( - ' '.repeat(depth + 1) + '~', - firstUpdate && firstUpdate.partialState, - firstUpdate.callback ? 'with callback' : '', - '[' + firstUpdate.priorityLevel + ']' - ); - var next; - while (next = firstUpdate.next) { - log( - ' '.repeat(depth + 1) + '~', - next.partialState, - next.callback ? 'with callback' : '', - '[' + firstUpdate.priorityLevel + ']' - ); - } - } - - function logFiber(fiber : Fiber, depth) { - log( - ' '.repeat(depth) + '- ' + (fiber.type ? fiber.type.name || fiber.type : '[root]'), - '[' + fiber.pendingWorkPriority + (fiber.pendingProps ? '*' : '') + ']' - ); - if (fiber.updateQueue) { - logUpdateQueue(fiber.updateQueue, depth); - } - const childInProgress = fiber.progressedChild; - if (childInProgress && childInProgress !== fiber.child) { - log(' '.repeat(depth + 1) + 'IN PROGRESS: ' + fiber.progressedPriority); - logFiber(childInProgress, depth + 1); - if (fiber.child) { - log(' '.repeat(depth + 1) + 'CURRENT'); - } - } else if (fiber.child && fiber.updateQueue) { - log(' '.repeat(depth + 1) + 'CHILDREN'); - } - if (fiber.child) { - logFiber(fiber.child, depth + 1); - } - if (fiber.sibling) { - logFiber(fiber.sibling, depth); - } - } - - log('HOST INSTANCES:'); - logContainer(rootContainer, 0); - log('FIBERS:'); - logFiber(root.current, 0); - - console.log(...bufferedLog); - }, - - simulateErrorInHostConfig(fn : () => void) { - failInBeginPhase = true; - try { - fn(); - } finally { - failInBeginPhase = false; - } - }, - - __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: { - // Private. Used only by fixtures/fiber-debugger. - // (To be fair, it's the only place where `react-noop-renderer` package is used at all.) - ReactFiberInstrumentation, - }, -}; - -module.exports = ReactNoop; diff --git a/Libraries/Renderer/src/renderers/shared/ReactDOMFrameScheduling.js b/Libraries/Renderer/src/renderers/shared/ReactDOMFrameScheduling.js deleted file mode 100644 index e08d430393..0000000000 --- a/Libraries/Renderer/src/renderers/shared/ReactDOMFrameScheduling.js +++ /dev/null @@ -1,170 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactDOMFrameScheduling - * @flow - */ - -'use strict'; - -// This a built-in polyfill for requestIdleCallback. It works by scheduling -// a requestAnimationFrame, store the time for the start of the frame, then -// schedule a postMessage which gets scheduled after paint. Within the -// postMessage handler do as much work as possible until time + frame rate. -// By separating the idle call into a separate event tick we ensure that -// layout, paint and other browser work is counted against the available time. -// The frame rate is dynamically adjusted. - -import type {Deadline} from 'ReactFiberReconciler'; - -var invariant = require('fbjs/lib/invariant'); -var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment'); - -// TODO: There's no way to cancel these, because Fiber doesn't atm. -let rAF: (callback: (time: number) => void) => number; -let rIC: (callback: (deadline: Deadline) => void) => number; - -if (!ExecutionEnvironment.canUseDOM) { - rAF = function(frameCallback: (time: number) => void): number { - setTimeout(frameCallback, 16); - return 0; - }; - - rIC = function(frameCallback: (deadline: Deadline) => void): number { - setTimeout(() => { - frameCallback({ - timeRemaining() { - return Infinity; - }, - }); - }); - return 0; - }; -} else if (typeof requestAnimationFrame !== 'function') { - invariant( - false, - 'React depends on requestAnimationFrame. Make sure that you load a ' + - 'polyfill in older browsers.', - ); -} else if (typeof requestIdleCallback !== 'function') { - // Wrap requestAnimationFrame and polyfill requestIdleCallback. - - var scheduledRAFCallback = null; - var scheduledRICCallback = null; - - var isIdleScheduled = false; - var isAnimationFrameScheduled = false; - - var frameDeadline = 0; - // We start out assuming that we run at 30fps but then the heuristic tracking - // will adjust this value to a faster fps if we get more frequent animation - // frames. - var previousFrameTime = 33; - var activeFrameTime = 33; - - var frameDeadlineObject = { - timeRemaining: typeof performance === 'object' && - typeof performance.now === 'function' - ? function() { - // We assume that if we have a performance timer that the rAF callback - // gets a performance timer value. Not sure if this is always true. - return frameDeadline - performance.now(); - } - : function() { - // As a fallback we use Date.now. - return frameDeadline - Date.now(); - }, - }; - - // We use the postMessage trick to defer idle work until after the repaint. - var messageKey = '__reactIdleCallback$' + Math.random().toString(36).slice(2); - var idleTick = function(event) { - if (event.source !== window || event.data !== messageKey) { - return; - } - isIdleScheduled = false; - var callback = scheduledRICCallback; - scheduledRICCallback = null; - if (callback) { - callback(frameDeadlineObject); - } - }; - // Assumes that we have addEventListener in this environment. Might need - // something better for old IE. - window.addEventListener('message', idleTick, false); - - var animationTick = function(rafTime) { - isAnimationFrameScheduled = false; - var nextFrameTime = rafTime - frameDeadline + activeFrameTime; - if ( - nextFrameTime < activeFrameTime && - previousFrameTime < activeFrameTime - ) { - if (nextFrameTime < 8) { - // Defensive coding. We don't support higher frame rates than 120hz. - // If we get lower than that, it is probably a bug. - nextFrameTime = 8; - } - // If one frame goes long, then the next one can be short to catch up. - // If two frames are short in a row, then that's an indication that we - // actually have a higher frame rate than what we're currently optimizing. - // We adjust our heuristic dynamically accordingly. For example, if we're - // running on 120hz display or 90hz VR display. - // Take the max of the two in case one of them was an anomaly due to - // missed frame deadlines. - activeFrameTime = nextFrameTime < previousFrameTime - ? previousFrameTime - : nextFrameTime; - } else { - previousFrameTime = nextFrameTime; - } - frameDeadline = rafTime + activeFrameTime; - if (!isIdleScheduled) { - isIdleScheduled = true; - window.postMessage(messageKey, '*'); - } - var callback = scheduledRAFCallback; - scheduledRAFCallback = null; - if (callback) { - callback(rafTime); - } - }; - - rAF = function(callback: (time: number) => void): number { - // This assumes that we only schedule one callback at a time because that's - // how Fiber uses it. - scheduledRAFCallback = callback; - if (!isAnimationFrameScheduled) { - // If rIC didn't already schedule one, we need to schedule a frame. - isAnimationFrameScheduled = true; - requestAnimationFrame(animationTick); - } - return 0; - }; - - rIC = function(callback: (deadline: Deadline) => void): number { - // This assumes that we only schedule one callback at a time because that's - // how Fiber uses it. - scheduledRICCallback = callback; - if (!isAnimationFrameScheduled) { - // If rAF didn't already schedule one, we need to schedule a frame. - // TODO: If this rAF doesn't materialize because the browser throttles, we - // might want to still have setTimeout trigger rIC as a backup to ensure - // that we keep performing work. - isAnimationFrameScheduled = true; - requestAnimationFrame(animationTick); - } - return 0; - }; -} else { - rAF = requestAnimationFrame; - rIC = requestIdleCallback; -} - -exports.rAF = rAF; -exports.rIC = rIC; diff --git a/Libraries/Renderer/src/renderers/shared/ReactDebugTool.js b/Libraries/Renderer/src/renderers/shared/ReactDebugTool.js deleted file mode 100644 index 9d4693420f..0000000000 --- a/Libraries/Renderer/src/renderers/shared/ReactDebugTool.js +++ /dev/null @@ -1,438 +0,0 @@ -/** - * Copyright 2016-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactDebugTool - * @flow - */ - -'use strict'; - -var ReactInvalidSetStateWarningHook = require('ReactInvalidSetStateWarningHook'); -var ReactHostOperationHistoryHook = require('ReactHostOperationHistoryHook'); -var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment'); -var {ReactComponentTreeHook} = require('ReactGlobalSharedState'); - -var performanceNow = require('fbjs/lib/performanceNow'); -var warning = require('fbjs/lib/warning'); - -import type {ReactElement} from 'ReactElementType'; -import type {DebugID} from 'ReactInstanceType'; -import type {Operation} from 'ReactHostOperationHistoryHook'; - -type Hook = any; - -type TimerType = - | 'ctor' - | 'render' - | 'componentWillMount' - | 'componentWillUnmount' - | 'componentWillReceiveProps' - | 'shouldComponentUpdate' - | 'componentWillUpdate' - | 'componentDidUpdate' - | 'componentDidMount'; - -type Measurement = { - timerType: TimerType, - instanceID: DebugID, - duration: number, -}; - -type TreeSnapshot = { - [key: DebugID]: { - displayName: string, - text: string, - updateCount: number, - childIDs: Array, - ownerID: DebugID, - parentID: DebugID, - }, -}; - -type HistoryItem = { - duration: number, - measurements: Array, - operations: Array, - treeSnapshot: TreeSnapshot, -}; - -export type FlushHistory = Array; - -// Trust the developer to only use this with a __DEV__ check -var ReactDebugTool = ((null: any): typeof ReactDebugTool); - -if (__DEV__) { - var hooks = []; - var didHookThrowForEvent = {}; - - const callHook = function(event, fn, context, arg1, arg2, arg3, arg4, arg5) { - try { - fn.call(context, arg1, arg2, arg3, arg4, arg5); - } catch (e) { - warning( - didHookThrowForEvent[event], - 'Exception thrown by hook while handling %s: %s', - event, - e + '\n' + e.stack, - ); - didHookThrowForEvent[event] = true; - } - }; - - const emitEvent = function(event, arg1, arg2, arg3, arg4, arg5) { - for (var i = 0; i < hooks.length; i++) { - var hook = hooks[i]; - var fn = hook[event]; - if (fn) { - callHook(event, fn, hook, arg1, arg2, arg3, arg4, arg5); - } - } - }; - - var isProfiling = false; - var flushHistory = []; - var lifeCycleTimerStack = []; - var currentFlushNesting = 0; - var currentFlushMeasurements = []; - var currentFlushStartTime = 0; - var currentTimerDebugID = null; - var currentTimerStartTime = 0; - var currentTimerNestedFlushDuration = 0; - var currentTimerType = null; - - var lifeCycleTimerHasWarned = false; - - const clearHistory = function() { - ReactComponentTreeHook.purgeUnmountedComponents(); - ReactHostOperationHistoryHook.clearHistory(); - }; - - const getTreeSnapshot = function(registeredIDs) { - return registeredIDs.reduce((tree, id) => { - var ownerID = ReactComponentTreeHook.getOwnerID(id); - var parentID = ReactComponentTreeHook.getParentID(id); - tree[id] = { - displayName: ReactComponentTreeHook.getDisplayName(id), - text: ReactComponentTreeHook.getText(id), - updateCount: ReactComponentTreeHook.getUpdateCount(id), - childIDs: ReactComponentTreeHook.getChildIDs(id), - // Text nodes don't have owners but this is close enough. - ownerID: ownerID || - (parentID && ReactComponentTreeHook.getOwnerID(parentID)) || - 0, - parentID, - }; - return tree; - }, {}); - }; - - const resetMeasurements = function() { - var previousStartTime = currentFlushStartTime; - var previousMeasurements = currentFlushMeasurements; - var previousOperations = ReactHostOperationHistoryHook.getHistory(); - - if (currentFlushNesting === 0) { - currentFlushStartTime = 0; - currentFlushMeasurements = []; - clearHistory(); - return; - } - - if (previousMeasurements.length || previousOperations.length) { - var registeredIDs = ReactComponentTreeHook.getRegisteredIDs(); - flushHistory.push({ - duration: performanceNow() - previousStartTime, - measurements: previousMeasurements || [], - operations: previousOperations || [], - treeSnapshot: getTreeSnapshot(registeredIDs), - }); - } - - clearHistory(); - currentFlushStartTime = performanceNow(); - currentFlushMeasurements = []; - }; - - const checkDebugID = function(debugID, allowRoot = false) { - if (allowRoot && debugID === 0) { - return; - } - if (!debugID) { - warning(false, 'ReactDebugTool: debugID may not be empty.'); - } - }; - - const beginLifeCycleTimer = function(debugID, timerType) { - if (currentFlushNesting === 0) { - return; - } - if (currentTimerType && !lifeCycleTimerHasWarned) { - warning( - false, - 'There is an internal error in the React performance measurement code.' + - '\n\nDid not expect %s timer to start while %s timer is still in ' + - 'progress for %s instance.', - timerType, - currentTimerType || 'no', - debugID === currentTimerDebugID ? 'the same' : 'another', - ); - lifeCycleTimerHasWarned = true; - } - currentTimerStartTime = performanceNow(); - currentTimerNestedFlushDuration = 0; - currentTimerDebugID = debugID; - currentTimerType = timerType; - }; - - const endLifeCycleTimer = function(debugID, timerType) { - if (currentFlushNesting === 0) { - return; - } - if (currentTimerType !== timerType && !lifeCycleTimerHasWarned) { - warning( - false, - 'There is an internal error in the React performance measurement code. ' + - 'We did not expect %s timer to stop while %s timer is still in ' + - 'progress for %s instance. Please report this as a bug in React.', - timerType, - currentTimerType || 'no', - debugID === currentTimerDebugID ? 'the same' : 'another', - ); - lifeCycleTimerHasWarned = true; - } - if (isProfiling) { - currentFlushMeasurements.push({ - timerType, - instanceID: debugID, - duration: performanceNow() - - currentTimerStartTime - - currentTimerNestedFlushDuration, - }); - } - currentTimerStartTime = 0; - currentTimerNestedFlushDuration = 0; - currentTimerDebugID = null; - currentTimerType = null; - }; - - const pauseCurrentLifeCycleTimer = function() { - var currentTimer = { - startTime: currentTimerStartTime, - nestedFlushStartTime: performanceNow(), - debugID: currentTimerDebugID, - timerType: currentTimerType, - }; - lifeCycleTimerStack.push(currentTimer); - currentTimerStartTime = 0; - currentTimerNestedFlushDuration = 0; - currentTimerDebugID = null; - currentTimerType = null; - }; - - const resumeCurrentLifeCycleTimer = function() { - var { - startTime, - nestedFlushStartTime, - debugID, - timerType, - } = lifeCycleTimerStack.pop(); - var nestedFlushDuration = performanceNow() - nestedFlushStartTime; - currentTimerStartTime = startTime; - currentTimerNestedFlushDuration += nestedFlushDuration; - currentTimerDebugID = debugID; - currentTimerType = timerType; - }; - - var lastMarkTimeStamp = 0; - var canUsePerformanceMeasure: boolean = - typeof performance !== 'undefined' && - typeof performance.mark === 'function' && - typeof performance.clearMarks === 'function' && - typeof performance.measure === 'function' && - typeof performance.clearMeasures === 'function'; - - const shouldMark = function(debugID) { - if (!isProfiling || !canUsePerformanceMeasure) { - return false; - } - var element = ReactComponentTreeHook.getElement(debugID); - if (element == null || typeof element !== 'object') { - return false; - } - var isHostElement = typeof element.type === 'string'; - if (isHostElement) { - return false; - } - return true; - }; - - const markBegin = function(debugID, markType) { - if (!shouldMark(debugID)) { - return; - } - - var markName = `${debugID}::${markType}`; - lastMarkTimeStamp = performanceNow(); - performance.mark(markName); - }; - - const markEnd = function(debugID, markType) { - if (!shouldMark(debugID)) { - return; - } - - var markName = `${debugID}::${markType}`; - var displayName = - ReactComponentTreeHook.getDisplayName(debugID) || 'Unknown'; - - // Chrome has an issue of dropping markers recorded too fast: - // https://bugs.chromium.org/p/chromium/issues/detail?id=640652 - // To work around this, we will not report very small measurements. - // I determined the magic number by tweaking it back and forth. - // 0.05ms was enough to prevent the issue, but I set it to 0.1ms to be safe. - // When the bug is fixed, we can `measure()` unconditionally if we want to. - var timeStamp = performanceNow(); - if (timeStamp - lastMarkTimeStamp > 0.1) { - var measurementName = `${displayName} [${markType}]`; - performance.measure(measurementName, markName); - } - - performance.clearMarks(markName); - if (measurementName) { - performance.clearMeasures(measurementName); - } - }; - - ReactDebugTool = { - addHook(hook: Hook): void { - hooks.push(hook); - }, - removeHook(hook: Hook): void { - for (var i = 0; i < hooks.length; i++) { - if (hooks[i] === hook) { - hooks.splice(i, 1); - i--; - } - } - }, - isProfiling(): boolean { - return isProfiling; - }, - beginProfiling(): void { - if (isProfiling) { - return; - } - - isProfiling = true; - flushHistory.length = 0; - resetMeasurements(); - ReactDebugTool.addHook(ReactHostOperationHistoryHook); - }, - endProfiling(): void { - if (!isProfiling) { - return; - } - - isProfiling = false; - resetMeasurements(); - ReactDebugTool.removeHook(ReactHostOperationHistoryHook); - }, - getFlushHistory(): FlushHistory { - return flushHistory; - }, - onBeginFlush(): void { - currentFlushNesting++; - resetMeasurements(); - pauseCurrentLifeCycleTimer(); - emitEvent('onBeginFlush'); - }, - onEndFlush(): void { - resetMeasurements(); - currentFlushNesting--; - resumeCurrentLifeCycleTimer(); - emitEvent('onEndFlush'); - }, - onBeginLifeCycleTimer(debugID: DebugID, timerType: TimerType): void { - checkDebugID(debugID); - emitEvent('onBeginLifeCycleTimer', debugID, timerType); - markBegin(debugID, timerType); - beginLifeCycleTimer(debugID, timerType); - }, - onEndLifeCycleTimer(debugID: DebugID, timerType: TimerType): void { - checkDebugID(debugID); - endLifeCycleTimer(debugID, timerType); - markEnd(debugID, timerType); - emitEvent('onEndLifeCycleTimer', debugID, timerType); - }, - onBeginProcessingChildContext(): void { - emitEvent('onBeginProcessingChildContext'); - }, - onEndProcessingChildContext(): void { - emitEvent('onEndProcessingChildContext'); - }, - onHostOperation(operation: Operation) { - checkDebugID(operation.instanceID); - emitEvent('onHostOperation', operation); - }, - onSetState(): void { - emitEvent('onSetState'); - }, - onSetChildren(debugID: DebugID, childDebugIDs: Array) { - checkDebugID(debugID); - childDebugIDs.forEach(checkDebugID); - emitEvent('onSetChildren', debugID, childDebugIDs); - }, - onBeforeMountComponent( - debugID: DebugID, - element: ReactElement, - parentDebugID: DebugID, - ): void { - checkDebugID(debugID); - checkDebugID(parentDebugID, true); - emitEvent('onBeforeMountComponent', debugID, element, parentDebugID); - markBegin(debugID, 'mount'); - }, - onMountComponent(debugID: DebugID): void { - checkDebugID(debugID); - markEnd(debugID, 'mount'); - emitEvent('onMountComponent', debugID); - }, - onBeforeUpdateComponent(debugID: DebugID, element: ReactElement): void { - checkDebugID(debugID); - emitEvent('onBeforeUpdateComponent', debugID, element); - markBegin(debugID, 'update'); - }, - onUpdateComponent(debugID: DebugID): void { - checkDebugID(debugID); - markEnd(debugID, 'update'); - emitEvent('onUpdateComponent', debugID); - }, - onBeforeUnmountComponent(debugID: DebugID): void { - checkDebugID(debugID); - emitEvent('onBeforeUnmountComponent', debugID); - markBegin(debugID, 'unmount'); - }, - onUnmountComponent(debugID: DebugID): void { - checkDebugID(debugID); - markEnd(debugID, 'unmount'); - emitEvent('onUnmountComponent', debugID); - }, - onTestEvent(): void { - emitEvent('onTestEvent'); - }, - }; - - ReactDebugTool.addHook(ReactInvalidSetStateWarningHook); - ReactDebugTool.addHook(ReactComponentTreeHook); - var url = (ExecutionEnvironment.canUseDOM && window.location.href) || ''; - if (/[?&]react_perf\b/.test(url)) { - ReactDebugTool.beginProfiling(); - } -} - -module.exports = ReactDebugTool; diff --git a/Libraries/Renderer/src/renderers/shared/ReactGlobalSharedState.js b/Libraries/Renderer/src/renderers/shared/ReactGlobalSharedState.js deleted file mode 100644 index 42e9d9bc01..0000000000 --- a/Libraries/Renderer/src/renderers/shared/ReactGlobalSharedState.js +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactGlobalSharedState - */ - -'use strict'; - -var ReactInternals = require('react') - .__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; - -var ReactGlobalSharedState = { - ReactCurrentOwner: ReactInternals.ReactCurrentOwner, -}; - -if (__DEV__) { - Object.assign(ReactGlobalSharedState, { - ReactComponentTreeHook: ReactInternals.ReactComponentTreeHook, - ReactDebugCurrentFrame: ReactInternals.ReactDebugCurrentFrame, - }); -} - -module.exports = ReactGlobalSharedState; diff --git a/Libraries/Renderer/src/renderers/shared/ReactInstrumentation.js b/Libraries/Renderer/src/renderers/shared/ReactInstrumentation.js deleted file mode 100644 index a5de36d00e..0000000000 --- a/Libraries/Renderer/src/renderers/shared/ReactInstrumentation.js +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright 2016-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactInstrumentation - * @flow - */ - -'use strict'; - -// Trust the developer to only use ReactInstrumentation with a __DEV__ check -var debugTool = ((null: any): typeof ReactDebugTool); - -if (__DEV__) { - var ReactDebugTool = require('ReactDebugTool'); - debugTool = ReactDebugTool; -} - -module.exports = {debugTool}; diff --git a/Libraries/Renderer/src/renderers/shared/ReactPerf.js b/Libraries/Renderer/src/renderers/shared/ReactPerf.js deleted file mode 100644 index d119959c55..0000000000 --- a/Libraries/Renderer/src/renderers/shared/ReactPerf.js +++ /dev/null @@ -1,458 +0,0 @@ -/** - * Copyright 2016-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactPerf - * @flow - */ - -'use strict'; - -var ReactDebugTool = require('ReactDebugTool'); -var warning = require('fbjs/lib/warning'); -var alreadyWarned = false; - -import type {FlushHistory} from 'ReactDebugTool'; - -function roundFloat(val, base = 2) { - var n = Math.pow(10, base); - return Math.floor(val * n) / n; -} - -// Flow type definition of console.table is too strict right now, see -// https://github.com/facebook/flow/pull/2353 for updates -function consoleTable(table: Array<{[key: string]: any}>): void { - console.table((table: any)); -} - -function warnInProduction() { - if (alreadyWarned) { - return; - } - alreadyWarned = true; - if (typeof console !== 'undefined') { - console.error( - 'ReactPerf is not supported in the production builds of React. ' + - 'To collect measurements, please use the development build of React instead.', - ); - } -} - -function getLastMeasurements() { - if (!__DEV__) { - warnInProduction(); - return []; - } - - return ReactDebugTool.getFlushHistory(); -} - -function getExclusive(flushHistory = getLastMeasurements()) { - if (!__DEV__) { - warnInProduction(); - return []; - } - - var aggregatedStats = {}; - var affectedIDs = {}; - - function updateAggregatedStats( - treeSnapshot, - instanceID, - timerType, - applyUpdate, - ) { - var {displayName} = treeSnapshot[instanceID]; - var key = displayName; - var stats = aggregatedStats[key]; - if (!stats) { - affectedIDs[key] = {}; - stats = aggregatedStats[key] = { - key, - instanceCount: 0, - counts: {}, - durations: {}, - totalDuration: 0, - }; - } - if (!stats.durations[timerType]) { - stats.durations[timerType] = 0; - } - if (!stats.counts[timerType]) { - stats.counts[timerType] = 0; - } - affectedIDs[key][instanceID] = true; - applyUpdate(stats); - } - - flushHistory.forEach(flush => { - var {measurements, treeSnapshot} = flush; - measurements.forEach(measurement => { - var {duration, instanceID, timerType} = measurement; - updateAggregatedStats(treeSnapshot, instanceID, timerType, stats => { - stats.totalDuration += duration; - stats.durations[timerType] += duration; - stats.counts[timerType]++; - }); - }); - }); - - return Object.keys(aggregatedStats) - .map(key => ({ - ...aggregatedStats[key], - instanceCount: Object.keys(affectedIDs[key]).length, - })) - .sort((a, b) => b.totalDuration - a.totalDuration); -} - -function getInclusive(flushHistory = getLastMeasurements()) { - if (!__DEV__) { - warnInProduction(); - return []; - } - - var aggregatedStats = {}; - var affectedIDs = {}; - - function updateAggregatedStats(treeSnapshot, instanceID, applyUpdate) { - var {displayName, ownerID} = treeSnapshot[instanceID]; - var owner = treeSnapshot[ownerID]; - var key = (owner ? owner.displayName + ' > ' : '') + displayName; - var stats = aggregatedStats[key]; - if (!stats) { - affectedIDs[key] = {}; - stats = aggregatedStats[key] = { - key, - instanceCount: 0, - inclusiveRenderDuration: 0, - renderCount: 0, - }; - } - affectedIDs[key][instanceID] = true; - applyUpdate(stats); - } - - var isCompositeByID = {}; - flushHistory.forEach(flush => { - var {measurements} = flush; - measurements.forEach(measurement => { - var {instanceID, timerType} = measurement; - if (timerType !== 'render') { - return; - } - isCompositeByID[instanceID] = true; - }); - }); - - flushHistory.forEach(flush => { - var {measurements, treeSnapshot} = flush; - measurements.forEach(measurement => { - var {duration, instanceID, timerType} = measurement; - if (timerType !== 'render') { - return; - } - updateAggregatedStats(treeSnapshot, instanceID, stats => { - stats.renderCount++; - }); - var nextParentID = instanceID; - while (nextParentID) { - // As we traverse parents, only count inclusive time towards composites. - // We know something is a composite if its render() was called. - if (isCompositeByID[nextParentID]) { - updateAggregatedStats(treeSnapshot, nextParentID, stats => { - stats.inclusiveRenderDuration += duration; - }); - } - nextParentID = treeSnapshot[nextParentID].parentID; - } - }); - }); - - return Object.keys(aggregatedStats) - .map(key => ({ - ...aggregatedStats[key], - instanceCount: Object.keys(affectedIDs[key]).length, - })) - .sort((a, b) => b.inclusiveRenderDuration - a.inclusiveRenderDuration); -} - -function getWasted(flushHistory = getLastMeasurements()) { - if (!__DEV__) { - warnInProduction(); - return []; - } - - var aggregatedStats = {}; - var affectedIDs = {}; - - function updateAggregatedStats(treeSnapshot, instanceID, applyUpdate) { - var {displayName, ownerID} = treeSnapshot[instanceID]; - var owner = treeSnapshot[ownerID]; - var key = (owner ? owner.displayName + ' > ' : '') + displayName; - var stats = aggregatedStats[key]; - if (!stats) { - affectedIDs[key] = {}; - stats = aggregatedStats[key] = { - key, - instanceCount: 0, - inclusiveRenderDuration: 0, - renderCount: 0, - }; - } - affectedIDs[key][instanceID] = true; - applyUpdate(stats); - } - - flushHistory.forEach(flush => { - var {measurements, treeSnapshot, operations} = flush; - var isDefinitelyNotWastedByID = {}; - - // Find host components associated with an operation in this batch. - // Mark all components in their parent tree as definitely not wasted. - operations.forEach(operation => { - var {instanceID} = operation; - var nextParentID = instanceID; - while (nextParentID) { - isDefinitelyNotWastedByID[nextParentID] = true; - nextParentID = treeSnapshot[nextParentID].parentID; - } - }); - - // Find composite components that rendered in this batch. - // These are potential candidates for being wasted renders. - var renderedCompositeIDs = {}; - measurements.forEach(measurement => { - var {instanceID, timerType} = measurement; - if (timerType !== 'render') { - return; - } - renderedCompositeIDs[instanceID] = true; - }); - - measurements.forEach(measurement => { - var {duration, instanceID, timerType} = measurement; - if (timerType !== 'render') { - return; - } - - // If there was a DOM update below this component, or it has just been - // mounted, its render() is not considered wasted. - var {updateCount} = treeSnapshot[instanceID]; - if (isDefinitelyNotWastedByID[instanceID] || updateCount === 0) { - return; - } - - // We consider this render() wasted. - updateAggregatedStats(treeSnapshot, instanceID, stats => { - stats.renderCount++; - }); - - var nextParentID = instanceID; - while (nextParentID) { - // Any parents rendered during this batch are considered wasted - // unless we previously marked them as dirty. - var isWasted = - renderedCompositeIDs[nextParentID] && - !isDefinitelyNotWastedByID[nextParentID]; - if (isWasted) { - updateAggregatedStats(treeSnapshot, nextParentID, stats => { - stats.inclusiveRenderDuration += duration; - }); - } - nextParentID = treeSnapshot[nextParentID].parentID; - } - }); - }); - - return Object.keys(aggregatedStats) - .map(key => ({ - ...aggregatedStats[key], - instanceCount: Object.keys(affectedIDs[key]).length, - })) - .sort((a, b) => b.inclusiveRenderDuration - a.inclusiveRenderDuration); -} - -function getOperations(flushHistory = getLastMeasurements()) { - if (!__DEV__) { - warnInProduction(); - return []; - } - - var stats = []; - flushHistory.forEach((flush, flushIndex) => { - var {operations, treeSnapshot} = flush; - operations.forEach(operation => { - var {instanceID, type, payload} = operation; - var {displayName, ownerID} = treeSnapshot[instanceID]; - var owner = treeSnapshot[ownerID]; - var key = (owner ? owner.displayName + ' > ' : '') + displayName; - - stats.push({ - flushIndex, - instanceID, - key, - type, - ownerID, - payload, - }); - }); - }); - return stats; -} - -function printExclusive(flushHistory?: FlushHistory) { - if (!__DEV__) { - warnInProduction(); - return; - } - - var stats = getExclusive(flushHistory); - var table = stats.map(item => { - var {key, instanceCount, totalDuration} = item; - var renderCount = item.counts.render || 0; - var renderDuration = item.durations.render || 0; - return { - Component: key, - 'Total time (ms)': roundFloat(totalDuration), - 'Instance count': instanceCount, - 'Total render time (ms)': roundFloat(renderDuration), - 'Average render time (ms)': renderCount - ? roundFloat(renderDuration / renderCount) - : undefined, - 'Render count': renderCount, - 'Total lifecycle time (ms)': roundFloat(totalDuration - renderDuration), - }; - }); - consoleTable(table); -} - -function printInclusive(flushHistory?: FlushHistory) { - if (!__DEV__) { - warnInProduction(); - return; - } - - var stats = getInclusive(flushHistory); - var table = stats.map(item => { - var {key, instanceCount, inclusiveRenderDuration, renderCount} = item; - return { - 'Owner > Component': key, - 'Inclusive render time (ms)': roundFloat(inclusiveRenderDuration), - 'Instance count': instanceCount, - 'Render count': renderCount, - }; - }); - consoleTable(table); -} - -function printWasted(flushHistory?: FlushHistory) { - if (!__DEV__) { - warnInProduction(); - return; - } - - var stats = getWasted(flushHistory); - var table = stats.map(item => { - var {key, instanceCount, inclusiveRenderDuration, renderCount} = item; - return { - 'Owner > Component': key, - 'Inclusive wasted time (ms)': roundFloat(inclusiveRenderDuration), - 'Instance count': instanceCount, - 'Render count': renderCount, - }; - }); - consoleTable(table); -} - -function printOperations(flushHistory?: FlushHistory) { - if (!__DEV__) { - warnInProduction(); - return; - } - - var stats = getOperations(flushHistory); - var table = stats.map(stat => ({ - 'Owner > Node': stat.key, - Operation: stat.type, - Payload: typeof stat.payload === 'object' - ? JSON.stringify(stat.payload) - : stat.payload, - 'Flush index': stat.flushIndex, - 'Owner Component ID': stat.ownerID, - 'DOM Component ID': stat.instanceID, - })); - consoleTable(table); -} - -var warnedAboutPrintDOM = false; -function printDOM(measurements: FlushHistory) { - warning( - warnedAboutPrintDOM, - '`ReactPerf.printDOM(...)` is deprecated. Use ' + - '`ReactPerf.printOperations(...)` instead.', - ); - warnedAboutPrintDOM = true; - return printOperations(measurements); -} - -var warnedAboutGetMeasurementsSummaryMap = false; -function getMeasurementsSummaryMap(measurements: FlushHistory) { - warning( - warnedAboutGetMeasurementsSummaryMap, - '`ReactPerf.getMeasurementsSummaryMap(...)` is deprecated. Use ' + - '`ReactPerf.getWasted(...)` instead.', - ); - warnedAboutGetMeasurementsSummaryMap = true; - return getWasted(measurements); -} - -function start() { - if (!__DEV__) { - warnInProduction(); - return; - } - - ReactDebugTool.beginProfiling(); -} - -function stop() { - if (!__DEV__) { - warnInProduction(); - return; - } - - ReactDebugTool.endProfiling(); -} - -function isRunning() { - if (!__DEV__) { - warnInProduction(); - return false; - } - - return ReactDebugTool.isProfiling(); -} - -var ReactPerfAnalysis = { - getLastMeasurements, - getExclusive, - getInclusive, - getWasted, - getOperations, - printExclusive, - printInclusive, - printWasted, - printOperations, - start, - stop, - isRunning, - // Deprecated: - printDOM, - getMeasurementsSummaryMap, -}; - -module.exports = ReactPerfAnalysis; diff --git a/Libraries/Renderer/src/renderers/shared/__tests__/ReactDOMFrameScheduling-test.js b/Libraries/Renderer/src/renderers/shared/__tests__/ReactDOMFrameScheduling-test.js deleted file mode 100644 index 5a8a532374..0000000000 --- a/Libraries/Renderer/src/renderers/shared/__tests__/ReactDOMFrameScheduling-test.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright 2016-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @emails react-core - */ - -'use strict'; - -const ReactDOMFeatureFlags = require('ReactDOMFeatureFlags'); -const describeFiber = ReactDOMFeatureFlags.useFiber ? describe : xdescribe; - -describeFiber('ReactDOMFrameScheduling', () => { - it('throws when requestAnimationFrame is not polyfilled in the browser', () => { - const previousRAF = global.requestAnimationFrame; - try { - global.requestAnimationFrame = undefined; - jest.resetModules(); - expect(() => { - require('ReactDOM'); - }).toThrow( - 'React depends on requestAnimationFrame. Make sure that you load a ' + - 'polyfill in older browsers.', - ); - } finally { - global.requestAnimationFrame = previousRAF; - } - }); - - // We're just testing importing, not using it. - // It is important because even isomorphic components may import it. - it('can import findDOMNode in Node environment', () => { - const previousRAF = global.requestAnimationFrame; - const previousRIC = global.requestIdleCallback; - const prevWindow = global.window; - try { - global.requestAnimationFrame = undefined; - global.requestIdleCallback = undefined; - // Simulate the Node environment: - delete global.window; - jest.resetModules(); - expect(() => { - require('ReactDOM'); - }).not.toThrow(); - } finally { - global.requestAnimationFrame = previousRAF; - global.requestIdleCallback = previousRIC; - global.window = prevWindow; - } - }); -}); diff --git a/Libraries/Renderer/src/renderers/shared/__tests__/ReactDebugTool-test.js b/Libraries/Renderer/src/renderers/shared/__tests__/ReactDebugTool-test.js deleted file mode 100644 index 3082b9eab9..0000000000 --- a/Libraries/Renderer/src/renderers/shared/__tests__/ReactDebugTool-test.js +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Copyright 2016-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @emails react-core - */ - -'use strict'; - -describe('ReactDebugTool', () => { - var ReactDebugTool; - - beforeEach(() => { - jest.resetModules(); - ReactDebugTool = require('ReactDebugTool'); - }); - - it('should add and remove hooks', () => { - var handler1 = jasmine.createSpy('spy'); - var handler2 = jasmine.createSpy('spy'); - var hook1 = {onTestEvent: handler1}; - var hook2 = {onTestEvent: handler2}; - - ReactDebugTool.addHook(hook1); - ReactDebugTool.onTestEvent(); - expect(handler1.calls.count()).toBe(1); - expect(handler2.calls.count()).toBe(0); - - ReactDebugTool.onTestEvent(); - expect(handler1.calls.count()).toBe(2); - expect(handler2.calls.count()).toBe(0); - - ReactDebugTool.addHook(hook2); - ReactDebugTool.onTestEvent(); - expect(handler1.calls.count()).toBe(3); - expect(handler2.calls.count()).toBe(1); - - ReactDebugTool.onTestEvent(); - expect(handler1.calls.count()).toBe(4); - expect(handler2.calls.count()).toBe(2); - - ReactDebugTool.removeHook(hook1); - ReactDebugTool.onTestEvent(); - expect(handler1.calls.count()).toBe(4); - expect(handler2.calls.count()).toBe(3); - - ReactDebugTool.removeHook(hook2); - ReactDebugTool.onTestEvent(); - expect(handler1.calls.count()).toBe(4); - expect(handler2.calls.count()).toBe(3); - }); - - it('warns once when an error is thrown in hook', () => { - spyOn(console, 'error'); - ReactDebugTool.addHook({ - onTestEvent() { - throw new Error('Hi.'); - }, - }); - - ReactDebugTool.onTestEvent(); - expectDev(console.error.calls.count()).toBe(1); - expectDev(console.error.calls.argsFor(0)[0]).toContain( - 'Exception thrown by hook while handling ' + 'onTestEvent: Error: Hi.', - ); - - ReactDebugTool.onTestEvent(); - expectDev(console.error.calls.count()).toBe(1); - }); - - it('returns isProfiling state', () => { - expect(ReactDebugTool.isProfiling()).toBe(false); - - ReactDebugTool.beginProfiling(); - expect(ReactDebugTool.isProfiling()).toBe(true); - - ReactDebugTool.endProfiling(); - expect(ReactDebugTool.isProfiling()).toBe(false); - }); -}); diff --git a/Libraries/Renderer/src/renderers/shared/fiber/ReactChildFiber.js b/Libraries/Renderer/src/renderers/shared/fiber/ReactChildFiber.js deleted file mode 100644 index 147efd09d9..0000000000 --- a/Libraries/Renderer/src/renderers/shared/fiber/ReactChildFiber.js +++ /dev/null @@ -1,1470 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactChildFiber - * @flow - */ - -'use strict'; - -import type {ReactElement} from 'ReactElementType'; -import type {ReactCoroutine, ReactYield} from 'ReactCoroutine'; -import type {ReactPortal} from 'ReactPortal'; -import type {Fiber} from 'ReactFiber'; -import type {ReactInstance} from 'ReactInstanceType'; -import type {PriorityLevel} from 'ReactPriorityLevel'; - -var REACT_ELEMENT_TYPE = require('ReactElementSymbol'); -var {REACT_COROUTINE_TYPE, REACT_YIELD_TYPE} = require('ReactCoroutine'); -var {REACT_PORTAL_TYPE} = require('ReactPortal'); - -var ReactFiber = require('ReactFiber'); -var ReactTypeOfSideEffect = require('ReactTypeOfSideEffect'); -var ReactTypeOfWork = require('ReactTypeOfWork'); - -var emptyObject = require('fbjs/lib/emptyObject'); -var getIteratorFn = require('getIteratorFn'); -var invariant = require('fbjs/lib/invariant'); -var ReactFeatureFlags = require('ReactFeatureFlags'); - -if (__DEV__) { - var {getCurrentFiberStackAddendum} = require('ReactDebugCurrentFiber'); - var warning = require('fbjs/lib/warning'); - var didWarnAboutMaps = false; - /** - * Warn if there's no key explicitly set on dynamic arrays of children or - * object keys are not valid. This allows us to keep track of children between - * updates. - */ - var ownerHasKeyUseWarning = {}; - - var warnForMissingKey = (child: mixed) => { - if (child === null || typeof child !== 'object') { - return; - } - if (!child._store || child._store.validated || child.key != null) { - return; - } - invariant( - typeof child._store === 'object', - 'React Component in warnForMissingKey should have a _store', - ); - child._store.validated = true; - - var currentComponentErrorInfo = - 'Each child in an array or iterator should have a unique ' + - '"key" prop. See https://fb.me/react-warning-keys for ' + - 'more information.' + - (getCurrentFiberStackAddendum() || ''); - if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { - return; - } - ownerHasKeyUseWarning[currentComponentErrorInfo] = true; - - warning( - false, - 'Each child in an array or iterator should have a unique ' + - '"key" prop. See https://fb.me/react-warning-keys for ' + - 'more information.%s', - getCurrentFiberStackAddendum(), - ); - }; -} - -const { - cloneFiber, - createFiberFromElement, - createFiberFromFragment, - createFiberFromText, - createFiberFromCoroutine, - createFiberFromYield, - createFiberFromPortal, -} = ReactFiber; - -const isArray = Array.isArray; - -const { - FunctionalComponent, - ClassComponent, - HostText, - HostPortal, - CoroutineComponent, - YieldComponent, - Fragment, -} = ReactTypeOfWork; - -const {NoEffect, Placement, Deletion} = ReactTypeOfSideEffect; - -function coerceRef(current: Fiber | null, element: ReactElement) { - let mixedRef = element.ref; - if (mixedRef !== null && typeof mixedRef !== 'function') { - if (element._owner) { - const owner: ?(Fiber | ReactInstance) = (element._owner: any); - let inst; - if (owner) { - if (typeof owner.tag === 'number') { - const ownerFiber = ((owner: any): Fiber); - invariant( - ownerFiber.tag === ClassComponent, - 'Stateless function components cannot have refs.', - ); - inst = ownerFiber.stateNode; - } else { - // Stack - inst = (owner: any).getPublicInstance(); - } - } - invariant( - inst, - 'Missing owner for string ref %s. This error is likely caused by a ' + - 'bug in React. Please file an issue.', - mixedRef, - ); - const stringRef = '' + mixedRef; - // Check if previous string ref matches new string ref - if ( - current !== null && - current.ref !== null && - current.ref._stringRef === stringRef - ) { - return current.ref; - } - const ref = function(value) { - const refs = inst.refs === emptyObject ? (inst.refs = {}) : inst.refs; - if (value === null) { - delete refs[stringRef]; - } else { - refs[stringRef] = value; - } - }; - ref._stringRef = stringRef; - return ref; - } - } - return mixedRef; -} - -function throwOnInvalidObjectType(returnFiber: Fiber, newChild: Object) { - if (returnFiber.type !== 'textarea') { - let addendum = ''; - if (__DEV__) { - addendum = - ' If you meant to render a collection of children, use an array ' + - 'instead.' + - (getCurrentFiberStackAddendum() || ''); - } - invariant( - false, - 'Objects are not valid as a React child (found: %s).%s', - Object.prototype.toString.call(newChild) === '[object Object]' - ? 'object with keys {' + Object.keys(newChild).join(', ') + '}' - : newChild, - addendum, - ); - } -} - -// This wrapper function exists because I expect to clone the code in each path -// to be able to optimize each path individually by branching early. This needs -// a compiler or we can do it manually. Helpers that don't need this branching -// live outside of this function. -function ChildReconciler(shouldClone, shouldTrackSideEffects) { - function deleteChild(returnFiber: Fiber, childToDelete: Fiber): void { - if (!shouldTrackSideEffects) { - // Noop. - return; - } - if (!shouldClone) { - // When we're reconciling in place we have a work in progress copy. We - // actually want the current copy. If there is no current copy, then we - // don't need to track deletion side-effects. - if (childToDelete.alternate === null) { - return; - } - childToDelete = childToDelete.alternate; - } - // Deletions are added in reversed order so we add it to the front. - const last = returnFiber.progressedLastDeletion; - if (last !== null) { - last.nextEffect = childToDelete; - returnFiber.progressedLastDeletion = childToDelete; - } else { - returnFiber.progressedFirstDeletion = returnFiber.progressedLastDeletion = childToDelete; - } - childToDelete.nextEffect = null; - childToDelete.effectTag = Deletion; - } - - function deleteRemainingChildren( - returnFiber: Fiber, - currentFirstChild: Fiber | null, - ): null { - if (!shouldTrackSideEffects) { - // Noop. - return null; - } - - // TODO: For the shouldClone case, this could be micro-optimized a bit by - // assuming that after the first child we've already added everything. - let childToDelete = currentFirstChild; - while (childToDelete !== null) { - deleteChild(returnFiber, childToDelete); - childToDelete = childToDelete.sibling; - } - return null; - } - - function mapRemainingChildren( - returnFiber: Fiber, - currentFirstChild: Fiber, - ): Map { - // Add the remaining children to a temporary map so that we can find them by - // keys quickly. Implicit (null) keys get added to this set with their index - // instead. - const existingChildren: Map = new Map(); - - let existingChild = currentFirstChild; - while (existingChild !== null) { - if (existingChild.key !== null) { - existingChildren.set(existingChild.key, existingChild); - } else { - existingChildren.set(existingChild.index, existingChild); - } - existingChild = existingChild.sibling; - } - return existingChildren; - } - - function useFiber(fiber: Fiber, priority: PriorityLevel): Fiber { - // We currently set sibling to null and index to 0 here because it is easy - // to forget to do before returning it. E.g. for the single child case. - if (shouldClone) { - const clone = cloneFiber(fiber, priority); - clone.index = 0; - clone.sibling = null; - return clone; - } else { - // We override the pending priority even if it is higher, because if - // we're reconciling at a lower priority that means that this was - // down-prioritized. - fiber.pendingWorkPriority = priority; - fiber.effectTag = NoEffect; - fiber.index = 0; - fiber.sibling = null; - return fiber; - } - } - - function placeChild( - newFiber: Fiber, - lastPlacedIndex: number, - newIndex: number, - ): number { - newFiber.index = newIndex; - if (!shouldTrackSideEffects) { - // Noop. - return lastPlacedIndex; - } - const current = newFiber.alternate; - if (current !== null) { - const oldIndex = current.index; - if (oldIndex < lastPlacedIndex) { - // This is a move. - newFiber.effectTag = Placement; - return lastPlacedIndex; - } else { - // This item can stay in place. - return oldIndex; - } - } else { - // This is an insertion. - newFiber.effectTag = Placement; - return lastPlacedIndex; - } - } - - function placeSingleChild(newFiber: Fiber): Fiber { - // This is simpler for the single child case. We only need to do a - // placement for inserting new children. - if (shouldTrackSideEffects && newFiber.alternate === null) { - newFiber.effectTag = Placement; - } - return newFiber; - } - - function updateTextNode( - returnFiber: Fiber, - current: Fiber | null, - textContent: string, - priority: PriorityLevel, - ) { - if (current === null || current.tag !== HostText) { - // Insert - const created = createFiberFromText( - textContent, - returnFiber.internalContextTag, - priority, - ); - created.return = returnFiber; - return created; - } else { - // Update - const existing = useFiber(current, priority); - existing.pendingProps = textContent; - existing.return = returnFiber; - return existing; - } - } - - function updateElement( - returnFiber: Fiber, - current: Fiber | null, - element: ReactElement, - priority: PriorityLevel, - ): Fiber { - if (current === null || current.type !== element.type) { - // Insert - const created = createFiberFromElement( - element, - returnFiber.internalContextTag, - priority, - ); - created.ref = coerceRef(current, element); - created.return = returnFiber; - return created; - } else { - // Move based on index - const existing = useFiber(current, priority); - existing.ref = coerceRef(current, element); - existing.pendingProps = element.props; - existing.return = returnFiber; - if (__DEV__) { - existing._debugSource = element._source; - existing._debugOwner = element._owner; - } - return existing; - } - } - - function updateCoroutine( - returnFiber: Fiber, - current: Fiber | null, - coroutine: ReactCoroutine, - priority: PriorityLevel, - ): Fiber { - // TODO: Should this also compare handler to determine whether to reuse? - if (current === null || current.tag !== CoroutineComponent) { - // Insert - const created = createFiberFromCoroutine( - coroutine, - returnFiber.internalContextTag, - priority, - ); - created.return = returnFiber; - return created; - } else { - // Move based on index - const existing = useFiber(current, priority); - existing.pendingProps = coroutine; - existing.return = returnFiber; - return existing; - } - } - - function updateYield( - returnFiber: Fiber, - current: Fiber | null, - yieldNode: ReactYield, - priority: PriorityLevel, - ): Fiber { - if (current === null || current.tag !== YieldComponent) { - // Insert - const created = createFiberFromYield( - yieldNode, - returnFiber.internalContextTag, - priority, - ); - created.type = yieldNode.value; - created.return = returnFiber; - return created; - } else { - // Move based on index - const existing = useFiber(current, priority); - existing.type = yieldNode.value; - existing.return = returnFiber; - return existing; - } - } - - function updatePortal( - returnFiber: Fiber, - current: Fiber | null, - portal: ReactPortal, - priority: PriorityLevel, - ): Fiber { - if ( - current === null || - current.tag !== HostPortal || - current.stateNode.containerInfo !== portal.containerInfo || - current.stateNode.implementation !== portal.implementation - ) { - // Insert - const created = createFiberFromPortal( - portal, - returnFiber.internalContextTag, - priority, - ); - created.return = returnFiber; - return created; - } else { - // Update - const existing = useFiber(current, priority); - existing.pendingProps = portal.children || []; - existing.return = returnFiber; - return existing; - } - } - - function updateFragment( - returnFiber: Fiber, - current: Fiber | null, - fragment: Iterable<*>, - priority: PriorityLevel, - ): Fiber { - if (current === null || current.tag !== Fragment) { - // Insert - const created = createFiberFromFragment( - fragment, - returnFiber.internalContextTag, - priority, - ); - created.return = returnFiber; - return created; - } else { - // Update - const existing = useFiber(current, priority); - existing.pendingProps = fragment; - existing.return = returnFiber; - return existing; - } - } - - function createChild( - returnFiber: Fiber, - newChild: any, - priority: PriorityLevel, - ): Fiber | null { - if (typeof newChild === 'string' || typeof newChild === 'number') { - // Text nodes doesn't have keys. If the previous node is implicitly keyed - // we can continue to replace it without aborting even if it is not a text - // node. - const created = createFiberFromText( - '' + newChild, - returnFiber.internalContextTag, - priority, - ); - created.return = returnFiber; - return created; - } - - if (typeof newChild === 'object' && newChild !== null) { - switch (newChild.$$typeof) { - case REACT_ELEMENT_TYPE: { - const created = createFiberFromElement( - newChild, - returnFiber.internalContextTag, - priority, - ); - created.ref = coerceRef(null, newChild); - created.return = returnFiber; - return created; - } - - case REACT_COROUTINE_TYPE: { - const created = createFiberFromCoroutine( - newChild, - returnFiber.internalContextTag, - priority, - ); - created.return = returnFiber; - return created; - } - - case REACT_YIELD_TYPE: { - const created = createFiberFromYield( - newChild, - returnFiber.internalContextTag, - priority, - ); - created.type = newChild.value; - created.return = returnFiber; - return created; - } - - case REACT_PORTAL_TYPE: { - const created = createFiberFromPortal( - newChild, - returnFiber.internalContextTag, - priority, - ); - created.return = returnFiber; - return created; - } - } - - if (isArray(newChild) || getIteratorFn(newChild)) { - const created = createFiberFromFragment( - newChild, - returnFiber.internalContextTag, - priority, - ); - created.return = returnFiber; - return created; - } - - throwOnInvalidObjectType(returnFiber, newChild); - } - - return null; - } - - function updateSlot( - returnFiber: Fiber, - oldFiber: Fiber | null, - newChild: any, - priority: PriorityLevel, - ): Fiber | null { - // Update the fiber if the keys match, otherwise return null. - - const key = oldFiber !== null ? oldFiber.key : null; - - if (typeof newChild === 'string' || typeof newChild === 'number') { - // Text nodes doesn't have keys. If the previous node is implicitly keyed - // we can continue to replace it without aborting even if it is not a text - // node. - if (key !== null) { - return null; - } - return updateTextNode(returnFiber, oldFiber, '' + newChild, priority); - } - - if (typeof newChild === 'object' && newChild !== null) { - switch (newChild.$$typeof) { - case REACT_ELEMENT_TYPE: { - if (newChild.key === key) { - return updateElement(returnFiber, oldFiber, newChild, priority); - } else { - return null; - } - } - - case REACT_COROUTINE_TYPE: { - if (newChild.key === key) { - return updateCoroutine(returnFiber, oldFiber, newChild, priority); - } else { - return null; - } - } - - case REACT_YIELD_TYPE: { - // Yields doesn't have keys. If the previous node is implicitly keyed - // we can continue to replace it without aborting even if it is not a - // yield. - if (key === null) { - return updateYield(returnFiber, oldFiber, newChild, priority); - } else { - return null; - } - } - - case REACT_PORTAL_TYPE: { - if (newChild.key === key) { - return updatePortal(returnFiber, oldFiber, newChild, priority); - } else { - return null; - } - } - } - - if (isArray(newChild) || getIteratorFn(newChild)) { - // Fragments doesn't have keys so if the previous key is implicit we can - // update it. - if (key !== null) { - return null; - } - return updateFragment(returnFiber, oldFiber, newChild, priority); - } - - throwOnInvalidObjectType(returnFiber, newChild); - } - - return null; - } - - function updateFromMap( - existingChildren: Map, - returnFiber: Fiber, - newIdx: number, - newChild: any, - priority: PriorityLevel, - ): Fiber | null { - if (typeof newChild === 'string' || typeof newChild === 'number') { - // Text nodes doesn't have keys, so we neither have to check the old nor - // new node for the key. If both are text nodes, they match. - const matchedFiber = existingChildren.get(newIdx) || null; - return updateTextNode(returnFiber, matchedFiber, '' + newChild, priority); - } - - if (typeof newChild === 'object' && newChild !== null) { - switch (newChild.$$typeof) { - case REACT_ELEMENT_TYPE: { - const matchedFiber = - existingChildren.get( - newChild.key === null ? newIdx : newChild.key, - ) || null; - return updateElement(returnFiber, matchedFiber, newChild, priority); - } - - case REACT_COROUTINE_TYPE: { - const matchedFiber = - existingChildren.get( - newChild.key === null ? newIdx : newChild.key, - ) || null; - return updateCoroutine(returnFiber, matchedFiber, newChild, priority); - } - - case REACT_YIELD_TYPE: { - // Yields doesn't have keys, so we neither have to check the old nor - // new node for the key. If both are yields, they match. - const matchedFiber = existingChildren.get(newIdx) || null; - return updateYield(returnFiber, matchedFiber, newChild, priority); - } - - case REACT_PORTAL_TYPE: { - const matchedFiber = - existingChildren.get( - newChild.key === null ? newIdx : newChild.key, - ) || null; - return updatePortal(returnFiber, matchedFiber, newChild, priority); - } - } - - if (isArray(newChild) || getIteratorFn(newChild)) { - const matchedFiber = existingChildren.get(newIdx) || null; - return updateFragment(returnFiber, matchedFiber, newChild, priority); - } - - throwOnInvalidObjectType(returnFiber, newChild); - } - - return null; - } - - /** - * Warns if there is a duplicate or missing key - */ - function warnOnInvalidKey( - child: mixed, - knownKeys: Set | null, - ): Set | null { - if (__DEV__) { - if (typeof child !== 'object' || child === null) { - return knownKeys; - } - switch (child.$$typeof) { - case REACT_ELEMENT_TYPE: - case REACT_COROUTINE_TYPE: - case REACT_PORTAL_TYPE: - warnForMissingKey(child); - const key = child.key; - if (typeof key !== 'string') { - break; - } - if (knownKeys === null) { - knownKeys = new Set(); - knownKeys.add(key); - break; - } - if (!knownKeys.has(key)) { - knownKeys.add(key); - break; - } - warning( - false, - 'Encountered two children with the same key, ' + - '`%s`. Child keys must be unique; when two children share a key, ' + - 'only the first child will be used.%s', - key, - getCurrentFiberStackAddendum(), - ); - break; - default: - break; - } - } - return knownKeys; - } - - function reconcileChildrenArray( - returnFiber: Fiber, - currentFirstChild: Fiber | null, - newChildren: Array<*>, - priority: PriorityLevel, - ): Fiber | null { - // This algorithm can't optimize by searching from boths ends since we - // don't have backpointers on fibers. I'm trying to see how far we can get - // with that model. If it ends up not being worth the tradeoffs, we can - // add it later. - - // Even with a two ended optimization, we'd want to optimize for the case - // where there are few changes and brute force the comparison instead of - // going for the Map. It'd like to explore hitting that path first in - // forward-only mode and only go for the Map once we notice that we need - // lots of look ahead. This doesn't handle reversal as well as two ended - // search but that's unusual. Besides, for the two ended optimization to - // work on Iterables, we'd need to copy the whole set. - - // In this first iteration, we'll just live with hitting the bad case - // (adding everything to a Map) in for every insert/move. - - // If you change this code, also update reconcileChildrenIterator() which - // uses the same algorithm. - - if (__DEV__) { - // First, validate keys. - let knownKeys = null; - for (let i = 0; i < newChildren.length; i++) { - const child = newChildren[i]; - knownKeys = warnOnInvalidKey(child, knownKeys); - } - } - - let resultingFirstChild: Fiber | null = null; - let previousNewFiber: Fiber | null = null; - - let oldFiber = currentFirstChild; - let lastPlacedIndex = 0; - let newIdx = 0; - let nextOldFiber = null; - for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) { - if (oldFiber.index > newIdx) { - nextOldFiber = oldFiber; - oldFiber = null; - } else { - nextOldFiber = oldFiber.sibling; - } - const newFiber = updateSlot( - returnFiber, - oldFiber, - newChildren[newIdx], - priority, - ); - if (newFiber === null) { - // TODO: This breaks on empty slots like null children. That's - // unfortunate because it triggers the slow path all the time. We need - // a better way to communicate whether this was a miss or null, - // boolean, undefined, etc. - if (oldFiber === null) { - oldFiber = nextOldFiber; - } - break; - } - if (shouldTrackSideEffects) { - if (oldFiber && newFiber.alternate === null) { - // We matched the slot, but we didn't reuse the existing fiber, so we - // need to delete the existing child. - deleteChild(returnFiber, oldFiber); - } - } - lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); - if (previousNewFiber === null) { - // TODO: Move out of the loop. This only happens for the first run. - resultingFirstChild = newFiber; - } else { - // TODO: Defer siblings if we're not at the right index for this slot. - // I.e. if we had null values before, then we want to defer this - // for each null value. However, we also don't want to call updateSlot - // with the previous one. - previousNewFiber.sibling = newFiber; - } - previousNewFiber = newFiber; - oldFiber = nextOldFiber; - } - - if (newIdx === newChildren.length) { - // We've reached the end of the new children. We can delete the rest. - deleteRemainingChildren(returnFiber, oldFiber); - return resultingFirstChild; - } - - if (oldFiber === null) { - // If we don't have any more existing children we can choose a fast path - // since the rest will all be insertions. - for (; newIdx < newChildren.length; newIdx++) { - const newFiber = createChild( - returnFiber, - newChildren[newIdx], - priority, - ); - if (!newFiber) { - continue; - } - lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); - if (previousNewFiber === null) { - // TODO: Move out of the loop. This only happens for the first run. - resultingFirstChild = newFiber; - } else { - previousNewFiber.sibling = newFiber; - } - previousNewFiber = newFiber; - } - return resultingFirstChild; - } - - // Add all children to a key map for quick lookups. - const existingChildren = mapRemainingChildren(returnFiber, oldFiber); - - // Keep scanning and use the map to restore deleted items as moves. - for (; newIdx < newChildren.length; newIdx++) { - const newFiber = updateFromMap( - existingChildren, - returnFiber, - newIdx, - newChildren[newIdx], - priority, - ); - if (newFiber) { - if (shouldTrackSideEffects) { - if (newFiber.alternate !== null) { - // The new fiber is a work in progress, but if there exists a - // current, that means that we reused the fiber. We need to delete - // it from the child list so that we don't add it to the deletion - // list. - existingChildren.delete( - newFiber.key === null ? newIdx : newFiber.key, - ); - } - } - lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); - if (previousNewFiber === null) { - resultingFirstChild = newFiber; - } else { - previousNewFiber.sibling = newFiber; - } - previousNewFiber = newFiber; - } - } - - if (shouldTrackSideEffects) { - // Any existing children that weren't consumed above were deleted. We need - // to add them to the deletion list. - existingChildren.forEach(child => deleteChild(returnFiber, child)); - } - - return resultingFirstChild; - } - - function reconcileChildrenIterator( - returnFiber: Fiber, - currentFirstChild: Fiber | null, - newChildrenIterable: Iterable<*>, - priority: PriorityLevel, - ): Fiber | null { - // This is the same implementation as reconcileChildrenArray(), - // but using the iterator instead. - - const iteratorFn = getIteratorFn(newChildrenIterable); - invariant( - typeof iteratorFn === 'function', - 'An object is not an iterable. This error is likely caused by a bug in ' + - 'React. Please file an issue.', - ); - - if (__DEV__) { - // Warn about using Maps as children - if (typeof newChildrenIterable.entries === 'function') { - const possibleMap = (newChildrenIterable: any); - if (possibleMap.entries === iteratorFn) { - warning( - didWarnAboutMaps, - 'Using Maps as children is unsupported and will likely yield ' + - 'unexpected results. Convert it to a sequence/iterable of keyed ' + - 'ReactElements instead.%s', - getCurrentFiberStackAddendum(), - ); - didWarnAboutMaps = true; - } - } - - // First, validate keys. - // We'll get a different iterator later for the main pass. - const newChildren = iteratorFn.call(newChildrenIterable); - if (newChildren) { - let knownKeys = null; - let step = newChildren.next(); - for (; !step.done; step = newChildren.next()) { - const child = step.value; - knownKeys = warnOnInvalidKey(child, knownKeys); - } - } - } - - const newChildren = iteratorFn.call(newChildrenIterable); - invariant(newChildren != null, 'An iterable object provided no iterator.'); - - let resultingFirstChild: Fiber | null = null; - let previousNewFiber: Fiber | null = null; - - let oldFiber = currentFirstChild; - let lastPlacedIndex = 0; - let newIdx = 0; - let nextOldFiber = null; - - let step = newChildren.next(); - for ( - ; - oldFiber !== null && !step.done; - newIdx++, (step = newChildren.next()) - ) { - if (oldFiber.index > newIdx) { - nextOldFiber = oldFiber; - oldFiber = null; - } else { - nextOldFiber = oldFiber.sibling; - } - const newFiber = updateSlot(returnFiber, oldFiber, step.value, priority); - if (newFiber === null) { - // TODO: This breaks on empty slots like null children. That's - // unfortunate because it triggers the slow path all the time. We need - // a better way to communicate whether this was a miss or null, - // boolean, undefined, etc. - if (!oldFiber) { - oldFiber = nextOldFiber; - } - break; - } - if (shouldTrackSideEffects) { - if (oldFiber && newFiber.alternate === null) { - // We matched the slot, but we didn't reuse the existing fiber, so we - // need to delete the existing child. - deleteChild(returnFiber, oldFiber); - } - } - lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); - if (previousNewFiber === null) { - // TODO: Move out of the loop. This only happens for the first run. - resultingFirstChild = newFiber; - } else { - // TODO: Defer siblings if we're not at the right index for this slot. - // I.e. if we had null values before, then we want to defer this - // for each null value. However, we also don't want to call updateSlot - // with the previous one. - previousNewFiber.sibling = newFiber; - } - previousNewFiber = newFiber; - oldFiber = nextOldFiber; - } - - if (step.done) { - // We've reached the end of the new children. We can delete the rest. - deleteRemainingChildren(returnFiber, oldFiber); - return resultingFirstChild; - } - - if (oldFiber === null) { - // If we don't have any more existing children we can choose a fast path - // since the rest will all be insertions. - for (; !step.done; newIdx++, (step = newChildren.next())) { - const newFiber = createChild(returnFiber, step.value, priority); - if (newFiber === null) { - continue; - } - lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); - if (previousNewFiber === null) { - // TODO: Move out of the loop. This only happens for the first run. - resultingFirstChild = newFiber; - } else { - previousNewFiber.sibling = newFiber; - } - previousNewFiber = newFiber; - } - return resultingFirstChild; - } - - // Add all children to a key map for quick lookups. - const existingChildren = mapRemainingChildren(returnFiber, oldFiber); - - // Keep scanning and use the map to restore deleted items as moves. - for (; !step.done; newIdx++, (step = newChildren.next())) { - const newFiber = updateFromMap( - existingChildren, - returnFiber, - newIdx, - step.value, - priority, - ); - if (newFiber !== null) { - if (shouldTrackSideEffects) { - if (newFiber.alternate !== null) { - // The new fiber is a work in progress, but if there exists a - // current, that means that we reused the fiber. We need to delete - // it from the child list so that we don't add it to the deletion - // list. - existingChildren.delete( - newFiber.key === null ? newIdx : newFiber.key, - ); - } - } - lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); - if (previousNewFiber === null) { - resultingFirstChild = newFiber; - } else { - previousNewFiber.sibling = newFiber; - } - previousNewFiber = newFiber; - } - } - - if (shouldTrackSideEffects) { - // Any existing children that weren't consumed above were deleted. We need - // to add them to the deletion list. - existingChildren.forEach(child => deleteChild(returnFiber, child)); - } - - return resultingFirstChild; - } - - function reconcileSingleTextNode( - returnFiber: Fiber, - currentFirstChild: Fiber | null, - textContent: string, - priority: PriorityLevel, - ): Fiber { - // There's no need to check for keys on text nodes since we don't have a - // way to define them. - if (currentFirstChild !== null && currentFirstChild.tag === HostText) { - // We already have an existing node so let's just update it and delete - // the rest. - deleteRemainingChildren(returnFiber, currentFirstChild.sibling); - const existing = useFiber(currentFirstChild, priority); - existing.pendingProps = textContent; - existing.return = returnFiber; - return existing; - } - // The existing first child is not a text node so we need to create one - // and delete the existing ones. - deleteRemainingChildren(returnFiber, currentFirstChild); - const created = createFiberFromText( - textContent, - returnFiber.internalContextTag, - priority, - ); - created.return = returnFiber; - return created; - } - - function reconcileSingleElement( - returnFiber: Fiber, - currentFirstChild: Fiber | null, - element: ReactElement, - priority: PriorityLevel, - ): Fiber { - const key = element.key; - let child = currentFirstChild; - while (child !== null) { - // TODO: If key === null and child.key === null, then this only applies to - // the first item in the list. - if (child.key === key) { - if (child.type === element.type) { - deleteRemainingChildren(returnFiber, child.sibling); - const existing = useFiber(child, priority); - existing.ref = coerceRef(child, element); - existing.pendingProps = element.props; - existing.return = returnFiber; - if (__DEV__) { - existing._debugSource = element._source; - existing._debugOwner = element._owner; - } - return existing; - } else { - deleteRemainingChildren(returnFiber, child); - break; - } - } else { - deleteChild(returnFiber, child); - } - child = child.sibling; - } - - const created = createFiberFromElement( - element, - returnFiber.internalContextTag, - priority, - ); - created.ref = coerceRef(currentFirstChild, element); - created.return = returnFiber; - return created; - } - - function reconcileSingleCoroutine( - returnFiber: Fiber, - currentFirstChild: Fiber | null, - coroutine: ReactCoroutine, - priority: PriorityLevel, - ): Fiber { - const key = coroutine.key; - let child = currentFirstChild; - while (child !== null) { - // TODO: If key === null and child.key === null, then this only applies to - // the first item in the list. - if (child.key === key) { - if (child.tag === CoroutineComponent) { - deleteRemainingChildren(returnFiber, child.sibling); - const existing = useFiber(child, priority); - existing.pendingProps = coroutine; - existing.return = returnFiber; - return existing; - } else { - deleteRemainingChildren(returnFiber, child); - break; - } - } else { - deleteChild(returnFiber, child); - } - child = child.sibling; - } - - const created = createFiberFromCoroutine( - coroutine, - returnFiber.internalContextTag, - priority, - ); - created.return = returnFiber; - return created; - } - - function reconcileSingleYield( - returnFiber: Fiber, - currentFirstChild: Fiber | null, - yieldNode: ReactYield, - priority: PriorityLevel, - ): Fiber { - // There's no need to check for keys on yields since they're stateless. - let child = currentFirstChild; - if (child !== null) { - if (child.tag === YieldComponent) { - deleteRemainingChildren(returnFiber, child.sibling); - const existing = useFiber(child, priority); - existing.type = yieldNode.value; - existing.return = returnFiber; - return existing; - } else { - deleteRemainingChildren(returnFiber, child); - } - } - - const created = createFiberFromYield( - yieldNode, - returnFiber.internalContextTag, - priority, - ); - created.type = yieldNode.value; - created.return = returnFiber; - return created; - } - - function reconcileSinglePortal( - returnFiber: Fiber, - currentFirstChild: Fiber | null, - portal: ReactPortal, - priority: PriorityLevel, - ): Fiber { - const key = portal.key; - let child = currentFirstChild; - while (child !== null) { - // TODO: If key === null and child.key === null, then this only applies to - // the first item in the list. - if (child.key === key) { - if ( - child.tag === HostPortal && - child.stateNode.containerInfo === portal.containerInfo && - child.stateNode.implementation === portal.implementation - ) { - deleteRemainingChildren(returnFiber, child.sibling); - const existing = useFiber(child, priority); - existing.pendingProps = portal.children || []; - existing.return = returnFiber; - return existing; - } else { - deleteRemainingChildren(returnFiber, child); - break; - } - } else { - deleteChild(returnFiber, child); - } - child = child.sibling; - } - - const created = createFiberFromPortal( - portal, - returnFiber.internalContextTag, - priority, - ); - created.return = returnFiber; - return created; - } - - // This API will tag the children with the side-effect of the reconciliation - // itself. They will be added to the side-effect list as we pass through the - // children and the parent. - function reconcileChildFibers( - returnFiber: Fiber, - currentFirstChild: Fiber | null, - newChild: any, - priority: PriorityLevel, - ): Fiber | null { - // This function is not recursive. - // If the top level item is an array, we treat it as a set of children, - // not as a fragment. Nested arrays on the other hand will be treated as - // fragment nodes. Recursion happens at the normal flow. - - const disableNewFiberFeatures = ReactFeatureFlags.disableNewFiberFeatures; - - // Handle object types - const isObject = typeof newChild === 'object' && newChild !== null; - if (isObject) { - // Support only the subset of return types that Stack supports. Treat - // everything else as empty, but log a warning. - if (disableNewFiberFeatures) { - switch (newChild.$$typeof) { - case REACT_ELEMENT_TYPE: - return placeSingleChild( - reconcileSingleElement( - returnFiber, - currentFirstChild, - newChild, - priority, - ), - ); - - case REACT_PORTAL_TYPE: - return placeSingleChild( - reconcileSinglePortal( - returnFiber, - currentFirstChild, - newChild, - priority, - ), - ); - } - } else { - switch (newChild.$$typeof) { - case REACT_ELEMENT_TYPE: - return placeSingleChild( - reconcileSingleElement( - returnFiber, - currentFirstChild, - newChild, - priority, - ), - ); - - case REACT_COROUTINE_TYPE: - return placeSingleChild( - reconcileSingleCoroutine( - returnFiber, - currentFirstChild, - newChild, - priority, - ), - ); - - case REACT_YIELD_TYPE: - return placeSingleChild( - reconcileSingleYield( - returnFiber, - currentFirstChild, - newChild, - priority, - ), - ); - - case REACT_PORTAL_TYPE: - return placeSingleChild( - reconcileSinglePortal( - returnFiber, - currentFirstChild, - newChild, - priority, - ), - ); - } - } - } - - if (disableNewFiberFeatures) { - // The new child is not an element. If it's not null or false, - // and the return fiber is a composite component, throw an error. - switch (returnFiber.tag) { - case ClassComponent: { - if (__DEV__) { - const instance = returnFiber.stateNode; - if ( - instance.render._isMockFunction && - typeof newChild === 'undefined' - ) { - // We allow auto-mocks to proceed as if they're - // returning null. - break; - } - } - const Component = returnFiber.type; - invariant( - newChild === null || newChild === false, - '%s.render(): A valid React element (or null) must be returned. ' + - 'You may have returned undefined, an array or some other ' + - 'invalid object.', - Component.displayName || Component.name || 'Component', - ); - break; - } - case FunctionalComponent: { - // Composites accept elements, portals, null, or false - const Component = returnFiber.type; - invariant( - newChild === null || newChild === false, - '%s(...): A valid React element (or null) must be returned. ' + - 'You may have returned undefined, an array or some other ' + - 'invalid object.', - Component.displayName || Component.name || 'Component', - ); - break; - } - } - } - - if (typeof newChild === 'string' || typeof newChild === 'number') { - return placeSingleChild( - reconcileSingleTextNode( - returnFiber, - currentFirstChild, - '' + newChild, - priority, - ), - ); - } - - if (isArray(newChild)) { - return reconcileChildrenArray( - returnFiber, - currentFirstChild, - newChild, - priority, - ); - } - - if (getIteratorFn(newChild)) { - return reconcileChildrenIterator( - returnFiber, - currentFirstChild, - newChild, - priority, - ); - } - - if (isObject) { - throwOnInvalidObjectType(returnFiber, newChild); - } - - if (!disableNewFiberFeatures && typeof newChild === 'undefined') { - // If the new child is undefined, and the return fiber is a composite - // component, throw an error. If Fiber return types are disabled, - // we already threw above. - switch (returnFiber.tag) { - case ClassComponent: { - if (__DEV__) { - const instance = returnFiber.stateNode; - if (instance.render._isMockFunction) { - // We allow auto-mocks to proceed as if they're returning null. - break; - } - } - } - // Intentionally fall through to the next case, which handles both - // functions and classes - // eslint-disable-next-lined no-fallthrough - case FunctionalComponent: { - const Component = returnFiber.type; - invariant( - false, - '%s(...): Nothing was returned from render. This usually means a ' + - 'return statement is missing. Or, to render nothing, ' + - 'return null.', - Component.displayName || Component.name || 'Component', - ); - } - } - } - - // Remaining cases are all treated as empty. - return deleteRemainingChildren(returnFiber, currentFirstChild); - } - - return reconcileChildFibers; -} - -exports.reconcileChildFibers = ChildReconciler(true, true); - -exports.reconcileChildFibersInPlace = ChildReconciler(false, true); - -exports.mountChildFibersInPlace = ChildReconciler(false, false); - -exports.cloneChildFibers = function( - current: Fiber | null, - workInProgress: Fiber, -): void { - if (!workInProgress.child) { - return; - } - if (current !== null && workInProgress.child === current.child) { - // We use workInProgress.child since that lets Flow know that it can't be - // null since we validated that already. However, as the line above suggests - // they're actually the same thing. - let currentChild = workInProgress.child; - // TODO: This used to reset the pending priority. Not sure if that is needed. - // workInProgress.pendingWorkPriority = current.pendingWorkPriority; - // TODO: The below priority used to be set to NoWork which would've - // dropped work. This is currently unobservable but will become - // observable when the first sibling has lower priority work remaining - // than the next sibling. At that point we should add tests that catches - // this. - let newChild = cloneFiber(currentChild, currentChild.pendingWorkPriority); - workInProgress.child = newChild; - - newChild.return = workInProgress; - while (currentChild.sibling !== null) { - currentChild = currentChild.sibling; - newChild = newChild.sibling = cloneFiber( - currentChild, - currentChild.pendingWorkPriority, - ); - newChild.return = workInProgress; - } - newChild.sibling = null; - } else { - // If there is no alternate, then we don't need to clone the children. - // If the children of the alternate fiber is a different set, then we don't - // need to clone. We need to reset the return fiber though since we'll - // traverse down into them. - let child = workInProgress.child; - while (child !== null) { - child.return = workInProgress; - child = child.sibling; - } - } -}; diff --git a/Libraries/Renderer/src/renderers/shared/fiber/ReactDebugCurrentFiber.js b/Libraries/Renderer/src/renderers/shared/fiber/ReactDebugCurrentFiber.js deleted file mode 100644 index 8e6f9c727c..0000000000 --- a/Libraries/Renderer/src/renderers/shared/fiber/ReactDebugCurrentFiber.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactDebugCurrentFiber - * @flow - */ - -'use strict'; - -import type {Fiber} from 'ReactFiber'; - -type LifeCyclePhase = 'render' | 'getChildContext'; - -if (__DEV__) { - var getComponentName = require('getComponentName'); - var { - getStackAddendumByWorkInProgressFiber, - } = require('ReactFiberComponentTreeHook'); -} - -function getCurrentFiberOwnerName(): string | null { - if (__DEV__) { - const fiber = ReactDebugCurrentFiber.current; - if (fiber === null) { - return null; - } - if (fiber._debugOwner != null) { - return getComponentName(fiber._debugOwner); - } - } - return null; -} - -function getCurrentFiberStackAddendum(): string | null { - if (__DEV__) { - const fiber = ReactDebugCurrentFiber.current; - if (fiber === null) { - return null; - } - // Safe because if current fiber exists, we are reconciling, - // and it is guaranteed to be the work-in-progress version. - return getStackAddendumByWorkInProgressFiber(fiber); - } - return null; -} - -var ReactDebugCurrentFiber = { - current: (null: Fiber | null), - phase: (null: LifeCyclePhase | null), - - getCurrentFiberOwnerName, - getCurrentFiberStackAddendum, -}; - -module.exports = ReactDebugCurrentFiber; diff --git a/Libraries/Renderer/src/renderers/shared/fiber/ReactDebugFiberPerf.js b/Libraries/Renderer/src/renderers/shared/fiber/ReactDebugFiberPerf.js deleted file mode 100644 index f1591e7ee3..0000000000 --- a/Libraries/Renderer/src/renderers/shared/fiber/ReactDebugFiberPerf.js +++ /dev/null @@ -1,401 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactDebugFiberPerf - * @flow - */ - -import type {Fiber} from 'ReactFiber'; - -type MeasurementPhase = - | 'componentWillMount' - | 'componentWillUnmount' - | 'componentWillReceiveProps' - | 'shouldComponentUpdate' - | 'componentWillUpdate' - | 'componentDidUpdate' - | 'componentDidMount' - | 'getChildContext'; - -// Trust the developer to only use this with a __DEV__ check -let ReactDebugFiberPerf = ((null: any): typeof ReactDebugFiberPerf); - -if (__DEV__) { - const { - HostRoot, - HostComponent, - HostText, - HostPortal, - YieldComponent, - Fragment, - } = require('ReactTypeOfWork'); - - const getComponentName = require('getComponentName'); - - // Prefix measurements so that it's possible to filter them. - // Longer prefixes are hard to read in DevTools. - const reactEmoji = '\u269B'; - const warningEmoji = '\u26D4'; - const supportsUserTiming = - typeof performance !== 'undefined' && - typeof performance.mark === 'function' && - typeof performance.clearMarks === 'function' && - typeof performance.measure === 'function' && - typeof performance.clearMeasures === 'function'; - - // Keep track of current fiber so that we know the path to unwind on pause. - // TODO: this looks the same as nextUnitOfWork in scheduler. Can we unify them? - let currentFiber: Fiber | null = null; - // If we're in the middle of user code, which fiber and method is it? - // Reusing `currentFiber` would be confusing for this because user code fiber - // can change during commit phase too, but we don't need to unwind it (since - // lifecycles in the commit phase don't resemble a tree). - let currentPhase: MeasurementPhase | null = null; - let currentPhaseFiber: Fiber | null = null; - // Did lifecycle hook schedule an update? This is often a performance problem, - // so we will keep track of it, and include it in the report. - // Track commits caused by cascading updates. - let isCommitting: boolean = false; - let hasScheduledUpdateInCurrentCommit: boolean = false; - let hasScheduledUpdateInCurrentPhase: boolean = false; - let commitCountInCurrentWorkLoop: number = 0; - let effectCountInCurrentCommit: number = 0; - // During commits, we only show a measurement once per method name - // to avoid stretch the commit phase with measurement overhead. - const labelsInCurrentCommit: Set = new Set(); - - const formatMarkName = (markName: string) => { - return `${reactEmoji} ${markName}`; - }; - - const formatLabel = (label: string, warning: string | null) => { - const prefix = warning ? `${warningEmoji} ` : `${reactEmoji} `; - const suffix = warning ? ` Warning: ${warning}` : ''; - return `${prefix}${label}${suffix}`; - }; - - const beginMark = (markName: string) => { - performance.mark(formatMarkName(markName)); - }; - - const clearMark = (markName: string) => { - performance.clearMarks(formatMarkName(markName)); - }; - - const endMark = (label: string, markName: string, warning: string | null) => { - const formattedMarkName = formatMarkName(markName); - const formattedLabel = formatLabel(label, warning); - try { - performance.measure(formattedLabel, formattedMarkName); - } catch (err) { - // If previous mark was missing for some reason, this will throw. - // This could only happen if React crashed in an unexpected place earlier. - // Don't pile on with more errors. - } - // Clear marks immediately to avoid growing buffer. - performance.clearMarks(formattedMarkName); - performance.clearMeasures(formattedLabel); - }; - - const getFiberMarkName = (label: string, debugID: number) => { - return `${label} (#${debugID})`; - }; - - const getFiberLabel = ( - componentName: string, - isMounted: boolean, - phase: MeasurementPhase | null, - ) => { - if (phase === null) { - // These are composite component total time measurements. - return `${componentName} [${isMounted ? 'update' : 'mount'}]`; - } else { - // Composite component methods. - return `${componentName}.${phase}`; - } - }; - - const beginFiberMark = ( - fiber: Fiber, - phase: MeasurementPhase | null, - ): boolean => { - const componentName = getComponentName(fiber) || 'Unknown'; - const debugID = ((fiber._debugID: any): number); - const isMounted = fiber.alternate !== null; - const label = getFiberLabel(componentName, isMounted, phase); - - if (isCommitting && labelsInCurrentCommit.has(label)) { - // During the commit phase, we don't show duplicate labels because - // there is a fixed overhead for every measurement, and we don't - // want to stretch the commit phase beyond necessary. - return false; - } - labelsInCurrentCommit.add(label); - - const markName = getFiberMarkName(label, debugID); - beginMark(markName); - return true; - }; - - const clearFiberMark = (fiber: Fiber, phase: MeasurementPhase | null) => { - const componentName = getComponentName(fiber) || 'Unknown'; - const debugID = ((fiber._debugID: any): number); - const isMounted = fiber.alternate !== null; - const label = getFiberLabel(componentName, isMounted, phase); - const markName = getFiberMarkName(label, debugID); - clearMark(markName); - }; - - const endFiberMark = ( - fiber: Fiber, - phase: MeasurementPhase | null, - warning: string | null, - ) => { - const componentName = getComponentName(fiber) || 'Unknown'; - const debugID = ((fiber._debugID: any): number); - const isMounted = fiber.alternate !== null; - const label = getFiberLabel(componentName, isMounted, phase); - const markName = getFiberMarkName(label, debugID); - endMark(label, markName, warning); - }; - - const shouldIgnoreFiber = (fiber: Fiber): boolean => { - // Host components should be skipped in the timeline. - // We could check typeof fiber.type, but does this work with RN? - switch (fiber.tag) { - case HostRoot: - case HostComponent: - case HostText: - case HostPortal: - case YieldComponent: - case Fragment: - return true; - default: - return false; - } - }; - - const clearPendingPhaseMeasurement = () => { - if (currentPhase !== null && currentPhaseFiber !== null) { - clearFiberMark(currentPhaseFiber, currentPhase); - } - currentPhaseFiber = null; - currentPhase = null; - hasScheduledUpdateInCurrentPhase = false; - }; - - const pauseTimers = () => { - // Stops all currently active measurements so that they can be resumed - // if we continue in a later deferred loop from the same unit of work. - let fiber = currentFiber; - while (fiber) { - if (fiber._debugIsCurrentlyTiming) { - endFiberMark(fiber, null, null); - } - fiber = fiber.return; - } - }; - - const resumeTimersRecursively = (fiber: Fiber) => { - if (fiber.return !== null) { - resumeTimersRecursively(fiber.return); - } - if (fiber._debugIsCurrentlyTiming) { - beginFiberMark(fiber, null); - } - }; - - const resumeTimers = () => { - // Resumes all measurements that were active during the last deferred loop. - if (currentFiber !== null) { - resumeTimersRecursively(currentFiber); - } - }; - - ReactDebugFiberPerf = { - recordEffect(): void { - effectCountInCurrentCommit++; - }, - - recordScheduleUpdate(): void { - if (isCommitting) { - hasScheduledUpdateInCurrentCommit = true; - } - if ( - currentPhase !== null && - currentPhase !== 'componentWillMount' && - currentPhase !== 'componentWillReceiveProps' - ) { - hasScheduledUpdateInCurrentPhase = true; - } - }, - - startWorkTimer(fiber: Fiber): void { - if (!supportsUserTiming || shouldIgnoreFiber(fiber)) { - return; - } - // If we pause, this is the fiber to unwind from. - currentFiber = fiber; - if (!beginFiberMark(fiber, null)) { - return; - } - fiber._debugIsCurrentlyTiming = true; - }, - - cancelWorkTimer(fiber: Fiber): void { - if (!supportsUserTiming || shouldIgnoreFiber(fiber)) { - return; - } - // Remember we shouldn't complete measurement for this fiber. - // Otherwise flamechart will be deep even for small updates. - fiber._debugIsCurrentlyTiming = false; - clearFiberMark(fiber, null); - }, - - stopWorkTimer(fiber: Fiber): void { - if (!supportsUserTiming || shouldIgnoreFiber(fiber)) { - return; - } - // If we pause, its parent is the fiber to unwind from. - currentFiber = fiber.return; - if (!fiber._debugIsCurrentlyTiming) { - return; - } - fiber._debugIsCurrentlyTiming = false; - endFiberMark(fiber, null, null); - }, - - startPhaseTimer(fiber: Fiber, phase: MeasurementPhase): void { - if (!supportsUserTiming) { - return; - } - clearPendingPhaseMeasurement(); - if (!beginFiberMark(fiber, phase)) { - return; - } - currentPhaseFiber = fiber; - currentPhase = phase; - }, - - stopPhaseTimer(): void { - if (!supportsUserTiming) { - return; - } - if (currentPhase !== null && currentPhaseFiber !== null) { - const warning = hasScheduledUpdateInCurrentPhase - ? 'Scheduled a cascading update' - : null; - endFiberMark(currentPhaseFiber, currentPhase, warning); - } - currentPhase = null; - currentPhaseFiber = null; - }, - - startWorkLoopTimer(): void { - if (!supportsUserTiming) { - return; - } - commitCountInCurrentWorkLoop = 0; - // This is top level call. - // Any other measurements are performed within. - beginMark('(React Tree Reconciliation)'); - // Resume any measurements that were in progress during the last loop. - resumeTimers(); - }, - - stopWorkLoopTimer(): void { - if (!supportsUserTiming) { - return; - } - const warning = commitCountInCurrentWorkLoop > 1 - ? 'There were cascading updates' - : null; - commitCountInCurrentWorkLoop = 0; - // Pause any measurements until the next loop. - pauseTimers(); - endMark( - '(React Tree Reconciliation)', - '(React Tree Reconciliation)', - warning, - ); - }, - - startCommitTimer(): void { - if (!supportsUserTiming) { - return; - } - isCommitting = true; - hasScheduledUpdateInCurrentCommit = false; - labelsInCurrentCommit.clear(); - beginMark('(Committing Changes)'); - }, - - stopCommitTimer(): void { - if (!supportsUserTiming) { - return; - } - - let warning = null; - if (hasScheduledUpdateInCurrentCommit) { - warning = 'Lifecycle hook scheduled a cascading update'; - } else if (commitCountInCurrentWorkLoop > 0) { - warning = 'Caused by a cascading update in earlier commit'; - } - hasScheduledUpdateInCurrentCommit = false; - commitCountInCurrentWorkLoop++; - isCommitting = false; - labelsInCurrentCommit.clear(); - - endMark('(Committing Changes)', '(Committing Changes)', warning); - }, - - startCommitHostEffectsTimer(): void { - if (!supportsUserTiming) { - return; - } - effectCountInCurrentCommit = 0; - beginMark('(Committing Host Effects)'); - }, - - stopCommitHostEffectsTimer(): void { - if (!supportsUserTiming) { - return; - } - const count = effectCountInCurrentCommit; - effectCountInCurrentCommit = 0; - endMark( - `(Committing Host Effects: ${count} Total)`, - '(Committing Host Effects)', - null, - ); - }, - - startCommitLifeCyclesTimer(): void { - if (!supportsUserTiming) { - return; - } - effectCountInCurrentCommit = 0; - beginMark('(Calling Lifecycle Methods)'); - }, - - stopCommitLifeCyclesTimer(): void { - if (!supportsUserTiming) { - return; - } - const count = effectCountInCurrentCommit; - effectCountInCurrentCommit = 0; - endMark( - `(Calling Lifecycle Methods: ${count} Total)`, - '(Calling Lifecycle Methods)', - null, - ); - }, - }; -} - -module.exports = ReactDebugFiberPerf; diff --git a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiber.js b/Libraries/Renderer/src/renderers/shared/fiber/ReactFiber.js deleted file mode 100644 index b7c6ed30c0..0000000000 --- a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiber.js +++ /dev/null @@ -1,474 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactFiber - * @flow - */ - -'use strict'; - -import type {ReactElement, Source} from 'ReactElementType'; -import type {ReactInstance, DebugID} from 'ReactInstanceType'; -import type {ReactFragment} from 'ReactTypes'; -import type {ReactCoroutine, ReactYield} from 'ReactCoroutine'; -import type {ReactPortal} from 'ReactPortal'; -import type {TypeOfWork} from 'ReactTypeOfWork'; -import type {TypeOfInternalContext} from 'ReactTypeOfInternalContext'; -import type {TypeOfSideEffect} from 'ReactTypeOfSideEffect'; -import type {PriorityLevel} from 'ReactPriorityLevel'; -import type {UpdateQueue} from 'ReactFiberUpdateQueue'; - -var { - IndeterminateComponent, - ClassComponent, - HostRoot, - HostComponent, - HostText, - HostPortal, - CoroutineComponent, - YieldComponent, - Fragment, -} = require('ReactTypeOfWork'); - -var {NoWork} = require('ReactPriorityLevel'); - -var {NoContext} = require('ReactTypeOfInternalContext'); - -var {NoEffect} = require('ReactTypeOfSideEffect'); - -var {cloneUpdateQueue} = require('ReactFiberUpdateQueue'); - -var invariant = require('fbjs/lib/invariant'); - -if (__DEV__) { - var getComponentName = require('getComponentName'); - - var hasBadMapPolyfill = false; - try { - const nonExtensibleObject = Object.preventExtensions({}); - /* eslint-disable no-new */ - new Map([[nonExtensibleObject, null]]); - new Set([nonExtensibleObject]); - /* eslint-enable no-new */ - } catch (e) { - // TODO: Consider warning about bad polyfills - hasBadMapPolyfill = true; - } -} - -// A Fiber is work on a Component that needs to be done or was done. There can -// be more than one per component. -export type Fiber = { - // __DEV__ only - _debugID?: DebugID, - _debugSource?: Source | null, - _debugOwner?: Fiber | ReactInstance | null, // Stack compatible - _debugIsCurrentlyTiming?: boolean, - - // These first fields are conceptually members of an Instance. This used to - // be split into a separate type and intersected with the other Fiber fields, - // but until Flow fixes its intersection bugs, we've merged them into a - // single type. - - // An Instance is shared between all versions of a component. We can easily - // break this out into a separate object to avoid copying so much to the - // alternate versions of the tree. We put this on a single object for now to - // minimize the number of objects created during the initial render. - - // Tag identifying the type of fiber. - tag: TypeOfWork, - - // Unique identifier of this child. - key: null | string, - - // The function/class/module associated with this fiber. - type: any, - - // The local state associated with this fiber. - stateNode: any, - - // Conceptual aliases - // parent : Instance -> return The parent happens to be the same as the - // return fiber since we've merged the fiber and instance. - - // Remaining fields belong to Fiber - - // The Fiber to return to after finishing processing this one. - // This is effectively the parent, but there can be multiple parents (two) - // so this is only the parent of the thing we're currently processing. - // It is conceptually the same as the return address of a stack frame. - return: Fiber | null, - - // Singly Linked List Tree Structure. - child: Fiber | null, - sibling: Fiber | null, - index: number, - - // The ref last used to attach this node. - // I'll avoid adding an owner field for prod and model that as functions. - ref: null | (((handle: mixed) => void) & {_stringRef: ?string}), - - // Input is the data coming into process this fiber. Arguments. Props. - pendingProps: any, // This type will be more specific once we overload the tag. - // TODO: I think that there is a way to merge pendingProps and memoizedProps. - memoizedProps: any, // The props used to create the output. - - // A queue of state updates and callbacks. - updateQueue: UpdateQueue | null, - - // The state used to create the output - memoizedState: any, - - // Bitfield that describes properties about the fiber and its subtree. E.g. - // the AsyncUpdates flag indicates whether the subtree should be async-by- - // default. When a fiber is created, it inherits the internalContextTag of its - // parent. Additional flags can be set at creation time, but after than the - // value should remain unchanged throughout the fiber's lifetime, particularly - // before its child fibers are created. - internalContextTag: TypeOfInternalContext, - - // Effect - effectTag: TypeOfSideEffect, - - // Singly linked list fast path to the next fiber with side-effects. - nextEffect: Fiber | null, - - // The first and last fiber with side-effect within this subtree. This allows - // us to reuse a slice of the linked list when we reuse the work done within - // this fiber. - firstEffect: Fiber | null, - lastEffect: Fiber | null, - - // This will be used to quickly determine if a subtree has no pending changes. - pendingWorkPriority: PriorityLevel, - - // This value represents the priority level that was last used to process this - // component. This indicates whether it is better to continue from the - // progressed work or if it is better to continue from the current state. - progressedPriority: PriorityLevel, - - // If work bails out on a Fiber that already had some work started at a lower - // priority, then we need to store the progressed work somewhere. This holds - // the started child set until we need to get back to working on it. It may - // or may not be the same as the "current" child. - progressedChild: Fiber | null, - - // When we reconcile children onto progressedChild it is possible that we have - // to delete some child fibers. We need to keep track of this side-effects so - // that if we continue later on, we have to include those effects. Deletions - // are added in the reverse order from sibling pointers. - progressedFirstDeletion: Fiber | null, - progressedLastDeletion: Fiber | null, - - // This is a pooled version of a Fiber. Every fiber that gets updated will - // eventually have a pair. There are cases when we can clean up pairs to save - // memory if we need to. - alternate: Fiber | null, - - // Conceptual aliases - // workInProgress : Fiber -> alternate The alternate used for reuse happens - // to be the same as work in progress. -}; - -if (__DEV__) { - var debugCounter = 1; -} - -// This is a constructor of a POJO instead of a constructor function for a few -// reasons: -// 1) Nobody should add any instance methods on this. Instance methods can be -// more difficult to predict when they get optimized and they are almost -// never inlined properly in static compilers. -// 2) Nobody should rely on `instanceof Fiber` for type testing. We should -// always know when it is a fiber. -// 3) We can easily go from a createFiber call to calling a constructor if that -// is faster. The opposite is not true. -// 4) We might want to experiment with using numeric keys since they are easier -// to optimize in a non-JIT environment. -// 5) It should be easy to port this to a C struct and keep a C implementation -// compatible. -var createFiber = function( - tag: TypeOfWork, - key: null | string, - internalContextTag: TypeOfInternalContext, -): Fiber { - var fiber: Fiber = { - // Instance - - tag: tag, - - key: key, - - type: null, - - stateNode: null, - - // Fiber - - return: null, - - child: null, - sibling: null, - index: 0, - - ref: null, - - pendingProps: null, - memoizedProps: null, - updateQueue: null, - memoizedState: null, - - internalContextTag, - - effectTag: NoEffect, - nextEffect: null, - firstEffect: null, - lastEffect: null, - - pendingWorkPriority: NoWork, - progressedPriority: NoWork, - progressedChild: null, - progressedFirstDeletion: null, - progressedLastDeletion: null, - - alternate: null, - }; - - if (__DEV__) { - fiber._debugID = debugCounter++; - fiber._debugSource = null; - fiber._debugOwner = null; - fiber._debugIsCurrentlyTiming = false; - if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') { - Object.preventExtensions(fiber); - } - } - - return fiber; -}; - -function shouldConstruct(Component) { - return !!(Component.prototype && Component.prototype.isReactComponent); -} - -// This is used to create an alternate fiber to do work on. -// TODO: Rename to createWorkInProgressFiber or something like that. -exports.cloneFiber = function( - fiber: Fiber, - priorityLevel: PriorityLevel, -): Fiber { - // We clone to get a work in progress. That means that this fiber is the - // current. To make it safe to reuse that fiber later on as work in progress - // we need to reset its work in progress flag now. We don't have an - // opportunity to do this earlier since we don't traverse the tree when - // the work in progress tree becomes the current tree. - // fiber.progressedPriority = NoWork; - // fiber.progressedChild = null; - - // We use a double buffering pooling technique because we know that we'll only - // ever need at most two versions of a tree. We pool the "other" unused node - // that we're free to reuse. This is lazily created to avoid allocating extra - // objects for things that are never updated. It also allow us to reclaim the - // extra memory if needed. - let alt = fiber.alternate; - if (alt !== null) { - // If we clone, then we do so from the "current" state. The current state - // can't have any side-effects that are still valid so we reset just to be - // sure. - alt.effectTag = NoEffect; - alt.nextEffect = null; - alt.firstEffect = null; - alt.lastEffect = null; - } else { - // This should not have an alternate already - alt = createFiber(fiber.tag, fiber.key, fiber.internalContextTag); - alt.type = fiber.type; - - alt.progressedChild = fiber.progressedChild; - alt.progressedPriority = fiber.progressedPriority; - - alt.alternate = fiber; - fiber.alternate = alt; - } - - alt.stateNode = fiber.stateNode; - alt.child = fiber.child; - alt.sibling = fiber.sibling; // This should always be overridden. TODO: null - alt.index = fiber.index; // This should always be overridden. - alt.ref = fiber.ref; - // pendingProps is here for symmetry but is unnecessary in practice for now. - // TODO: Pass in the new pendingProps as an argument maybe? - alt.pendingProps = fiber.pendingProps; - cloneUpdateQueue(fiber, alt); - alt.pendingWorkPriority = priorityLevel; - - alt.memoizedProps = fiber.memoizedProps; - alt.memoizedState = fiber.memoizedState; - - if (__DEV__) { - alt._debugID = fiber._debugID; - alt._debugSource = fiber._debugSource; - alt._debugOwner = fiber._debugOwner; - } - - return alt; -}; - -exports.createHostRootFiber = function(): Fiber { - const fiber = createFiber(HostRoot, null, NoContext); - return fiber; -}; - -exports.createFiberFromElement = function( - element: ReactElement, - internalContextTag: TypeOfInternalContext, - priorityLevel: PriorityLevel, -): Fiber { - let owner = null; - if (__DEV__) { - owner = element._owner; - } - - const fiber = createFiberFromElementType( - element.type, - element.key, - internalContextTag, - owner, - ); - fiber.pendingProps = element.props; - fiber.pendingWorkPriority = priorityLevel; - - if (__DEV__) { - fiber._debugSource = element._source; - fiber._debugOwner = element._owner; - } - - return fiber; -}; - -exports.createFiberFromFragment = function( - elements: ReactFragment, - internalContextTag: TypeOfInternalContext, - priorityLevel: PriorityLevel, -): Fiber { - // TODO: Consider supporting keyed fragments. Technically, we accidentally - // support that in the existing React. - const fiber = createFiber(Fragment, null, internalContextTag); - fiber.pendingProps = elements; - fiber.pendingWorkPriority = priorityLevel; - return fiber; -}; - -exports.createFiberFromText = function( - content: string, - internalContextTag: TypeOfInternalContext, - priorityLevel: PriorityLevel, -): Fiber { - const fiber = createFiber(HostText, null, internalContextTag); - fiber.pendingProps = content; - fiber.pendingWorkPriority = priorityLevel; - return fiber; -}; - -function createFiberFromElementType( - type: mixed, - key: null | string, - internalContextTag: TypeOfInternalContext, - debugOwner: null | Fiber | ReactInstance, -): Fiber { - let fiber; - if (typeof type === 'function') { - fiber = shouldConstruct(type) - ? createFiber(ClassComponent, key, internalContextTag) - : createFiber(IndeterminateComponent, key, internalContextTag); - fiber.type = type; - } else if (typeof type === 'string') { - fiber = createFiber(HostComponent, key, internalContextTag); - fiber.type = type; - } else if ( - typeof type === 'object' && - type !== null && - typeof type.tag === 'number' - ) { - // Currently assumed to be a continuation and therefore is a fiber already. - // TODO: The yield system is currently broken for updates in some cases. - // The reified yield stores a fiber, but we don't know which fiber that is; - // the current or a workInProgress? When the continuation gets rendered here - // we don't know if we can reuse that fiber or if we need to clone it. - // There is probably a clever way to restructure this. - fiber = ((type: any): Fiber); - } else { - let info = ''; - if (__DEV__) { - if ( - type === undefined || - (typeof type === 'object' && - type !== null && - Object.keys(type).length === 0) - ) { - info += - ' You likely forgot to export your component from the file ' + - "it's defined in."; - } - const ownerName = debugOwner ? getComponentName(debugOwner) : null; - if (ownerName) { - info += '\n\nCheck the render method of `' + ownerName + '`.'; - } - } - invariant( - false, - 'Element type is invalid: expected a string (for built-in components) ' + - 'or a class/function (for composite components) but got: %s.%s', - type == null ? type : typeof type, - info, - ); - } - return fiber; -} - -exports.createFiberFromElementType = createFiberFromElementType; - -exports.createFiberFromCoroutine = function( - coroutine: ReactCoroutine, - internalContextTag: TypeOfInternalContext, - priorityLevel: PriorityLevel, -): Fiber { - const fiber = createFiber( - CoroutineComponent, - coroutine.key, - internalContextTag, - ); - fiber.type = coroutine.handler; - fiber.pendingProps = coroutine; - fiber.pendingWorkPriority = priorityLevel; - return fiber; -}; - -exports.createFiberFromYield = function( - yieldNode: ReactYield, - internalContextTag: TypeOfInternalContext, - priorityLevel: PriorityLevel, -): Fiber { - const fiber = createFiber(YieldComponent, null, internalContextTag); - return fiber; -}; - -exports.createFiberFromPortal = function( - portal: ReactPortal, - internalContextTag: TypeOfInternalContext, - priorityLevel: PriorityLevel, -): Fiber { - const fiber = createFiber(HostPortal, portal.key, internalContextTag); - fiber.pendingProps = portal.children || []; - fiber.pendingWorkPriority = priorityLevel; - fiber.stateNode = { - containerInfo: portal.containerInfo, - implementation: portal.implementation, - }; - return fiber; -}; diff --git a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberBeginWork.js b/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberBeginWork.js deleted file mode 100644 index f0393658fe..0000000000 --- a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberBeginWork.js +++ /dev/null @@ -1,871 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactFiberBeginWork - * @flow - */ - -'use strict'; - -import type {ReactCoroutine} from 'ReactCoroutine'; -import type {Fiber} from 'ReactFiber'; -import type {HostContext} from 'ReactFiberHostContext'; -import type {FiberRoot} from 'ReactFiberRoot'; -import type {HostConfig} from 'ReactFiberReconciler'; -import type {PriorityLevel} from 'ReactPriorityLevel'; - -var { - mountChildFibersInPlace, - reconcileChildFibers, - reconcileChildFibersInPlace, - cloneChildFibers, -} = require('ReactChildFiber'); -var {beginUpdateQueue} = require('ReactFiberUpdateQueue'); -var ReactTypeOfWork = require('ReactTypeOfWork'); -var { - getMaskedContext, - getUnmaskedContext, - hasContextChanged, - pushContextProvider, - pushTopLevelContextObject, - invalidateContextProvider, -} = require('ReactFiberContext'); -var { - IndeterminateComponent, - FunctionalComponent, - ClassComponent, - HostRoot, - HostComponent, - HostText, - HostPortal, - CoroutineComponent, - CoroutineHandlerPhase, - YieldComponent, - Fragment, -} = ReactTypeOfWork; -var {NoWork, OffscreenPriority} = require('ReactPriorityLevel'); -var {Placement, ContentReset, Err, Ref} = require('ReactTypeOfSideEffect'); -var ReactFiberClassComponent = require('ReactFiberClassComponent'); -var {ReactCurrentOwner} = require('ReactGlobalSharedState'); -var invariant = require('fbjs/lib/invariant'); - -if (__DEV__) { - var ReactDebugCurrentFiber = require('ReactDebugCurrentFiber'); - var {cancelWorkTimer} = require('ReactDebugFiberPerf'); - var warning = require('fbjs/lib/warning'); - - var warnedAboutStatelessRefs = {}; -} - -module.exports = function( - config: HostConfig, - hostContext: HostContext, - scheduleUpdate: (fiber: Fiber, priorityLevel: PriorityLevel) => void, - getPriorityContext: (fiber: Fiber, forceAsync: boolean) => PriorityLevel, -) { - const { - shouldSetTextContent, - useSyncScheduling, - shouldDeprioritizeSubtree, - } = config; - - const {pushHostContext, pushHostContainer} = hostContext; - - const { - adoptClassInstance, - constructClassInstance, - mountClassInstance, - resumeMountClassInstance, - updateClassInstance, - } = ReactFiberClassComponent( - scheduleUpdate, - getPriorityContext, - memoizeProps, - memoizeState, - ); - - function markChildAsProgressed(current, workInProgress, priorityLevel) { - // We now have clones. Let's store them as the currently progressed work. - workInProgress.progressedChild = workInProgress.child; - workInProgress.progressedPriority = priorityLevel; - if (current !== null) { - // We also store it on the current. When the alternate swaps in we can - // continue from this point. - current.progressedChild = workInProgress.progressedChild; - current.progressedPriority = workInProgress.progressedPriority; - } - } - - function clearDeletions(workInProgress) { - workInProgress.progressedFirstDeletion = workInProgress.progressedLastDeletion = null; - } - - function transferDeletions(workInProgress) { - // Any deletions get added first into the effect list. - workInProgress.firstEffect = workInProgress.progressedFirstDeletion; - workInProgress.lastEffect = workInProgress.progressedLastDeletion; - } - - function reconcileChildren(current, workInProgress, nextChildren) { - const priorityLevel = workInProgress.pendingWorkPriority; - reconcileChildrenAtPriority( - current, - workInProgress, - nextChildren, - priorityLevel, - ); - } - - function reconcileChildrenAtPriority( - current, - workInProgress, - nextChildren, - priorityLevel, - ) { - // At this point any memoization is no longer valid since we'll have changed - // the children. - workInProgress.memoizedProps = null; - if (current === null) { - // If this is a fresh new component that hasn't been rendered yet, we - // won't update its child set by applying minimal side-effects. Instead, - // we will add them all to the child before it gets rendered. That means - // we can optimize this reconciliation pass by not tracking side-effects. - workInProgress.child = mountChildFibersInPlace( - workInProgress, - workInProgress.child, - nextChildren, - priorityLevel, - ); - } else if (current.child === workInProgress.child) { - // If the current child is the same as the work in progress, it means that - // we haven't yet started any work on these children. Therefore, we use - // the clone algorithm to create a copy of all the current children. - - // If we had any progressed work already, that is invalid at this point so - // let's throw it out. - clearDeletions(workInProgress); - - workInProgress.child = reconcileChildFibers( - workInProgress, - workInProgress.child, - nextChildren, - priorityLevel, - ); - - transferDeletions(workInProgress); - } else { - // If, on the other hand, it is already using a clone, that means we've - // already begun some work on this tree and we can continue where we left - // off by reconciling against the existing children. - workInProgress.child = reconcileChildFibersInPlace( - workInProgress, - workInProgress.child, - nextChildren, - priorityLevel, - ); - - transferDeletions(workInProgress); - } - markChildAsProgressed(current, workInProgress, priorityLevel); - } - - function updateFragment(current, workInProgress) { - var nextChildren = workInProgress.pendingProps; - if (hasContextChanged()) { - // Normally we can bail out on props equality but if context has changed - // we don't do the bailout and we have to reuse existing props instead. - if (nextChildren === null) { - nextChildren = workInProgress.memoizedProps; - } - } else if ( - nextChildren === null || - workInProgress.memoizedProps === nextChildren - ) { - return bailoutOnAlreadyFinishedWork(current, workInProgress); - } - reconcileChildren(current, workInProgress, nextChildren); - memoizeProps(workInProgress, nextChildren); - return workInProgress.child; - } - - function markRef(current: Fiber | null, workInProgress: Fiber) { - const ref = workInProgress.ref; - if (ref !== null && (!current || current.ref !== ref)) { - // Schedule a Ref effect - workInProgress.effectTag |= Ref; - } - } - - function updateFunctionalComponent(current, workInProgress) { - var fn = workInProgress.type; - var nextProps = workInProgress.pendingProps; - - const memoizedProps = workInProgress.memoizedProps; - if (hasContextChanged()) { - // Normally we can bail out on props equality but if context has changed - // we don't do the bailout and we have to reuse existing props instead. - if (nextProps === null) { - nextProps = memoizedProps; - } - } else { - if (nextProps === null || memoizedProps === nextProps) { - return bailoutOnAlreadyFinishedWork(current, workInProgress); - } - // TODO: Disable this before release, since it is not part of the public API - // I use this for testing to compare the relative overhead of classes. - if ( - typeof fn.shouldComponentUpdate === 'function' && - !fn.shouldComponentUpdate(memoizedProps, nextProps) - ) { - // Memoize props even if shouldComponentUpdate returns false - memoizeProps(workInProgress, nextProps); - return bailoutOnAlreadyFinishedWork(current, workInProgress); - } - } - - var unmaskedContext = getUnmaskedContext(workInProgress); - var context = getMaskedContext(workInProgress, unmaskedContext); - - var nextChildren; - - if (__DEV__) { - ReactCurrentOwner.current = workInProgress; - ReactDebugCurrentFiber.phase = 'render'; - nextChildren = fn(nextProps, context); - ReactDebugCurrentFiber.phase = null; - } else { - nextChildren = fn(nextProps, context); - } - reconcileChildren(current, workInProgress, nextChildren); - memoizeProps(workInProgress, nextProps); - return workInProgress.child; - } - - function updateClassComponent( - current: Fiber | null, - workInProgress: Fiber, - priorityLevel: PriorityLevel, - ) { - // Push context providers early to prevent context stack mismatches. - // During mounting we don't know the child context yet as the instance doesn't exist. - // We will invalidate the child context in finishClassComponent() right after rendering. - const hasContext = pushContextProvider(workInProgress); - - let shouldUpdate; - if (current === null) { - if (!workInProgress.stateNode) { - // In the initial pass we might need to construct the instance. - constructClassInstance(workInProgress, workInProgress.pendingProps); - mountClassInstance(workInProgress, priorityLevel); - shouldUpdate = true; - } else { - // In a resume, we'll already have an instance we can reuse. - shouldUpdate = resumeMountClassInstance(workInProgress, priorityLevel); - } - } else { - shouldUpdate = updateClassInstance( - current, - workInProgress, - priorityLevel, - ); - } - return finishClassComponent( - current, - workInProgress, - shouldUpdate, - hasContext, - ); - } - - function finishClassComponent( - current: Fiber | null, - workInProgress: Fiber, - shouldUpdate: boolean, - hasContext: boolean, - ) { - // Refs should update even if shouldComponentUpdate returns false - markRef(current, workInProgress); - - if (!shouldUpdate) { - return bailoutOnAlreadyFinishedWork(current, workInProgress); - } - - const instance = workInProgress.stateNode; - - // Rerender - ReactCurrentOwner.current = workInProgress; - let nextChildren; - if (__DEV__) { - ReactDebugCurrentFiber.phase = 'render'; - nextChildren = instance.render(); - ReactDebugCurrentFiber.phase = null; - } else { - nextChildren = instance.render(); - } - reconcileChildren(current, workInProgress, nextChildren); - // Memoize props and state using the values we just used to render. - // TODO: Restructure so we never read values from the instance. - memoizeState(workInProgress, instance.state); - memoizeProps(workInProgress, instance.props); - - // The context might have changed so we need to recalculate it. - if (hasContext) { - invalidateContextProvider(workInProgress); - } - return workInProgress.child; - } - - function updateHostRoot(current, workInProgress, priorityLevel) { - const root = (workInProgress.stateNode: FiberRoot); - if (root.pendingContext) { - pushTopLevelContextObject( - workInProgress, - root.pendingContext, - root.pendingContext !== root.context, - ); - } else if (root.context) { - // Should always be set - pushTopLevelContextObject(workInProgress, root.context, false); - } - - pushHostContainer(workInProgress, root.containerInfo); - - const updateQueue = workInProgress.updateQueue; - if (updateQueue !== null) { - const prevState = workInProgress.memoizedState; - const state = beginUpdateQueue( - workInProgress, - updateQueue, - null, - prevState, - null, - priorityLevel, - ); - if (prevState === state) { - // If the state is the same as before, that's a bailout because we had - // no work matching this priority. - return bailoutOnAlreadyFinishedWork(current, workInProgress); - } - const element = state.element; - reconcileChildren(current, workInProgress, element); - memoizeState(workInProgress, state); - return workInProgress.child; - } - // If there is no update queue, that's a bailout because the root has no props. - return bailoutOnAlreadyFinishedWork(current, workInProgress); - } - - function updateHostComponent(current, workInProgress) { - pushHostContext(workInProgress); - - let nextProps = workInProgress.pendingProps; - const prevProps = current !== null ? current.memoizedProps : null; - const memoizedProps = workInProgress.memoizedProps; - if (hasContextChanged()) { - // Normally we can bail out on props equality but if context has changed - // we don't do the bailout and we have to reuse existing props instead. - if (nextProps === null) { - nextProps = memoizedProps; - invariant( - nextProps !== null, - 'We should always have pending or current props. This error is ' + - 'likely caused by a bug in React. Please file an issue.', - ); - } - } else if (nextProps === null || memoizedProps === nextProps) { - if ( - !useSyncScheduling && - shouldDeprioritizeSubtree(workInProgress.type, memoizedProps) && - workInProgress.pendingWorkPriority !== OffscreenPriority - ) { - // This subtree still has work, but it should be deprioritized so we need - // to bail out and not do any work yet. - // TODO: It would be better if this tree got its correct priority set - // during scheduleUpdate instead because otherwise we'll start a higher - // priority reconciliation first before we can get down here. However, - // that is a bit tricky since workInProgress and current can have - // different "hidden" settings. - let child = workInProgress.progressedChild; - while (child !== null) { - // To ensure that this subtree gets its priority reset, the children - // need to be reset. - child.pendingWorkPriority = OffscreenPriority; - child = child.sibling; - } - return null; - } - return bailoutOnAlreadyFinishedWork(current, workInProgress); - } - - let nextChildren = nextProps.children; - const isDirectTextChild = shouldSetTextContent(nextProps); - - if (isDirectTextChild) { - // We special case a direct text child of a host node. This is a common - // case. We won't handle it as a reified child. We will instead handle - // this in the host environment that also have access to this prop. That - // avoids allocating another HostText fiber and traversing it. - nextChildren = null; - } else if (prevProps && shouldSetTextContent(prevProps)) { - // If we're switching from a direct text child to a normal child, or to - // empty, we need to schedule the text content to be reset. - workInProgress.effectTag |= ContentReset; - } - - markRef(current, workInProgress); - - if ( - !useSyncScheduling && - shouldDeprioritizeSubtree(workInProgress.type, nextProps) && - workInProgress.pendingWorkPriority !== OffscreenPriority - ) { - // If this host component is hidden, we can bail out on the children. - // We'll rerender the children later at the lower priority. - - // It is unfortunate that we have to do the reconciliation of these - // children already since that will add them to the tree even though - // they are not actually done yet. If this is a large set it is also - // confusing that this takes time to do right now instead of later. - - if (workInProgress.progressedPriority === OffscreenPriority) { - // If we already made some progress on the offscreen priority before, - // then we should continue from where we left off. - workInProgress.child = workInProgress.progressedChild; - } - - // Reconcile the children and stash them for later work. - reconcileChildrenAtPriority( - current, - workInProgress, - nextChildren, - OffscreenPriority, - ); - memoizeProps(workInProgress, nextProps); - workInProgress.child = current !== null ? current.child : null; - - if (current === null) { - // If this doesn't have a current we won't track it for placement - // effects. However, when we come back around to this we have already - // inserted the parent which means that we'll infact need to make this a - // placement. - // TODO: There has to be a better solution to this problem. - let child = workInProgress.progressedChild; - while (child !== null) { - child.effectTag = Placement; - child = child.sibling; - } - } - - // Abort and don't process children yet. - return null; - } else { - reconcileChildren(current, workInProgress, nextChildren); - memoizeProps(workInProgress, nextProps); - return workInProgress.child; - } - } - - function updateHostText(current, workInProgress) { - let nextProps = workInProgress.pendingProps; - if (nextProps === null) { - nextProps = workInProgress.memoizedProps; - } - memoizeProps(workInProgress, nextProps); - // Nothing to do here. This is terminal. We'll do the completion step - // immediately after. - return null; - } - - function mountIndeterminateComponent(current, workInProgress, priorityLevel) { - invariant( - current === null, - 'An indeterminate component should never have mounted. This error is ' + - 'likely caused by a bug in React. Please file an issue.', - ); - var fn = workInProgress.type; - var props = workInProgress.pendingProps; - var unmaskedContext = getUnmaskedContext(workInProgress); - var context = getMaskedContext(workInProgress, unmaskedContext); - - var value; - - if (__DEV__) { - ReactCurrentOwner.current = workInProgress; - value = fn(props, context); - } else { - value = fn(props, context); - } - - if ( - typeof value === 'object' && - value !== null && - typeof value.render === 'function' - ) { - // Proceed under the assumption that this is a class instance - workInProgress.tag = ClassComponent; - - // Push context providers early to prevent context stack mismatches. - // During mounting we don't know the child context yet as the instance doesn't exist. - // We will invalidate the child context in finishClassComponent() right after rendering. - const hasContext = pushContextProvider(workInProgress); - adoptClassInstance(workInProgress, value); - mountClassInstance(workInProgress, priorityLevel); - return finishClassComponent(current, workInProgress, true, hasContext); - } else { - // Proceed under the assumption that this is a functional component - workInProgress.tag = FunctionalComponent; - if (__DEV__) { - const Component = workInProgress.type; - - if (Component) { - warning( - !Component.childContextTypes, - '%s(...): childContextTypes cannot be defined on a functional component.', - Component.displayName || Component.name || 'Component', - ); - } - if (workInProgress.ref !== null) { - let info = ''; - const ownerName = ReactDebugCurrentFiber.getCurrentFiberOwnerName(); - if (ownerName) { - info += '\n\nCheck the render method of `' + ownerName + '`.'; - } - - let warningKey = ownerName || workInProgress._debugID || ''; - const debugSource = workInProgress._debugSource; - if (debugSource) { - warningKey = debugSource.fileName + ':' + debugSource.lineNumber; - } - if (!warnedAboutStatelessRefs[warningKey]) { - warnedAboutStatelessRefs[warningKey] = true; - warning( - false, - 'Stateless function components cannot be given refs. ' + - 'Attempts to access this ref will fail.%s%s', - info, - ReactDebugCurrentFiber.getCurrentFiberStackAddendum(), - ); - } - } - } - reconcileChildren(current, workInProgress, value); - memoizeProps(workInProgress, props); - return workInProgress.child; - } - } - - function updateCoroutineComponent(current, workInProgress) { - var nextCoroutine = (workInProgress.pendingProps: null | ReactCoroutine); - if (hasContextChanged()) { - // Normally we can bail out on props equality but if context has changed - // we don't do the bailout and we have to reuse existing props instead. - if (nextCoroutine === null) { - nextCoroutine = current && current.memoizedProps; - invariant( - nextCoroutine !== null, - 'We should always have pending or current props. This error is ' + - 'likely caused by a bug in React. Please file an issue.', - ); - } - } else if ( - nextCoroutine === null || - workInProgress.memoizedProps === nextCoroutine - ) { - nextCoroutine = workInProgress.memoizedProps; - // TODO: When bailing out, we might need to return the stateNode instead - // of the child. To check it for work. - // return bailoutOnAlreadyFinishedWork(current, workInProgress); - } - - const nextChildren = nextCoroutine.children; - const priorityLevel = workInProgress.pendingWorkPriority; - - // The following is a fork of reconcileChildrenAtPriority but using - // stateNode to store the child. - - // At this point any memoization is no longer valid since we'll have changed - // the children. - workInProgress.memoizedProps = null; - if (current === null) { - workInProgress.stateNode = mountChildFibersInPlace( - workInProgress, - workInProgress.stateNode, - nextChildren, - priorityLevel, - ); - } else if (current.child === workInProgress.child) { - clearDeletions(workInProgress); - - workInProgress.stateNode = reconcileChildFibers( - workInProgress, - workInProgress.stateNode, - nextChildren, - priorityLevel, - ); - - transferDeletions(workInProgress); - } else { - workInProgress.stateNode = reconcileChildFibersInPlace( - workInProgress, - workInProgress.stateNode, - nextChildren, - priorityLevel, - ); - - transferDeletions(workInProgress); - } - - memoizeProps(workInProgress, nextCoroutine); - // This doesn't take arbitrary time so we could synchronously just begin - // eagerly do the work of workInProgress.child as an optimization. - return workInProgress.stateNode; - } - - function updatePortalComponent(current, workInProgress) { - pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); - const priorityLevel = workInProgress.pendingWorkPriority; - let nextChildren = workInProgress.pendingProps; - if (hasContextChanged()) { - // Normally we can bail out on props equality but if context has changed - // we don't do the bailout and we have to reuse existing props instead. - if (nextChildren === null) { - nextChildren = current && current.memoizedProps; - invariant( - nextChildren != null, - 'We should always have pending or current props. This error is ' + - 'likely caused by a bug in React. Please file an issue.', - ); - } - } else if ( - nextChildren === null || - workInProgress.memoizedProps === nextChildren - ) { - return bailoutOnAlreadyFinishedWork(current, workInProgress); - } - - if (current === null) { - // Portals are special because we don't append the children during mount - // but at commit. Therefore we need to track insertions which the normal - // flow doesn't do during mount. This doesn't happen at the root because - // the root always starts with a "current" with a null child. - // TODO: Consider unifying this with how the root works. - workInProgress.child = reconcileChildFibersInPlace( - workInProgress, - workInProgress.child, - nextChildren, - priorityLevel, - ); - memoizeProps(workInProgress, nextChildren); - markChildAsProgressed(current, workInProgress, priorityLevel); - } else { - reconcileChildren(current, workInProgress, nextChildren); - memoizeProps(workInProgress, nextChildren); - } - return workInProgress.child; - } - - /* - function reuseChildrenEffects(returnFiber : Fiber, firstChild : Fiber) { - let child = firstChild; - do { - // Ensure that the first and last effect of the parent corresponds - // to the children's first and last effect. - if (!returnFiber.firstEffect) { - returnFiber.firstEffect = child.firstEffect; - } - if (child.lastEffect) { - if (returnFiber.lastEffect) { - returnFiber.lastEffect.nextEffect = child.firstEffect; - } - returnFiber.lastEffect = child.lastEffect; - } - } while (child = child.sibling); - } - */ - - function bailoutOnAlreadyFinishedWork( - current, - workInProgress: Fiber, - ): Fiber | null { - if (__DEV__) { - cancelWorkTimer(workInProgress); - } - - const priorityLevel = workInProgress.pendingWorkPriority; - // TODO: We should ideally be able to bail out early if the children have no - // more work to do. However, since we don't have a separation of this - // Fiber's priority and its children yet - we don't know without doing lots - // of the same work we do anyway. Once we have that separation we can just - // bail out here if the children has no more work at this priority level. - // if (workInProgress.priorityOfChildren <= priorityLevel) { - // // If there are side-effects in these children that have not yet been - // // committed we need to ensure that they get properly transferred up. - // if (current && current.child !== workInProgress.child) { - // reuseChildrenEffects(workInProgress, child); - // } - // return null; - // } - - if (current && workInProgress.child === current.child) { - // If we had any progressed work already, that is invalid at this point so - // let's throw it out. - clearDeletions(workInProgress); - } - - cloneChildFibers(current, workInProgress); - markChildAsProgressed(current, workInProgress, priorityLevel); - return workInProgress.child; - } - - function bailoutOnLowPriority(current, workInProgress) { - if (__DEV__) { - cancelWorkTimer(workInProgress); - } - - // TODO: Handle HostComponent tags here as well and call pushHostContext()? - // See PR 8590 discussion for context - switch (workInProgress.tag) { - case ClassComponent: - pushContextProvider(workInProgress); - break; - case HostPortal: - pushHostContainer( - workInProgress, - workInProgress.stateNode.containerInfo, - ); - break; - } - // TODO: What if this is currently in progress? - // How can that happen? How is this not being cloned? - return null; - } - - function memoizeProps(workInProgress: Fiber, nextProps: any) { - workInProgress.memoizedProps = nextProps; - // Reset the pending props - workInProgress.pendingProps = null; - } - - function memoizeState(workInProgress: Fiber, nextState: any) { - workInProgress.memoizedState = nextState; - // Don't reset the updateQueue, in case there are pending updates. Resetting - // is handled by beginUpdateQueue. - } - - function beginWork( - current: Fiber | null, - workInProgress: Fiber, - priorityLevel: PriorityLevel, - ): Fiber | null { - if ( - workInProgress.pendingWorkPriority === NoWork || - workInProgress.pendingWorkPriority > priorityLevel - ) { - return bailoutOnLowPriority(current, workInProgress); - } - - if (__DEV__) { - ReactDebugCurrentFiber.current = workInProgress; - } - - // If we don't bail out, we're going be recomputing our children so we need - // to drop our effect list. - workInProgress.firstEffect = null; - workInProgress.lastEffect = null; - - if (workInProgress.progressedPriority === priorityLevel) { - // If we have progressed work on this priority level already, we can - // proceed this that as the child. - workInProgress.child = workInProgress.progressedChild; - } - - switch (workInProgress.tag) { - case IndeterminateComponent: - return mountIndeterminateComponent( - current, - workInProgress, - priorityLevel, - ); - case FunctionalComponent: - return updateFunctionalComponent(current, workInProgress); - case ClassComponent: - return updateClassComponent(current, workInProgress, priorityLevel); - case HostRoot: - return updateHostRoot(current, workInProgress, priorityLevel); - case HostComponent: - return updateHostComponent(current, workInProgress); - case HostText: - return updateHostText(current, workInProgress); - case CoroutineHandlerPhase: - // This is a restart. Reset the tag to the initial phase. - workInProgress.tag = CoroutineComponent; - // Intentionally fall through since this is now the same. - case CoroutineComponent: - return updateCoroutineComponent(current, workInProgress); - case YieldComponent: - // A yield component is just a placeholder, we can just run through the - // next one immediately. - return null; - case HostPortal: - return updatePortalComponent(current, workInProgress); - case Fragment: - return updateFragment(current, workInProgress); - default: - invariant( - false, - 'Unknown unit of work tag. This error is likely caused by a bug in ' + - 'React. Please file an issue.', - ); - } - } - - function beginFailedWork( - current: Fiber | null, - workInProgress: Fiber, - priorityLevel: PriorityLevel, - ) { - invariant( - workInProgress.tag === ClassComponent || workInProgress.tag === HostRoot, - 'Invalid type of work. This error is likely caused by a bug in React. ' + - 'Please file an issue.', - ); - - // Add an error effect so we can handle the error during the commit phase - workInProgress.effectTag |= Err; - - if ( - workInProgress.pendingWorkPriority === NoWork || - workInProgress.pendingWorkPriority > priorityLevel - ) { - return bailoutOnLowPriority(current, workInProgress); - } - - // If we don't bail out, we're going be recomputing our children so we need - // to drop our effect list. - workInProgress.firstEffect = null; - workInProgress.lastEffect = null; - - // Unmount the current children as if the component rendered null - const nextChildren = null; - reconcileChildren(current, workInProgress, nextChildren); - - if (workInProgress.tag === ClassComponent) { - const instance = workInProgress.stateNode; - workInProgress.memoizedProps = instance.props; - workInProgress.memoizedState = instance.state; - workInProgress.pendingProps = null; - } - - return workInProgress.child; - } - - return { - beginWork, - beginFailedWork, - }; -}; diff --git a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberClassComponent.js b/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberClassComponent.js deleted file mode 100644 index ba6425308e..0000000000 --- a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberClassComponent.js +++ /dev/null @@ -1,597 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactFiberClassComponent - * @flow - */ - -'use strict'; - -import type {Fiber} from 'ReactFiber'; -import type {PriorityLevel} from 'ReactPriorityLevel'; - -var {Update} = require('ReactTypeOfSideEffect'); - -var ReactFeatureFlags = require('ReactFeatureFlags'); -var {AsyncUpdates} = require('ReactTypeOfInternalContext'); - -var { - cacheContext, - getMaskedContext, - getUnmaskedContext, - isContextConsumer, -} = require('ReactFiberContext'); -var { - addUpdate, - addReplaceUpdate, - addForceUpdate, - beginUpdateQueue, -} = require('ReactFiberUpdateQueue'); -var {hasContextChanged} = require('ReactFiberContext'); -var {isMounted} = require('ReactFiberTreeReflection'); -var ReactInstanceMap = require('ReactInstanceMap'); -var emptyObject = require('fbjs/lib/emptyObject'); -var getComponentName = require('getComponentName'); -var shallowEqual = require('fbjs/lib/shallowEqual'); -var invariant = require('fbjs/lib/invariant'); - -const isArray = Array.isArray; - -if (__DEV__) { - var {startPhaseTimer, stopPhaseTimer} = require('ReactDebugFiberPerf'); - var warning = require('fbjs/lib/warning'); - var warnOnInvalidCallback = function(callback: mixed, callerName: string) { - warning( - callback === null || typeof callback === 'function', - '%s(...): Expected the last optional `callback` argument to be a ' + - 'function. Instead received: %s.', - callerName, - callback, - ); - }; -} - -module.exports = function( - scheduleUpdate: (fiber: Fiber, priorityLevel: PriorityLevel) => void, - getPriorityContext: (fiber: Fiber, forceAsync: boolean) => PriorityLevel, - memoizeProps: (workInProgress: Fiber, props: any) => void, - memoizeState: (workInProgress: Fiber, state: any) => void, -) { - // Class component state updater - const updater = { - isMounted, - enqueueSetState(instance, partialState, callback) { - const fiber = ReactInstanceMap.get(instance); - const priorityLevel = getPriorityContext(fiber, false); - callback = callback === undefined ? null : callback; - if (__DEV__) { - warnOnInvalidCallback(callback, 'setState'); - } - addUpdate(fiber, partialState, callback, priorityLevel); - scheduleUpdate(fiber, priorityLevel); - }, - enqueueReplaceState(instance, state, callback) { - const fiber = ReactInstanceMap.get(instance); - const priorityLevel = getPriorityContext(fiber, false); - callback = callback === undefined ? null : callback; - if (__DEV__) { - warnOnInvalidCallback(callback, 'replaceState'); - } - addReplaceUpdate(fiber, state, callback, priorityLevel); - scheduleUpdate(fiber, priorityLevel); - }, - enqueueForceUpdate(instance, callback) { - const fiber = ReactInstanceMap.get(instance); - const priorityLevel = getPriorityContext(fiber, false); - callback = callback === undefined ? null : callback; - if (__DEV__) { - warnOnInvalidCallback(callback, 'forceUpdate'); - } - addForceUpdate(fiber, callback, priorityLevel); - scheduleUpdate(fiber, priorityLevel); - }, - }; - - function checkShouldComponentUpdate( - workInProgress, - oldProps, - newProps, - oldState, - newState, - newContext, - ) { - if ( - oldProps === null || - (workInProgress.updateQueue !== null && - workInProgress.updateQueue.hasForceUpdate) - ) { - // If the workInProgress already has an Update effect, return true - return true; - } - - const instance = workInProgress.stateNode; - const type = workInProgress.type; - if (typeof instance.shouldComponentUpdate === 'function') { - if (__DEV__) { - startPhaseTimer(workInProgress, 'shouldComponentUpdate'); - } - const shouldUpdate = instance.shouldComponentUpdate( - newProps, - newState, - newContext, - ); - if (__DEV__) { - stopPhaseTimer(); - } - - if (__DEV__) { - warning( - shouldUpdate !== undefined, - '%s.shouldComponentUpdate(): Returned undefined instead of a ' + - 'boolean value. Make sure to return true or false.', - getComponentName(workInProgress) || 'Unknown', - ); - } - - return shouldUpdate; - } - - if (type.prototype && type.prototype.isPureReactComponent) { - return ( - !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState) - ); - } - - return true; - } - - function checkClassInstance(workInProgress: Fiber) { - const instance = workInProgress.stateNode; - const type = workInProgress.type; - if (__DEV__) { - const name = getComponentName(workInProgress); - const renderPresent = instance.render; - warning( - renderPresent, - '%s(...): No `render` method found on the returned component ' + - 'instance: you may have forgotten to define `render`.', - name, - ); - const noGetInitialStateOnES6 = - !instance.getInitialState || - instance.getInitialState.isReactClassApproved || - instance.state; - warning( - noGetInitialStateOnES6, - 'getInitialState was defined on %s, a plain JavaScript class. ' + - 'This is only supported for classes created using React.createClass. ' + - 'Did you mean to define a state property instead?', - name, - ); - const noGetDefaultPropsOnES6 = - !instance.getDefaultProps || - instance.getDefaultProps.isReactClassApproved; - warning( - noGetDefaultPropsOnES6, - 'getDefaultProps was defined on %s, a plain JavaScript class. ' + - 'This is only supported for classes created using React.createClass. ' + - 'Use a static property to define defaultProps instead.', - name, - ); - const noInstancePropTypes = !instance.propTypes; - warning( - noInstancePropTypes, - 'propTypes was defined as an instance property on %s. Use a static ' + - 'property to define propTypes instead.', - name, - ); - const noInstanceContextTypes = !instance.contextTypes; - warning( - noInstanceContextTypes, - 'contextTypes was defined as an instance property on %s. Use a static ' + - 'property to define contextTypes instead.', - name, - ); - const noComponentShouldUpdate = - typeof instance.componentShouldUpdate !== 'function'; - warning( - noComponentShouldUpdate, - '%s has a method called ' + - 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + - 'The name is phrased as a question because the function is ' + - 'expected to return a value.', - name, - ); - if ( - type.prototype && - type.prototype.isPureReactComponent && - typeof instance.shouldComponentUpdate !== 'undefined' - ) { - warning( - false, - '%s has a method called shouldComponentUpdate(). ' + - 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + - 'Please extend React.Component if shouldComponentUpdate is used.', - getComponentName(workInProgress) || 'A pure component', - ); - } - const noComponentDidUnmount = - typeof instance.componentDidUnmount !== 'function'; - warning( - noComponentDidUnmount, - '%s has a method called ' + - 'componentDidUnmount(). But there is no such lifecycle method. ' + - 'Did you mean componentWillUnmount()?', - name, - ); - const noComponentWillRecieveProps = - typeof instance.componentWillRecieveProps !== 'function'; - warning( - noComponentWillRecieveProps, - '%s has a method called ' + - 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', - name, - ); - const hasMutatedProps = instance.props !== workInProgress.pendingProps; - warning( - instance.props === undefined || !hasMutatedProps, - '%s(...): When calling super() in `%s`, make sure to pass ' + - "up the same props that your component's constructor was passed.", - name, - name, - ); - const noInstanceDefaultProps = !instance.defaultProps; - warning( - noInstanceDefaultProps, - 'Setting defaultProps as an instance property on %s is not supported and will be ignored.' + - ' Instead, define defaultProps as a static property on %s.', - name, - name, - ); - } - - const state = instance.state; - if (state && (typeof state !== 'object' || isArray(state))) { - invariant( - false, - '%s.state: must be set to an object or null', - getComponentName(workInProgress), - ); - } - if (typeof instance.getChildContext === 'function') { - invariant( - typeof workInProgress.type.childContextTypes === 'object', - '%s.getChildContext(): childContextTypes must be defined in order to ' + - 'use getChildContext().', - getComponentName(workInProgress), - ); - } - } - - function resetInputPointers(workInProgress: Fiber, instance: any) { - instance.props = workInProgress.memoizedProps; - instance.state = workInProgress.memoizedState; - } - - function adoptClassInstance(workInProgress: Fiber, instance: any): void { - instance.updater = updater; - workInProgress.stateNode = instance; - // The instance needs access to the fiber so that it can schedule updates - ReactInstanceMap.set(instance, workInProgress); - } - - function constructClassInstance(workInProgress: Fiber, props: any): any { - const ctor = workInProgress.type; - const unmaskedContext = getUnmaskedContext(workInProgress); - const needsContext = isContextConsumer(workInProgress); - const context = needsContext - ? getMaskedContext(workInProgress, unmaskedContext) - : emptyObject; - const instance = new ctor(props, context); - adoptClassInstance(workInProgress, instance); - - // Cache unmasked context so we can avoid recreating masked context unless necessary. - // ReactFiberContext usually updates this cache but can't for newly-created instances. - if (needsContext) { - cacheContext(workInProgress, unmaskedContext, context); - } - - return instance; - } - - // Invokes the mount life-cycles on a previously never rendered instance. - function mountClassInstance( - workInProgress: Fiber, - priorityLevel: PriorityLevel, - ): void { - if (__DEV__) { - checkClassInstance(workInProgress); - } - - const instance = workInProgress.stateNode; - const state = instance.state || null; - - let props = workInProgress.pendingProps; - invariant( - props, - 'There must be pending props for an initial mount. This error is ' + - 'likely caused by a bug in React. Please file an issue.', - ); - - const unmaskedContext = getUnmaskedContext(workInProgress); - - instance.props = props; - instance.state = state; - instance.refs = emptyObject; - instance.context = getMaskedContext(workInProgress, unmaskedContext); - - if ( - ReactFeatureFlags.enableAsyncSubtreeAPI && - workInProgress.type != null && - workInProgress.type.unstable_asyncUpdates === true - ) { - workInProgress.internalContextTag |= AsyncUpdates; - } - - if (typeof instance.componentWillMount === 'function') { - if (__DEV__) { - startPhaseTimer(workInProgress, 'componentWillMount'); - } - instance.componentWillMount(); - if (__DEV__) { - stopPhaseTimer(); - } - // If we had additional state updates during this life-cycle, let's - // process them now. - const updateQueue = workInProgress.updateQueue; - if (updateQueue !== null) { - instance.state = beginUpdateQueue( - workInProgress, - updateQueue, - instance, - state, - props, - priorityLevel, - ); - } - } - if (typeof instance.componentDidMount === 'function') { - workInProgress.effectTag |= Update; - } - } - - // Called on a preexisting class instance. Returns false if a resumed render - // could be reused. - function resumeMountClassInstance( - workInProgress: Fiber, - priorityLevel: PriorityLevel, - ): boolean { - const instance = workInProgress.stateNode; - resetInputPointers(workInProgress, instance); - - let newState = workInProgress.memoizedState; - let newProps = workInProgress.pendingProps; - if (!newProps) { - // If there isn't any new props, then we'll reuse the memoized props. - // This could be from already completed work. - newProps = workInProgress.memoizedProps; - invariant( - newProps != null, - 'There should always be pending or memoized props. This error is ' + - 'likely caused by a bug in React. Please file an issue.', - ); - } - const newUnmaskedContext = getUnmaskedContext(workInProgress); - const newContext = getMaskedContext(workInProgress, newUnmaskedContext); - - // TODO: Should we deal with a setState that happened after the last - // componentWillMount and before this componentWillMount? Probably - // unsupported anyway. - - if ( - !checkShouldComponentUpdate( - workInProgress, - workInProgress.memoizedProps, - newProps, - workInProgress.memoizedState, - newState, - newContext, - ) - ) { - // Update the existing instance's state, props, and context pointers even - // though we're bailing out. - instance.props = newProps; - instance.state = newState; - instance.context = newContext; - return false; - } - - // If we didn't bail out we need to construct a new instance. We don't - // want to reuse one that failed to fully mount. - const newInstance = constructClassInstance(workInProgress, newProps); - newInstance.props = newProps; - newInstance.state = newState = newInstance.state || null; - newInstance.context = newContext; - - if (typeof newInstance.componentWillMount === 'function') { - if (__DEV__) { - startPhaseTimer(workInProgress, 'componentWillMount'); - } - newInstance.componentWillMount(); - if (__DEV__) { - stopPhaseTimer(); - } - } - // If we had additional state updates, process them now. - // They may be from componentWillMount() or from error boundary's setState() - // during initial mounting. - const newUpdateQueue = workInProgress.updateQueue; - if (newUpdateQueue !== null) { - newInstance.state = beginUpdateQueue( - workInProgress, - newUpdateQueue, - newInstance, - newState, - newProps, - priorityLevel, - ); - } - if (typeof instance.componentDidMount === 'function') { - workInProgress.effectTag |= Update; - } - return true; - } - - // Invokes the update life-cycles and returns false if it shouldn't rerender. - function updateClassInstance( - current: Fiber, - workInProgress: Fiber, - priorityLevel: PriorityLevel, - ): boolean { - const instance = workInProgress.stateNode; - resetInputPointers(workInProgress, instance); - - const oldProps = workInProgress.memoizedProps; - let newProps = workInProgress.pendingProps; - if (!newProps) { - // If there aren't any new props, then we'll reuse the memoized props. - // This could be from already completed work. - newProps = oldProps; - invariant( - newProps != null, - 'There should always be pending or memoized props. This error is ' + - 'likely caused by a bug in React. Please file an issue.', - ); - } - const oldContext = instance.context; - const newUnmaskedContext = getUnmaskedContext(workInProgress); - const newContext = getMaskedContext(workInProgress, newUnmaskedContext); - - // Note: During these life-cycles, instance.props/instance.state are what - // ever the previously attempted to render - not the "current". However, - // during componentDidUpdate we pass the "current" props. - - if (oldProps !== newProps || oldContext !== newContext) { - if (typeof instance.componentWillReceiveProps === 'function') { - if (__DEV__) { - startPhaseTimer(workInProgress, 'componentWillReceiveProps'); - } - instance.componentWillReceiveProps(newProps, newContext); - if (__DEV__) { - stopPhaseTimer(); - } - - if (instance.state !== workInProgress.memoizedState) { - if (__DEV__) { - warning( - false, - '%s.componentWillReceiveProps(): Assigning directly to ' + - "this.state is deprecated (except inside a component's " + - 'constructor). Use setState instead.', - getComponentName(workInProgress), - ); - } - updater.enqueueReplaceState(instance, instance.state, null); - } - } - } - - // Compute the next state using the memoized state and the update queue. - const updateQueue = workInProgress.updateQueue; - const oldState = workInProgress.memoizedState; - // TODO: Previous state can be null. - let newState; - if (updateQueue !== null) { - newState = beginUpdateQueue( - workInProgress, - updateQueue, - instance, - oldState, - newProps, - priorityLevel, - ); - } else { - newState = oldState; - } - - if ( - oldProps === newProps && - oldState === newState && - !hasContextChanged() && - !(updateQueue !== null && updateQueue.hasForceUpdate) - ) { - // If an update was already in progress, we should schedule an Update - // effect even though we're bailing out, so that cWU/cDU are called. - if (typeof instance.componentDidUpdate === 'function') { - if ( - oldProps !== current.memoizedProps || - oldState !== current.memoizedState - ) { - workInProgress.effectTag |= Update; - } - } - return false; - } - - const shouldUpdate = checkShouldComponentUpdate( - workInProgress, - oldProps, - newProps, - oldState, - newState, - newContext, - ); - - if (shouldUpdate) { - if (typeof instance.componentWillUpdate === 'function') { - if (__DEV__) { - startPhaseTimer(workInProgress, 'componentWillUpdate'); - } - instance.componentWillUpdate(newProps, newState, newContext); - if (__DEV__) { - stopPhaseTimer(); - } - } - if (typeof instance.componentDidUpdate === 'function') { - workInProgress.effectTag |= Update; - } - } else { - // If an update was already in progress, we should schedule an Update - // effect even though we're bailing out, so that cWU/cDU are called. - if (typeof instance.componentDidUpdate === 'function') { - if ( - oldProps !== current.memoizedProps || - oldState !== current.memoizedState - ) { - workInProgress.effectTag |= Update; - } - } - - // If shouldComponentUpdate returned false, we should still update the - // memoized props/state to indicate that this work can be reused. - memoizeProps(workInProgress, newProps); - memoizeState(workInProgress, newState); - } - - // Update the existing instance's state, props, and context pointers even - // if shouldComponentUpdate returns false. - instance.props = newProps; - instance.state = newState; - instance.context = newContext; - - return shouldUpdate; - } - - return { - adoptClassInstance, - constructClassInstance, - mountClassInstance, - resumeMountClassInstance, - updateClassInstance, - }; -}; diff --git a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberCommitWork.js b/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberCommitWork.js deleted file mode 100644 index 2703f06589..0000000000 --- a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberCommitWork.js +++ /dev/null @@ -1,541 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactFiberCommitWork - * @flow - */ - -'use strict'; - -import type {Fiber} from 'ReactFiber'; -import type {HostConfig} from 'ReactFiberReconciler'; - -var ReactTypeOfWork = require('ReactTypeOfWork'); -var { - ClassComponent, - HostRoot, - HostComponent, - HostText, - HostPortal, - CoroutineComponent, -} = ReactTypeOfWork; -var {commitCallbacks} = require('ReactFiberUpdateQueue'); -var {onCommitUnmount} = require('ReactFiberDevToolsHook'); -var {invokeGuardedCallback} = require('ReactErrorUtils'); - -var { - Placement, - Update, - Callback, - ContentReset, -} = require('ReactTypeOfSideEffect'); - -var invariant = require('fbjs/lib/invariant'); - -if (__DEV__) { - var {startPhaseTimer, stopPhaseTimer} = require('ReactDebugFiberPerf'); -} - -module.exports = function( - config: HostConfig, - captureError: (failedFiber: Fiber, error: Error) => Fiber | null, -) { - const { - commitMount, - commitUpdate, - resetTextContent, - commitTextUpdate, - appendChild, - insertBefore, - removeChild, - getPublicInstance, - } = config; - - if (__DEV__) { - var callComponentWillUnmountWithTimerInDev = function(current, instance) { - startPhaseTimer(current, 'componentWillUnmount'); - instance.componentWillUnmount(); - stopPhaseTimer(); - }; - } - - // Capture errors so they don't interrupt unmounting. - function safelyCallComponentWillUnmount(current, instance) { - if (__DEV__) { - const unmountError = invokeGuardedCallback( - null, - callComponentWillUnmountWithTimerInDev, - null, - current, - instance, - ); - if (unmountError) { - captureError(current, unmountError); - } - } else { - try { - instance.componentWillUnmount(); - } catch (unmountError) { - captureError(current, unmountError); - } - } - } - - function safelyDetachRef(current: Fiber) { - const ref = current.ref; - if (ref !== null) { - if (__DEV__) { - const refError = invokeGuardedCallback(null, ref, null, null); - if (refError !== null) { - captureError(current, refError); - } - } else { - try { - ref(null); - } catch (refError) { - captureError(current, refError); - } - } - } - } - - function getHostParent(fiber: Fiber): I | C { - let parent = fiber.return; - while (parent !== null) { - switch (parent.tag) { - case HostComponent: - return parent.stateNode; - case HostRoot: - return parent.stateNode.containerInfo; - case HostPortal: - return parent.stateNode.containerInfo; - } - parent = parent.return; - } - invariant( - false, - 'Expected to find a host parent. This error is likely caused by a bug ' + - 'in React. Please file an issue.', - ); - } - - function getHostParentFiber(fiber: Fiber): Fiber { - let parent = fiber.return; - while (parent !== null) { - if (isHostParent(parent)) { - return parent; - } - parent = parent.return; - } - invariant( - false, - 'Expected to find a host parent. This error is likely caused by a bug ' + - 'in React. Please file an issue.', - ); - } - - function isHostParent(fiber: Fiber): boolean { - return ( - fiber.tag === HostComponent || - fiber.tag === HostRoot || - fiber.tag === HostPortal - ); - } - - function getHostSibling(fiber: Fiber): ?I { - // We're going to search forward into the tree until we find a sibling host - // node. Unfortunately, if multiple insertions are done in a row we have to - // search past them. This leads to exponential search for the next sibling. - // TODO: Find a more efficient way to do this. - let node: Fiber = fiber; - siblings: while (true) { - // If we didn't find anything, let's try the next sibling. - while (node.sibling === null) { - if (node.return === null || isHostParent(node.return)) { - // If we pop out of the root or hit the parent the fiber we are the - // last sibling. - return null; - } - node = node.return; - } - node.sibling.return = node.return; - node = node.sibling; - while (node.tag !== HostComponent && node.tag !== HostText) { - // If it is not host node and, we might have a host node inside it. - // Try to search down until we find one. - if (node.effectTag & Placement) { - // If we don't have a child, try the siblings instead. - continue siblings; - } - // If we don't have a child, try the siblings instead. - // We also skip portals because they are not part of this host tree. - if (node.child === null || node.tag === HostPortal) { - continue siblings; - } else { - node.child.return = node; - node = node.child; - } - } - // Check if this host node is stable or about to be placed. - if (!(node.effectTag & Placement)) { - // Found it! - return node.stateNode; - } - } - } - - function commitPlacement(finishedWork: Fiber): void { - // Recursively insert all host nodes into the parent. - const parentFiber = getHostParentFiber(finishedWork); - let parent; - switch (parentFiber.tag) { - case HostComponent: - parent = parentFiber.stateNode; - break; - case HostRoot: - parent = parentFiber.stateNode.containerInfo; - break; - case HostPortal: - parent = parentFiber.stateNode.containerInfo; - break; - default: - invariant( - false, - 'Invalid host parent fiber. This error is likely caused by a bug ' + - 'in React. Please file an issue.', - ); - } - if (parentFiber.effectTag & ContentReset) { - // Reset the text content of the parent before doing any insertions - resetTextContent(parent); - // Clear ContentReset from the effect tag - parentFiber.effectTag &= ~ContentReset; - } - - const before = getHostSibling(finishedWork); - // We only have the top Fiber that was inserted but we need recurse down its - // children to find all the terminal nodes. - let node: Fiber = finishedWork; - while (true) { - if (node.tag === HostComponent || node.tag === HostText) { - if (before) { - insertBefore(parent, node.stateNode, before); - } else { - appendChild(parent, node.stateNode); - } - } else if (node.tag === HostPortal) { - // If the insertion itself is a portal, then we don't want to traverse - // down its children. Instead, we'll get insertions from each child in - // the portal directly. - } else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - if (node === finishedWork) { - return; - } - while (node.sibling === null) { - if (node.return === null || node.return === finishedWork) { - return; - } - node = node.return; - } - node.sibling.return = node.return; - node = node.sibling; - } - } - - function commitNestedUnmounts(root: Fiber): void { - // While we're inside a removed host node we don't want to call - // removeChild on the inner nodes because they're removed by the top - // call anyway. We also want to call componentWillUnmount on all - // composites before this host node is removed from the tree. Therefore - // we do an inner loop while we're still inside the host node. - let node: Fiber = root; - while (true) { - commitUnmount(node); - // Visit children because they may contain more composite or host nodes. - // Skip portals because commitUnmount() currently visits them recursively. - if (node.child !== null && node.tag !== HostPortal) { - node.child.return = node; - node = node.child; - continue; - } - if (node === root) { - return; - } - while (node.sibling === null) { - if (node.return === null || node.return === root) { - return; - } - node = node.return; - } - node.sibling.return = node.return; - node = node.sibling; - } - } - - function unmountHostComponents(parent, current): void { - // We only have the top Fiber that was inserted but we need recurse down its - // children to find all the terminal nodes. - let node: Fiber = current; - while (true) { - if (node.tag === HostComponent || node.tag === HostText) { - commitNestedUnmounts(node); - // After all the children have unmounted, it is now safe to remove the - // node from the tree. - removeChild(parent, node.stateNode); - // Don't visit children because we already visited them. - } else if (node.tag === HostPortal) { - // When we go into a portal, it becomes the parent to remove from. - // We will reassign it back when we pop the portal on the way up. - parent = node.stateNode.containerInfo; - // Visit children because portals might contain host components. - if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - } else { - commitUnmount(node); - // Visit children because we may find more host components below. - if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - } - if (node === current) { - return; - } - while (node.sibling === null) { - if (node.return === null || node.return === current) { - return; - } - node = node.return; - if (node.tag === HostPortal) { - // When we go out of the portal, we need to restore the parent. - // Since we don't keep a stack of them, we will search for it. - parent = getHostParent(node); - } - } - node.sibling.return = node.return; - node = node.sibling; - } - } - - function commitDeletion(current: Fiber): void { - // Recursively delete all host nodes from the parent. - const parent = getHostParent(current); - // Detach refs and call componentWillUnmount() on the whole subtree. - unmountHostComponents(parent, current); - - // Cut off the return pointers to disconnect it from the tree. Ideally, we - // should clear the child pointer of the parent alternate to let this - // get GC:ed but we don't know which for sure which parent is the current - // one so we'll settle for GC:ing the subtree of this child. This child - // itself will be GC:ed when the parent updates the next time. - current.return = null; - current.child = null; - if (current.alternate) { - current.alternate.child = null; - current.alternate.return = null; - } - } - - // User-originating errors (lifecycles and refs) should not interrupt - // deletion, so don't let them throw. Host-originating errors should - // interrupt deletion, so it's okay - function commitUnmount(current: Fiber): void { - if (typeof onCommitUnmount === 'function') { - onCommitUnmount(current); - } - - switch (current.tag) { - case ClassComponent: { - safelyDetachRef(current); - const instance = current.stateNode; - if (typeof instance.componentWillUnmount === 'function') { - safelyCallComponentWillUnmount(current, instance); - } - return; - } - case HostComponent: { - safelyDetachRef(current); - return; - } - case CoroutineComponent: { - commitNestedUnmounts(current.stateNode); - return; - } - case HostPortal: { - // TODO: this is recursive. - // We are also not using this parent because - // the portal will get pushed immediately. - const parent = getHostParent(current); - unmountHostComponents(parent, current); - return; - } - } - } - - function commitWork(current: Fiber | null, finishedWork: Fiber): void { - switch (finishedWork.tag) { - case ClassComponent: { - return; - } - case HostComponent: { - const instance: I = finishedWork.stateNode; - if (instance != null && current !== null) { - // Commit the work prepared earlier. - const newProps = finishedWork.memoizedProps; - const oldProps = current.memoizedProps; - const type = finishedWork.type; - // TODO: Type the updateQueue to be specific to host components. - const updatePayload: null | PL = (finishedWork.updateQueue: any); - finishedWork.updateQueue = null; - if (updatePayload !== null) { - commitUpdate( - instance, - updatePayload, - type, - oldProps, - newProps, - finishedWork, - ); - } - } - return; - } - case HostText: { - invariant( - finishedWork.stateNode !== null && current !== null, - 'This should only be done during updates. This error is likely ' + - 'caused by a bug in React. Please file an issue.', - ); - const textInstance: TI = finishedWork.stateNode; - const newText: string = finishedWork.memoizedProps; - const oldText: string = current.memoizedProps; - commitTextUpdate(textInstance, oldText, newText); - return; - } - case HostRoot: { - return; - } - case HostPortal: { - return; - } - default: { - invariant( - false, - 'This unit of work tag should not have side-effects. This error is ' + - 'likely caused by a bug in React. Please file an issue.', - ); - } - } - } - - function commitLifeCycles(current: Fiber | null, finishedWork: Fiber): void { - switch (finishedWork.tag) { - case ClassComponent: { - const instance = finishedWork.stateNode; - if (finishedWork.effectTag & Update) { - if (current === null) { - if (__DEV__) { - startPhaseTimer(finishedWork, 'componentDidMount'); - } - instance.componentDidMount(); - if (__DEV__) { - stopPhaseTimer(); - } - } else { - const prevProps = current.memoizedProps; - const prevState = current.memoizedState; - if (__DEV__) { - startPhaseTimer(finishedWork, 'componentDidUpdate'); - } - instance.componentDidUpdate(prevProps, prevState); - if (__DEV__) { - stopPhaseTimer(); - } - } - } - if ( - finishedWork.effectTag & Callback && - finishedWork.updateQueue !== null - ) { - commitCallbacks(finishedWork, finishedWork.updateQueue, instance); - } - return; - } - case HostRoot: { - const updateQueue = finishedWork.updateQueue; - if (updateQueue !== null) { - const instance = finishedWork.child && finishedWork.child.stateNode; - commitCallbacks(finishedWork, updateQueue, instance); - } - return; - } - case HostComponent: { - const instance: I = finishedWork.stateNode; - - // Renderers may schedule work to be done after host components are mounted - // (eg DOM renderer may schedule auto-focus for inputs and form controls). - // These effects should only be committed when components are first mounted, - // aka when there is no current/alternate. - if (current === null && finishedWork.effectTag & Update) { - const type = finishedWork.type; - const props = finishedWork.memoizedProps; - commitMount(instance, type, props, finishedWork); - } - - return; - } - case HostText: { - // We have no life-cycles associated with text. - return; - } - case HostPortal: { - // We have no life-cycles associated with portals. - return; - } - default: { - invariant( - false, - 'This unit of work tag should not have side-effects. This error is ' + - 'likely caused by a bug in React. Please file an issue.', - ); - } - } - } - - function commitAttachRef(finishedWork: Fiber) { - const ref = finishedWork.ref; - if (ref !== null) { - const instance = getPublicInstance(finishedWork.stateNode); - ref(instance); - } - } - - function commitDetachRef(current: Fiber) { - const currentRef = current.ref; - if (currentRef !== null) { - currentRef(null); - } - } - - return { - commitPlacement, - commitDeletion, - commitWork, - commitLifeCycles, - commitAttachRef, - commitDetachRef, - }; -}; diff --git a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberCompleteWork.js b/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberCompleteWork.js deleted file mode 100644 index 644356983b..0000000000 --- a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberCompleteWork.js +++ /dev/null @@ -1,361 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactFiberCompleteWork - * @flow - */ - -'use strict'; - -import type {ReactCoroutine} from 'ReactCoroutine'; -import type {Fiber} from 'ReactFiber'; -import type {HostContext} from 'ReactFiberHostContext'; -import type {FiberRoot} from 'ReactFiberRoot'; -import type {HostConfig} from 'ReactFiberReconciler'; - -var {reconcileChildFibers} = require('ReactChildFiber'); -var {popContextProvider} = require('ReactFiberContext'); -var ReactTypeOfWork = require('ReactTypeOfWork'); -var ReactTypeOfSideEffect = require('ReactTypeOfSideEffect'); -var { - IndeterminateComponent, - FunctionalComponent, - ClassComponent, - HostRoot, - HostComponent, - HostText, - HostPortal, - CoroutineComponent, - CoroutineHandlerPhase, - YieldComponent, - Fragment, -} = ReactTypeOfWork; -var {Ref, Update} = ReactTypeOfSideEffect; - -if (__DEV__) { - var ReactDebugCurrentFiber = require('ReactDebugCurrentFiber'); -} - -var invariant = require('fbjs/lib/invariant'); - -module.exports = function( - config: HostConfig, - hostContext: HostContext, -) { - const { - createInstance, - createTextInstance, - appendInitialChild, - finalizeInitialChildren, - prepareUpdate, - } = config; - - const { - getRootHostContainer, - popHostContext, - getHostContext, - popHostContainer, - } = hostContext; - - function markChildAsProgressed(current, workInProgress, priorityLevel) { - // We now have clones. Let's store them as the currently progressed work. - workInProgress.progressedChild = workInProgress.child; - workInProgress.progressedPriority = priorityLevel; - if (current !== null) { - // We also store it on the current. When the alternate swaps in we can - // continue from this point. - current.progressedChild = workInProgress.progressedChild; - current.progressedPriority = workInProgress.progressedPriority; - } - } - - function markUpdate(workInProgress: Fiber) { - // Tag the fiber with an update effect. This turns a Placement into - // an UpdateAndPlacement. - workInProgress.effectTag |= Update; - } - - function markRef(workInProgress: Fiber) { - workInProgress.effectTag |= Ref; - } - - function appendAllYields(yields: Array, workInProgress: Fiber) { - let node = workInProgress.stateNode; - if (node) { - node.return = workInProgress; - } - while (node !== null) { - if ( - node.tag === HostComponent || - node.tag === HostText || - node.tag === HostPortal - ) { - invariant(false, 'A coroutine cannot have host component children.'); - } else if (node.tag === YieldComponent) { - yields.push(node.type); - } else if (node.child !== null) { - node.child.return = node; - node = node.child; - continue; - } - while (node.sibling === null) { - if (node.return === null || node.return === workInProgress) { - return; - } - node = node.return; - } - node.sibling.return = node.return; - node = node.sibling; - } - } - - function moveCoroutineToHandlerPhase( - current: Fiber | null, - workInProgress: Fiber, - ) { - var coroutine = (workInProgress.memoizedProps: ?ReactCoroutine); - invariant( - coroutine, - 'Should be resolved by now. This error is likely caused by a bug in ' + - 'React. Please file an issue.', - ); - - // First step of the coroutine has completed. Now we need to do the second. - // TODO: It would be nice to have a multi stage coroutine represented by a - // single component, or at least tail call optimize nested ones. Currently - // that requires additional fields that we don't want to add to the fiber. - // So this requires nested handlers. - // Note: This doesn't mutate the alternate node. I don't think it needs to - // since this stage is reset for every pass. - workInProgress.tag = CoroutineHandlerPhase; - - // Build up the yields. - // TODO: Compare this to a generator or opaque helpers like Children. - var yields: Array = []; - appendAllYields(yields, workInProgress); - var fn = coroutine.handler; - var props = coroutine.props; - var nextChildren = fn(props, yields); - - var currentFirstChild = current !== null ? current.child : null; - // Inherit the priority of the returnFiber. - const priority = workInProgress.pendingWorkPriority; - workInProgress.child = reconcileChildFibers( - workInProgress, - currentFirstChild, - nextChildren, - priority, - ); - markChildAsProgressed(current, workInProgress, priority); - return workInProgress.child; - } - - function appendAllChildren(parent: I, workInProgress: Fiber) { - // We only have the top Fiber that was created but we need recurse down its - // children to find all the terminal nodes. - let node = workInProgress.child; - while (node !== null) { - if (node.tag === HostComponent || node.tag === HostText) { - appendInitialChild(parent, node.stateNode); - } else if (node.tag === HostPortal) { - // If we have a portal child, then we don't want to traverse - // down its children. Instead, we'll get insertions from each child in - // the portal directly. - } else if (node.child !== null) { - node = node.child; - continue; - } - if (node === workInProgress) { - return; - } - while (node.sibling === null) { - if (node.return === null || node.return === workInProgress) { - return; - } - node = node.return; - } - node = node.sibling; - } - } - - function completeWork( - current: Fiber | null, - workInProgress: Fiber, - ): Fiber | null { - if (__DEV__) { - ReactDebugCurrentFiber.current = workInProgress; - } - - switch (workInProgress.tag) { - case FunctionalComponent: - return null; - case ClassComponent: { - // We are leaving this subtree, so pop context if any. - popContextProvider(workInProgress); - return null; - } - case HostRoot: { - // TODO: Pop the host container after #8607 lands. - const fiberRoot = (workInProgress.stateNode: FiberRoot); - if (fiberRoot.pendingContext) { - fiberRoot.context = fiberRoot.pendingContext; - fiberRoot.pendingContext = null; - } - return null; - } - case HostComponent: { - popHostContext(workInProgress); - const rootContainerInstance = getRootHostContainer(); - const type = workInProgress.type; - const newProps = workInProgress.memoizedProps; - if (current !== null && workInProgress.stateNode != null) { - // If we have an alternate, that means this is an update and we need to - // schedule a side-effect to do the updates. - const oldProps = current.memoizedProps; - // If we get updated because one of our children updated, we don't - // have newProps so we'll have to reuse them. - // TODO: Split the update API as separate for the props vs. children. - // Even better would be if children weren't special cased at all tho. - const instance: I = workInProgress.stateNode; - const currentHostContext = getHostContext(); - const updatePayload = prepareUpdate( - instance, - type, - oldProps, - newProps, - rootContainerInstance, - currentHostContext, - ); - - // TODO: Type this specific to this type of component. - workInProgress.updateQueue = (updatePayload: any); - // If the update payload indicates that there is a change or if there - // is a new ref we mark this as an update. - if (updatePayload) { - markUpdate(workInProgress); - } - if (current.ref !== workInProgress.ref) { - markRef(workInProgress); - } - } else { - if (!newProps) { - invariant( - workInProgress.stateNode !== null, - 'We must have new props for new mounts. This error is likely ' + - 'caused by a bug in React. Please file an issue.', - ); - // This can happen when we abort work. - return null; - } - - const currentHostContext = getHostContext(); - // TODO: Move createInstance to beginWork and keep it on a context - // "stack" as the parent. Then append children as we go in beginWork - // or completeWork depending on we want to add then top->down or - // bottom->up. Top->down is faster in IE11. - const instance = createInstance( - type, - newProps, - rootContainerInstance, - currentHostContext, - workInProgress, - ); - - appendAllChildren(instance, workInProgress); - - // Certain renderers require commit-time effects for initial mount. - // (eg DOM renderer supports auto-focus for certain elements). - // Make sure such renderers get scheduled for later work. - if ( - finalizeInitialChildren( - instance, - type, - newProps, - rootContainerInstance, - ) - ) { - markUpdate(workInProgress); - } - - workInProgress.stateNode = instance; - if (workInProgress.ref !== null) { - // If there is a ref on a host node we need to schedule a callback - markRef(workInProgress); - } - } - return null; - } - case HostText: { - let newText = workInProgress.memoizedProps; - if (current && workInProgress.stateNode != null) { - const oldText = current.memoizedProps; - // If we have an alternate, that means this is an update and we need - // to schedule a side-effect to do the updates. - if (oldText !== newText) { - markUpdate(workInProgress); - } - } else { - if (typeof newText !== 'string') { - invariant( - workInProgress.stateNode !== null, - 'We must have new props for new mounts. This error is likely ' + - 'caused by a bug in React. Please file an issue.', - ); - // This can happen when we abort work. - return null; - } - const rootContainerInstance = getRootHostContainer(); - const currentHostContext = getHostContext(); - const textInstance = createTextInstance( - newText, - rootContainerInstance, - currentHostContext, - workInProgress, - ); - workInProgress.stateNode = textInstance; - } - return null; - } - case CoroutineComponent: - return moveCoroutineToHandlerPhase(current, workInProgress); - case CoroutineHandlerPhase: - // Reset the tag to now be a first phase coroutine. - workInProgress.tag = CoroutineComponent; - return null; - case YieldComponent: - // Does nothing. - return null; - case Fragment: - return null; - case HostPortal: - // TODO: Only mark this as an update if we have any pending callbacks. - markUpdate(workInProgress); - popHostContainer(workInProgress); - return null; - // Error cases - case IndeterminateComponent: - invariant( - false, - 'An indeterminate component should have become determinate before ' + - 'completing. This error is likely caused by a bug in React. Please ' + - 'file an issue.', - ); - // eslint-disable-next-line no-fallthrough - default: - invariant( - false, - 'Unknown unit of work tag. This error is likely caused by a bug in ' + - 'React. Please file an issue.', - ); - } - } - - return { - completeWork, - }; -}; diff --git a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberContext.js b/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberContext.js deleted file mode 100644 index 8a2c606409..0000000000 --- a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberContext.js +++ /dev/null @@ -1,289 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactFiberContext - * @flow - */ - -'use strict'; - -import type {Fiber} from 'ReactFiber'; -import type {StackCursor} from 'ReactFiberStack'; - -var checkPropTypes = require('prop-types/checkPropTypes'); -var emptyObject = require('fbjs/lib/emptyObject'); -var getComponentName = require('getComponentName'); -var invariant = require('fbjs/lib/invariant'); -var warning = require('fbjs/lib/warning'); -var {isFiberMounted} = require('ReactFiberTreeReflection'); -var {ClassComponent, HostRoot} = require('ReactTypeOfWork'); -const {createCursor, pop, push} = require('ReactFiberStack'); - -if (__DEV__) { - var ReactDebugCurrentFiber = require('ReactDebugCurrentFiber'); - var {ReactDebugCurrentFrame} = require('ReactGlobalSharedState'); - var {startPhaseTimer, stopPhaseTimer} = require('ReactDebugFiberPerf'); - var warnedAboutMissingGetChildContext = {}; -} - -// A cursor to the current merged context object on the stack. -let contextStackCursor: StackCursor = createCursor(emptyObject); -// A cursor to a boolean indicating whether the context has changed. -let didPerformWorkStackCursor: StackCursor = createCursor(false); -// Keep track of the previous context object that was on the stack. -// We use this to get access to the parent context after we have already -// pushed the next context provider, and now need to merge their contexts. -let previousContext: Object = emptyObject; - -function getUnmaskedContext(workInProgress: Fiber): Object { - const hasOwnContext = isContextProvider(workInProgress); - if (hasOwnContext) { - // If the fiber is a context provider itself, when we read its context - // we have already pushed its own child context on the stack. A context - // provider should not "see" its own child context. Therefore we read the - // previous (parent) context instead for a context provider. - return previousContext; - } - return contextStackCursor.current; -} -exports.getUnmaskedContext = getUnmaskedContext; - -function cacheContext( - workInProgress: Fiber, - unmaskedContext: Object, - maskedContext: Object, -) { - const instance = workInProgress.stateNode; - instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext; - instance.__reactInternalMemoizedMaskedChildContext = maskedContext; -} -exports.cacheContext = cacheContext; - -exports.getMaskedContext = function( - workInProgress: Fiber, - unmaskedContext: Object, -) { - const type = workInProgress.type; - const contextTypes = type.contextTypes; - if (!contextTypes) { - return emptyObject; - } - - // Avoid recreating masked context unless unmasked context has changed. - // Failing to do this will result in unnecessary calls to componentWillReceiveProps. - // This may trigger infinite loops if componentWillReceiveProps calls setState. - const instance = workInProgress.stateNode; - if ( - instance && - instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext - ) { - return instance.__reactInternalMemoizedMaskedChildContext; - } - - const context = {}; - for (let key in contextTypes) { - context[key] = unmaskedContext[key]; - } - - if (__DEV__) { - const name = getComponentName(workInProgress) || 'Unknown'; - ReactDebugCurrentFrame.current = workInProgress; - checkPropTypes( - contextTypes, - context, - 'context', - name, - ReactDebugCurrentFrame.getStackAddendum, - ); - ReactDebugCurrentFrame.current = null; - } - - // Cache unmasked context so we can avoid recreating masked context unless necessary. - // Context is created before the class component is instantiated so check for instance. - if (instance) { - cacheContext(workInProgress, unmaskedContext, context); - } - - return context; -}; - -exports.hasContextChanged = function(): boolean { - return didPerformWorkStackCursor.current; -}; - -function isContextConsumer(fiber: Fiber): boolean { - return fiber.tag === ClassComponent && fiber.type.contextTypes != null; -} -exports.isContextConsumer = isContextConsumer; - -function isContextProvider(fiber: Fiber): boolean { - return fiber.tag === ClassComponent && fiber.type.childContextTypes != null; -} -exports.isContextProvider = isContextProvider; - -function popContextProvider(fiber: Fiber): void { - if (!isContextProvider(fiber)) { - return; - } - - pop(didPerformWorkStackCursor, fiber); - pop(contextStackCursor, fiber); -} -exports.popContextProvider = popContextProvider; - -exports.pushTopLevelContextObject = function( - fiber: Fiber, - context: Object, - didChange: boolean, -): void { - invariant( - contextStackCursor.cursor == null, - 'Unexpected context found on stack', - ); - - push(contextStackCursor, context, fiber); - push(didPerformWorkStackCursor, didChange, fiber); -}; - -function processChildContext( - fiber: Fiber, - parentContext: Object, - isReconciling: boolean, -): Object { - const instance = fiber.stateNode; - const childContextTypes = fiber.type.childContextTypes; - - // TODO (bvaughn) Replace this behavior with an invariant() in the future. - // It has only been added in Fiber to match the (unintentional) behavior in Stack. - if (typeof instance.getChildContext !== 'function') { - if (__DEV__) { - const componentName = getComponentName(fiber) || 'Unknown'; - - if (!warnedAboutMissingGetChildContext[componentName]) { - warnedAboutMissingGetChildContext[componentName] = true; - warning( - false, - '%s.childContextTypes is specified but there is no getChildContext() method ' + - 'on the instance. You can either define getChildContext() on %s or remove ' + - 'childContextTypes from it.', - componentName, - componentName, - ); - } - } - return parentContext; - } - - let childContext; - if (__DEV__) { - ReactDebugCurrentFiber.phase = 'getChildContext'; - startPhaseTimer(fiber, 'getChildContext'); - childContext = instance.getChildContext(); - stopPhaseTimer(); - ReactDebugCurrentFiber.phase = null; - } else { - childContext = instance.getChildContext(); - } - for (let contextKey in childContext) { - invariant( - contextKey in childContextTypes, - '%s.getChildContext(): key "%s" is not defined in childContextTypes.', - getComponentName(fiber) || 'Unknown', - contextKey, - ); - } - if (__DEV__) { - const name = getComponentName(fiber) || 'Unknown'; - // We can only provide accurate element stacks if we pass work-in-progress tree - // during the begin or complete phase. However currently this function is also - // called from unstable_renderSubtree legacy implementation. In this case it unsafe to - // assume anything about the given fiber. We won't pass it down if we aren't sure. - // TODO: remove this hack when we delete unstable_renderSubtree in Fiber. - const workInProgress = isReconciling ? fiber : null; - ReactDebugCurrentFrame.current = workInProgress; - checkPropTypes( - childContextTypes, - childContext, - 'child context', - name, - ReactDebugCurrentFrame.getStackAddendum, - ); - ReactDebugCurrentFrame.current = null; - } - - return {...parentContext, ...childContext}; -} -exports.processChildContext = processChildContext; - -exports.pushContextProvider = function(workInProgress: Fiber): boolean { - if (!isContextProvider(workInProgress)) { - return false; - } - - const instance = workInProgress.stateNode; - // We push the context as early as possible to ensure stack integrity. - // If the instance does not exist yet, we will push null at first, - // and replace it on the stack later when invalidating the context. - const memoizedMergedChildContext = - (instance && instance.__reactInternalMemoizedMergedChildContext) || - emptyObject; - - // Remember the parent context so we can merge with it later. - previousContext = contextStackCursor.current; - push(contextStackCursor, memoizedMergedChildContext, workInProgress); - push(didPerformWorkStackCursor, false, workInProgress); - - return true; -}; - -exports.invalidateContextProvider = function(workInProgress: Fiber): void { - const instance = workInProgress.stateNode; - invariant(instance, 'Expected to have an instance by this point.'); - - // Merge parent and own context. - const mergedContext = processChildContext( - workInProgress, - previousContext, - true, - ); - instance.__reactInternalMemoizedMergedChildContext = mergedContext; - - // Replace the old (or empty) context with the new one. - // It is important to unwind the context in the reverse order. - pop(didPerformWorkStackCursor, workInProgress); - pop(contextStackCursor, workInProgress); - // Now push the new context and mark that it has changed. - push(contextStackCursor, mergedContext, workInProgress); - push(didPerformWorkStackCursor, true, workInProgress); -}; - -exports.resetContext = function(): void { - previousContext = emptyObject; - contextStackCursor.current = emptyObject; - didPerformWorkStackCursor.current = false; -}; - -exports.findCurrentUnmaskedContext = function(fiber: Fiber): Object { - // Currently this is only used with renderSubtreeIntoContainer; not sure if it - // makes sense elsewhere - invariant( - isFiberMounted(fiber) && fiber.tag === ClassComponent, - 'Expected subtree parent to be a mounted class component', - ); - - let node: Fiber = fiber; - while (node.tag !== HostRoot) { - if (isContextProvider(node)) { - return node.stateNode.__reactInternalMemoizedMergedChildContext; - } - const parent = node.return; - invariant(parent, 'Found unexpected detached subtree parent'); - node = parent; - } - return node.stateNode.context; -}; diff --git a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberDevToolsHook.js b/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberDevToolsHook.js deleted file mode 100644 index dbf88b8349..0000000000 --- a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberDevToolsHook.js +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactFiberDevToolsHook - * @flow - */ - -'use strict'; - -var warning = require('fbjs/lib/warning'); - -import type {Fiber} from 'ReactFiber'; -import type {FiberRoot} from 'ReactFiberRoot'; - -declare var __REACT_DEVTOOLS_GLOBAL_HOOK__: Object | void; - -let rendererID = null; -let injectInternals = null; -let onCommitRoot = null; -let onCommitUnmount = null; -if ( - typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && - __REACT_DEVTOOLS_GLOBAL_HOOK__.supportsFiber -) { - let { - inject, - onCommitFiberRoot, - onCommitFiberUnmount, - } = __REACT_DEVTOOLS_GLOBAL_HOOK__; - - injectInternals = function(internals: Object) { - warning(rendererID == null, 'Cannot inject into DevTools twice.'); - rendererID = inject(internals); - }; - - onCommitRoot = function(root: FiberRoot) { - if (rendererID == null) { - return; - } - try { - onCommitFiberRoot(rendererID, root); - } catch (err) { - // Catch all errors because it is unsafe to throw in the commit phase. - if (__DEV__) { - warning(false, 'React DevTools encountered an error: %s', err); - } - } - }; - - onCommitUnmount = function(fiber: Fiber) { - if (rendererID == null) { - return; - } - try { - onCommitFiberUnmount(rendererID, fiber); - } catch (err) { - // Catch all errors because it is unsafe to throw in the commit phase. - if (__DEV__) { - warning(false, 'React DevTools encountered an error: %s', err); - } - } - }; -} - -exports.injectInternals = injectInternals; -exports.onCommitRoot = onCommitRoot; -exports.onCommitUnmount = onCommitUnmount; diff --git a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberErrorLogger.js b/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberErrorLogger.js deleted file mode 100644 index 9289f00a75..0000000000 --- a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberErrorLogger.js +++ /dev/null @@ -1,116 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactFiberErrorLogger - * @flow - */ - -'use strict'; - -const invariant = require('fbjs/lib/invariant'); - -import type {CapturedError} from 'ReactFiberScheduler'; - -const defaultShowDialog = (capturedError: CapturedError) => true; - -let showDialog = defaultShowDialog; - -function logCapturedError(capturedError: CapturedError): void { - const logError = showDialog(capturedError); - - // Allow injected showDialog() to prevent default console.error logging. - // This enables renderers like ReactNative to better manage redbox behavior. - if (logError === false) { - return; - } - - if (__DEV__) { - const { - componentName, - componentStack, - error, - errorBoundaryName, - errorBoundaryFound, - willRetry, - } = capturedError; - - const {message, name, stack} = error; - - const errorSummary = message ? `${name}: ${message}` : name; - - const componentNameMessage = componentName - ? `React caught an error thrown by ${componentName}.` - : 'React caught an error thrown by one of your components.'; - - // Error stack varies by browser, eg: - // Chrome prepends the Error name and type. - // Firefox, Safari, and IE don't indent the stack lines. - // Format it in a consistent way for error logging. - let formattedCallStack = stack.slice(0, errorSummary.length) === - errorSummary - ? stack.slice(errorSummary.length) - : stack; - formattedCallStack = formattedCallStack - .trim() - .split('\n') - .map(line => `\n ${line.trim()}`) - .join(); - - let errorBoundaryMessage; - // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow. - if (errorBoundaryFound && errorBoundaryName) { - if (willRetry) { - errorBoundaryMessage = - `React will try to recreate this component tree from scratch ` + - `using the error boundary you provided, ${errorBoundaryName}.`; - } else { - errorBoundaryMessage = - `This error was initially handled by the error boundary ${errorBoundaryName}. ` + - `Recreating the tree from scratch failed so React will unmount the tree.`; - } - } else { - // TODO Link to unstable_handleError() documentation once it exists. - errorBoundaryMessage = - 'Consider adding an error boundary to your tree to customize error handling behavior.'; - } - - console.error( - `${componentNameMessage} You should fix this error in your code. ${errorBoundaryMessage}\n\n` + - `${errorSummary}\n\n` + - `The error is located at: ${componentStack}\n\n` + - `The error was thrown at: ${formattedCallStack}`, - ); - } - - if (!__DEV__) { - const {error} = capturedError; - console.error( - `React caught an error thrown by one of your components.\n\n${error.stack}`, - ); - } -} - -exports.injection = { - /** - * Display custom dialog for lifecycle errors. - * Return false to prevent default behavior of logging to console.error. - */ - injectDialog(fn: (e: CapturedError) => boolean) { - invariant( - showDialog === defaultShowDialog, - 'The custom dialog was already injected.', - ); - invariant( - typeof fn === 'function', - 'Injected showDialog() must be a function.', - ); - showDialog = fn; - }, -}; - -exports.logCapturedError = logCapturedError; diff --git a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberHostContext.js b/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberHostContext.js deleted file mode 100644 index 448bd8c72e..0000000000 --- a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberHostContext.js +++ /dev/null @@ -1,130 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactFiberHostContext - * @flow - */ - -'use strict'; - -import type {Fiber} from 'ReactFiber'; -import type {HostConfig} from 'ReactFiberReconciler'; -import type {StackCursor} from 'ReactFiberStack'; - -const {createCursor, pop, push} = require('ReactFiberStack'); - -const invariant = require('fbjs/lib/invariant'); - -declare class NoContextT {} -const NO_CONTEXT: NoContextT = ({}: any); - -export type HostContext = { - getHostContext(): CX, - getRootHostContainer(): C, - popHostContainer(fiber: Fiber): void, - popHostContext(fiber: Fiber): void, - pushHostContainer(fiber: Fiber, container: C): void, - pushHostContext(fiber: Fiber): void, - resetHostContainer(): void, -}; - -module.exports = function( - config: HostConfig, -): HostContext { - const {getChildHostContext, getRootHostContext} = config; - - let contextStackCursor: StackCursor = createCursor( - NO_CONTEXT, - ); - let contextFiberStackCursor: StackCursor = createCursor( - NO_CONTEXT, - ); - let rootInstanceStackCursor: StackCursor = createCursor( - NO_CONTEXT, - ); - - function requiredContext(c: Value | NoContextT): Value { - invariant( - c !== NO_CONTEXT, - 'Expected host context to exist. This error is likely caused by a bug ' + - 'in React. Please file an issue.', - ); - return (c: any); - } - - function getRootHostContainer(): C { - const rootInstance = requiredContext(rootInstanceStackCursor.current); - return rootInstance; - } - - function pushHostContainer(fiber: Fiber, nextRootInstance: C) { - // Push current root instance onto the stack; - // This allows us to reset root when portals are popped. - push(rootInstanceStackCursor, nextRootInstance, fiber); - - const nextRootContext = getRootHostContext(nextRootInstance); - - // Track the context and the Fiber that provided it. - // This enables us to pop only Fibers that provide unique contexts. - push(contextFiberStackCursor, fiber, fiber); - push(contextStackCursor, nextRootContext, fiber); - } - - function popHostContainer(fiber: Fiber) { - pop(contextStackCursor, fiber); - pop(contextFiberStackCursor, fiber); - pop(rootInstanceStackCursor, fiber); - } - - function getHostContext(): CX { - const context = requiredContext(contextStackCursor.current); - return context; - } - - function pushHostContext(fiber: Fiber): void { - const rootInstance = requiredContext(rootInstanceStackCursor.current); - const context = requiredContext(contextStackCursor.current); - const nextContext = getChildHostContext(context, fiber.type, rootInstance); - - // Don't push this Fiber's context unless it's unique. - if (context === nextContext) { - return; - } - - // Track the context and the Fiber that provided it. - // This enables us to pop only Fibers that provide unique contexts. - push(contextFiberStackCursor, fiber, fiber); - push(contextStackCursor, nextContext, fiber); - } - - function popHostContext(fiber: Fiber): void { - // Do not pop unless this Fiber provided the current context. - // pushHostContext() only pushes Fibers that provide unique contexts. - if (contextFiberStackCursor.current !== fiber) { - return; - } - - pop(contextStackCursor, fiber); - pop(contextFiberStackCursor, fiber); - } - - function resetHostContainer() { - contextStackCursor.current = NO_CONTEXT; - rootInstanceStackCursor.current = NO_CONTEXT; - } - - return { - getHostContext, - getRootHostContainer, - popHostContainer, - popHostContext, - pushHostContainer, - pushHostContext, - resetHostContainer, - }; -}; diff --git a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberInstrumentation.js b/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberInstrumentation.js deleted file mode 100644 index bb2abc533b..0000000000 --- a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberInstrumentation.js +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactFiberInstrumentation - * @flow - */ - -'use strict'; - -// This lets us hook into Fiber to debug what it's doing. -// See https://github.com/facebook/react/pull/8033. -// This is not part of the public API, not even for React DevTools. -// You may only inject a debugTool if you work on React Fiber itself. -var ReactFiberInstrumentation = { - debugTool: null, -}; - -module.exports = ReactFiberInstrumentation; diff --git a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberReconciler.js b/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberReconciler.js deleted file mode 100644 index a081838df8..0000000000 --- a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberReconciler.js +++ /dev/null @@ -1,271 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactFiberReconciler - * @flow - */ - -'use strict'; - -import type {Fiber} from 'ReactFiber'; -import type {FiberRoot} from 'ReactFiberRoot'; -import type {PriorityLevel} from 'ReactPriorityLevel'; -import type {ReactNodeList} from 'ReactTypes'; - -var ReactFeatureFlags = require('ReactFeatureFlags'); - -var {addTopLevelUpdate} = require('ReactFiberUpdateQueue'); - -var { - findCurrentUnmaskedContext, - isContextProvider, - processChildContext, -} = require('ReactFiberContext'); -var {createFiberRoot} = require('ReactFiberRoot'); -var ReactFiberScheduler = require('ReactFiberScheduler'); - -if (__DEV__) { - var warning = require('fbjs/lib/warning'); - var ReactFiberInstrumentation = require('ReactFiberInstrumentation'); - var ReactDebugCurrentFiber = require('ReactDebugCurrentFiber'); - var getComponentName = require('getComponentName'); -} - -var {findCurrentHostFiber} = require('ReactFiberTreeReflection'); - -var getContextForSubtree = require('getContextForSubtree'); - -export type Deadline = { - timeRemaining: () => number, -}; - -type OpaqueHandle = Fiber; -type OpaqueRoot = FiberRoot; - -export type HostConfig = { - getRootHostContext(rootContainerInstance: C): CX, - getChildHostContext(parentHostContext: CX, type: T, instance: C): CX, - getPublicInstance(instance: I | TI): PI, - - createInstance( - type: T, - props: P, - rootContainerInstance: C, - hostContext: CX, - internalInstanceHandle: OpaqueHandle, - ): I, - appendInitialChild(parentInstance: I, child: I | TI): void, - finalizeInitialChildren( - parentInstance: I, - type: T, - props: P, - rootContainerInstance: C, - ): boolean, - - prepareUpdate( - instance: I, - type: T, - oldProps: P, - newProps: P, - rootContainerInstance: C, - hostContext: CX, - ): null | PL, - commitUpdate( - instance: I, - updatePayload: PL, - type: T, - oldProps: P, - newProps: P, - internalInstanceHandle: OpaqueHandle, - ): void, - commitMount( - instance: I, - type: T, - newProps: P, - internalInstanceHandle: OpaqueHandle, - ): void, - - shouldSetTextContent(props: P): boolean, - resetTextContent(instance: I): void, - shouldDeprioritizeSubtree(type: T, props: P): boolean, - - createTextInstance( - text: string, - rootContainerInstance: C, - hostContext: CX, - internalInstanceHandle: OpaqueHandle, - ): TI, - commitTextUpdate(textInstance: TI, oldText: string, newText: string): void, - - appendChild(parentInstance: I | C, child: I | TI): void, - insertBefore(parentInstance: I | C, child: I | TI, beforeChild: I | TI): void, - removeChild(parentInstance: I | C, child: I | TI): void, - - scheduleAnimationCallback(callback: () => void): number | void, - scheduleDeferredCallback( - callback: (deadline: Deadline) => void, - ): number | void, - - prepareForCommit(): void, - resetAfterCommit(): void, - - useSyncScheduling?: boolean, -}; - -export type Reconciler = { - createContainer(containerInfo: C): OpaqueRoot, - updateContainer( - element: ReactNodeList, - container: OpaqueRoot, - parentComponent: ?ReactComponent, - callback: ?Function, - ): void, - performWithPriority(priorityLevel: PriorityLevel, fn: Function): void, - batchedUpdates(fn: () => A): A, - unbatchedUpdates(fn: () => A): A, - syncUpdates(fn: () => A): A, - deferredUpdates(fn: () => A): A, - - // Used to extract the return value from the initial render. Legacy API. - getPublicRootInstance( - container: OpaqueRoot, - ): ReactComponent | TI | I | null, - - // Use for findDOMNode/findHostNode. Legacy API. - findHostInstance(component: Fiber): I | TI | null, -}; - -getContextForSubtree._injectFiber(function(fiber: Fiber) { - const parentContext = findCurrentUnmaskedContext(fiber); - return isContextProvider(fiber) - ? processChildContext(fiber, parentContext, false) - : parentContext; -}); - -module.exports = function( - config: HostConfig, -): Reconciler { - var { - scheduleUpdate, - getPriorityContext, - performWithPriority, - batchedUpdates, - unbatchedUpdates, - syncUpdates, - deferredUpdates, - } = ReactFiberScheduler(config); - - function scheduleTopLevelUpdate( - current: Fiber, - element: ReactNodeList, - callback: ?Function, - ) { - if (__DEV__) { - if ( - ReactDebugCurrentFiber.phase === 'render' && - ReactDebugCurrentFiber.current !== null - ) { - warning( - false, - 'Render methods should be a pure function of props and state; ' + - 'triggering nested component updates from render is not allowed. ' + - 'If necessary, trigger nested updates in componentDidUpdate.\n\n' + - 'Check the render method of %s.', - getComponentName(ReactDebugCurrentFiber.current) || 'Unknown', - ); - } - } - - // Check if the top-level element is an async wrapper component. If so, treat - // updates to the root as async. This is a bit weird but lets us avoid a separate - // `renderAsync` API. - const forceAsync = - (ReactFeatureFlags : any).enableAsyncSubtreeAPI && - element != null && - element.type != null && - (element.type: any).unstable_asyncUpdates === true; - const priorityLevel = getPriorityContext(current, forceAsync); - const nextState = {element}; - callback = callback === undefined ? null : callback; - if (__DEV__) { - warning( - callback === null || typeof callback === 'function', - 'render(...): Expected the last optional `callback` argument to be a ' + - 'function. Instead received: %s.', - callback, - ); - } - addTopLevelUpdate(current, nextState, callback, priorityLevel); - scheduleUpdate(current, priorityLevel); - } - - return { - createContainer(containerInfo: C): OpaqueRoot { - return createFiberRoot(containerInfo); - }, - - updateContainer( - element: ReactNodeList, - container: OpaqueRoot, - parentComponent: ?ReactComponent, - callback: ?Function, - ): void { - // TODO: If this is a nested container, this won't be the root. - const current = container.current; - - if (__DEV__) { - if (ReactFiberInstrumentation.debugTool) { - if (current.alternate === null) { - ReactFiberInstrumentation.debugTool.onMountContainer(container); - } else if (element === null) { - ReactFiberInstrumentation.debugTool.onUnmountContainer(container); - } else { - ReactFiberInstrumentation.debugTool.onUpdateContainer(container); - } - } - } - - const context = getContextForSubtree(parentComponent); - if (container.context === null) { - container.context = context; - } else { - container.pendingContext = context; - } - - scheduleTopLevelUpdate(current, element, callback); - }, - - performWithPriority, - - batchedUpdates, - - unbatchedUpdates, - - syncUpdates, - - deferredUpdates, - - getPublicRootInstance( - container: OpaqueRoot, - ): ReactComponent | I | TI | null { - const containerFiber = container.current; - if (!containerFiber.child) { - return null; - } - return containerFiber.child.stateNode; - }, - - findHostInstance(fiber: Fiber): I | TI | null { - const hostFiber = findCurrentHostFiber(fiber); - if (hostFiber === null) { - return null; - } - return hostFiber.stateNode; - }, - }; -}; diff --git a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberRoot.js b/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberRoot.js deleted file mode 100644 index 409b706554..0000000000 --- a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberRoot.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactFiberRoot - * @flow - */ - -'use strict'; - -import type {Fiber} from 'ReactFiber'; - -const {createHostRootFiber} = require('ReactFiber'); - -export type FiberRoot = { - // Any additional information from the host associated with this root. - containerInfo: any, - // The currently active root fiber. This is the mutable root of the tree. - current: Fiber, - // Determines if this root has already been added to the schedule for work. - isScheduled: boolean, - // The work schedule is a linked list. - nextScheduledRoot: FiberRoot | null, - // Top context object, used by renderSubtreeIntoContainer - context: Object | null, - pendingContext: Object | null, -}; - -exports.createFiberRoot = function(containerInfo: any): FiberRoot { - // Cyclic construction. This cheats the type system right now because - // stateNode is any. - const uninitializedFiber = createHostRootFiber(); - const root = { - current: uninitializedFiber, - containerInfo: containerInfo, - isScheduled: false, - nextScheduledRoot: null, - context: null, - pendingContext: null, - }; - uninitializedFiber.stateNode = root; - return root; -}; diff --git a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberScheduler.js b/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberScheduler.js deleted file mode 100644 index b889c8157d..0000000000 --- a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberScheduler.js +++ /dev/null @@ -1,1439 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactFiberScheduler - * @flow - */ - -'use strict'; - -import type {Fiber} from 'ReactFiber'; -import type {FiberRoot} from 'ReactFiberRoot'; -import type {HostConfig, Deadline} from 'ReactFiberReconciler'; -import type {PriorityLevel} from 'ReactPriorityLevel'; - -export type CapturedError = { - componentName: ?string, - componentStack: string, - error: Error, - errorBoundary: ?Object, - errorBoundaryFound: boolean, - errorBoundaryName: string | null, - willRetry: boolean, -}; - -export type HandleErrorInfo = { - componentStack: string, -}; - -var {popContextProvider} = require('ReactFiberContext'); -const {reset} = require('ReactFiberStack'); -var { - getStackAddendumByWorkInProgressFiber, -} = require('ReactFiberComponentTreeHook'); -var {logCapturedError} = require('ReactFiberErrorLogger'); -var {invokeGuardedCallback} = require('ReactErrorUtils'); - -var ReactFiberBeginWork = require('ReactFiberBeginWork'); -var ReactFiberCompleteWork = require('ReactFiberCompleteWork'); -var ReactFiberCommitWork = require('ReactFiberCommitWork'); -var ReactFiberHostContext = require('ReactFiberHostContext'); -var ReactFeatureFlags = require('ReactFeatureFlags'); -var {ReactCurrentOwner} = require('ReactGlobalSharedState'); -var getComponentName = require('getComponentName'); - -var {cloneFiber} = require('ReactFiber'); -var {onCommitRoot} = require('ReactFiberDevToolsHook'); - -var { - NoWork, - SynchronousPriority, - TaskPriority, - AnimationPriority, - HighPriority, - LowPriority, - OffscreenPriority, -} = require('ReactPriorityLevel'); - -var {AsyncUpdates} = require('ReactTypeOfInternalContext'); - -var { - NoEffect, - Placement, - Update, - PlacementAndUpdate, - Deletion, - ContentReset, - Callback, - Err, - Ref, -} = require('ReactTypeOfSideEffect'); - -var { - HostRoot, - HostComponent, - HostPortal, - ClassComponent, -} = require('ReactTypeOfWork'); - -var {getPendingPriority} = require('ReactFiberUpdateQueue'); - -var {resetContext} = require('ReactFiberContext'); - -var invariant = require('fbjs/lib/invariant'); - -if (__DEV__) { - var warning = require('fbjs/lib/warning'); - var ReactFiberInstrumentation = require('ReactFiberInstrumentation'); - var ReactDebugCurrentFiber = require('ReactDebugCurrentFiber'); - var { - recordEffect, - recordScheduleUpdate, - startWorkTimer, - stopWorkTimer, - startWorkLoopTimer, - stopWorkLoopTimer, - startCommitTimer, - stopCommitTimer, - startCommitHostEffectsTimer, - stopCommitHostEffectsTimer, - startCommitLifeCyclesTimer, - stopCommitLifeCyclesTimer, - } = require('ReactDebugFiberPerf'); - - var warnAboutUpdateOnUnmounted = function(instance: ReactClass) { - const ctor = instance.constructor; - warning( - false, - 'Can only update a mounted or mounting component. This usually means ' + - 'you called setState, replaceState, or forceUpdate on an unmounted ' + - 'component. This is a no-op.\n\nPlease check the code for the ' + - '%s component.', - (ctor && (ctor.displayName || ctor.name)) || 'ReactClass', - ); - }; - - var warnAboutInvalidUpdates = function(instance: ReactClass) { - switch (ReactDebugCurrentFiber.phase) { - case 'getChildContext': - warning( - false, - 'setState(...): Cannot call setState() inside getChildContext()', - ); - break; - case 'render': - warning( - false, - 'Cannot update during an existing state transition (such as within ' + - "`render` or another component's constructor). Render methods should " + - 'be a pure function of props and state; constructor side-effects are ' + - 'an anti-pattern, but can be moved to `componentWillMount`.', - ); - break; - } - }; -} - -var timeHeuristicForUnitOfWork = 1; - -module.exports = function( - config: HostConfig, -) { - const hostContext = ReactFiberHostContext(config); - const {popHostContainer, popHostContext, resetHostContainer} = hostContext; - const {beginWork, beginFailedWork} = ReactFiberBeginWork( - config, - hostContext, - scheduleUpdate, - getPriorityContext, - ); - const {completeWork} = ReactFiberCompleteWork(config, hostContext); - const { - commitPlacement, - commitDeletion, - commitWork, - commitLifeCycles, - commitAttachRef, - commitDetachRef, - } = ReactFiberCommitWork(config, captureError); - const { - scheduleAnimationCallback: hostScheduleAnimationCallback, - scheduleDeferredCallback: hostScheduleDeferredCallback, - useSyncScheduling, - prepareForCommit, - resetAfterCommit, - } = config; - - // The priority level to use when scheduling an update. We use NoWork to - // represent the default priority. - // TODO: Should we change this to an array instead of using the call stack? - // Might be less confusing. - let priorityContext: PriorityLevel = NoWork; - - // Keep track of this so we can reset the priority context if an error - // is thrown during reconciliation. - let priorityContextBeforeReconciliation: PriorityLevel = NoWork; - - // Keeps track of whether we're currently in a work loop. - let isPerformingWork: boolean = false; - - // Keeps track of whether the current deadline has expired. - let deadlineHasExpired: boolean = false; - - // Keeps track of whether we should should batch sync updates. - let isBatchingUpdates: boolean = false; - - // The next work in progress fiber that we're currently working on. - let nextUnitOfWork: Fiber | null = null; - let nextPriorityLevel: PriorityLevel = NoWork; - - // The next fiber with an effect that we're currently committing. - let nextEffect: Fiber | null = null; - - let pendingCommit: Fiber | null = null; - - // Linked list of roots with scheduled work on them. - let nextScheduledRoot: FiberRoot | null = null; - let lastScheduledRoot: FiberRoot | null = null; - - // Keep track of which host environment callbacks are scheduled. - let isAnimationCallbackScheduled: boolean = false; - let isDeferredCallbackScheduled: boolean = false; - - // Keep track of which fibers have captured an error that need to be handled. - // Work is removed from this collection after unstable_handleError is called. - let capturedErrors: Map | null = null; - // Keep track of which fibers have failed during the current batch of work. - // This is a different set than capturedErrors, because it is not reset until - // the end of the batch. This is needed to propagate errors correctly if a - // subtree fails more than once. - let failedBoundaries: Set | null = null; - // Error boundaries that captured an error during the current commit. - let commitPhaseBoundaries: Set | null = null; - let firstUncaughtError: Error | null = null; - let fatalError: Error | null = null; - - let isCommitting: boolean = false; - let isUnmounting: boolean = false; - - function scheduleAnimationCallback(callback) { - if (!isAnimationCallbackScheduled) { - isAnimationCallbackScheduled = true; - hostScheduleAnimationCallback(callback); - } - } - - function scheduleDeferredCallback(callback) { - if (!isDeferredCallbackScheduled) { - isDeferredCallbackScheduled = true; - hostScheduleDeferredCallback(callback); - } - } - - function resetContextStack() { - // Reset the stack - reset(); - // Reset the cursors - resetContext(); - resetHostContainer(); - } - - // findNextUnitOfWork mutates the current priority context. It is reset after - // after the workLoop exits, so never call findNextUnitOfWork from outside - // the work loop. - function findNextUnitOfWork() { - // Clear out roots with no more work on them, or if they have uncaught errors - while ( - nextScheduledRoot !== null && - nextScheduledRoot.current.pendingWorkPriority === NoWork - ) { - // Unschedule this root. - nextScheduledRoot.isScheduled = false; - // Read the next pointer now. - // We need to clear it in case this root gets scheduled again later. - const next = nextScheduledRoot.nextScheduledRoot; - nextScheduledRoot.nextScheduledRoot = null; - // Exit if we cleared all the roots and there's no work to do. - if (nextScheduledRoot === lastScheduledRoot) { - nextScheduledRoot = null; - lastScheduledRoot = null; - nextPriorityLevel = NoWork; - return null; - } - // Continue with the next root. - // If there's no work on it, it will get unscheduled too. - nextScheduledRoot = next; - } - - let root = nextScheduledRoot; - let highestPriorityRoot = null; - let highestPriorityLevel = NoWork; - while (root !== null) { - if ( - root.current.pendingWorkPriority !== NoWork && - (highestPriorityLevel === NoWork || - highestPriorityLevel > root.current.pendingWorkPriority) - ) { - highestPriorityLevel = root.current.pendingWorkPriority; - highestPriorityRoot = root; - } - // We didn't find anything to do in this root, so let's try the next one. - root = root.nextScheduledRoot; - } - if (highestPriorityRoot !== null) { - nextPriorityLevel = highestPriorityLevel; - priorityContext = nextPriorityLevel; - - // Before we start any new work, let's make sure that we have a fresh - // stack to work from. - // TODO: This call is buried a bit too deep. It would be nice to have - // a single point which happens right before any new work and - // unfortunately this is it. - resetContextStack(); - - return cloneFiber(highestPriorityRoot.current, highestPriorityLevel); - } - - nextPriorityLevel = NoWork; - return null; - } - - function commitAllHostEffects() { - while (nextEffect !== null) { - if (__DEV__) { - ReactDebugCurrentFiber.current = nextEffect; - recordEffect(); - } - - const effectTag = nextEffect.effectTag; - if (effectTag & ContentReset) { - config.resetTextContent(nextEffect.stateNode); - } - - if (effectTag & Ref) { - const current = nextEffect.alternate; - if (current !== null) { - commitDetachRef(current); - } - } - - // The following switch statement is only concerned about placement, - // updates, and deletions. To avoid needing to add a case for every - // possible bitmap value, we remove the secondary effects from the - // effect tag and switch on that value. - let primaryEffectTag = effectTag & ~(Callback | Err | ContentReset | Ref); - switch (primaryEffectTag) { - case Placement: { - commitPlacement(nextEffect); - // Clear the "placement" from effect tag so that we know that this is inserted, before - // any life-cycles like componentDidMount gets called. - // TODO: findDOMNode doesn't rely on this any more but isMounted - // does and isMounted is deprecated anyway so we should be able - // to kill this. - nextEffect.effectTag &= ~Placement; - break; - } - case PlacementAndUpdate: { - // Placement - commitPlacement(nextEffect); - // Clear the "placement" from effect tag so that we know that this is inserted, before - // any life-cycles like componentDidMount gets called. - nextEffect.effectTag &= ~Placement; - - // Update - const current = nextEffect.alternate; - commitWork(current, nextEffect); - break; - } - case Update: { - const current = nextEffect.alternate; - commitWork(current, nextEffect); - break; - } - case Deletion: { - isUnmounting = true; - commitDeletion(nextEffect); - isUnmounting = false; - break; - } - } - nextEffect = nextEffect.nextEffect; - } - - if (__DEV__) { - ReactDebugCurrentFiber.current = null; - } - } - - function commitAllLifeCycles() { - while (nextEffect !== null) { - const effectTag = nextEffect.effectTag; - - // Use Task priority for lifecycle updates - if (effectTag & (Update | Callback)) { - if (__DEV__) { - recordEffect(); - } - const current = nextEffect.alternate; - commitLifeCycles(current, nextEffect); - } - - if (effectTag & Ref) { - if (__DEV__) { - recordEffect(); - } - commitAttachRef(nextEffect); - } - - if (effectTag & Err) { - if (__DEV__) { - recordEffect(); - } - commitErrorHandling(nextEffect); - } - - const next = nextEffect.nextEffect; - // Ensure that we clean these up so that we don't accidentally keep them. - // I'm not actually sure this matters because we can't reset firstEffect - // and lastEffect since they're on every node, not just the effectful - // ones. So we have to clean everything as we reuse nodes anyway. - nextEffect.nextEffect = null; - // Ensure that we reset the effectTag here so that we can rely on effect - // tags to reason about the current life-cycle. - nextEffect = next; - } - } - - function commitAllWork(finishedWork: Fiber) { - // We keep track of this so that captureError can collect any boundaries - // that capture an error during the commit phase. The reason these aren't - // local to this function is because errors that occur during cWU are - // captured elsewhere, to prevent the unmount from being interrupted. - isCommitting = true; - if (__DEV__) { - startCommitTimer(); - } - - pendingCommit = null; - const root: FiberRoot = (finishedWork.stateNode: any); - invariant( - root.current !== finishedWork, - 'Cannot commit the same tree as before. This is probably a bug ' + - 'related to the return field. This error is likely caused by a bug ' + - 'in React. Please file an issue.', - ); - - // Reset this to null before calling lifecycles - ReactCurrentOwner.current = null; - - // Updates that occur during the commit phase should have Task priority - const previousPriorityContext = priorityContext; - priorityContext = TaskPriority; - - let firstEffect; - if (finishedWork.effectTag !== NoEffect) { - // A fiber's effect list consists only of its children, not itself. So if - // the root has an effect, we need to add it to the end of the list. The - // resulting list is the set that would belong to the root's parent, if - // it had one; that is, all the effects in the tree including the root. - if (finishedWork.lastEffect !== null) { - finishedWork.lastEffect.nextEffect = finishedWork; - firstEffect = finishedWork.firstEffect; - } else { - firstEffect = finishedWork; - } - } else { - // There is no effect on the root. - firstEffect = finishedWork.firstEffect; - } - - prepareForCommit(); - - // Commit all the side-effects within a tree. We'll do this in two passes. - // The first pass performs all the host insertions, updates, deletions and - // ref unmounts. - nextEffect = firstEffect; - if (__DEV__) { - startCommitHostEffectsTimer(); - } - while (nextEffect !== null) { - let error = null; - if (__DEV__) { - error = invokeGuardedCallback( - null, - commitAllHostEffects, - null, - ); - } else { - try { - commitAllHostEffects(); - } catch (e) { - error = e; - } - } - if (error !== null) { - invariant( - nextEffect !== null, - 'Should have next effect. This error is likely caused by a bug ' + - 'in React. Please file an issue.', - ); - captureError(nextEffect, error); - // Clean-up - if (nextEffect !== null) { - nextEffect = nextEffect.nextEffect; - } - } - } - if (__DEV__) { - stopCommitHostEffectsTimer(); - } - - resetAfterCommit(); - - // The work-in-progress tree is now the current tree. This must come after - // the first pass of the commit phase, so that the previous tree is still - // current during componentWillUnmount, but before the second pass, so that - // the finished work is current during componentDidMount/Update. - root.current = finishedWork; - - // In the second pass we'll perform all life-cycles and ref callbacks. - // Life-cycles happen as a separate pass so that all placements, updates, - // and deletions in the entire tree have already been invoked. - // This pass also triggers any renderer-specific initial effects. - nextEffect = firstEffect; - if (__DEV__) { - startCommitLifeCyclesTimer(); - } - while (nextEffect !== null) { - let error = null; - if (__DEV__) { - error = invokeGuardedCallback( - null, - commitAllLifeCycles, - null, - ); - } else { - try { - commitAllLifeCycles(); - } catch (e) { - error = e; - } - } - if (error !== null) { - invariant( - nextEffect !== null, - 'Should have next effect. This error is likely caused by a bug ' + - 'in React. Please file an issue.', - ); - captureError(nextEffect, error); - if (nextEffect !== null) { - nextEffect = nextEffect.nextEffect; - } - } - } - - isCommitting = false; - if (__DEV__) { - stopCommitLifeCyclesTimer(); - stopCommitTimer(); - } - if (typeof onCommitRoot === 'function') { - onCommitRoot(finishedWork.stateNode); - } - if (__DEV__ && ReactFiberInstrumentation.debugTool) { - ReactFiberInstrumentation.debugTool.onCommitWork(finishedWork); - } - - // If we caught any errors during this commit, schedule their boundaries - // to update. - if (commitPhaseBoundaries) { - commitPhaseBoundaries.forEach(scheduleErrorRecovery); - commitPhaseBoundaries = null; - } - - priorityContext = previousPriorityContext; - } - - function resetWorkPriority(workInProgress: Fiber) { - let newPriority = NoWork; - - // Check for pending update priority. This is usually null so it shouldn't - // be a perf issue. - const queue = workInProgress.updateQueue; - const tag = workInProgress.tag; - if ( - queue !== null && - // TODO: Revisit once updateQueue is typed properly to distinguish between - // update payloads for host components and update queues for composites - (tag === ClassComponent || tag === HostRoot) - ) { - newPriority = getPendingPriority(queue); - } - - // TODO: Coroutines need to visit stateNode - - // progressedChild is going to be the child set with the highest priority. - // Either it is the same as child, or it just bailed out because it choose - // not to do the work. - let child = workInProgress.progressedChild; - while (child !== null) { - // Ensure that remaining work priority bubbles up. - if ( - child.pendingWorkPriority !== NoWork && - (newPriority === NoWork || newPriority > child.pendingWorkPriority) - ) { - newPriority = child.pendingWorkPriority; - } - child = child.sibling; - } - workInProgress.pendingWorkPriority = newPriority; - } - - function completeUnitOfWork(workInProgress: Fiber): Fiber | null { - while (true) { - // The current, flushed, state of this fiber is the alternate. - // Ideally nothing should rely on this, but relying on it here - // means that we don't need an additional field on the work in - // progress. - const current = workInProgress.alternate; - const next = completeWork(current, workInProgress); - - const returnFiber = workInProgress.return; - const siblingFiber = workInProgress.sibling; - - resetWorkPriority(workInProgress); - - if (next !== null) { - if (__DEV__) { - stopWorkTimer(workInProgress); - } - if (__DEV__ && ReactFiberInstrumentation.debugTool) { - ReactFiberInstrumentation.debugTool.onCompleteWork(workInProgress); - } - // If completing this work spawned new work, do that next. We'll come - // back here again. - return next; - } - - if (returnFiber !== null) { - // Append all the effects of the subtree and this fiber onto the effect - // list of the parent. The completion order of the children affects the - // side-effect order. - if (returnFiber.firstEffect === null) { - returnFiber.firstEffect = workInProgress.firstEffect; - } - if (workInProgress.lastEffect !== null) { - if (returnFiber.lastEffect !== null) { - returnFiber.lastEffect.nextEffect = workInProgress.firstEffect; - } - returnFiber.lastEffect = workInProgress.lastEffect; - } - - // If this fiber had side-effects, we append it AFTER the children's - // side-effects. We can perform certain side-effects earlier if - // needed, by doing multiple passes over the effect list. We don't want - // to schedule our own side-effect on our own list because if end up - // reusing children we'll schedule this effect onto itself since we're - // at the end. - if (workInProgress.effectTag !== NoEffect) { - if (returnFiber.lastEffect !== null) { - returnFiber.lastEffect.nextEffect = workInProgress; - } else { - returnFiber.firstEffect = workInProgress; - } - returnFiber.lastEffect = workInProgress; - } - } - - if (__DEV__) { - stopWorkTimer(workInProgress); - } - if (__DEV__ && ReactFiberInstrumentation.debugTool) { - ReactFiberInstrumentation.debugTool.onCompleteWork(workInProgress); - } - - if (siblingFiber !== null) { - // If there is more work to do in this returnFiber, do that next. - return siblingFiber; - } else if (returnFiber !== null) { - // If there's no more work in this returnFiber. Complete the returnFiber. - workInProgress = returnFiber; - continue; - } else { - // We've reached the root. Unless we're current performing deferred - // work, we should commit the completed work immediately. If we are - // performing deferred work, returning null indicates to the caller - // that we just completed the root so they can handle that case correctly. - if (nextPriorityLevel < HighPriority) { - // Otherwise, we should commit immediately. - commitAllWork(workInProgress); - } else { - pendingCommit = workInProgress; - } - return null; - } - } - - // Without this explicit null return Flow complains of invalid return type - // TODO Remove the above while(true) loop - // eslint-disable-next-line no-unreachable - return null; - } - - function performUnitOfWork(workInProgress: Fiber): Fiber | null { - // The current, flushed, state of this fiber is the alternate. - // Ideally nothing should rely on this, but relying on it here - // means that we don't need an additional field on the work in - // progress. - const current = workInProgress.alternate; - - // See if beginning this work spawns more work. - if (__DEV__) { - startWorkTimer(workInProgress); - } - let next = beginWork(current, workInProgress, nextPriorityLevel); - if (__DEV__ && ReactFiberInstrumentation.debugTool) { - ReactFiberInstrumentation.debugTool.onBeginWork(workInProgress); - } - - if (next === null) { - // If this doesn't spawn new work, complete the current work. - next = completeUnitOfWork(workInProgress); - } - - ReactCurrentOwner.current = null; - if (__DEV__) { - ReactDebugCurrentFiber.current = null; - } - - return next; - } - - function performFailedUnitOfWork(workInProgress: Fiber): Fiber | null { - // The current, flushed, state of this fiber is the alternate. - // Ideally nothing should rely on this, but relying on it here - // means that we don't need an additional field on the work in - // progress. - const current = workInProgress.alternate; - - // See if beginning this work spawns more work. - if (__DEV__) { - startWorkTimer(workInProgress); - } - let next = beginFailedWork(current, workInProgress, nextPriorityLevel); - if (__DEV__ && ReactFiberInstrumentation.debugTool) { - ReactFiberInstrumentation.debugTool.onBeginWork(workInProgress); - } - - if (next === null) { - // If this doesn't spawn new work, complete the current work. - next = completeUnitOfWork(workInProgress); - } - - ReactCurrentOwner.current = null; - if (__DEV__) { - ReactDebugCurrentFiber.current = null; - } - - return next; - } - - function performDeferredWork(deadline) { - // We pass the lowest deferred priority here because it acts as a minimum. - // Higher priorities will also be performed. - isDeferredCallbackScheduled = false; - performWork(OffscreenPriority, deadline); - } - - function performAnimationWork() { - isAnimationCallbackScheduled = false; - performWork(AnimationPriority, null); - } - - function clearErrors() { - if (nextUnitOfWork === null) { - nextUnitOfWork = findNextUnitOfWork(); - } - // Keep performing work until there are no more errors - while ( - capturedErrors !== null && - capturedErrors.size && - nextUnitOfWork !== null && - nextPriorityLevel !== NoWork && - nextPriorityLevel <= TaskPriority - ) { - if (hasCapturedError(nextUnitOfWork)) { - // Use a forked version of performUnitOfWork - nextUnitOfWork = performFailedUnitOfWork(nextUnitOfWork); - } else { - nextUnitOfWork = performUnitOfWork(nextUnitOfWork); - } - if (nextUnitOfWork === null) { - // If performUnitOfWork returns null, that means we just committed - // a root. Normally we'd need to clear any errors that were scheduled - // during the commit phase. But we're already clearing errors, so - // we can continue. - nextUnitOfWork = findNextUnitOfWork(); - } - } - } - - function workLoop(priorityLevel, deadline: Deadline | null) { - // Clear any errors. - clearErrors(); - - if (nextUnitOfWork === null) { - nextUnitOfWork = findNextUnitOfWork(); - } - - let hostRootTimeMarker; - if ( - ReactFeatureFlags.logTopLevelRenders && - nextUnitOfWork !== null && - nextUnitOfWork.tag === HostRoot && - nextUnitOfWork.child !== null - ) { - const componentName = getComponentName(nextUnitOfWork.child) || ''; - hostRootTimeMarker = 'React update: ' + componentName; - console.time(hostRootTimeMarker); - } - - // If there's a deadline, and we're not performing Task work, perform work - // using this loop that checks the deadline on every iteration. - if (deadline !== null && priorityLevel > TaskPriority) { - // The deferred work loop will run until there's no time left in - // the current frame. - while (nextUnitOfWork !== null && !deadlineHasExpired) { - if (deadline.timeRemaining() > timeHeuristicForUnitOfWork) { - nextUnitOfWork = performUnitOfWork(nextUnitOfWork); - // In a deferred work batch, iff nextUnitOfWork returns null, we just - // completed a root and a pendingCommit exists. Logically, we could - // omit either of the checks in the following condition, but we need - // both to satisfy Flow. - if (nextUnitOfWork === null && pendingCommit !== null) { - // If we have time, we should commit the work now. - if (deadline.timeRemaining() > timeHeuristicForUnitOfWork) { - commitAllWork(pendingCommit); - nextUnitOfWork = findNextUnitOfWork(); - // Clear any errors that were scheduled during the commit phase. - clearErrors(); - } else { - deadlineHasExpired = true; - } - // Otherwise the root will committed in the next frame. - } - } else { - deadlineHasExpired = true; - } - } - } else { - // If there's no deadline, or if we're performing Task work, use this loop - // that doesn't check how much time is remaining. It will keep running - // until we run out of work at this priority level. - while ( - nextUnitOfWork !== null && - nextPriorityLevel !== NoWork && - nextPriorityLevel <= priorityLevel - ) { - nextUnitOfWork = performUnitOfWork(nextUnitOfWork); - if (nextUnitOfWork === null) { - nextUnitOfWork = findNextUnitOfWork(); - // performUnitOfWork returned null, which means we just committed a - // root. Clear any errors that were scheduled during the commit phase. - clearErrors(); - } - } - } - - if (hostRootTimeMarker) { - console.timeEnd(hostRootTimeMarker); - } - } - - function performWork( - priorityLevel: PriorityLevel, - deadline: Deadline | null, - ) { - if (__DEV__) { - startWorkLoopTimer(); - } - - invariant( - !isPerformingWork, - 'performWork was called recursively. This error is likely caused ' + - 'by a bug in React. Please file an issue.', - ); - isPerformingWork = true; - const isPerformingDeferredWork = !!deadline; - - // This outer loop exists so that we can restart the work loop after - // catching an error. It also lets us flush Task work at the end of a - // deferred batch. - while (priorityLevel !== NoWork && !fatalError) { - invariant( - deadline !== null || priorityLevel < HighPriority, - 'Cannot perform deferred work without a deadline. This error is ' + - 'likely caused by a bug in React. Please file an issue.', - ); - - // Before starting any work, check to see if there are any pending - // commits from the previous frame. - if (pendingCommit !== null && !deadlineHasExpired) { - commitAllWork(pendingCommit); - } - - // Nothing in performWork should be allowed to throw. All unsafe - // operations must happen within workLoop, which is extracted to a - // separate function so that it can be optimized by the JS engine. - priorityContextBeforeReconciliation = priorityContext; - let error = null; - if (__DEV__) { - error = invokeGuardedCallback( - null, - workLoop, - null, - priorityLevel, - deadline, - ); - } else { - try { - workLoop(priorityLevel, deadline); - } catch (e) { - error = e; - } - } - // Reset the priority context to its value before reconcilation. - priorityContext = priorityContextBeforeReconciliation; - - if (error !== null) { - // We caught an error during either the begin or complete phases. - const failedWork = nextUnitOfWork; - - if (failedWork !== null) { - // "Capture" the error by finding the nearest boundary. If there is no - // error boundary, the nearest host container acts as one. If - // captureError returns null, the error was intentionally ignored. - const maybeBoundary = captureError(failedWork, error); - if (maybeBoundary !== null) { - const boundary = maybeBoundary; - - // Complete the boundary as if it rendered null. This will unmount - // the failed tree. - beginFailedWork(boundary.alternate, boundary, priorityLevel); - - // The next unit of work is now the boundary that captured the error. - // Conceptually, we're unwinding the stack. We need to unwind the - // context stack, too, from the failed work to the boundary that - // captured the error. - // TODO: If we set the memoized props in beginWork instead of - // completeWork, rather than unwind the stack, we can just restart - // from the root. Can't do that until then because without memoized - // props, the nodes higher up in the tree will rerender unnecessarily. - unwindContexts(failedWork, boundary); - nextUnitOfWork = completeUnitOfWork(boundary); - } - // Continue performing work - continue; - } else if (fatalError === null) { - // There is no current unit of work. This is a worst-case scenario - // and should only be possible if there's a bug in the renderer, e.g. - // inside resetAfterCommit. - fatalError = error; - } - } - - // Stop performing work - priorityLevel = NoWork; - - // If have we more work, and we're in a deferred batch, check to see - // if the deadline has expired. - if ( - nextPriorityLevel !== NoWork && - isPerformingDeferredWork && - !deadlineHasExpired - ) { - // We have more time to do work. - priorityLevel = nextPriorityLevel; - continue; - } - - // There might be work left. Depending on the priority, we should - // either perform it now or schedule a callback to perform it later. - switch (nextPriorityLevel) { - case SynchronousPriority: - case TaskPriority: - // Perform work immediately by switching the priority level - // and continuing the loop. - priorityLevel = nextPriorityLevel; - break; - case AnimationPriority: - scheduleAnimationCallback(performAnimationWork); - // Even though the next unit of work has animation priority, there - // may still be deferred work left over as well. I think this is - // only important for unit tests. In a real app, a deferred callback - // would be scheduled during the next animation frame. - scheduleDeferredCallback(performDeferredWork); - break; - case HighPriority: - case LowPriority: - case OffscreenPriority: - scheduleDeferredCallback(performDeferredWork); - break; - } - } - - const errorToThrow = fatalError || firstUncaughtError; - - // We're done performing work. Time to clean up. - isPerformingWork = false; - deadlineHasExpired = false; - fatalError = null; - firstUncaughtError = null; - capturedErrors = null; - failedBoundaries = null; - if (__DEV__) { - stopWorkLoopTimer(); - } - - // It's safe to throw any unhandled errors. - if (errorToThrow !== null) { - throw errorToThrow; - } - } - - // Returns the boundary that captured the error, or null if the error is ignored - function captureError(failedWork: Fiber, error: Error): Fiber | null { - // It is no longer valid because we exited the user code. - ReactCurrentOwner.current = null; - if (__DEV__) { - ReactDebugCurrentFiber.current = null; - ReactDebugCurrentFiber.phase = null; - } - // It is no longer valid because this unit of work failed. - nextUnitOfWork = null; - - // Search for the nearest error boundary. - let boundary: Fiber | null = null; - - // Passed to logCapturedError() - let errorBoundaryFound: boolean = false; - let willRetry: boolean = false; - let errorBoundaryName: string | null = null; - - // Host containers are a special case. If the failed work itself is a host - // container, then it acts as its own boundary. In all other cases, we - // ignore the work itself and only search through the parents. - if (failedWork.tag === HostRoot) { - boundary = failedWork; - - if (isFailedBoundary(failedWork)) { - // If this root already failed, there must have been an error when - // attempting to unmount it. This is a worst-case scenario and - // should only be possible if there's a bug in the renderer. - fatalError = error; - } - } else { - let node = failedWork.return; - while (node !== null && boundary === null) { - if (node.tag === ClassComponent) { - const instance = node.stateNode; - if (typeof instance.unstable_handleError === 'function') { - errorBoundaryFound = true; - errorBoundaryName = getComponentName(node); - - // Found an error boundary! - boundary = node; - willRetry = true; - } - } else if (node.tag === HostRoot) { - // Treat the root like a no-op error boundary. - boundary = node; - } - - if (isFailedBoundary(node)) { - // This boundary is already in a failed state. - - // If we're currently unmounting, that means this error was - // thrown while unmounting a failed subtree. We should ignore - // the error. - if (isUnmounting) { - return null; - } - - // If we're in the commit phase, we should check to see if - // this boundary already captured an error during this commit. - // This case exists because multiple errors can be thrown during - // a single commit without interruption. - if ( - commitPhaseBoundaries !== null && - (commitPhaseBoundaries.has(node) || - (node.alternate !== null && - commitPhaseBoundaries.has(node.alternate))) - ) { - // If so, we should ignore this error. - return null; - } - - // The error should propagate to the next boundary -— we keep looking. - boundary = null; - willRetry = false; - } - - node = node.return; - } - } - - if (boundary !== null) { - // Add to the collection of failed boundaries. This lets us know that - // subsequent errors in this subtree should propagate to the next boundary. - if (failedBoundaries === null) { - failedBoundaries = new Set(); - } - failedBoundaries.add(boundary); - - // This method is unsafe outside of the begin and complete phases. - // We might be in the commit phase when an error is captured. - // The risk is that the return path from this Fiber may not be accurate. - // That risk is acceptable given the benefit of providing users more context. - const componentStack = getStackAddendumByWorkInProgressFiber(failedWork); - const componentName = getComponentName(failedWork); - - // Add to the collection of captured errors. This is stored as a global - // map of errors and their component stack location keyed by the boundaries - // that capture them. We mostly use this Map as a Set; it's a Map only to - // avoid adding a field to Fiber to store the error. - if (capturedErrors === null) { - capturedErrors = new Map(); - } - capturedErrors.set(boundary, { - componentName, - componentStack, - error, - errorBoundary: errorBoundaryFound ? boundary.stateNode : null, - errorBoundaryFound, - errorBoundaryName, - willRetry, - }); - - // If we're in the commit phase, defer scheduling an update on the - // boundary until after the commit is complete - if (isCommitting) { - if (commitPhaseBoundaries === null) { - commitPhaseBoundaries = new Set(); - } - commitPhaseBoundaries.add(boundary); - } else { - // Otherwise, schedule an update now. - scheduleErrorRecovery(boundary); - } - return boundary; - } else if (firstUncaughtError === null) { - // If no boundary is found, we'll need to throw the error - firstUncaughtError = error; - } - return null; - } - - function hasCapturedError(fiber: Fiber): boolean { - // TODO: capturedErrors should store the boundary instance, to avoid needing - // to check the alternate. - return ( - capturedErrors !== null && - (capturedErrors.has(fiber) || - (fiber.alternate !== null && capturedErrors.has(fiber.alternate))) - ); - } - - function isFailedBoundary(fiber: Fiber): boolean { - // TODO: failedBoundaries should store the boundary instance, to avoid - // needing to check the alternate. - return ( - failedBoundaries !== null && - (failedBoundaries.has(fiber) || - (fiber.alternate !== null && failedBoundaries.has(fiber.alternate))) - ); - } - - function commitErrorHandling(effectfulFiber: Fiber) { - let capturedError; - if (capturedErrors !== null) { - capturedError = capturedErrors.get(effectfulFiber); - capturedErrors.delete(effectfulFiber); - if (capturedError == null) { - if (effectfulFiber.alternate !== null) { - effectfulFiber = effectfulFiber.alternate; - capturedError = capturedErrors.get(effectfulFiber); - capturedErrors.delete(effectfulFiber); - } - } - } - - invariant( - capturedError != null, - 'No error for given unit of work. This error is likely caused by a ' + - 'bug in React. Please file an issue.', - ); - - const error = capturedError.error; - try { - logCapturedError(capturedError); - } catch (e) { - // Prevent cycle if logCapturedError() throws. - // A cycle may still occur if logCapturedError renders a component that throws. - console.error(e); - } - - switch (effectfulFiber.tag) { - case ClassComponent: - const instance = effectfulFiber.stateNode; - - const info: HandleErrorInfo = { - componentStack: capturedError.componentStack, - }; - - // Allow the boundary to handle the error, usually by scheduling - // an update to itself - instance.unstable_handleError(error, info); - return; - case HostRoot: - if (firstUncaughtError === null) { - // If this is the host container, we treat it as a no-op error - // boundary. We'll throw the first uncaught error once it's safe to - // do so, at the end of the batch. - firstUncaughtError = error; - } - return; - default: - invariant( - false, - 'Invalid type of work. This error is likely caused by a bug in ' + - 'React. Please file an issue.', - ); - } - } - - function unwindContexts(from: Fiber, to: Fiber) { - let node = from; - while (node !== null && node !== to && node.alternate !== to) { - switch (node.tag) { - case ClassComponent: - popContextProvider(node); - break; - case HostComponent: - popHostContext(node); - break; - case HostRoot: - popHostContainer(node); - break; - case HostPortal: - popHostContainer(node); - break; - } - if (__DEV__) { - stopWorkTimer(node); - } - node = node.return; - } - } - - function scheduleRoot(root: FiberRoot, priorityLevel: PriorityLevel) { - if (priorityLevel === NoWork) { - return; - } - - if (!root.isScheduled) { - root.isScheduled = true; - if (lastScheduledRoot) { - // Schedule ourselves to the end. - lastScheduledRoot.nextScheduledRoot = root; - lastScheduledRoot = root; - } else { - // We're the only work scheduled. - nextScheduledRoot = root; - lastScheduledRoot = root; - } - } - } - - function scheduleUpdate(fiber: Fiber, priorityLevel: PriorityLevel) { - if (__DEV__) { - recordScheduleUpdate(); - } - - if (priorityLevel <= nextPriorityLevel) { - // We must reset the current unit of work pointer so that we restart the - // search from the root during the next tick, in case there is now higher - // priority work somewhere earlier than before. - nextUnitOfWork = null; - } - - if (__DEV__) { - if (fiber.tag === ClassComponent) { - const instance = fiber.stateNode; - warnAboutInvalidUpdates(instance); - } - } - - let node = fiber; - let shouldContinue = true; - while (node !== null && shouldContinue) { - // Walk the parent path to the root and update each node's priority. Once - // we reach a node whose priority matches (and whose alternate's priority - // matches) we can exit safely knowing that the rest of the path is correct. - shouldContinue = false; - if ( - node.pendingWorkPriority === NoWork || - node.pendingWorkPriority > priorityLevel - ) { - // Priority did not match. Update and keep going. - shouldContinue = true; - node.pendingWorkPriority = priorityLevel; - } - if (node.alternate !== null) { - if ( - node.alternate.pendingWorkPriority === NoWork || - node.alternate.pendingWorkPriority > priorityLevel - ) { - // Priority did not match. Update and keep going. - shouldContinue = true; - node.alternate.pendingWorkPriority = priorityLevel; - } - } - if (node.return === null) { - if (node.tag === HostRoot) { - const root: FiberRoot = (node.stateNode: any); - scheduleRoot(root, priorityLevel); - // Depending on the priority level, either perform work now or - // schedule a callback to perform work later. - switch (priorityLevel) { - case SynchronousPriority: - performWork(SynchronousPriority, null); - return; - case TaskPriority: - // TODO: If we're not already performing work, schedule a - // deferred callback. - return; - case AnimationPriority: - scheduleAnimationCallback(performAnimationWork); - return; - case HighPriority: - case LowPriority: - case OffscreenPriority: - scheduleDeferredCallback(performDeferredWork); - return; - } - } else { - if (__DEV__) { - if (fiber.tag === ClassComponent) { - warnAboutUpdateOnUnmounted(fiber.stateNode); - } - } - return; - } - } - node = node.return; - } - } - - function getPriorityContext( - fiber: Fiber, - forceAsync: boolean, - ): PriorityLevel { - let priorityLevel = priorityContext; - if (priorityLevel === NoWork) { - if ( - !useSyncScheduling || - fiber.internalContextTag & AsyncUpdates || - forceAsync - ) { - priorityLevel = LowPriority; - } else { - priorityLevel = SynchronousPriority; - } - } - - // If we're in a batch, or if we're already performing work, downgrade sync - // priority to task priority - if ( - priorityLevel === SynchronousPriority && - (isPerformingWork || isBatchingUpdates) - ) { - return TaskPriority; - } - return priorityLevel; - } - - function scheduleErrorRecovery(fiber: Fiber) { - scheduleUpdate(fiber, TaskPriority); - } - - function performWithPriority(priorityLevel: PriorityLevel, fn: Function) { - const previousPriorityContext = priorityContext; - priorityContext = priorityLevel; - try { - fn(); - } finally { - priorityContext = previousPriorityContext; - } - } - - function batchedUpdates(fn: (a: A) => R, a: A): R { - const previousIsBatchingUpdates = isBatchingUpdates; - isBatchingUpdates = true; - try { - return fn(a); - } finally { - isBatchingUpdates = previousIsBatchingUpdates; - // If we're not already inside a batch, we need to flush any task work - // that was created by the user-provided function. - if (!isPerformingWork && !isBatchingUpdates) { - performWork(TaskPriority, null); - } - } - } - - function unbatchedUpdates(fn: () => A): A { - const previousIsBatchingUpdates = isBatchingUpdates; - isBatchingUpdates = false; - try { - return fn(); - } finally { - isBatchingUpdates = previousIsBatchingUpdates; - } - } - - function syncUpdates(fn: () => A): A { - const previousPriorityContext = priorityContext; - priorityContext = SynchronousPriority; - try { - return fn(); - } finally { - priorityContext = previousPriorityContext; - } - } - - function deferredUpdates(fn: () => A): A { - const previousPriorityContext = priorityContext; - priorityContext = LowPriority; - try { - return fn(); - } finally { - priorityContext = previousPriorityContext; - } - } - - return { - scheduleUpdate: scheduleUpdate, - getPriorityContext: getPriorityContext, - performWithPriority: performWithPriority, - batchedUpdates: batchedUpdates, - unbatchedUpdates: unbatchedUpdates, - syncUpdates: syncUpdates, - deferredUpdates: deferredUpdates, - }; -}; diff --git a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberStack.js b/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberStack.js deleted file mode 100644 index 697271eaee..0000000000 --- a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberStack.js +++ /dev/null @@ -1,92 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactFiberStack - * @flow - */ - -'use strict'; - -import type {Fiber} from 'ReactFiber'; - -export type StackCursor = { - current: T, -}; - -const warning = require('fbjs/lib/warning'); - -const valueStack: Array = []; - -if (__DEV__) { - var fiberStack: Array = []; -} - -let index = -1; - -exports.createCursor = function(defaultValue: T): StackCursor { - return { - current: defaultValue, - }; -}; - -exports.isEmpty = function(): boolean { - return index === -1; -}; - -exports.pop = function(cursor: StackCursor, fiber: Fiber): void { - if (index < 0) { - if (__DEV__) { - warning(false, 'Unexpected pop.'); - } - return; - } - - if (__DEV__) { - if (fiber !== fiberStack[index]) { - warning(false, 'Unexpected Fiber popped.'); - } - } - - cursor.current = valueStack[index]; - - valueStack[index] = null; - - if (__DEV__) { - fiberStack[index] = null; - } - - index--; -}; - -exports.push = function( - cursor: StackCursor, - value: T, - fiber: Fiber, -): void { - index++; - - valueStack[index] = cursor.current; - - if (__DEV__) { - fiberStack[index] = fiber; - } - - cursor.current = value; -}; - -exports.reset = function(): void { - while (index > -1) { - valueStack[index] = null; - - if (__DEV__) { - fiberStack[index] = null; - } - - index--; - } -}; diff --git a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberTreeReflection.js b/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberTreeReflection.js deleted file mode 100644 index 94d7c88072..0000000000 --- a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberTreeReflection.js +++ /dev/null @@ -1,265 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactFiberTreeReflection - * @flow - */ - -'use strict'; - -import type {Fiber} from 'ReactFiber'; - -var ReactInstanceMap = require('ReactInstanceMap'); -var {ReactCurrentOwner} = require('ReactGlobalSharedState'); - -var getComponentName = require('getComponentName'); -var invariant = require('fbjs/lib/invariant'); - -if (__DEV__) { - var warning = require('fbjs/lib/warning'); -} - -var { - HostRoot, - HostComponent, - HostText, - ClassComponent, -} = require('ReactTypeOfWork'); - -var {NoEffect, Placement} = require('ReactTypeOfSideEffect'); - -var MOUNTING = 1; -var MOUNTED = 2; -var UNMOUNTED = 3; - -function isFiberMountedImpl(fiber: Fiber): number { - let node = fiber; - if (!fiber.alternate) { - // If there is no alternate, this might be a new tree that isn't inserted - // yet. If it is, then it will have a pending insertion effect on it. - if ((node.effectTag & Placement) !== NoEffect) { - return MOUNTING; - } - while (node.return) { - node = node.return; - if ((node.effectTag & Placement) !== NoEffect) { - return MOUNTING; - } - } - } else { - while (node.return) { - node = node.return; - } - } - if (node.tag === HostRoot) { - // TODO: Check if this was a nested HostRoot when used with - // renderContainerIntoSubtree. - return MOUNTED; - } - // If we didn't hit the root, that means that we're in an disconnected tree - // that has been unmounted. - return UNMOUNTED; -} -exports.isFiberMounted = function(fiber: Fiber): boolean { - return isFiberMountedImpl(fiber) === MOUNTED; -}; - -exports.isMounted = function( - component: ReactComponent, -): boolean { - if (__DEV__) { - const owner = (ReactCurrentOwner.current: any); - if (owner !== null && owner.tag === ClassComponent) { - const ownerFiber: Fiber = owner; - const instance = ownerFiber.stateNode; - warning( - instance._warnedAboutRefsInRender, - '%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) || 'A component', - ); - instance._warnedAboutRefsInRender = true; - } - } - - var fiber: ?Fiber = ReactInstanceMap.get(component); - if (!fiber) { - return false; - } - return isFiberMountedImpl(fiber) === MOUNTED; -}; - -function assertIsMounted(fiber) { - invariant( - isFiberMountedImpl(fiber) === MOUNTED, - 'Unable to find node on an unmounted component.', - ); -} - -function findCurrentFiberUsingSlowPath(fiber: Fiber): Fiber | null { - let alternate = fiber.alternate; - if (!alternate) { - // If there is no alternate, then we only need to check if it is mounted. - const state = isFiberMountedImpl(fiber); - invariant( - state !== UNMOUNTED, - 'Unable to find node on an unmounted component.', - ); - if (state === MOUNTING) { - 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. - let a = fiber; - let b = alternate; - while (true) { - let parentA = a.return; - let parentB = parentA ? parentA.alternate : null; - if (!parentA || !parentB) { - // 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) { - let 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. - invariant(false, '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 pointer 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 - let didFindChild = false; - let 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; - } - invariant( - didFindChild, - 'Child was not found in either parent set. This indicates a bug ' + - 'related to the return pointer.', - ); - } - } - - invariant( - a.alternate === b, - "Return fibers should always be each others' alternates.", - ); - } - // If the root is not a host container, we're in a disconnected tree. I.e. - // unmounted. - invariant( - a.tag === HostRoot, - 'Unable to find node on an unmounted component.', - ); - 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; -} -exports.findCurrentFiberUsingSlowPath = findCurrentFiberUsingSlowPath; - -exports.findCurrentHostFiber = function(parent: Fiber): Fiber | null { - const currentParent = findCurrentFiberUsingSlowPath(parent); - if (!currentParent) { - return null; - } - - // Next we'll drill down this component to find the first HostComponent/Text. - let node: Fiber = currentParent; - while (true) { - if (node.tag === HostComponent || node.tag === HostText) { - return node; - } else if (node.child) { - // TODO: If we hit a Portal, we're supposed to skip it. - 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; -}; diff --git a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberUpdateQueue.js b/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberUpdateQueue.js deleted file mode 100644 index b3fd536c9d..0000000000 --- a/Libraries/Renderer/src/renderers/shared/fiber/ReactFiberUpdateQueue.js +++ /dev/null @@ -1,509 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactFiberUpdateQueue - * @flow - */ - -'use strict'; - -import type {Fiber} from 'ReactFiber'; -import type {PriorityLevel} from 'ReactPriorityLevel'; - -const {Callback: CallbackEffect} = require('ReactTypeOfSideEffect'); - -const { - NoWork, - SynchronousPriority, - TaskPriority, -} = require('ReactPriorityLevel'); - -const invariant = require('fbjs/lib/invariant'); -if (__DEV__) { - var warning = require('fbjs/lib/warning'); -} - -type PartialState = - | $Subtype - | ((prevState: State, props: Props) => $Subtype); - -// Callbacks are not validated until invocation -type Callback = mixed; - -type Update = { - priorityLevel: PriorityLevel, - partialState: PartialState, - callback: Callback | null, - isReplace: boolean, - isForced: boolean, - isTopLevelUnmount: boolean, - next: Update | null, -}; - -// Singly linked-list of updates. When an update is scheduled, it is added to -// the queue of the current fiber and the work-in-progress fiber. The two queues -// are separate but they share a persistent structure. -// -// During reconciliation, updates are removed from the work-in-progress fiber, -// but they remain on the current fiber. That ensures that if a work-in-progress -// is aborted, the aborted updates are recovered by cloning from current. -// -// The work-in-progress queue is always a subset of the current queue. -// -// When the tree is committed, the work-in-progress becomes the current. -export type UpdateQueue = { - first: Update | null, - last: Update | null, - hasForceUpdate: boolean, - callbackList: null | Array, - - // Dev only - isProcessing?: boolean, -}; - -function comparePriority(a: PriorityLevel, b: PriorityLevel): number { - // When comparing update priorities, treat sync and Task work as equal. - // TODO: Could we avoid the need for this by always coercing sync priority - // to Task when scheduling an update? - if ( - (a === TaskPriority || a === SynchronousPriority) && - (b === TaskPriority || b === SynchronousPriority) - ) { - return 0; - } - if (a === NoWork && b !== NoWork) { - return -255; - } - if (a !== NoWork && b === NoWork) { - return 255; - } - return a - b; -} - -// Ensures that a fiber has an update queue, creating a new one if needed. -// Returns the new or existing queue. -function ensureUpdateQueue(fiber: Fiber): UpdateQueue { - if (fiber.updateQueue !== null) { - // We already have an update queue. - return fiber.updateQueue; - } - - let queue; - if (__DEV__) { - queue = { - first: null, - last: null, - hasForceUpdate: false, - callbackList: null, - isProcessing: false, - }; - } else { - queue = { - first: null, - last: null, - hasForceUpdate: false, - callbackList: null, - }; - } - - fiber.updateQueue = queue; - return queue; -} - -// Clones an update queue from a source fiber onto its alternate. -function cloneUpdateQueue( - current: Fiber, - workInProgress: Fiber, -): UpdateQueue | null { - const currentQueue = current.updateQueue; - if (currentQueue === null) { - // The source fiber does not have an update queue. - workInProgress.updateQueue = null; - return null; - } - // If the alternate already has a queue, reuse the previous object. - const altQueue = workInProgress.updateQueue !== null - ? workInProgress.updateQueue - : {}; - altQueue.first = currentQueue.first; - altQueue.last = currentQueue.last; - - // These fields are invalid by the time we clone from current. Reset them. - altQueue.hasForceUpdate = false; - altQueue.callbackList = null; - altQueue.isProcessing = false; - - workInProgress.updateQueue = altQueue; - - return altQueue; -} -exports.cloneUpdateQueue = cloneUpdateQueue; - -function cloneUpdate(update: Update): Update { - return { - priorityLevel: update.priorityLevel, - partialState: update.partialState, - callback: update.callback, - isReplace: update.isReplace, - isForced: update.isForced, - isTopLevelUnmount: update.isTopLevelUnmount, - next: null, - }; -} - -function insertUpdateIntoQueue( - queue: UpdateQueue, - update: Update, - insertAfter: Update | null, - insertBefore: Update | null, -) { - if (insertAfter !== null) { - insertAfter.next = update; - } else { - // This is the first item in the queue. - update.next = queue.first; - queue.first = update; - } - - if (insertBefore !== null) { - update.next = insertBefore; - } else { - // This is the last item in the queue. - queue.last = update; - } -} - -// Returns the update after which the incoming update should be inserted into -// the queue, or null if it should be inserted at beginning. -function findInsertionPosition(queue, update): Update | null { - const priorityLevel = update.priorityLevel; - let insertAfter = null; - let insertBefore = null; - if ( - queue.last !== null && - comparePriority(queue.last.priorityLevel, priorityLevel) <= 0 - ) { - // Fast path for the common case where the update should be inserted at - // the end of the queue. - insertAfter = queue.last; - } else { - insertBefore = queue.first; - while ( - insertBefore !== null && - comparePriority(insertBefore.priorityLevel, priorityLevel) <= 0 - ) { - insertAfter = insertBefore; - insertBefore = insertBefore.next; - } - } - return insertAfter; -} - -// The work-in-progress queue is a subset of the current queue (if it exists). -// We need to insert the incoming update into both lists. However, it's possible -// that the correct position in one list will be different from the position in -// the other. Consider the following case: -// -// Current: 3-5-6 -// Work-in-progress: 6 -// -// Then we receive an update with priority 4 and insert it into each list: -// -// Current: 3-4-5-6 -// Work-in-progress: 4-6 -// -// In the current queue, the new update's `next` pointer points to the update -// with priority 5. But in the work-in-progress queue, the pointer points to the -// update with priority 6. Because these two queues share the same persistent -// data structure, this won't do. (This can only happen when the incoming update -// has higher priority than all the updates in the work-in-progress queue.) -// -// To solve this, in the case where the incoming update needs to be inserted -// into two different positions, we'll make a clone of the update and insert -// each copy into a separate queue. This forks the list while maintaining a -// persistent structure, because the update that is added to the work-in-progress -// is always added to the front of the list. -// -// However, if incoming update is inserted into the same position of both lists, -// we shouldn't make a copy. -// -// If the update is cloned, it returns the cloned update. -function insertUpdate(fiber: Fiber, update: Update): Update | null { - const queue1 = ensureUpdateQueue(fiber); - const queue2 = fiber.alternate !== null - ? ensureUpdateQueue(fiber.alternate) - : null; - - // Warn if an update is scheduled from inside an updater function. - if (__DEV__) { - if (queue1.isProcessing || (queue2 !== null && queue2.isProcessing)) { - warning( - false, - 'An update (setState, replaceState, or forceUpdate) was scheduled ' + - 'from inside an update function. Update functions should be pure, ' + - 'with zero side-effects. Consider using componentDidUpdate or a ' + - 'callback.', - ); - } - } - - // Find the insertion position in the first queue. - const insertAfter1 = findInsertionPosition(queue1, update); - const insertBefore1 = insertAfter1 !== null - ? insertAfter1.next - : queue1.first; - - if (queue2 === null) { - // If there's no alternate queue, there's nothing else to do but insert. - insertUpdateIntoQueue(queue1, update, insertAfter1, insertBefore1); - return null; - } - - // If there is an alternate queue, find the insertion position. - const insertAfter2 = findInsertionPosition(queue2, update); - const insertBefore2 = insertAfter2 !== null - ? insertAfter2.next - : queue2.first; - - // Now we can insert into the first queue. This must come after finding both - // insertion positions because it mutates the list. - insertUpdateIntoQueue(queue1, update, insertAfter1, insertBefore1); - - if (insertBefore1 !== insertBefore2) { - // The insertion positions are different, so we need to clone the update and - // insert the clone into the alternate queue. - const update2 = cloneUpdate(update); - insertUpdateIntoQueue(queue2, update2, insertAfter2, insertBefore2); - return update2; - } else { - // The insertion positions are the same, so when we inserted into the first - // queue, it also inserted into the alternate. All we need to do is update - // the alternate queue's `first` and `last` pointers, in case they - // have changed. - if (insertAfter2 === null) { - queue2.first = update; - } - if (insertBefore2 === null) { - queue2.last = null; - } - } - - return null; -} - -function addUpdate( - fiber: Fiber, - partialState: PartialState | null, - callback: mixed, - priorityLevel: PriorityLevel, -): void { - const update = { - priorityLevel, - partialState, - callback, - isReplace: false, - isForced: false, - isTopLevelUnmount: false, - next: null, - }; - insertUpdate(fiber, update); -} -exports.addUpdate = addUpdate; - -function addReplaceUpdate( - fiber: Fiber, - state: any | null, - callback: Callback | null, - priorityLevel: PriorityLevel, -): void { - const update = { - priorityLevel, - partialState: state, - callback, - isReplace: true, - isForced: false, - isTopLevelUnmount: false, - next: null, - }; - insertUpdate(fiber, update); -} -exports.addReplaceUpdate = addReplaceUpdate; - -function addForceUpdate( - fiber: Fiber, - callback: Callback | null, - priorityLevel: PriorityLevel, -): void { - const update = { - priorityLevel, - partialState: null, - callback, - isReplace: false, - isForced: true, - isTopLevelUnmount: false, - next: null, - }; - insertUpdate(fiber, update); -} -exports.addForceUpdate = addForceUpdate; - -function getPendingPriority(queue: UpdateQueue): PriorityLevel { - return queue.first !== null ? queue.first.priorityLevel : NoWork; -} -exports.getPendingPriority = getPendingPriority; - -function addTopLevelUpdate( - fiber: Fiber, - partialState: PartialState, - callback: Callback | null, - priorityLevel: PriorityLevel, -): void { - const isTopLevelUnmount = partialState.element === null; - - const update = { - priorityLevel, - partialState, - callback, - isReplace: false, - isForced: false, - isTopLevelUnmount, - next: null, - }; - const update2 = insertUpdate(fiber, update); - - if (isTopLevelUnmount) { - // Drop all updates that are lower-priority, so that the tree is not - // remounted. We need to do this for both queues. - const queue1 = fiber.updateQueue; - const queue2 = fiber.alternate !== null - ? fiber.alternate.updateQueue - : null; - - if (queue1 !== null && update.next !== null) { - update.next = null; - queue1.last = update; - } - if (queue2 !== null && update2 !== null && update2.next !== null) { - update2.next = null; - queue2.last = update; - } - } -} -exports.addTopLevelUpdate = addTopLevelUpdate; - -function getStateFromUpdate(update, instance, prevState, props) { - const partialState = update.partialState; - if (typeof partialState === 'function') { - const updateFn = partialState; - return updateFn.call(instance, prevState, props); - } else { - return partialState; - } -} - -function beginUpdateQueue( - workInProgress: Fiber, - queue: UpdateQueue, - instance: any, - prevState: any, - props: any, - priorityLevel: PriorityLevel, -): any { - if (__DEV__) { - // Set this flag so we can warn if setState is called inside the update - // function of another setState. - queue.isProcessing = true; - } - - queue.hasForceUpdate = false; - - // Applies updates with matching priority to the previous state to create - // a new state object. - let state = prevState; - let dontMutatePrevState = true; - let callbackList = null; - let update = queue.first; - while ( - update !== null && - comparePriority(update.priorityLevel, priorityLevel) <= 0 - ) { - // Remove each update from the queue right before it is processed. That way - // if setState is called from inside an updater function, the new update - // will be inserted in the correct position. - queue.first = update.next; - if (queue.first === null) { - queue.last = null; - } - - let partialState; - if (update.isReplace) { - state = getStateFromUpdate(update, instance, state, props); - dontMutatePrevState = true; - } else { - partialState = getStateFromUpdate(update, instance, state, props); - if (partialState) { - if (dontMutatePrevState) { - state = Object.assign({}, state, partialState); - } else { - state = Object.assign(state, partialState); - } - dontMutatePrevState = false; - } - } - if (update.isForced) { - queue.hasForceUpdate = true; - } - // Second condition ignores top-level unmount callbacks if they are not the - // last update in the queue, since a subsequent update will cause a remount. - if ( - update.callback !== null && - !(update.isTopLevelUnmount && update.next !== null) - ) { - callbackList = callbackList || []; - callbackList.push(update.callback); - workInProgress.effectTag |= CallbackEffect; - } - update = update.next; - } - - queue.callbackList = callbackList; - - if (queue.first === null && callbackList === null && !queue.hasForceUpdate) { - // The queue is empty and there are no callbacks. We can reset it. - workInProgress.updateQueue = null; - } - - if (__DEV__) { - queue.isProcessing = false; - } - - return state; -} -exports.beginUpdateQueue = beginUpdateQueue; - -function commitCallbacks( - finishedWork: Fiber, - queue: UpdateQueue, - context: mixed, -) { - const callbackList = queue.callbackList; - if (callbackList === null) { - return; - } - for (let i = 0; i < callbackList.length; i++) { - const callback = callbackList[i]; - invariant( - typeof callback === 'function', - 'Invalid argument passed as callback. Expected a function. Instead ' + - 'received: %s', - callback, - ); - callback.call(context); - } -} -exports.commitCallbacks = commitCallbacks; diff --git a/Libraries/Renderer/src/renderers/shared/fiber/ReactPriorityLevel.js b/Libraries/Renderer/src/renderers/shared/fiber/ReactPriorityLevel.js deleted file mode 100644 index a0c9a7a7c0..0000000000 --- a/Libraries/Renderer/src/renderers/shared/fiber/ReactPriorityLevel.js +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactPriorityLevel - * @flow - */ - -'use strict'; - -export type PriorityLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6; - -module.exports = { - NoWork: 0, // No work is pending. - SynchronousPriority: 1, // For controlled text inputs. Synchronous side-effects. - TaskPriority: 2, // Completes at the end of the current tick. - AnimationPriority: 3, // Needs to complete before the next frame. - HighPriority: 4, // Interaction that needs to complete pretty soon to feel responsive. - LowPriority: 5, // Data fetching, or result from updating stores. - OffscreenPriority: 6, // Won't be visible but do the work in case it becomes visible. -}; diff --git a/Libraries/Renderer/src/renderers/shared/fiber/ReactTypeOfSideEffect.js b/Libraries/Renderer/src/renderers/shared/fiber/ReactTypeOfSideEffect.js deleted file mode 100644 index 408d1d5001..0000000000 --- a/Libraries/Renderer/src/renderers/shared/fiber/ReactTypeOfSideEffect.js +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactTypeOfSideEffect - * @flow - */ - -'use strict'; - -export type TypeOfSideEffect = number; - -module.exports = { - NoEffect: 0, // 0b0000000 - Placement: 1, // 0b0000001 - Update: 2, // 0b0000010 - PlacementAndUpdate: 3, // 0b0000011 - Deletion: 4, // 0b0000100 - ContentReset: 8, // 0b0001000 - Callback: 16, // 0b0010000 - Err: 32, // 0b0100000 - Ref: 64, // 0b1000000 -}; diff --git a/Libraries/Renderer/src/renderers/shared/fiber/__tests__/ReactCoroutine-test.js b/Libraries/Renderer/src/renderers/shared/fiber/__tests__/ReactCoroutine-test.js deleted file mode 100644 index f54d5c180e..0000000000 --- a/Libraries/Renderer/src/renderers/shared/fiber/__tests__/ReactCoroutine-test.js +++ /dev/null @@ -1,247 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @emails react-core - */ - -'use strict'; - -var React; -var ReactNoop; -var ReactCoroutine; -var ReactFeatureFlags; - -describe('ReactCoroutine', () => { - beforeEach(() => { - jest.resetModules(); - React = require('react'); - ReactNoop = require('ReactNoop'); - ReactCoroutine = require('ReactCoroutine'); - ReactFeatureFlags = require('ReactFeatureFlags'); - ReactFeatureFlags.disableNewFiberFeatures = false; - }); - - function div(...children) { - children = children.map(c => (typeof c === 'string' ? {text: c} : c)); - return {type: 'div', children, prop: undefined}; - } - - function span(prop) { - return {type: 'span', children: [], prop}; - } - - it('should render a coroutine', () => { - var ops = []; - - function Continuation({isSame}) { - ops.push(['Continuation', isSame]); - return ; - } - - // An alternative API could mark Continuation as something that needs - // yielding. E.g. Continuation.yieldType = 123; - function Child({bar}) { - ops.push(['Child', bar]); - return ReactCoroutine.createYield({ - props: { - bar: bar, - }, - continuation: Continuation, - }); - } - - function Indirection() { - ops.push('Indirection'); - return [, ]; - } - - function HandleYields(props, yields) { - ops.push('HandleYields'); - return yields.map((y, i) => ( - - )); - } - - // An alternative API could mark Parent as something that needs - // yielding. E.g. Parent.handler = HandleYields; - function Parent(props) { - ops.push('Parent'); - return ReactCoroutine.createCoroutine( - props.children, - HandleYields, - props, - ); - } - - function App() { - return
; - } - - ReactNoop.render(); - ReactNoop.flush(); - - expect(ops).toEqual([ - 'Parent', - 'Indirection', - ['Child', true], - // Yield - ['Child', false], - // Yield - 'HandleYields', - // Continue yields - ['Continuation', true], - ['Continuation', false], - ]); - expect(ReactNoop.getChildren()).toEqual([ - div(span('foo==bar'), span('foo!=bar')), - ]); - }); - - it('should update a coroutine', () => { - function Continuation({isSame}) { - return ; - } - - function Child({bar}) { - return ReactCoroutine.createYield({ - props: { - bar: bar, - }, - continuation: Continuation, - }); - } - - function Indirection() { - return [, ]; - } - - function HandleYields(props, yields) { - return yields.map((y, i) => ( - - )); - } - - function Parent(props) { - return ReactCoroutine.createCoroutine( - props.children, - HandleYields, - props, - ); - } - - function App(props) { - return
; - } - - ReactNoop.render(); - ReactNoop.flush(); - expect(ReactNoop.getChildren()).toEqual([ - div(span('foo==bar'), span('foo!=bar')), - ]); - - ReactNoop.render(); - ReactNoop.flush(); - expect(ReactNoop.getChildren()).toEqual([ - div(span('foo!=bar'), span('foo==bar')), - ]); - }); - - it('should unmount a composite in a coroutine', () => { - var ops = []; - - class Continuation extends React.Component { - render() { - ops.push('Continuation'); - return
; - } - componentWillUnmount() { - ops.push('Unmount Continuation'); - } - } - - class Child extends React.Component { - render() { - ops.push('Child'); - return ReactCoroutine.createYield(Continuation); - } - componentWillUnmount() { - ops.push('Unmount Child'); - } - } - - function HandleYields(props, yields) { - ops.push('HandleYields'); - return yields.map((ContinuationComponent, i) => ( - - )); - } - - class Parent extends React.Component { - render() { - ops.push('Parent'); - return ReactCoroutine.createCoroutine( - this.props.children, - HandleYields, - this.props, - ); - } - componentWillUnmount() { - ops.push('Unmount Parent'); - } - } - - ReactNoop.render(); - ReactNoop.flush(); - - expect(ops).toEqual(['Parent', 'Child', 'HandleYields', 'Continuation']); - - ops = []; - - ReactNoop.render(
); - ReactNoop.flush(); - - expect(ops).toEqual([ - 'Unmount Parent', - 'Unmount Child', - 'Unmount Continuation', - ]); - }); - - it('should handle deep updates in coroutine', () => { - let instances = {}; - - class Counter extends React.Component { - state = {value: 5}; - render() { - instances[this.props.id] = this; - return ReactCoroutine.createYield(this.state.value); - } - } - - function App(props) { - return ReactCoroutine.createCoroutine( - [ - , - , - , - ], - (p, yields) => yields.map((y, i) => ), - {}, - ); - } - - ReactNoop.render(); - ReactNoop.flush(); - expect(ReactNoop.getChildren()).toEqual([span(500), span(500), span(500)]); - - instances.a.setState({value: 1}); - instances.b.setState({value: 2}); - ReactNoop.flush(); - expect(ReactNoop.getChildren()).toEqual([span(100), span(200), span(500)]); - }); -}); diff --git a/Libraries/Renderer/src/renderers/shared/fiber/__tests__/ReactFiberHostContext-test.js b/Libraries/Renderer/src/renderers/shared/fiber/__tests__/ReactFiberHostContext-test.js deleted file mode 100644 index b39352987c..0000000000 --- a/Libraries/Renderer/src/renderers/shared/fiber/__tests__/ReactFiberHostContext-test.js +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @emails react-core - */ - -'use strict'; - -var React; -var ReactFiberReconciler; - -describe('ReactFiberHostContext', () => { - beforeEach(() => { - jest.resetModules(); - React = require('React'); - ReactFiberReconciler = require('ReactFiberReconciler'); - }); - - it('works with null host context', () => { - var creates = 0; - var Renderer = ReactFiberReconciler({ - prepareForCommit: function() {}, - resetAfterCommit: function() {}, - getRootHostContext: function() { - return null; - }, - getChildHostContext: function() { - return null; - }, - shouldSetTextContent: function() { - return false; - }, - createInstance: function() { - creates++; - }, - finalizeInitialChildren: function() { - return null; - }, - appendInitialChild: function() { - return null; - }, - appendChild: function() { - return null; - }, - useSyncScheduling: true, - }); - - const container = Renderer.createContainer(/* root: */ null); - Renderer.updateContainer( - , - container, - /* parentComponent: */ null, - /* callback: */ null, - ); - expect(creates).toBe(2); - }); -}); diff --git a/Libraries/Renderer/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js b/Libraries/Renderer/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js deleted file mode 100644 index d4eeb88377..0000000000 --- a/Libraries/Renderer/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js +++ /dev/null @@ -1,2289 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @emails react-core - */ - -'use strict'; - -var React; -var ReactNoop; -var ReactFeatureFlags; -var PropTypes; - -describe('ReactIncremental', () => { - beforeEach(() => { - jest.resetModules(); - React = require('react'); - ReactNoop = require('ReactNoop'); - PropTypes = require('prop-types'); - - ReactFeatureFlags = require('ReactFeatureFlags'); - ReactFeatureFlags.disableNewFiberFeatures = false; - }); - - it('should render a simple component', () => { - function Bar() { - return
Hello World
; - } - - function Foo() { - return ; - } - - ReactNoop.render(); - ReactNoop.flush(); - }); - - it('should render a simple component, in steps if needed', () => { - var renderCallbackCalled = false; - var barCalled = false; - function Bar() { - barCalled = true; - return
Hello World
; - } - - var fooCalled = false; - function Foo() { - fooCalled = true; - return [, ]; - } - - ReactNoop.render(, () => (renderCallbackCalled = true)); - expect(fooCalled).toBe(false); - expect(barCalled).toBe(false); - expect(renderCallbackCalled).toBe(false); - // Do one step of work. - ReactNoop.flushDeferredPri(7 + 5); - expect(fooCalled).toBe(true); - expect(barCalled).toBe(false); - expect(renderCallbackCalled).toBe(false); - // Do the rest of the work. - ReactNoop.flushDeferredPri(50); - expect(fooCalled).toBe(true); - expect(barCalled).toBe(true); - expect(renderCallbackCalled).toBe(true); - }); - - it('updates a previous render', () => { - var ops = []; - - function Header() { - ops.push('Header'); - return

Hi

; - } - - function Content(props) { - ops.push('Content'); - return
{props.children}
; - } - - function Footer() { - ops.push('Footer'); - return
Bye
; - } - - var header =
; - var footer =