UNPKG

react-art

Version:

React ART is a JavaScript library for drawing vector graphics using React. It provides declarative and reactive bindings to the ART library. Using the same declarative API you can render the output to either Canvas, SVG or VML (IE8).

1,717 lines (1,410 loc) • 618 kB
/** @license React v16.10.2 * react-art.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; if (process.env.NODE_ENV !== "production") { (function() { 'use strict'; var React = require('react'); var _assign = require('object-assign'); var Transform = require('art/core/transform'); var Mode = require('art/modes/current'); var checkPropTypes = require('prop-types/checkPropTypes'); var Scheduler = require('scheduler'); var tracing = require('scheduler/tracing'); var FastNoSideEffects = require('art/modes/fast-noSideEffects'); function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } // TODO: this is special because it gets imported during build. var ReactVersion = '16.10.2'; var LegacyRoot = 0; var BatchedRoot = 1; var ConcurrentRoot = 2; // Do not require this module directly! Use normal `invariant` calls with // template literal strings. The messages will be converted to ReactError during // build, and in production they will be minified. // Do not require this module directly! Use normal `invariant` calls with // template literal strings. The messages will be converted to ReactError during // build, and in production they will be minified. function ReactError(error) { error.name = 'Invariant Violation'; return error; } var FunctionComponent = 0; var ClassComponent = 1; var IndeterminateComponent = 2; // Before we know whether it is function or class var HostRoot = 3; // Root of a host tree. Could be nested inside another node. var HostPortal = 4; // A subtree. Could be an entry point to a different renderer. var HostComponent = 5; var HostText = 6; var Fragment = 7; var Mode$1 = 8; var ContextConsumer = 9; var ContextProvider = 10; var ForwardRef = 11; var Profiler = 12; var SuspenseComponent = 13; var MemoComponent = 14; var SimpleMemoComponent = 15; var LazyComponent = 16; var IncompleteClassComponent = 17; var DehydratedFragment = 18; var SuspenseListComponent = 19; var FundamentalComponent = 20; var ScopeComponent = 21; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warningWithoutStack = function () {}; { warningWithoutStack = function (condition, format) { for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } if (format === undefined) { throw new Error('`warningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument'); } if (args.length > 8) { // Check before the condition to catch violations early. throw new Error('warningWithoutStack() currently supports at most 8 arguments.'); } if (condition) { return; } if (typeof console !== 'undefined') { var argsWithFormat = args.map(function (item) { return '' + item; }); argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it // breaks IE9: https://github.com/facebook/react/issues/13610 Function.prototype.apply.call(console.error, console, argsWithFormat); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); throw new Error(message); } catch (x) {} }; } var warningWithoutStack$1 = warningWithoutStack; /** * `ReactInstanceMap` maintains a mapping from a public facing stateful * instance (key) and the internal representation (value). This allows public * methods to accept the user facing instance as an argument and map them back * to internal methods. * * Note that this module is currently shared and assumed to be stateless. * If this becomes an actual Map, that will break. */ /** * This API should be called `delete` but we'd have to make sure to always * transform these to strings for IE support. When this transform is fully * supported we can rename it. */ function get(key) { return key._reactInternalFiber; } function set$1(key, value) { key._reactInternalFiber = value; } var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; // Prevent newer renderers from RTE when used with older react package versions. // Current owner and dispatcher used to share the same ref, // but PR #14548 split them out to better support the react-debug-tools package. if (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) { ReactSharedInternals.ReactCurrentDispatcher = { current: null }; } if (!ReactSharedInternals.hasOwnProperty('ReactCurrentBatchConfig')) { ReactSharedInternals.ReactCurrentBatchConfig = { suspense: null }; } // The Symbol used to tag the ReactElement-like types. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var hasSymbol = typeof Symbol === 'function' && Symbol.for; var REACT_ELEMENT_TYPE$1 = hasSymbol ? Symbol.for('react.element') : 0xeac7; var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca; var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb; var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc; var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2; var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd; var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary // (unstable) APIs that have been removed. Can we remove the symbols? var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf; var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0; var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1; var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8; var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3; var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4; var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5; var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6; var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7; var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== 'object') { return null; } var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; if (typeof maybeIterator === 'function') { return maybeIterator; } return null; } /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = warningWithoutStack$1; { warning = function (condition, format) { if (condition) { return; } var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; var stack = ReactDebugCurrentFrame.getStackAddendum(); // eslint-disable-next-line react-internal/warning-and-invariant-args for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } warningWithoutStack$1.apply(void 0, [false, format + '%s'].concat(args, [stack])); }; } var warning$1 = warning; var Uninitialized = -1; var Pending = 0; var Resolved = 1; var Rejected = 2; function refineResolvedLazyComponent(lazyComponent) { return lazyComponent._status === Resolved ? lazyComponent._result : null; } function initializeLazyComponentType(lazyComponent) { if (lazyComponent._status === Uninitialized) { lazyComponent._status = Pending; var ctor = lazyComponent._ctor; var thenable = ctor(); lazyComponent._result = thenable; thenable.then(function (moduleObject) { if (lazyComponent._status === Pending) { var defaultExport = moduleObject.default; { if (defaultExport === undefined) { warning$1(false, 'lazy: Expected the result of a dynamic import() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + "const MyComponent = lazy(() => import('./MyComponent'))", moduleObject); } } lazyComponent._status = Resolved; lazyComponent._result = defaultExport; } }, function (error) { if (lazyComponent._status === Pending) { lazyComponent._status = Rejected; lazyComponent._result = error; } }); } } function getWrappedName(outerType, innerType, wrapperName) { var functionName = innerType.displayName || innerType.name || ''; return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName); } function getComponentName(type) { if (type == null) { // Host root, text node or just invalid type. return null; } { if (typeof type.tag === 'number') { warningWithoutStack$1(false, 'Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.'); } } if (typeof type === 'function') { return type.displayName || type.name || null; } if (typeof type === 'string') { return type; } switch (type) { case REACT_FRAGMENT_TYPE: return 'Fragment'; case REACT_PORTAL_TYPE: return 'Portal'; case REACT_PROFILER_TYPE: return "Profiler"; case REACT_STRICT_MODE_TYPE: return 'StrictMode'; case REACT_SUSPENSE_TYPE: return 'Suspense'; case REACT_SUSPENSE_LIST_TYPE: return 'SuspenseList'; } if (typeof type === 'object') { switch (type.$$typeof) { case REACT_CONTEXT_TYPE: return 'Context.Consumer'; case REACT_PROVIDER_TYPE: return 'Context.Provider'; case REACT_FORWARD_REF_TYPE: return getWrappedName(type, type.render, 'ForwardRef'); case REACT_MEMO_TYPE: return getComponentName(type.type); case REACT_LAZY_TYPE: { var thenable = type; var resolvedThenable = refineResolvedLazyComponent(thenable); if (resolvedThenable) { return getComponentName(resolvedThenable); } break; } } } return null; } // Don't change these two values. They're used by React Dev Tools. var NoEffect = /* */ 0; var PerformedWork = /* */ 1; // You can change the rest (and add more). var Placement = /* */ 2; var Update = /* */ 4; var PlacementAndUpdate = /* */ 6; var Deletion = /* */ 8; var ContentReset = /* */ 16; var Callback = /* */ 32; var DidCapture = /* */ 64; var Ref = /* */ 128; var Snapshot = /* */ 256; var Passive = /* */ 512; var Hydrating = /* */ 1024; var HydratingAndUpdate = /* */ 1028; // Passive & Update & Callback & Ref & Snapshot var LifecycleEffectMask = /* */ 932; // Union of all host effects var HostEffectMask = /* */ 2047; var Incomplete = /* */ 2048; var ShouldCapture = /* */ 4096; var enableUserTimingAPI = true; // Helps identify side effects in begin-phase lifecycle hooks and setState reducers: var debugRenderPhaseSideEffects = false; // In some cases, StrictMode should also double-render lifecycles. // This can be confusing for tests though, // And it can be bad for performance in production. // This feature flag can be used to control the behavior: var debugRenderPhaseSideEffectsForStrictMode = true; // To preserve the "Pause on caught exceptions" behavior of the debugger, we // replay the begin phase of a failed component inside invokeGuardedCallback. var replayFailedUnitOfWorkWithInvokeGuardedCallback = true; // Warn about deprecated, async-unsafe lifecycles; relates to RFC #6: var warnAboutDeprecatedLifecycles = true; // Gather advanced timing metrics for Profiler subtrees. var enableProfilerTimer = true; // Trace which interactions trigger each commit. var enableSchedulerTracing = true; // Only used in www builds. var enableSuspenseServerRenderer = false; // TODO: true? Here it might just be false. // Only used in www builds. // Only used in www builds. // Disable javascript: URL strings in href for XSS protection. // React Fire: prevent the value and checked attributes from syncing // with their related DOM properties // These APIs will no longer be "unstable" in the upcoming 16.7 release, // Control this behavior with a flag to support 16.6 minor releases in the meanwhile. // See https://github.com/react-native-community/discussions-and-proposals/issues/72 for more information // This is a flag so we can fix warnings in RN core before turning it on // Experimental React Flare event system and event components support. var enableFlareAPI = false; // Experimental Host Component support. var enableFundamentalAPI = false; // Experimental Scope support. var enableScopeAPI = false; // New API for JSX transforms to target - https://github.com/reactjs/rfcs/pull/107 // We will enforce mocking scheduler with scheduler/unstable_mock at some point. (v17?) // Till then, we warn about the missing mock, but still fallback to a sync mode compatible version var warnAboutUnmockedScheduler = false; // For tests, we flush suspense fallbacks in an act scope; // *except* in some of our own tests, where we test incremental loading states. var flushSuspenseFallbacksInTests = true; // Changes priority of some events like mousemove to user-blocking priority, // but without making them discrete. The flag exists in case it causes // starvation problems. // Add a callback property to suspense to notify which promises are currently // in the update queue. This allows reporting and tracing of what is causing // the user to see a loading state. // Also allows hydration callbacks to fire when a dehydrated boundary gets // hydrated or deleted. var enableSuspenseCallback = false; // Part of the simplification of React.createElement so we can eventually move // from React.createElement to React.jsx // https://github.com/reactjs/rfcs/blob/createlement-rfc/text/0000-create-element-changes.md var warnAboutDefaultPropsOnFunctionComponents = false; var warnAboutStringRefs = false; var disableLegacyContext = false; var disableSchedulerTimeoutBasedOnReactExpirationTime = false; var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; function getNearestMountedFiber(fiber) { var node = fiber; var nearestMounted = fiber; if (!fiber.alternate) { // If there is no alternate, this might be a new tree that isn't inserted // yet. If it is, then it will have a pending insertion effect on it. var nextNode = node; do { node = nextNode; if ((node.effectTag & (Placement | Hydrating)) !== NoEffect) { // This is an insertion or in-progress hydration. The nearest possible // mounted fiber is the parent but we need to continue to figure out // if that one is still mounted. nearestMounted = node.return; } nextNode = node.return; } while (nextNode); } else { while (node.return) { node = node.return; } } if (node.tag === HostRoot) { // TODO: Check if this was a nested HostRoot when used with // renderContainerIntoSubtree. return nearestMounted; } // If we didn't hit the root, that means that we're in an disconnected tree // that has been unmounted. return null; } function isFiberMounted(fiber) { return getNearestMountedFiber(fiber) === fiber; } function isMounted(component) { { var owner = ReactCurrentOwner.current; if (owner !== null && owner.tag === ClassComponent) { var ownerFiber = owner; var instance = ownerFiber.stateNode; !instance._warnedAboutRefsInRender ? warningWithoutStack$1(false, '%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentName(ownerFiber.type) || 'A component') : void 0; instance._warnedAboutRefsInRender = true; } } var fiber = get(component); if (!fiber) { return false; } return getNearestMountedFiber(fiber) === fiber; } function assertIsMounted(fiber) { (function () { if (!(getNearestMountedFiber(fiber) === fiber)) { { throw ReactError(Error("Unable to find node on an unmounted component.")); } } })(); } function findCurrentFiberUsingSlowPath(fiber) { var alternate = fiber.alternate; if (!alternate) { // If there is no alternate, then we only need to check if it is mounted. var nearestMounted = getNearestMountedFiber(fiber); (function () { if (!(nearestMounted !== null)) { { throw ReactError(Error("Unable to find node on an unmounted component.")); } } })(); if (nearestMounted !== fiber) { return null; } return fiber; } // If we have two possible branches, we'll walk backwards up to the root // to see what path the root points to. On the way we may hit one of the // special cases and we'll deal with them. var a = fiber; var b = alternate; while (true) { var parentA = a.return; if (parentA === null) { // We're at the root. break; } var parentB = parentA.alternate; if (parentB === null) { // There is no alternate. This is an unusual case. Currently, it only // happens when a Suspense component is hidden. An extra fragment fiber // is inserted in between the Suspense fiber and its children. Skip // over this extra fragment fiber and proceed to the next parent. var nextParent = parentA.return; if (nextParent !== null) { a = b = nextParent; continue; } // If there's no parent, we're at the root. break; } // If both copies of the parent fiber point to the same child, we can // assume that the child is current. This happens when we bailout on low // priority: the bailed out fiber's child reuses the current child. if (parentA.child === parentB.child) { var child = parentA.child; while (child) { if (child === a) { // We've determined that A is the current branch. assertIsMounted(parentA); return fiber; } if (child === b) { // We've determined that B is the current branch. assertIsMounted(parentA); return alternate; } child = child.sibling; } // We should never have an alternate for any mounting node. So the only // way this could possibly happen is if this was unmounted, if at all. (function () { { { throw ReactError(Error("Unable to find node on an unmounted component.")); } } })(); } if (a.return !== b.return) { // The return pointer of A and the return pointer of B point to different // fibers. We assume that return pointers never criss-cross, so A must // belong to the child set of A.return, and B must belong to the child // set of B.return. a = parentA; b = parentB; } else { // The return pointers point to the same fiber. We'll have to use the // default, slow path: scan the child sets of each parent alternate to see // which child belongs to which set. // // Search parent A's child set var didFindChild = false; var _child = parentA.child; while (_child) { if (_child === a) { didFindChild = true; a = parentA; b = parentB; break; } if (_child === b) { didFindChild = true; b = parentA; a = parentB; break; } _child = _child.sibling; } if (!didFindChild) { // Search parent B's child set _child = parentB.child; while (_child) { if (_child === a) { didFindChild = true; a = parentB; b = parentA; break; } if (_child === b) { didFindChild = true; b = parentB; a = parentA; break; } _child = _child.sibling; } (function () { if (!didFindChild) { { throw ReactError(Error("Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue.")); } } })(); } } (function () { if (!(a.alternate === b)) { { throw ReactError(Error("Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue.")); } } })(); } // If the root is not a host container, we're in a disconnected tree. I.e. // unmounted. (function () { if (!(a.tag === HostRoot)) { { throw ReactError(Error("Unable to find node on an unmounted component.")); } } })(); if (a.stateNode.current === a) { // We've determined that A is the current branch. return fiber; } // Otherwise B has to be current branch. return alternate; } function findCurrentHostFiber(parent) { var currentParent = findCurrentFiberUsingSlowPath(parent); if (!currentParent) { return null; } // Next we'll drill down this component to find the first HostComponent/Text. var node = currentParent; while (true) { if (node.tag === HostComponent || node.tag === HostText) { return node; } else if (node.child) { node.child.return = node; node = node.child; continue; } if (node === currentParent) { return null; } while (!node.sibling) { if (!node.return || node.return === currentParent) { return null; } node = node.return; } node.sibling.return = node.return; node = node.sibling; } // Flow needs the return null here, but ESLint complains about it. // eslint-disable-next-line no-unreachable return null; } var TYPES = { CLIPPING_RECTANGLE: 'ClippingRectangle', GROUP: 'Group', SHAPE: 'Shape', TEXT: 'Text' }; var EVENT_TYPES = { onClick: 'click', onMouseMove: 'mousemove', onMouseOver: 'mouseover', onMouseOut: 'mouseout', onMouseUp: 'mouseup', onMouseDown: 'mousedown' }; function childrenAsString(children) { if (!children) { return ''; } else if (typeof children === 'string') { return children; } else if (children.length) { return children.join(''); } else { return ''; } } // can re-export everything from this module. function shim() { (function () { { { throw ReactError(Error("The current renderer does not support persistence. This error is likely caused by a bug in React. Please file an issue.")); } } })(); } // Persistence (when unsupported) var supportsPersistence = false; var cloneInstance = shim; var cloneFundamentalInstance = shim; var createContainerChildSet = shim; var appendChildToContainerChildSet = shim; var finalizeContainerChildren = shim; var replaceContainerChildren = shim; var cloneHiddenInstance = shim; var cloneHiddenTextInstance = shim; // can re-export everything from this module. function shim$1() { (function () { { { throw ReactError(Error("The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue.")); } } })(); } // Hydration (when unsupported) var supportsHydration = false; var canHydrateInstance = shim$1; var canHydrateTextInstance = shim$1; var canHydrateSuspenseInstance = shim$1; var isSuspenseInstancePending = shim$1; var isSuspenseInstanceFallback = shim$1; var registerSuspenseInstanceRetry = shim$1; var getNextHydratableSibling = shim$1; var getFirstHydratableChild = shim$1; var hydrateInstance = shim$1; var hydrateTextInstance = shim$1; var hydrateSuspenseInstance = shim$1; var getNextHydratableInstanceAfterSuspenseInstance = shim$1; var commitHydratedContainer = shim$1; var commitHydratedSuspenseInstance = shim$1; var clearSuspenseBoundary = shim$1; var clearSuspenseBoundaryFromContainer = shim$1; var didNotMatchHydratedContainerTextInstance = shim$1; var didNotMatchHydratedTextInstance = shim$1; var didNotHydrateContainerInstance = shim$1; var didNotHydrateInstance = shim$1; var didNotFindHydratableContainerInstance = shim$1; var didNotFindHydratableContainerTextInstance = shim$1; var didNotFindHydratableContainerSuspenseInstance = shim$1; var didNotFindHydratableInstance = shim$1; var didNotFindHydratableTextInstance = shim$1; var didNotFindHydratableSuspenseInstance = shim$1; var pooledTransform = new Transform(); var NO_CONTEXT = {}; var UPDATE_SIGNAL = {}; { Object.freeze(NO_CONTEXT); Object.freeze(UPDATE_SIGNAL); } /** Helper Methods */ function addEventListeners(instance, type, listener) { // We need to explicitly unregister before unmount. // For this reason we need to track subscriptions. if (!instance._listeners) { instance._listeners = {}; instance._subscriptions = {}; } instance._listeners[type] = listener; if (listener) { if (!instance._subscriptions[type]) { instance._subscriptions[type] = instance.subscribe(type, createEventHandler(instance), instance); } } else { if (instance._subscriptions[type]) { instance._subscriptions[type](); delete instance._subscriptions[type]; } } } function createEventHandler(instance) { return function handleEvent(event) { var listener = instance._listeners[event.type]; if (!listener) {// Noop } else if (typeof listener === 'function') { listener.call(instance, event); } else if (listener.handleEvent) { listener.handleEvent(event); } }; } function destroyEventListeners(instance) { if (instance._subscriptions) { for (var type in instance._subscriptions) { instance._subscriptions[type](); } } instance._subscriptions = null; instance._listeners = null; } function getScaleX(props) { if (props.scaleX != null) { return props.scaleX; } else if (props.scale != null) { return props.scale; } else { return 1; } } function getScaleY(props) { if (props.scaleY != null) { return props.scaleY; } else if (props.scale != null) { return props.scale; } else { return 1; } } function isSameFont(oldFont, newFont) { if (oldFont === newFont) { return true; } else if (typeof newFont === 'string' || typeof oldFont === 'string') { return false; } else { return newFont.fontSize === oldFont.fontSize && newFont.fontStyle === oldFont.fontStyle && newFont.fontVariant === oldFont.fontVariant && newFont.fontWeight === oldFont.fontWeight && newFont.fontFamily === oldFont.fontFamily; } } /** Render Methods */ function applyClippingRectangleProps(instance, props) { var prevProps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; applyNodeProps(instance, props, prevProps); instance.width = props.width; instance.height = props.height; } function applyGroupProps(instance, props) { var prevProps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; applyNodeProps(instance, props, prevProps); instance.width = props.width; instance.height = props.height; } function applyNodeProps(instance, props) { var prevProps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var scaleX = getScaleX(props); var scaleY = getScaleY(props); pooledTransform.transformTo(1, 0, 0, 1, 0, 0).move(props.x || 0, props.y || 0).rotate(props.rotation || 0, props.originX, props.originY).scale(scaleX, scaleY, props.originX, props.originY); if (props.transform != null) { pooledTransform.transform(props.transform); } if (instance.xx !== pooledTransform.xx || instance.yx !== pooledTransform.yx || instance.xy !== pooledTransform.xy || instance.yy !== pooledTransform.yy || instance.x !== pooledTransform.x || instance.y !== pooledTransform.y) { instance.transformTo(pooledTransform); } if (props.cursor !== prevProps.cursor || props.title !== prevProps.title) { instance.indicate(props.cursor, props.title); } if (instance.blend && props.opacity !== prevProps.opacity) { instance.blend(props.opacity == null ? 1 : props.opacity); } if (props.visible !== prevProps.visible) { if (props.visible == null || props.visible) { instance.show(); } else { instance.hide(); } } for (var type in EVENT_TYPES) { addEventListeners(instance, EVENT_TYPES[type], props[type]); } } function applyRenderableNodeProps(instance, props) { var prevProps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; applyNodeProps(instance, props, prevProps); if (prevProps.fill !== props.fill) { if (props.fill && props.fill.applyFill) { props.fill.applyFill(instance); } else { instance.fill(props.fill); } } if (prevProps.stroke !== props.stroke || prevProps.strokeWidth !== props.strokeWidth || prevProps.strokeCap !== props.strokeCap || prevProps.strokeJoin !== props.strokeJoin || // TODO: Consider deep check of stokeDash; may benefit VML in IE. prevProps.strokeDash !== props.strokeDash) { instance.stroke(props.stroke, props.strokeWidth, props.strokeCap, props.strokeJoin, props.strokeDash); } } function applyShapeProps(instance, props) { var prevProps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; applyRenderableNodeProps(instance, props, prevProps); var path = props.d || childrenAsString(props.children); var prevDelta = instance._prevDelta; var prevPath = instance._prevPath; if (path !== prevPath || path.delta !== prevDelta || prevProps.height !== props.height || prevProps.width !== props.width) { instance.draw(path, props.width, props.height); instance._prevDelta = path.delta; instance._prevPath = path; } } function applyTextProps(instance, props) { var prevProps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; applyRenderableNodeProps(instance, props, prevProps); var string = props.children; if (instance._currentString !== string || !isSameFont(props.font, prevProps.font) || props.alignment !== prevProps.alignment || props.path !== prevProps.path) { instance.draw(string, props.font, props.alignment, props.path); instance._currentString = string; } } function appendInitialChild(parentInstance, child) { if (typeof child === 'string') { // Noop for string children of Text (eg <Text>{'foo'}{'bar'}</Text>) (function () { { { throw ReactError(Error("Text children should already be flattened.")); } } })(); return; } child.inject(parentInstance); } function createInstance(type, props, internalInstanceHandle) { var instance; switch (type) { case TYPES.CLIPPING_RECTANGLE: instance = Mode.ClippingRectangle(); instance._applyProps = applyClippingRectangleProps; break; case TYPES.GROUP: instance = Mode.Group(); instance._applyProps = applyGroupProps; break; case TYPES.SHAPE: instance = Mode.Shape(); instance._applyProps = applyShapeProps; break; case TYPES.TEXT: instance = Mode.Text(props.children, props.font, props.alignment, props.path); instance._applyProps = applyTextProps; break; } (function () { if (!instance) { { throw ReactError(Error("ReactART does not support the type \"" + type + "\"")); } } })(); instance._applyProps(instance, props); return instance; } function createTextInstance(text, rootContainerInstance, internalInstanceHandle) { return text; } function finalizeInitialChildren(domElement, type, props) { return false; } function getPublicInstance(instance) { return instance; } function prepareForCommit() {// Noop } function prepareUpdate(domElement, type, oldProps, newProps) { return UPDATE_SIGNAL; } function resetAfterCommit() {// Noop } function resetTextContent(domElement) {// Noop } function shouldDeprioritizeSubtree(type, props) { return false; } function getRootHostContext() { return NO_CONTEXT; } function getChildHostContext() { return NO_CONTEXT; } var scheduleTimeout = setTimeout; var cancelTimeout = clearTimeout; var noTimeout = -1; function shouldSetTextContent(type, props) { return typeof props.children === 'string' || typeof props.children === 'number'; } // The ART renderer is secondary to the React DOM renderer. var isPrimaryRenderer = false; // The ART renderer shouldn't trigger missing act() warnings var warnsIfNotActing = false; var supportsMutation = true; function appendChild(parentInstance, child) { if (child.parentNode === parentInstance) { child.eject(); } child.inject(parentInstance); } function appendChildToContainer(parentInstance, child) { if (child.parentNode === parentInstance) { child.eject(); } child.inject(parentInstance); } function insertBefore(parentInstance, child, beforeChild) { (function () { if (!(child !== beforeChild)) { { throw ReactError(Error("ReactART: Can not insert node before itself")); } } })(); child.injectBefore(beforeChild); } function insertInContainerBefore(parentInstance, child, beforeChild) { (function () { if (!(child !== beforeChild)) { { throw ReactError(Error("ReactART: Can not insert node before itself")); } } })(); child.injectBefore(beforeChild); } function removeChild(parentInstance, child) { destroyEventListeners(child); child.eject(); } function removeChildFromContainer(parentInstance, child) { destroyEventListeners(child); child.eject(); } function commitUpdate(instance, updatePayload, type, oldProps, newProps) { instance._applyProps(instance, newProps, oldProps); } function hideInstance(instance) { instance.hide(); } function unhideInstance(instance, props) { if (props.visible == null || props.visible) { instance.show(); } } function unhideTextInstance(textInstance, text) {// Noop } function mountResponderInstance(responder, responderInstance, props, state, instance) { throw new Error('Not yet implemented.'); } function unmountResponderInstance(responderInstance) { throw new Error('Not yet implemented.'); } function getFundamentalComponentInstance(fundamentalInstance) { throw new Error('Not yet implemented.'); } function mountFundamentalComponent(fundamentalInstance) { throw new Error('Not yet implemented.'); } function shouldUpdateFundamentalComponent(fundamentalInstance) { throw new Error('Not yet implemented.'); } function updateFundamentalComponent(fundamentalInstance) { throw new Error('Not yet implemented.'); } function unmountFundamentalComponent(fundamentalInstance) { throw new Error('Not yet implemented.'); } var BEFORE_SLASH_RE = /^(.*)[\\\/]/; var describeComponentFrame = function (name, source, ownerName) { var sourceInfo = ''; if (source) { var path = source.fileName; var fileName = path.replace(BEFORE_SLASH_RE, ''); { // In DEV, include code for a common special case: // prefer "folder/index.js" instead of just "index.js". if (/^index\./.test(fileName)) { var match = path.match(BEFORE_SLASH_RE); if (match) { var pathBeforeSlash = match[1]; if (pathBeforeSlash) { var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, ''); fileName = folderName + '/' + fileName; } } } } sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')'; } else if (ownerName) { sourceInfo = ' (created by ' + ownerName + ')'; } return '\n in ' + (name || 'Unknown') + sourceInfo; }; var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; function describeFiber(fiber) { switch (fiber.tag) { case HostRoot: case HostPortal: case HostText: case Fragment: case ContextProvider: case ContextConsumer: return ''; default: var owner = fiber._debugOwner; var source = fiber._debugSource; var name = getComponentName(fiber.type); var ownerName = null; if (owner) { ownerName = getComponentName(owner.type); } return describeComponentFrame(name, source, ownerName); } } function getStackByFiberInDevAndProd(workInProgress) { var info = ''; var node = workInProgress; do { info += describeFiber(node); node = node.return; } while (node); return info; } var current = null; var phase = null; function getCurrentFiberOwnerNameInDevOrNull() { { if (current === null) { return null; } var owner = current._debugOwner; if (owner !== null && typeof owner !== 'undefined') { return getComponentName(owner.type); } } return null; } function getCurrentFiberStackInDev() { { if (current === null) { return ''; } // Safe because if current fiber exists, we are reconciling, // and it is guaranteed to be the work-in-progress version. return getStackByFiberInDevAndProd(current); } return ''; } function resetCurrentFiber() { { ReactDebugCurrentFrame.getCurrentStack = null; current = null; phase = null; } } function setCurrentFiber(fiber) { { ReactDebugCurrentFrame.getCurrentStack = getCurrentFiberStackInDev; current = fiber; phase = null; } } function setCurrentPhase(lifeCyclePhase) { { phase = lifeCyclePhase; } } // Prefix measurements so that it's possible to filter them. // Longer prefixes are hard to read in DevTools. var reactEmoji = "\u269B"; var warningEmoji = "\u26D4"; var 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? var currentFiber = null; // If we're in the middle of user code, which fiber and method is it? // Reusing `currentFiber` would be confusing for this because user code fiber // can change during commit phase too, but we don't need to unwind it (since // lifecycles in the commit phase don't resemble a tree). var currentPhase = null; var currentPhaseFiber = null; // Did lifecycle hook schedule an update? This is often a performance problem, // so we will keep track of it, and include it in the report. // Track commits caused by cascading updates. var isCommitting = false; var hasScheduledUpdateInCurrentCommit = false; var hasScheduledUpdateInCurrentPhase = false; var commitCountInCurrentWorkLoop = 0; var effectCountInCurrentCommit = 0; // to avoid stretch the commit phase with measurement overhead. var labelsInCurrentCommit = new Set(); var formatMarkName = function (markName) { return reactEmoji + " " + markName; }; var formatLabel = function (label, warning) { var prefix = warning ? warningEmoji + " " : reactEmoji + " "; var suffix = warning ? " Warning: " + warning : ''; return "" + prefix + label + suffix; }; var beginMark = function (markName) { performance.mark(formatMarkName(markName)); }; var clearMark = function (markName) { performance.clearMarks(formatMarkName(markName)); }; var endMark = function (label, markName, warning) { var formattedMarkName = formatMarkName(markName); var formattedLabel = formatLabel(label, warning); try { performance.measure(formattedLabel, formattedMarkName); } catch (err) {} // If previous mark was missing for some reason, this will throw. // 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); }; var getFiberMarkName = function (label, debugID) { return label + " (#" + debugID + ")"; }; var getFiberLabel = function (componentName, isMounted, phase) { if (phase === null) { // These are composite component total time measurements. return componentName + " [" + (isMounted ? 'update' : 'mount') + "]"; } else { // Composite component methods. return componentName + "." + phase; } }; var beginFiberMark = function (fiber, phase) { var componentName = getComponentName(fiber.type) || 'Unknown'; var debugID = fiber._debugID; var isMounted = fiber.alternate !== null; var 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); var markName = getFiberMarkName(label, debugID); beginMark(markName); return true; }; var clearFiberMark = function (fiber, phase) { var componentName = getComponentName(fiber.type) || 'Unknown'; var debugID = fiber._debugID; var isMounted = fiber.alternate !== null; var label = getFiberLabel(componentName, isMounted, phase); var markName = getFiberMarkName(label, debugID); clearMark(markName); }; var endFiberMark = function (fiber, phase, warning) { var componentName = getComponentName(fiber.type) || 'Unknown'; var debugID = fiber._debugID; var isMounted = fiber.alternate !== null; var label = getFiberLabel(componentName, isMounted, phase); var markName = getFiberMarkName(label, debugID); endMark(label, markName, warning); }; var shouldIgnoreFiber = function (fiber) { // 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 Fragment: case ContextProvider: case ContextConsumer: case Mode$1: return true; default: return false; } }; var clearPendingPhaseMeasurement = function () { if (currentPhase !== null && currentPhaseFiber !== null) { clearFiberMark(currentPhaseFiber, currentPhase); } currentPhaseFiber = null; currentPhase = null; hasScheduledUpdateInCurrentPhase = false; }; var pauseTimers = function () { // Stops all currently active measurements so that they can be resumed // if we continue in a later deferred loop from the same unit of work. var fiber = currentFiber; while (fiber) { if (fiber._debugIsCurrentlyTiming) { endFiberMark(fiber, null, null); } fiber = fiber.return; } }; var resumeTimersRecursively = function (fiber) { if (fiber.return !== null) { resumeTimersRecursively(fiber.return); } if (fiber._debugIsCurrentlyTiming) { beginFiberMark(fiber, null); } }; var resumeTimers = function () { // Resumes all measurements that were active during the last deferred loop. if (currentFiber !== null) { resumeTimersRecursively(currentFiber); } }; function recordEffect() { if (enableUserTimingAPI) { effectCountInCurrentCommit++; } } function recordScheduleUpdate() { if (enableUserTimingAPI) { if (isCommitting) { hasScheduledUpdateInCurrentCommit = true; } if (currentPhase !== null && currentPhase !== 'componentWillMount' && currentPhase !== 'componentWillReceiveProps') { hasScheduledUpdateInCurrentPhase = true; } } } function startWorkTimer(fiber) { if (enableUserTimingAPI) { 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; } } function cancelWorkTimer(fiber) { if (enableUserTimingAPI) { 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); } } function stopWorkTimer(fiber) { if (enableUserTimingAPI) { 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); } } function stopFailedWorkTimer(fiber) { if (enableUserTimingAPI) { 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; var warning = fiber.tag === SuspenseComponent ? 'Rendering was suspended' : 'An error was thrown inside this error boundary'; endFiberMark(fiber, null, warning); } } function startPhaseTimer(fiber, phase) { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } clearPendingPhaseMeasurement(); if (!beginFiberMark(fiber, phase)) { return; } currentPhaseFiber = fiber; currentPhase = phase; } } function stopPhaseTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } if (currentPhase !== null && currentPhaseFiber !== null) { var warning = hasScheduledUpdateInCurrentPhase ? 'Scheduled a cascading update' : null; endFiberMark(currentPhaseFiber, currentPhase, warning); } currentPhase = null; currentPhaseFiber = null; } } function startWorkLoopTimer(nextUnitOfWork) { if (enableUserTimingAPI) { currentFiber = nextUnitOfWork; if (!supportsUserTiming) { return; } commitCountInCurrentWorkLoop = 0; // This is top level call. // Any other measurements are performed within. beginMark('(React Tree Reconciliation)'); // Resume any measurements that were in progress during the last loop. resumeTimers(); } } function stopWorkLoopTimer(interruptedBy, didCompleteRoot) { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } var warning = null; if (interruptedBy !== null) { if (interruptedBy.tag === HostRoot) { warning = 'A top-level update interrupted the previous render'; } else { var componentName = getComponentName(interruptedBy.type) || 'Unknown'; warning = "An update to " + componentName + " interrupted the previous render"; } } else if (commitCountInCurrentWorkLoop > 1) { warning = 'There were cascading updates'; } commitCountInCurrentWorkLoop = 0; var label = didCompleteRoot ? '(React Tree Reconciliation: Completed Root)' : '(React Tree Reconciliation: Yielded)'; // Pause any measurements until the next loop. pauseTimers(); endMark(label, '(React Tree Reconciliation)', warning); } } function startCommitTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } isCommitting = true; hasScheduledUpdateInCurrentCommit = false; labelsInCurrentCommit.clear(); beginMark('(Committing Changes)'); } } function stopCommitTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } var warning = null; if (hasSchedu