UNPKG

@visactor/vrender-core

Version:
1,494 lines (1,462 loc) 1.14 MB
import { tau, halfPi as halfPi$1, AABBBounds, degreeToRadian, PointService, Point, abs, max, min, atan2, epsilon, Matrix, pi2, Logger, pi, isArray, isPointInLine, isNumberClose, TextMeasure, EventEmitter, isBoolean, isObject, isFunction, isString, has, isUndefined, cos, sin, pointAt, isNumber, getDecimalPlaces, isValidNumber, clamp, getAngleByPoint, isNil, Bounds, getIntersectPoint, Color, DEFAULT_COLORS, sqrt, OBBBounds, normalTransform, isValidUrl, isBase64, acos, LRU, lowerCamelCaseToMiddle, isValid, transformBoundsWithMatrix, getContextFont, rotatePoint, clampAngleByRadian, asin, arrayEqual, getRectIntersect, isRectIntersect, merge, calculateAnchorOfBounds, styleStringToObject } from '@visactor/vutils'; class Generator { static GenAutoIncrementId() { return Generator.auto_increment_id++; } } Generator.auto_increment_id = 0; class ContainerModule { constructor(registry) { this.id = Generator.GenAutoIncrementId(); this.registry = registry; } } const NAMED_TAG = 'named'; const INJECT_TAG = 'inject'; const MULTI_INJECT_TAG = 'multi_inject'; const TAGGED = 'inversify:tagged'; const PARAM_TYPES = 'inversify:paramtypes'; class Metadata { constructor(key, value) { this.key = key; this.value = value; } toString() { if (this.key === NAMED_TAG) { return `named: ${String(this.value).toString()} `; } return `tagged: { key:${this.key.toString()}, value: ${String(this.value)} }`; } } var Reflect$1 = (function (Reflect) { (function (factory) { const exporter = makeExporter(Reflect); factory(exporter); function makeExporter(target, previous) { return function (key, value) { if (typeof target[key] !== 'function') { Object.defineProperty(target, key, { configurable: true, writable: true, value: value }); } if (previous) { previous(key, value); } }; } })(function (exporter) { const supportsSymbol = typeof Symbol === 'function'; const toPrimitiveSymbol = supportsSymbol && typeof Symbol.toPrimitive !== 'undefined' ? Symbol.toPrimitive : '@@toPrimitive'; const functionPrototype = Object.getPrototypeOf(Function); typeof process === 'object' && process.env && process.env.REFLECT_METADATA_USE_MAP_POLYFILL === 'true'; const _Map = Map; const _WeakMap = WeakMap; const Metadata = new _WeakMap(); function defineMetadata(metadataKey, metadataValue, target, propertyKey) { if (!IsObject(target)) { throw new TypeError(); } return OrdinaryDefineOwnMetadata(metadataKey, metadataValue, target, propertyKey); } exporter('defineMetadata', defineMetadata); function hasMetadata(metadataKey, target, propertyKey) { if (!IsObject(target)) { throw new TypeError(); } if (!IsUndefined(propertyKey)) { propertyKey = ToPropertyKey(propertyKey); } return OrdinaryHasMetadata(metadataKey, target, propertyKey); } exporter('hasMetadata', hasMetadata); function hasOwnMetadata(metadataKey, target, propertyKey) { if (!IsObject(target)) { throw new TypeError(); } if (!IsUndefined(propertyKey)) { propertyKey = ToPropertyKey(propertyKey); } return OrdinaryHasOwnMetadata(metadataKey, target, propertyKey); } exporter('hasOwnMetadata', hasOwnMetadata); function getMetadata(metadataKey, target, propertyKey) { if (!IsObject(target)) { throw new TypeError(); } if (!IsUndefined(propertyKey)) { propertyKey = ToPropertyKey(propertyKey); } return OrdinaryGetMetadata(metadataKey, target, propertyKey); } exporter('getMetadata', getMetadata); function GetOrCreateMetadataMap(O, P, Create) { let targetMetadata = Metadata.get(O); if (IsUndefined(targetMetadata)) { if (!Create) { return undefined; } targetMetadata = new _Map(); Metadata.set(O, targetMetadata); } let metadataMap = targetMetadata.get(P); if (IsUndefined(metadataMap)) { if (!Create) { return undefined; } metadataMap = new _Map(); targetMetadata.set(P, metadataMap); } return metadataMap; } function OrdinaryHasMetadata(MetadataKey, O, P) { const hasOwn = OrdinaryHasOwnMetadata(MetadataKey, O, P); if (hasOwn) { return true; } const parent = OrdinaryGetPrototypeOf(O); if (!IsNull(parent)) { return OrdinaryHasMetadata(MetadataKey, parent, P); } return false; } function OrdinaryHasOwnMetadata(MetadataKey, O, P) { const metadataMap = GetOrCreateMetadataMap(O, P, false); if (IsUndefined(metadataMap)) { return false; } return ToBoolean(metadataMap.has(MetadataKey)); } function OrdinaryGetMetadata(MetadataKey, O, P) { const hasOwn = OrdinaryHasOwnMetadata(MetadataKey, O, P); if (hasOwn) { return OrdinaryGetOwnMetadata(MetadataKey, O, P); } const parent = OrdinaryGetPrototypeOf(O); if (!IsNull(parent)) { return OrdinaryGetMetadata(MetadataKey, parent, P); } return undefined; } function OrdinaryGetOwnMetadata(MetadataKey, O, P) { const metadataMap = GetOrCreateMetadataMap(O, P, false); if (IsUndefined(metadataMap)) { return undefined; } return metadataMap.get(MetadataKey); } function OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P) { const metadataMap = GetOrCreateMetadataMap(O, P, true); metadataMap.set(MetadataKey, MetadataValue); } function Type(x) { if (x === null) { return 1; } switch (typeof x) { case 'undefined': return 0; case 'boolean': return 2; case 'string': return 3; case 'symbol': return 4; case 'number': return 5; case 'object': return x === null ? 1 : 6; default: return 6; } } function IsUndefined(x) { return x === undefined; } function IsNull(x) { return x === null; } function IsSymbol(x) { return typeof x === 'symbol'; } function IsObject(x) { return typeof x === 'object' ? x !== null : typeof x === 'function'; } function ToPrimitive(input, PreferredType) { switch (Type(input)) { case 0: return input; case 1: return input; case 2: return input; case 3: return input; case 4: return input; case 5: return input; } const hint = PreferredType === 3 ? 'string' : PreferredType === 5 ? 'number' : 'default'; const exoticToPrim = GetMethod(input, toPrimitiveSymbol); if (exoticToPrim !== undefined) { const result = exoticToPrim.call(input, hint); if (IsObject(result)) { throw new TypeError(); } return result; } return OrdinaryToPrimitive(input, hint === 'default' ? 'number' : hint); } function OrdinaryToPrimitive(O, hint) { if (hint === 'string') { const toString_1 = O.toString; if (IsCallable(toString_1)) { const result = toString_1.call(O); if (!IsObject(result)) { return result; } } const valueOf = O.valueOf; if (IsCallable(valueOf)) { const result = valueOf.call(O); if (!IsObject(result)) { return result; } } } else { const valueOf = O.valueOf; if (IsCallable(valueOf)) { const result = valueOf.call(O); if (!IsObject(result)) { return result; } } const toString_2 = O.toString; if (IsCallable(toString_2)) { const result = toString_2.call(O); if (!IsObject(result)) { return result; } } } throw new TypeError(); } function ToBoolean(argument) { return !!argument; } function ToString(argument) { return '' + argument; } function ToPropertyKey(argument) { const key = ToPrimitive(argument, 3); if (IsSymbol(key)) { return key; } return ToString(key); } function IsCallable(argument) { return typeof argument === 'function'; } function GetMethod(V, P) { const func = V[P]; if (func === undefined || func === null) { return undefined; } if (!IsCallable(func)) { throw new TypeError(); } return func; } function OrdinaryGetPrototypeOf(O) { const proto = Object.getPrototypeOf(O); if (typeof O !== 'function' || O === functionPrototype) { return proto; } if (proto !== functionPrototype) { return proto; } const prototype = O.prototype; const prototypeProto = prototype && Object.getPrototypeOf(prototype); if (prototypeProto == null || prototypeProto === Object.prototype) { return proto; } const constructor = prototypeProto.constructor; if (typeof constructor !== 'function') { return proto; } if (constructor === O) { return proto; } return constructor; } }); return Reflect; })({}); function _tagParameterOrProperty(metadataKey, annotationTarget, key, metadata) { const metadatas = [metadata]; let paramsOrPropertiesMetadata = {}; if (Reflect$1.hasOwnMetadata(metadataKey, annotationTarget)) { paramsOrPropertiesMetadata = Reflect$1.getMetadata(metadataKey, annotationTarget); } let paramOrPropertyMetadata = paramsOrPropertiesMetadata[key]; if (paramOrPropertyMetadata === undefined) { paramOrPropertyMetadata = []; } paramOrPropertyMetadata.push(...metadatas); paramsOrPropertiesMetadata[key] = paramOrPropertyMetadata; Reflect$1.defineMetadata(metadataKey, paramsOrPropertiesMetadata, annotationTarget); } function tagParameter(annotationTarget, parameterName, parameterIndex, metadata) { _tagParameterOrProperty(TAGGED, annotationTarget, parameterIndex.toString(), metadata); } function createTaggedDecorator(metadata) { return (target, targetKey, indexOrPropertyDescriptor) => { tagParameter(target, targetKey, indexOrPropertyDescriptor, metadata); }; } function injectBase(metadataKey) { return (serviceIdentifier) => { return (target, targetKey, indexOrPropertyDescriptor) => { return createTaggedDecorator(new Metadata(metadataKey, serviceIdentifier))(target, targetKey, indexOrPropertyDescriptor); }; }; } const inject = injectBase(INJECT_TAG); const multiInject = injectBase(MULTI_INJECT_TAG); function injectable() { return function (target) { Reflect$1.defineMetadata(PARAM_TYPES, null, target); return target; }; } function named(name) { return createTaggedDecorator(new Metadata(NAMED_TAG, name)); } const BindingScopeEnum = { Singleton: 'Singleton', Transient: 'Transient' }; const BindingTypeEnum = { ConstantValue: 'ConstantValue', Constructor: 'Constructor', DynamicValue: 'DynamicValue', Factory: 'Factory', Function: 'Function', Instance: 'Instance', Invalid: 'Invalid', Provider: 'Provider' }; class Binding { constructor(serviceIdentifier, scope) { this.id = Generator.GenAutoIncrementId(); this.activated = false; this.serviceIdentifier = serviceIdentifier; this.scope = scope; this.type = BindingTypeEnum.Invalid; this.constraint = (request) => true; this.implementationType = null; this.cache = null; this.factory = null; this.provider = null; this.dynamicValue = null; } clone() { const clone = new Binding(this.serviceIdentifier, this.scope); clone.activated = clone.scope === BindingScopeEnum.Singleton ? this.activated : false; clone.implementationType = this.implementationType; clone.dynamicValue = this.dynamicValue; clone.scope = this.scope; clone.type = this.type; clone.provider = this.provider; clone.constraint = this.constraint; clone.cache = this.cache; return clone; } } class MetadataReader { getConstructorMetadata(constructorFunc) { const compilerGeneratedMetadata = Reflect$1.getMetadata(PARAM_TYPES, constructorFunc); const userGeneratedMetadata = Reflect$1.getMetadata(TAGGED, constructorFunc); return { compilerGeneratedMetadata, userGeneratedMetadata: userGeneratedMetadata || {} }; } getPropertiesMetadata(constructorFunc) { throw new Error('暂未实现'); } } const taggedConstraint = (key) => (value) => { const constraint = (request) => { if (request == null) { return false; } if (request.key === key && request.value === value) { return true; } if (request.constructorArgsMetadata == null) { return false; } const constructorArgsMetadata = request.constructorArgsMetadata; for (let i = 0; i < constructorArgsMetadata.length; i++) { if (constructorArgsMetadata[i].key === key && constructorArgsMetadata[i].value === value) { return true; } } return false; }; constraint.metaData = new Metadata(key, value); return constraint; }; const namedConstraint = taggedConstraint(NAMED_TAG); class BindingInSyntax { constructor(binding) { this._binding = binding; } inRequestScope() { throw new Error('暂未实现'); } inSingletonScope() { this._binding.scope = BindingScopeEnum.Singleton; return this; } inTransientScope() { this._binding.scope = BindingScopeEnum.Transient; return this; } whenTargetNamed(name) { this._binding.constraint = namedConstraint(name); return this; } } class BindingToSyntax { constructor(binding) { this._binding = binding; } to(constructor) { this._binding.type = BindingTypeEnum.Instance; this._binding.implementationType = constructor; return new BindingInSyntax(this._binding); } toSelf() { const self = this._binding.serviceIdentifier; return this.to(self); } toDynamicValue(func) { this._binding.type = BindingTypeEnum.DynamicValue; this._binding.cache = null; this._binding.dynamicValue = func; this._binding.implementationType = null; return new BindingInSyntax(this._binding); } toConstantValue(value) { this._binding.type = BindingTypeEnum.ConstantValue; this._binding.cache = value; this._binding.dynamicValue = null; this._binding.implementationType = null; this._binding.scope = BindingScopeEnum.Singleton; return new BindingInSyntax(this._binding); } toFactory(factory) { this._binding.type = BindingTypeEnum.Factory; this._binding.factory = factory; this._binding.scope = BindingScopeEnum.Singleton; return new BindingInSyntax(this._binding); } toService(service) { this.toDynamicValue(context => context.container.get(service)); } } class Container { constructor(containerOptions) { const options = containerOptions || {}; options.defaultScope = options.defaultScope || BindingScopeEnum.Transient; this.options = options; this.id = Generator.GenAutoIncrementId(); this._bindingDictionary = new Map(); this._metadataReader = new MetadataReader(); } load(module) { const getHelpers = this._getContainerModuleHelpersFactory(); const containerModuleHelpers = getHelpers(module.id); module.registry(containerModuleHelpers.bindFunction, containerModuleHelpers.unbindFunction, containerModuleHelpers.isboundFunction, containerModuleHelpers.rebindFunction); } get(serviceIdentifier) { const getArgs = this._getNotAllArgs(serviceIdentifier, false); return this._get(getArgs); } getAll(serviceIdentifier) { const getArgs = this._getAllArgs(serviceIdentifier); return this._get(getArgs); } getTagged(serviceIdentifier, key, value) { const getArgs = this._getNotAllArgs(serviceIdentifier, false, key, value); return this._get(getArgs); } getNamed(serviceIdentifier, named) { return this.getTagged(serviceIdentifier, NAMED_TAG, named); } isBound(serviceIdentifier) { return this._bindingDictionary.has(serviceIdentifier); } bind(serviceIdentifier) { const scope = this.options.defaultScope; const binding = new Binding(serviceIdentifier, scope); const list = this._bindingDictionary.get(serviceIdentifier) || []; list.push(binding); this._bindingDictionary.set(serviceIdentifier, list); return new BindingToSyntax(binding); } unbind(serviceIdentifier) { this._bindingDictionary.delete(serviceIdentifier); } rebind(serviceIdentifier) { this.unbind(serviceIdentifier); return this.bind(serviceIdentifier); } _getContainerModuleHelpersFactory() { const setModuleId = (bindingToSyntax, moduleId) => { bindingToSyntax._binding.moduleId = moduleId; }; const getBindFunction = (moduleId) => (serviceIdentifier) => { const bindingToSyntax = this.bind(serviceIdentifier); setModuleId(bindingToSyntax, moduleId); return bindingToSyntax; }; const getUnbindFunction = () => (serviceIdentifier) => { return this.unbind(serviceIdentifier); }; const getUnbindAsyncFunction = () => (serviceIdentifier) => { return null; }; const getIsboundFunction = () => (serviceIdentifier) => { return this.isBound(serviceIdentifier); }; const getRebindFunction = (moduleId) => (serviceIdentifier) => { const bindingToSyntax = this.rebind(serviceIdentifier); setModuleId(bindingToSyntax, moduleId); return bindingToSyntax; }; return (mId) => ({ bindFunction: getBindFunction(mId), isboundFunction: getIsboundFunction(), rebindFunction: getRebindFunction(mId), unbindFunction: getUnbindFunction(), unbindAsyncFunction: getUnbindAsyncFunction() }); } _getNotAllArgs(serviceIdentifier, isMultiInject, key, value) { return { avoidConstraints: false, isMultiInject, serviceIdentifier, key, value }; } _getAllArgs(serviceIdentifier) { return { avoidConstraints: true, isMultiInject: true, serviceIdentifier }; } _get(getArgs) { const result = []; const bindings = this._bindingDictionary.get(getArgs.serviceIdentifier).filter(b => { return b.constraint(getArgs); }); bindings.forEach(binding => { result.push(this._resolveFromBinding(binding)); }); return !getArgs.isMultiInject && result.length === 1 ? result[0] : result; } _getChildRequest(binding) { const constr = binding.implementationType; const { userGeneratedMetadata } = this._metadataReader.getConstructorMetadata(constr); const keys = Object.keys(userGeneratedMetadata); const arr = []; for (let i = 0; i < keys.length; i++) { const constructorArgsMetadata = userGeneratedMetadata[i]; const targetMetadataMap = {}; constructorArgsMetadata.forEach(md => { targetMetadataMap[md.key] = md.value; }); const metadata = { inject: targetMetadataMap[INJECT_TAG], multiInject: targetMetadataMap[MULTI_INJECT_TAG] }; const injectIdentifier = metadata.inject || metadata.multiInject; const target = { serviceIdentifier: injectIdentifier, constructorArgsMetadata }; const bindings = (this._bindingDictionary.get(injectIdentifier) || []).filter(b => { return b.constraint(target); }); if (bindings.length) { const request = { injectIdentifier, metadata: constructorArgsMetadata, bindings: bindings }; arr.push(request); } } return arr; } _resolveFromBinding(binding) { const result = this._getResolvedFromBinding(binding); this._saveToScope(binding, result); return result; } _getResolvedFromBinding(binding) { let result; switch (binding.type) { case BindingTypeEnum.ConstantValue: case BindingTypeEnum.Function: result = binding.cache; break; case BindingTypeEnum.Instance: result = this._resolveInstance(binding, binding.implementationType); break; default: result = binding.dynamicValue({ container: this }); } return result; } _resolveInstance(binding, constr) { if (binding.activated) { return binding.cache; } const childRequests = this._getChildRequest(binding); return this._createInstance(constr, childRequests); } _createInstance(constr, childRequests) { if (childRequests.length) { const resolved = this._resolveRequests(childRequests); const obj = new constr(...resolved); return obj; } const obj = new constr(); return obj; } _resolveRequests(childRequests) { return childRequests.map(request => { return request.bindings.length > 1 ? request.bindings.map(binding => this._resolveFromBinding(binding)) : this._resolveFromBinding(request.bindings[0]); }); } _saveToScope(binding, result) { if (binding.scope === BindingScopeEnum.Singleton) { binding.cache = result; binding.activated = true; } } } /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); }; } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; const ContributionProvider = Symbol('ContributionProvider'); class ContributionProviderCache { constructor(serviceIdentifier, container) { this.serviceIdentifier = serviceIdentifier; this.container = container; } getContributions() { if (!this.caches) { this.caches = []; this.container && this.container.isBound(this.serviceIdentifier) && this.caches.push(...this.container.getAll(this.serviceIdentifier)); } return this.caches; } } function bindContributionProvider(bind, id) { bind(ContributionProvider) .toDynamicValue(({ container }) => new ContributionProviderCache(id, container)) .inSingletonScope() .whenTargetNamed(id); } function bindContributionProviderNoSingletonScope(bind, id) { bind(ContributionProvider) .toDynamicValue(({ container }) => new ContributionProviderCache(id, container)) .whenTargetNamed(id); } class Hook { constructor(args, name) { this._args = args; this.name = name; this.taps = []; } tap(options, fn) { this._tap('sync', options, fn); } unTap(options, fn) { const name = typeof options === 'string' ? options.trim() : options.name; if (name) { this.taps = this.taps.filter(tap => !(tap.name === name && (!fn || tap.fn === fn))); } } _parseOptions(type, options, fn) { let _options; if (typeof options === 'string') { _options = { name: options.trim() }; } else if (typeof options !== 'object' || options === null) { throw new Error('Invalid tap options'); } if (typeof _options.name !== 'string' || _options.name === '') { throw new Error('Missing name for tap'); } _options = Object.assign({ type, fn }, _options); return _options; } _tap(type, options, fn) { this._insert(this._parseOptions(type, options, fn)); } _insert(item) { let before; if (typeof item.before === 'string') { before = new Set([item.before]); } else if (Array.isArray(item.before)) { before = new Set(item.before); } let stage = 0; if (typeof item.stage === 'number') { stage = item.stage; } let i = this.taps.length; while (i > 0) { i--; const x = this.taps[i]; this.taps[i + 1] = x; const xStage = x.stage || 0; if (before) { if (before.has(x.name)) { before.delete(x.name); continue; } if (before.size > 0) { continue; } } if (xStage > stage) { continue; } i++; break; } this.taps[i] = item; } } class SyncHook extends Hook { call(...args) { const cbs = this.taps.map(t => t.fn); cbs.forEach(cb => cb(...args)); return undefined; } } const EnvContribution = Symbol.for('EnvContribution'); const VGlobal = Symbol.for('VGlobal'); const DEFAULT_TEXT_FONT_FAMILY = 'PingFang SC,Helvetica Neue,Microsoft Yahei,system-ui,-apple-system,segoe ui,Roboto,Helvetica,Arial,sans-serif,apple color emoji,segoe ui emoji,segoe ui symbol'; const defaultEnv = 'browser'; let DefaultGlobal = class DefaultGlobal { get env() { return this._env; } get isImageAnonymous() { return this._isImageAnonymous; } set isImageAnonymous(isImageAnonymous) { this._isImageAnonymous = isImageAnonymous; } get devicePixelRatio() { if (!this._env) { this.setEnv(defaultEnv); } return this.envContribution.getDevicePixelRatio(); } get supportEvent() { if (!this._env) { this.setEnv(defaultEnv); } return this.envContribution.supportEvent; } set supportEvent(support) { if (!this._env) { this.setEnv(defaultEnv); } this.envContribution.supportEvent = support; } get supportsTouchEvents() { if (!this._env) { this.setEnv(defaultEnv); } return this.envContribution.supportsTouchEvents; } set supportsTouchEvents(support) { if (!this._env) { this.setEnv(defaultEnv); } this.envContribution.supportsTouchEvents = support; } get supportsPointerEvents() { if (!this._env) { this.setEnv(defaultEnv); } return this.envContribution.supportsPointerEvents; } set supportsPointerEvents(support) { if (!this._env) { this.setEnv(defaultEnv); } this.envContribution.supportsPointerEvents = support; } get supportsMouseEvents() { if (!this._env) { this.setEnv(defaultEnv); } return this.envContribution.supportsMouseEvents; } set supportsMouseEvents(support) { if (!this._env) { this.setEnv(defaultEnv); } this.envContribution.supportsMouseEvents = support; } get applyStyles() { if (!this._env) { this.setEnv(defaultEnv); } return this.envContribution.applyStyles; } set applyStyles(support) { if (!this._env) { this.setEnv(defaultEnv); } this.envContribution.applyStyles = support; } constructor(contributions) { this.contributions = contributions; this._isImageAnonymous = true; this.id = Generator.GenAutoIncrementId(); this.hooks = { onSetEnv: new SyncHook(['lastEnv', 'env', 'global']) }; this.measureTextMethod = 'native'; this.optimizeVisible = false; } bindContribution(params) { const promiseArr = []; this.contributions.getContributions().forEach(contribution => { const data = contribution.configure(this, params); if (data && data.then) { promiseArr.push(data); } }); if (promiseArr.length) { return Promise.all(promiseArr); } } getDynamicCanvasCount() { if (!this._env) { this.setEnv(defaultEnv); } return this.envContribution.getDynamicCanvasCount(); } getStaticCanvasCount() { if (!this._env) { this.setEnv(defaultEnv); } return this.envContribution.getStaticCanvasCount(); } setEnv(env, params) { if (!(params && params.force === true) && this._env === env) { return; } this.deactiveCurrentEnv(); return this.activeEnv(env, params); } deactiveCurrentEnv() { this.envContribution && this.envContribution.release(); } activeEnv(env, params) { const lastEnv = this._env; this._env = env; const data = this.bindContribution(params); if (data && data.then) { return data.then(() => { this.envParams = params; this.hooks.onSetEnv.call(lastEnv, env, this); }); } this.envParams = params; this.hooks.onSetEnv.call(lastEnv, env, this); } setActiveEnvContribution(contribution) { this.envContribution = contribution; } createCanvas(params) { if (!this._env) { this.setEnv(defaultEnv); } return this.envContribution.createCanvas(params); } createOffscreenCanvas(params) { if (!this._env) { this.setEnv(defaultEnv); } return this.envContribution.createOffscreenCanvas(params); } releaseCanvas(canvas) { if (!this._env) { this.setEnv(defaultEnv); } return this.envContribution.releaseCanvas(canvas); } addEventListener(type, listener, options) { if (!this._env) { this.setEnv(defaultEnv); } return this.envContribution.addEventListener(type, listener, options); } removeEventListener(type, listener, options) { if (!this._env) { this.setEnv(defaultEnv); } return this.envContribution.removeEventListener(type, listener, options); } dispatchEvent(event) { if (!this._env) { this.setEnv(defaultEnv); } return this.envContribution.dispatchEvent(event); } getRequestAnimationFrame() { if (!this._env) { this.setEnv(defaultEnv); } return this.envContribution.getRequestAnimationFrame(); } getCancelAnimationFrame() { if (!this._env) { this.setEnv(defaultEnv); } return this.envContribution.getCancelAnimationFrame(); } getElementById(str) { if (!this._env) { this.setEnv(defaultEnv); } if (!this.envContribution.getElementById) { return null; } return this.envContribution.getElementById(str); } getRootElement() { if (!this._env) { this.setEnv(defaultEnv); } if (!this.envContribution.getRootElement) { return null; } return this.envContribution.getRootElement(); } getDocument() { if (!this._env) { this.setEnv(defaultEnv); } if (!this.envContribution.getDocument) { return null; } return this.envContribution.getDocument(); } mapToCanvasPoint(event, domElement) { if (!this._env) { this.setEnv(defaultEnv); } if (!this.envContribution.mapToCanvasPoint) { return null; } return this.envContribution.mapToCanvasPoint(event, domElement); } loadImage(url) { if (!this._env) { this.setEnv('browser'); } return this.envContribution.loadImage(url); } loadSvg(str) { if (!this._env) { this.setEnv('browser'); } return this.envContribution.loadSvg(str); } loadJson(url) { if (!this._env) { this.setEnv('browser'); } return this.envContribution.loadJson(url); } loadArrayBuffer(url) { if (!this._env) { this.setEnv('browser'); } return this.envContribution.loadArrayBuffer(url); } loadBlob(url) { if (!this._env) { this.setEnv('browser'); } return this.envContribution.loadBlob(url); } loadFont(name, source, descriptors) { return __awaiter(this, void 0, void 0, function* () { if (!this._env) { this.setEnv('browser'); } return this.envContribution.loadFont(name, source, descriptors); }); } isChrome() { if (this._isChrome != null) { return this._isChrome; } if (!this._env) { this.setEnv('browser'); } this._isChrome = this._env === 'browser' && navigator.userAgent.indexOf('Chrome') > -1; return this._isChrome; } isSafari() { if (this._isSafari != null) { return this._isSafari; } if (!this._env) { this.setEnv('browser'); } this._isSafari = this._env === 'browser' && /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent); return this._isSafari; } getNativeAABBBounds(dom) { if (!this._env) { this.setEnv('browser'); } return this.envContribution.getNativeAABBBounds(dom); } removeDom(dom) { if (!this._env) { this.setEnv('browser'); } return this.envContribution.removeDom(dom); } createDom(params) { if (!this._env) { this.setEnv('browser'); } return this.envContribution.createDom(params); } updateDom(dom, params) { if (!this._env) { this.setEnv('browser'); } return this.envContribution.updateDom(dom, params); } getElementTop(dom, baseWindow = false) { if (!this._env) { this.setEnv('browser'); } return this.envContribution.getElementTop(dom, baseWindow); } getElementLeft(dom, baseWindow = false) { if (!this._env) { this.setEnv('browser'); } return this.envContribution.getElementLeft(dom, baseWindow); } getElementTopLeft(dom, baseWindow = false) { if (!this._env) { this.setEnv('browser'); } return this.envContribution.getElementTopLeft(dom, baseWindow); } isMacOS() { if (!this._env) { this.setEnv('browser'); } return this.envContribution.isMacOS(); } copyToClipBoard(text) { if (!this._env) { this.setEnv('browser'); } return this.envContribution.copyToClipBoard(text); } }; DefaultGlobal = __decorate([ injectable(), __param(0, inject(ContributionProvider)), __param(0, named(EnvContribution)), __metadata("design:paramtypes", [Object]) ], DefaultGlobal); var params; (function (params) { params[params["W"] = 1] = "W"; params[params["H"] = 2] = "H"; params[params["WH"] = 3] = "WH"; })(params || (params = {})); var MeasureModeEnum; (function (MeasureModeEnum) { MeasureModeEnum[MeasureModeEnum["estimate"] = 0] = "estimate"; MeasureModeEnum[MeasureModeEnum["actualBounding"] = 1] = "actualBounding"; MeasureModeEnum[MeasureModeEnum["fontBounding"] = 2] = "fontBounding"; })(MeasureModeEnum || (MeasureModeEnum = {})); const strCommandMap = [ 'arc', 'arcTo', 'bezierCurveTo', 'closePath', 'ellipse', 'lineTo', 'moveTo', 'quadraticCurveTo', 'rect' ]; const circleThreshold = tau - 1e-8; class BoundsContext { constructor(bounds) { this.init(bounds); } init(bounds) { this.bounds = bounds; } arc(cx, cy, r, sa, ea, ccw) { if (Math.abs(ea - sa) > circleThreshold) { this.bounds.add(cx - r, cy - r); this.bounds.add(cx + r, cy + r); return; } let xmin = Infinity; let xmax = -Infinity; let ymin = Infinity; let ymax = -Infinity; let s; let i; let x; let y; function update(a) { x = r * Math.cos(a); y = r * Math.sin(a); if (x < xmin) { xmin = x; } if (x > xmax) { xmax = x; } if (y < ymin) { ymin = y; } if (y > ymax) { ymax = y; } } update(sa); update(ea); if (ea !== sa) { sa = sa % tau; if (sa < 0) { sa += tau; } ea = ea % tau; if (ea < 0) { ea += tau; } if (ea < sa) { ccw = !ccw; s = sa; sa = ea; ea = s; } if (ccw) { ea -= tau; s = sa - (sa % halfPi$1); for (i = 0; i < 4 && s > ea; ++i, s -= halfPi$1) { update(s); } } else { s = sa - (sa % halfPi$1) + halfPi$1; for (i = 0; i < 4 && s < ea; ++i, s = s + halfPi$1) { update(s); } } } this.bounds.add(cx + xmin, cy + ymin); this.bounds.add(cx + xmax, cy + ymax); } arcTo(x1, y1, x2, y2, radius) { this.bounds.add(x1, y1); } bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) { this.bounds.add(cp1x, cp1y); this.bounds.add(cp2x, cp2y); this.bounds.add(x, y); } closePath() { } ellipse() { throw new Error('不支持ellipse'); } lineTo(x, y) { this.bounds.add(x, y); } moveTo(x, y) { this.bounds.add(x, y); } quadraticCurveTo(cpx, cpy, x, y) { this.bounds.add(cpx, cpy); this.bounds.add(x, y); } rect(x, y, w, h) { this.bounds.add(x, y); this.bounds.add(x + w, y + h); } clear() { this.bounds.clear(); } release(...params) { return; } } class CurvePath { constructor() { this._curves = []; this.bounds = new AABBBounds(); } get curves() { return this._curves; } getCurveLengths() { return this._curves.map(curve => curve.getLength()); } getPointAt(t) { return { x: 0, y: 0 }; } getLength() { return 0; } getBounds() { return this.bounds; } } const rePathCommand = /([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi; const commandLengths = { m: 2, l: 2, h: 1, v: 1, c: 6, s: 4, q: 4, t: 2, a: 7, M: 2, L: 2, H: 1, V: 1, C: 6, S: 4, Q: 4, T: 2, A: 7 }; const enumCommandMap = { A: 0, AT: 1, C: 2, Z: 3, E: 4, L: 5, M: 6, Q: 7, R: 8 }; let currPath; let coordsStr; let commandChar; let coordStr; let coordNumber; let standardCommandLen; function parseSvgPath(str) { if (!str) { return []; } const paths = str.match(/[mzlhvcsqta][^mzlhvcsqta]*/gi); if (paths === null) { return []; } let currCommandData; let coordsStrArr; const result = []; for (let i = 0, len = paths.length; i < len; i++) { currPath = paths[i]; coordsStr = currPath.slice(1); commandChar = currPath[0]; currCommandData = [commandChar]; coordsStrArr = coordsStr.match(rePathCommand); if (coordsStrArr === null) { result.push(currCommandData); continue; } for (let i = 0, len = coordsStrArr.length; i < len; i++) { coordStr = coordsStrArr[i]; coordNumber = parseFloat(coordStr); if (!Number.isNaN(coordNumber)) { currCommandData.push(coordNumber); } } standardCommandLen = commandLengths[commandChar]; if (currCommandData.length - 1 > standardCommandLen) { let subCommand; let bestCommandChar = commandChar; for (let i = 1, len = currCommandData.length; i < len; i += standardCommandLen) { subCommand = [bestCommandChar]; for (let j = i, subLen = i + standardCommandLen; j < subLen; j++) { subCommand.push(currCommandData[j]); } result.push(subCommand); if (bestCommandChar === 'm') { bestCommandChar = 'l'; } else if (bestCommandChar === 'M') { bestCommandChar = 'L'; } } } else { result.push(currCommandData); } } return result; } var UpdateTag; (function (UpdateTag) { UpdateTag[UpdateTag["NONE"] = 0] = "NONE"; UpdateTag[UpdateTag["UPDATE_BOUNDS"] = 1] = "UPDATE_BOUNDS"; UpdateTag[UpdateTag["UPDATE_SHAPE"] = 2] = "UPDATE_SHAPE"; UpdateTag[UpdateTag["CLEAR_SHAPE"] = 253] = "CLEAR_SHAPE"; UpdateTag[UpdateTag["UPDATE_SHAPE_AND_BOUNDS"] = 3] = "UPDATE_SHAPE_AND_BOUNDS"; UpdateTag[UpdateTag["INIT"] = 179] = "INIT"; UpdateTag[UpdateTag["CLEAR_BOUNDS"] = 254] = "CLEAR_BOUNDS"; UpdateTag[UpdateTag["UPDATE_GLOBAL_MATRIX"] = 32] = "UPDATE_GLOBAL_MATRIX"; UpdateTag[UpdateTag["CLEAR_GLOBAL_MATRIX"] = 223] = "CLEAR_GLOBAL_MATRIX"; UpdateTag[UpdateTag["UPDATE_LOCAL_MATRIX"] = 16] = "UPDATE_LOCAL_MATRIX"; UpdateTag[UpdateTag["CLEAR_LOCAL_MATRIX"] = 239] = "CLEAR_LOCAL_MATRIX"; UpdateTag[UpdateTag["UPDATE_GLOBAL_LOCAL_MATRIX"] = 48] = "UPDATE_GLOBAL_LOCAL_MATRIX"; UpdateTag[UpdateTag["UPDATE_LAYOUT"] = 128] = "UPDATE_LAYOUT"; UpdateTag[UpdateTag["CLEAR_LAYOUT"] = 127] = "CLEAR_LAYOUT"; })(UpdateTag || (UpdateTag = {})); var IContainPointMode; (function (IContainPointMode) { IContainPointMode[IContainPointMode["GLOBAL"] = 1] = "GLOBAL"; IContainPointMode[IContainPointMode["LOCAL"] = 16] = "LOCAL"; IContainPointMode[IContainPointMode["GLOBAL_ACCURATE"] = 3] = "GLOBAL_ACCURATE"; IContainPointMode[IContainPointMode["LOCAL_ACCURATE"] = 48] = "LOCAL_ACCURATE"; })(IContainPointMode || (IContainPointMode = {})); var AttributeUpdateType; (function (AttributeUpdateType) { AttributeUpdateType[AttributeUpdateType["INIT"] = 0] = "INIT"; AttributeUpdateType[AttributeUpdateType["DEFAULT"] = 1] = "DEFAULT"; AttributeUpdateType[AttributeUpdateType["STATE"] = 2] = "STATE"; AttributeUpdateType[AttributeUpdateType["ANIMATE_BIND"] = 10] = "ANIMATE_BIND"; AttributeUpdateType[AttributeUpdateType["ANIMATE_PLAY"] = 11] = "ANIMATE_PLAY"; AttributeUpdateType[AttributeUpdateType["ANIMATE_START"] = 12] = "ANIMATE_START"; AttributeUpdateType[AttributeUpdateType["ANIMATE_UPDATE"] = 13] = "ANIMATE_UPDATE"; AttributeUpdateType[AttributeUpdateType["ANIMATE_END"] = 14] = "ANIMATE_END"; AttributeUpdateType[AttributeUpdateType["TRANSLATE"] = 20] = "TRANSLATE"; AttributeUpdateType[AttributeUpdateType["TRANSLATE_TO"] = 21] = "TRANSLATE_TO"; AttributeUpdateType[AttributeUpdateType["SCALE"] = 22] = "SCALE"; AttributeUpdateType[AttributeUpdateType["SCALE_TO"] = 23] = "SCALE_TO"; AttributeUpdateType[AttributeUpdateType["ROTATE"] = 24] = "ROTATE"; AttributeUpdateType[AttributeUpdateType["ROTATE_TO"] = 25] = "ROTATE_TO"; })(AttributeUpdateType || (AttributeUpdateType = {})); var AnimateStatus; (function (AnimateStatus) { AnimateStatus[AnimateStatus["INITIAL"] = 0] = "INITIAL"; AnimateStatus[AnimateStatus["RUNNING"] = 1] = "RUNNING"; AnimateStatus[AnimateStatus["PAUSED"] = 2] = "PAUSED"; AnimateStatus[AnimateStatus["END"] = 3] = "END"; })(AnimateStatus || (AnimateStatus = {})); var AnimateMode; (function (AnimateMode) { AnimateMode[AnimateMode["NORMAL"] = 0] = "NORMAL"; AnimateMode[AnimateMode["SET_ATTR_IMMEDIATELY"] = 1] = "SET_ATTR_IMME