UNPKG

@visactor/vrender-core

Version:

```typescript import { xxx } from '@visactor/vrender-core'; ```

1,469 lines (1,432 loc) 1.09 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 as isNumber$1, sqrt, Color, DEFAULT_COLORS, LRU, OBBBounds, isNil, normalTransform, isValidUrl, isBase64, acos, lowerCamelCaseToMiddle, isValid, transformBoundsWithMatrix, getContextFont, rotatePoint, clampAngleByRadian, asin, arrayEqual, Bounds, getRectIntersect, isRectIntersect, isEqual, getIntersectPoint, 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; ContributionStore.setStore(this.serviceIdentifier, this); } getContributions() { if (!this.caches) { this.caches = []; this.container && this.container.isBound(this.serviceIdentifier) && this.caches.push(...this.container.getAll(this.serviceIdentifier)); } return this.caches; } refresh() { if (!this.caches) { return; } this.caches.length = 0; this.container && this.container.isBound(this.serviceIdentifier) && this.caches.push(...this.container.getAll(this.serviceIdentifier)); } } 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 ContributionStore { static getStore(id) { return this.store.get(id); } static setStore(id, cache) { this.store.set(id, cache); } static refreshAllContributions() { this.store.forEach(cache => { cache.refresh(); }); } } ContributionStore.store = new Map(); 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 container = new Container(); const RenderService = Symbol.for('RenderService'); const BeforeRenderConstribution = Symbol.for('BeforeRenderConstribution'); class Application { get renderService() { if (!this._renderService) { this._renderService = container.get(RenderService); } return this._renderService; } } const application = new Application(); let idx = 0; class PerformanceRAF { constructor() { this.nextAnimationFrameCbs = new Map(); this._rafHandle = null; this.runAnimationFrame = (time) => { this._rafHandle = null; const cbs = this.nextAnimationFrameCbs; this.nextAnimationFrameCbs = new Map(); cbs.forEach(cb => cb(time)); }; this.tryRunAnimationFrameNextFrame = () => { if (this._rafHandle !== null || this.nextAnimationFrameCbs.size === 0) { return; } this._rafHandle = application.global.getRequestAnimationFrame()(this.runAnimationFrame); }; } addAnimationFrameCb(callback) { this.nextAnimationFrameCbs.set(++idx, callback); this.tryRunAnimationFrameNextFrame(); return idx; } removeAnimationFrameCb(index) { if (this.nextAnimationFrameCbs.has(index)) { this.nextAnimationFrameCbs.delete(index); return true; } return false; } } class EventListenerManager { constructor() { this._listenerMap = new Map(); this._eventListenerTransformer = event => event; } setEventListenerTransformer(transformer) { this._eventListenerTransformer = transformer || (event => event); } addEventListener(type, listener, options) { if (!listener) { return; } const capture = this._resolveCapture(options); const once = this._resolveOnce(options); const listenerTypeMap = this._getOrCreateListenerTypeMap(type); const wrappedMap = this._getOrCreateWrappedMap(listenerTypeMap, listener); if (wrappedMap.has(capture)) { return; } const wrappedListener = (event) => { const transformedEvent = this._eventListenerTransformer(event); if (typeof listener === 'function') { listener(transformedEvent); } else if (listener.handleEvent) { listener.handleEvent(transformedEvent); } if (once) { this._deleteListenerRecord(type, listener, capture); } }; wrappedMap.set(capture, { wrappedListener, options }); this._nativeAddEventListener(type, wrappedListener, options); } removeEventListener(type, listener, options) { var _a, _b; if (!listener) { return; } const capture = this._resolveCapture(options); const wrappedRecord = (_b = (_a = this._listenerMap.get(type)) === null || _a === void 0 ? void 0 : _a.get(listener)) === null || _b === void 0 ? void 0 : _b.get(capture); if (wrappedRecord) { this._nativeRemoveEventListener(type, wrappedRecord.wrappedListener, capture); this._deleteListenerRecord(type, listener, capture); } } dispatchEvent(event) { return this._nativeDispatchEvent(event); } clearAllEventListeners() { this._listenerMap.forEach((listenerMap, type) => { listenerMap.forEach(wrappedMap => { wrappedMap.forEach((wrappedRecord, capture) => { this._nativeRemoveEventListener(type, wrappedRecord.wrappedListener, capture); }); }); }); this._listenerMap.clear(); } _resolveCapture(options) { if (typeof options === 'boolean') { return options; } return !!(options === null || options === void 0 ? void 0 : options.capture); } _resolveOnce(options) { return typeof options === 'object' && !!(options === null || options === void 0 ? void 0 : options.once); } _getOrCreateListenerTypeMap(type) { let listenerTypeMap = this._listenerMap.get(type); if (!listenerTypeMap) { listenerTypeMap = new Map(); this._listenerMap.set(type, listenerTypeMap); } return listenerTypeMap; } _getOrCreateWrappedMap(listenerTypeMap, listener) { let wrappedMap = listenerTypeMap.get(listener); if (!wrappedMap) { wrappedMap = new Map(); listenerTypeMap.set(listener, wrappedMap); } return wrappedMap; } _deleteListenerRecord(type, listener, capture) { const listenerTypeMap = this._listenerMap.get(type); if (!listenerTypeMap) { return; } const wrappedMap = listenerTypeMap.get(listener); if (!wrappedMap) { return; } wrappedMap.delete(capture); if (wrappedMap.size === 0) { listenerTypeMap.delete(listener); } if (listenerTypeMap.size === 0) { this._listenerMap.delete(type); } } _nativeAddEventListener(type, listener, options) { throw new Error('_nativeAddEventListener must be implemented by derived classes'); } _nativeRemoveEventListener(type, listener, options) { throw new Error('_nativeRemoveEventListener must be implemented by derived classes'); } _nativeDispatchEvent(event) { throw new Error('_nativeDispatchEvent must be implemented by derived classes'); } } const defaultEnv = 'browser'; let DefaultGlobal = class DefaultGlobal extends EventListenerManager { 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) { super(); this.contributions = contributions; this._isImageAnonymous = true; this._performanceRAFList = []; this.eventListenerTransformer = event => event; this.id = Generator.GenAutoIncrementId(); this.hooks = { onSetEnv: new SyncHook(['lastEnv', 'env', 'global']) }; this.measureTextMethod = 'native'; this.optimizeVisible = false; } _nativeAddEventListener(type, listener, options) { if (!this._env) { this.setEnv(defaultEnv); } return this.envContribution.addEventListener(type, listener, options); } _nativeRemoveEventListener(type, listener, options) { if (!this._env) { this.setEnv(defaultEnv); } return this.envContribution.removeEventListener(type, listener, options); } _nativeDispatchEvent(event) { if (!this._env) { this.setEnv(defaultEnv); } return this.envContribution.dispatchEvent(event); } 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); } getRequestAnimationFrame() { if (!this._env) { this.setEnv(defaultEnv); } return this.envContribution.getRequestAnimationFrame(); } getSpecifiedRequestAnimationFrame(id) { if (!this._env) { this.setEnv(defaultEnv); } if (!this._performanceRAFList[id]) { this._performanceRAFList[id] = new PerformanceRAF(); } const performanceRAF = this._performanceRAFList[id]; return (callback) => { return performanceRAF.addAnimationFrameCb(callback); }; } getSpecifiedCancelAnimationFrame(id) { if (!this._env) { this.setEnv(defaultEnv); } if (!this._performanceRAFList[id]) { return () => false; } const performanceRAF = this._performanceRAFList[id]; return (handle) => { return performanceRAF.removeAnimationFrameCb(handle); }; } 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' ]; var AnimateMode; (function (AnimateMode) { AnimateMode[AnimateMode["NORMAL"] = 0] = "NORMAL"; AnimateMode[AnimateMode["SET_ATTR_IMMEDIATELY"] = 1] = "SET_ATTR_IMMEDIATELY"; })(AnimateMode || (AnimateMode = {})); var STATUS$1; (function (STATUS) { STATUS[STATUS["INITIAL"] = 0] = "INITIAL"; STATUS[STATUS["RUNNING"] = 1] = "RUNNING"; STATUS[STATUS["PAUSE"] = 2] = "PAUSE"; })(STATUS$1 || (STATUS$1 = {})); var AnimateStepType; (function (AnimateStepType) { AnimateStepType["wait"] = "wait"; AnimateStepType["from"] = "from"; AnimateStepType["to"] = "to"; AnimateStepType["customAnimate"] = "customAnimate"; })(AnimateStepType || (AnimateStepType = {})); 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 = {})); const circleThreshold = tau - 1e-8; class BoundsContext { constructor(bounds) { this.init(bounds); } init(bounds) { this.bounds = bounds; } arc(cx, cy