UNPKG

ag-charts-community

Version:

Advanced Charting / Charts supporting Javascript / Typescript / React / Angular / Vue

1,621 lines (1,594 loc) 274 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __decorateClass = (decorators, target, key, kind) => { var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target; for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result; if (kind && result) __defProp(target, key, result); return result; }; // packages/ag-charts-community/src/integrated-charts-scene.ts var integrated_charts_scene_exports = {}; __export(integrated_charts_scene_exports, { Arc: () => Arc, BBox: () => BBox, Caption: () => Caption, CategoryScale: () => CategoryScale, Group: () => Group, Line: () => Line, LinearScale: () => LinearScale, Marker: () => Marker, Path: () => Path, RadialColumnShape: () => RadialColumnShape, Rect: () => Rect, Scene: () => Scene, Sector: () => Sector, Shape: () => Shape, TranslatableGroup: () => TranslatableGroup, getRadialColumnWidth: () => getRadialColumnWidth, toRadians: () => toRadians }); module.exports = __toCommonJS(integrated_charts_scene_exports); // packages/ag-charts-community/src/chart/caption.ts var import_ag_charts_core28 = require("ag-charts-core"); // packages/ag-charts-community/src/scene/node.ts var import_ag_charts_core4 = require("ag-charts-core"); // packages/ag-charts-community/src/util/object.ts var import_ag_charts_core = require("ag-charts-core"); // packages/ag-charts-community/src/util/decorator.ts var BREAK_TRANSFORM_CHAIN = Symbol("BREAK"); var CONFIG_KEY = "__decorator_config"; var ACCESSORS_KEY = "__decorator_accessors"; function addFakeTransformToInstanceProperty(target, propertyKeyOrSymbol) { initialiseConfig(target, propertyKeyOrSymbol).optional = true; } function initialiseConfig(target, propertyKeyOrSymbol) { if (Object.getOwnPropertyDescriptor(target, CONFIG_KEY) == null) { Object.defineProperty(target, CONFIG_KEY, { value: {} }); } if (Object.getOwnPropertyDescriptor(target, ACCESSORS_KEY) == null) { const parentAccessors = Object.getPrototypeOf(target)?.[ACCESSORS_KEY]; const accessors = parentAccessors?.slice() ?? []; Object.defineProperty(target, ACCESSORS_KEY, { value: accessors }); } const config = target[CONFIG_KEY]; const propertyKey = propertyKeyOrSymbol.toString(); if (config[propertyKey] != null) { return config[propertyKey]; } config[propertyKey] = { setters: [], getters: [], observers: [] }; const descriptor = Object.getOwnPropertyDescriptor(target, propertyKeyOrSymbol); let prevGet = descriptor?.get; let prevSet = descriptor?.set; if (prevGet == null || prevSet == null) { const accessors = target[ACCESSORS_KEY]; let index = accessors.indexOf(propertyKeyOrSymbol); if (index === -1) { index = accessors.push(propertyKeyOrSymbol) - 1; } prevGet ?? (prevGet = function() { let accessorValues = this.__accessors; if (accessorValues == null) { accessorValues = accessors.slice().fill(void 0); Object.defineProperty(this, "__accessors", { value: accessorValues }); } return accessorValues[index]; }); prevSet ?? (prevSet = function(value) { let accessorValues = this.__accessors; if (accessorValues == null) { accessorValues = accessors.slice().fill(void 0); Object.defineProperty(this, "__accessors", { value: accessorValues }); } accessorValues[index] = value; }); } const getter = function() { let value = prevGet.call(this); for (const transformFn of config[propertyKey].getters) { value = transformFn(this, propertyKeyOrSymbol, value); if (value === BREAK_TRANSFORM_CHAIN) { return; } } return value; }; const setter = function(value) { const { setters, observers } = config[propertyKey]; let oldValue; if (setters.some((f) => f.length > 2)) { oldValue = prevGet.call(this); } for (const transformFn of setters) { value = transformFn(this, propertyKeyOrSymbol, value, oldValue); if (value === BREAK_TRANSFORM_CHAIN) { return; } } prevSet.call(this, value); for (const observerFn of observers) { observerFn(this, value, oldValue); } }; Object.defineProperty(target, propertyKeyOrSymbol, { set: setter, get: getter, enumerable: true, configurable: false }); return config[propertyKey]; } function addTransformToInstanceProperty(setTransform, getTransform, configMetadata) { return (target, propertyKeyOrSymbol) => { const config = initialiseConfig(target, propertyKeyOrSymbol); config.setters.push(setTransform); if (getTransform) { config.getters.unshift(getTransform); } if (configMetadata) { Object.assign(config, configMetadata); } }; } function addObserverToInstanceProperty(setObserver) { return (target, propertyKeyOrSymbol) => { initialiseConfig(target, propertyKeyOrSymbol).observers.push(setObserver); }; } function isDecoratedObject(target) { return typeof target !== "undefined" && CONFIG_KEY in target; } function listDecoratedProperties(target) { const targets = /* @__PURE__ */ new Set(); while (isDecoratedObject(target)) { targets.add(target?.[CONFIG_KEY]); target = Object.getPrototypeOf(target); } return Array.from(targets).flatMap((configMap) => Object.keys(configMap)); } // packages/ag-charts-community/src/util/object.ts function objectsEqual(a, b) { if (Array.isArray(a)) { if (!Array.isArray(b)) return false; if (a.length !== b.length) return false; return a.every((av, i) => objectsEqual(av, b[i])); } else if ((0, import_ag_charts_core.isPlainObject)(a)) { if (!(0, import_ag_charts_core.isPlainObject)(b)) return false; return objectsEqualWith(a, b, objectsEqual); } return a === b; } function objectsEqualWith(a, b, cmp2) { if (Object.is(a, b)) return true; for (const key of Object.keys(b)) { if (!(key in a)) return false; } for (const key of Object.keys(a)) { if (!(key in b)) return false; if (!cmp2(a[key], b[key])) return false; } return true; } function mergeDefaults(...sources) { const target = {}; for (const source of sources) { if (!(0, import_ag_charts_core.isObject)(source)) continue; const keys = isDecoratedObject(source) ? listDecoratedProperties(source) : Object.keys(source); for (const key of keys) { if ((0, import_ag_charts_core.isPlainObject)(target[key]) && (0, import_ag_charts_core.isPlainObject)(source[key])) { target[key] = mergeDefaults(target[key], source[key]); } else { target[key] ?? (target[key] = source[key]); } } } return target; } function merge(...sources) { const target = {}; for (const source of sources) { if (!(0, import_ag_charts_core.isObject)(source)) continue; const keys = isDecoratedObject(source) ? listDecoratedProperties(source) : Object.keys(source); for (const key of keys) { if ((0, import_ag_charts_core.isPlainObject)(target[key]) && (0, import_ag_charts_core.isPlainObject)(source[key])) { target[key] = merge(target[key], source[key]); } else if (!(key in target)) { target[key] ?? (target[key] = source[key]); } } } return target; } // packages/ag-charts-community/src/scene/bbox.ts var import_ag_charts_core2 = require("ag-charts-core"); // packages/ag-charts-community/src/util/interpolating.ts var interpolate = Symbol("interpolate"); // packages/ag-charts-community/src/util/nearest.ts function nearestSquared(x, y, objects, maxDistanceSquared = Infinity) { const result = { nearest: void 0, distanceSquared: maxDistanceSquared }; for (const obj of objects) { const thisDistance = obj.distanceSquared(x, y); if (thisDistance === 0) { return { nearest: obj, distanceSquared: 0 }; } else if (thisDistance < result.distanceSquared) { result.nearest = obj; result.distanceSquared = thisDistance; } } return result; } // packages/ag-charts-community/src/scene/bbox.ts var _BBox = class _BBox { constructor(x, y, width, height) { this.x = x; this.y = y; this.width = width; this.height = height; } static fromDOMRect({ x, y, width, height }) { return new _BBox(x, y, width, height); } static merge(boxes) { let left = Infinity; let top = Infinity; let right = -Infinity; let bottom = -Infinity; for (const box of boxes) { if (box.x < left) { left = box.x; } if (box.y < top) { top = box.y; } if (box.x + box.width > right) { right = box.x + box.width; } if (box.y + box.height > bottom) { bottom = box.y + box.height; } } return new _BBox(left, top, right - left, bottom - top); } static nearestBox(x, y, boxes) { return nearestSquared(x, y, boxes); } toDOMRect() { return { x: this.x, y: this.y, width: this.width, height: this.height, top: this.y, left: this.x, right: this.x + this.width, bottom: this.y + this.height, toJSON() { return {}; } }; } clone() { const { x, y, width, height } = this; return new _BBox(x, y, width, height); } equals(other) { return (0, import_ag_charts_core2.boxesEqual)(this, other); } containsPoint(x, y) { return (0, import_ag_charts_core2.boxContains)(this, x, y); } intersection(other) { if (!this.collidesBBox(other)) return; const newX1 = (0, import_ag_charts_core2.clamp)(other.x, this.x, other.x + other.width); const newY1 = (0, import_ag_charts_core2.clamp)(other.y, this.y, other.y + other.height); const newX2 = (0, import_ag_charts_core2.clamp)(other.x, this.x + this.width, other.x + other.width); const newY2 = (0, import_ag_charts_core2.clamp)(other.y, this.y + this.height, other.y + other.height); return new _BBox(newX1, newY1, newX2 - newX1, newY2 - newY1); } collidesBBox(other) { return this.x < other.x + other.width && this.x + this.width > other.x && this.y < other.y + other.height && this.y + this.height > other.y; } computeCenter() { return { x: this.x + this.width / 2, y: this.y + this.height / 2 }; } isFinite() { return Number.isFinite(this.x) && Number.isFinite(this.y) && Number.isFinite(this.width) && Number.isFinite(this.height); } distanceSquared(x, y) { if (this.containsPoint(x, y)) { return 0; } const dx = x - (0, import_ag_charts_core2.clamp)(this.x, x, this.x + this.width); const dy = y - (0, import_ag_charts_core2.clamp)(this.y, y, this.y + this.height); return dx * dx + dy * dy; } shrink(amount, position) { if (typeof amount === "number") { this.applyMargin(amount, position); } else { for (const key of Object.keys(amount)) { const value = amount[key]; if (typeof value === "number") { this.applyMargin(value, key); } } } if (this.width < 0) { this.width = 0; } if (this.height < 0) { this.height = 0; } return this; } grow(amount, position) { if (typeof amount === "number") { this.applyMargin(-amount, position); } else { for (const key of Object.keys(amount)) { const value = amount[key]; if (typeof value === "number") { this.applyMargin(-value, key); } } } return this; } applyMargin(value, position) { switch (position) { case "top": this.y += value; case "bottom": this.height -= value; break; case "left": this.x += value; case "right": this.width -= value; break; case "vertical": this.y += value; this.height -= value * 2; break; case "horizontal": this.x += value; this.width -= value * 2; break; case void 0: this.x += value; this.y += value; this.width -= value * 2; this.height -= value * 2; break; } } translate(x, y) { this.x += x; this.y += y; return this; } [interpolate](other, d) { return new _BBox( this.x * (1 - d) + other.x * d, this.y * (1 - d) + other.y * d, this.width * (1 - d) + other.width * d, this.height * (1 - d) + other.height * d ); } }; _BBox.zero = Object.freeze(new _BBox(0, 0, 0, 0)); _BBox.NaN = Object.freeze(new _BBox(NaN, NaN, NaN, NaN)); var BBox = _BBox; // packages/ag-charts-community/src/scene/changeDetectable.ts var import_ag_charts_core3 = require("ag-charts-core"); var TRIPLE_EQ = (lhs, rhs) => lhs === rhs; function SceneChangeDetection(opts) { return function(target, key) { const privateKey = `__${key}`; if (target[key]) return; prepareGetSet(target, key, privateKey, opts); }; } function SceneRefChangeDetection(opts) { return SceneChangeDetection(opts); } function SceneObjectChangeDetection(opts) { return SceneChangeDetection(opts); } function SceneArrayChangeDetection(opts) { const baseOpts = opts ?? {}; baseOpts.equals = import_ag_charts_core3.arraysEqual; return SceneChangeDetection(opts); } function prepareGetSet(target, key, privateKey, opts) { const { changeCb, convertor, checkDirtyOnAssignment = false } = opts ?? {}; const requiredOpts = { changeCb, checkDirtyOnAssignment, convertor }; const setter = buildCheckDirtyChain( privateKey, buildChangeCallbackChain( buildConvertorChain(buildSetter(privateKey, requiredOpts), requiredOpts), requiredOpts ), requiredOpts ); const getter = function() { return this[privateKey]; }; Object.defineProperty(target, key, { set: setter, get: getter, enumerable: true, configurable: true }); } function buildConvertorChain(setterFn, opts) { const { convertor } = opts; if (convertor) { return function(value) { setterFn.call(this, convertor(value)); }; } return setterFn; } var NO_CHANGE = Symbol("no-change"); function buildChangeCallbackChain(setterFn, opts) { const { changeCb } = opts; if (changeCb) { return function(value) { const change = setterFn.call(this, value); if (change !== NO_CHANGE) { changeCb.call(this, this); } return change; }; } return setterFn; } function buildCheckDirtyChain(privateKey, setterFn, opts) { const { checkDirtyOnAssignment } = opts; if (checkDirtyOnAssignment) { return function(value) { const change = setterFn.call(this, value); if (value?._dirty === true) { this.markDirty(privateKey); } return change; }; } return setterFn; } function buildSetter(privateKey, opts) { const { equals = TRIPLE_EQ } = opts; return function(value) { const oldValue = this[privateKey]; if (!equals(value, oldValue)) { this[privateKey] = value; this.onChangeDetection(privateKey); return value; } return NO_CHANGE; }; } // packages/ag-charts-community/src/scene/zIndex.ts var cmp = (a, b) => Math.sign(a - b); function compareZIndex(a, b) { if (typeof a === "number" && typeof b === "number") { return cmp(a, b); } const aArray = typeof a === "number" ? [a] : a; const bArray = typeof b === "number" ? [b] : b; const length = Math.min(aArray.length, bArray.length); for (let i = 0; i < length; i += 1) { const diff = cmp(aArray[i], bArray[i]); if (diff !== 0) return diff; } return cmp(aArray.length, bArray.length); } // packages/ag-charts-community/src/scene/node.ts var MAX_ERROR_COUNT = 5; var _Node = class _Node { constructor(options) { /** Unique number to allow creation order to be easily determined. */ this.serialNumber = _Node._nextSerialNumber++; this.childNodeCounts = { groups: 0, nonGroups: 0, thisComplexity: 0, complexity: 0 }; /** Unique node ID in the form `ClassName-NaturalNumber`. */ this.id = (0, import_ag_charts_core4.createId)(this); this.name = void 0; this.transitionOut = void 0; this.pointerEvents = 0 /* All */; this._datum = void 0; this._previousDatum = void 0; this.scene = void 0; this._debugDirtyProperties = void 0; this.parentNode = void 0; this.cachedBBox = void 0; /** * To simplify the type system (especially in Selections) we don't have the `Parent` node * (one that has children). Instead, we mimic HTML DOM, where any node can have children. * But we still need to distinguish regular leaf nodes from container leafs somehow. */ this.isContainerNode = false; this.visible = true; this.zIndex = 0; this.batchLevel = 0; this.batchDirty = false; this.name = options?.name; this.tag = options?.tag ?? NaN; this.zIndex = options?.zIndex ?? 0; this.scene = options?.scene; if (options?.debugDirty ?? _Node._debugEnabled) { this._debugDirtyProperties = /* @__PURE__ */ new Map([["__first__", []]]); } } static toSVG(node, width, height) { const svg = node?.toSVG(); if (svg == null || !svg.elements.length && !svg.defs?.length) return; const root = (0, import_ag_charts_core4.createSvgElement)("svg"); root.setAttribute("width", String(width)); root.setAttribute("height", String(height)); root.setAttribute("viewBox", `0 0 ${width} ${height}`); root.setAttribute("overflow", "visible"); if (svg.defs?.length) { const defs = (0, import_ag_charts_core4.createSvgElement)("defs"); defs.append(...svg.defs); root.append(defs); } root.append(...svg.elements); return root.outerHTML; } static *extractBBoxes(nodes, skipInvisible) { for (const n of nodes) { if (!skipInvisible || n.visible && !n.transitionOut) { const bbox = n.getBBox(); if (bbox) yield bbox; } } } /** * Some arbitrary data bound to the node. */ get datum() { return this._datum; } set datum(datum) { if (this._datum !== datum) { this._previousDatum = this._datum; this._datum = datum; } } get previousDatum() { return this._previousDatum; } get layerManager() { return this.scene?.layersManager; } get imageLoader() { return this.scene?.imageLoader; } closestDatum() { for (const { datum } of this.traverseUp(true)) { if (datum != null) { return datum; } } } /** Perform any pre-rendering initialization. */ preRender(_renderCtx, thisComplexity = 1) { this.childNodeCounts.groups = 0; this.childNodeCounts.nonGroups = 1; this.childNodeCounts.complexity = thisComplexity; this.childNodeCounts.thisComplexity = thisComplexity; if (this.batchLevel > 0 || this.batchDirty) { throw new Error("AG Charts - illegal rendering state; batched update in progress"); } return this.childNodeCounts; } /** Guaranteed isolated render - if there is any failure, the Cavans2D context is returned to its prior state. */ isolatedRender(renderCtx) { renderCtx.ctx.save(); try { this.render(renderCtx); } catch (e) { const errorCount = e.errorCount ?? 1; if (errorCount >= MAX_ERROR_COUNT) { e.errorCount = errorCount; throw e; } import_ag_charts_core4.Logger.warnOnce("Error during rendering", e, e.stack); } finally { renderCtx.ctx.restore(); } } render(renderCtx) { const { stats } = renderCtx; this.debugDirtyProperties(); if (renderCtx.debugNodeSearch) { const idOrName = this.name ?? this.id; if (renderCtx.debugNodeSearch.some((v) => typeof v === "string" ? v === idOrName : v.test(idOrName))) { renderCtx.debugNodes[this.name ?? this.id] = this; } } if (stats) { stats.nodesRendered++; stats.opsPerformed += this.childNodeCounts.thisComplexity; } } setScene(scene) { this.scene = scene; } *traverseUp(includeSelf) { let node = this; if (includeSelf) { yield node; } while (node = node.parentNode) { yield node; } } /** * Checks if the node is the root (has no parent). */ isRoot() { return !this.parentNode; } removeChild(node) { throw new Error( `AG Charts - internal error, unknown child node ${node.name ?? node.id} in $${this.name ?? this.id}` ); } remove() { this.parentNode?.removeChild(this); } destroy() { this.parentNode?.removeChild(this); } batchedUpdate(fn) { this.batchLevel++; fn(); this.batchLevel--; if (this.batchLevel === 0 && this.batchDirty) { this.markDirty(); this.batchDirty = false; } } setProperties(styles) { this.batchLevel++; Object.assign(this, styles); this.batchLevel--; if (this.batchLevel === 0 && this.batchDirty) { this.markDirty(); this.batchDirty = false; } return this; } containsPoint(_x, _y) { return false; } pickNode(x, y) { if (this.containsPoint(x, y)) { return this; } } pickNodes(x, y, into = []) { if (this.containsPoint(x, y)) { into.push(this); } return into; } getBBox() { this.cachedBBox ?? (this.cachedBBox = Object.freeze(this.computeBBox())); return this.cachedBBox; } computeBBox() { return; } onChangeDetection(property) { this.markDirty(property); } markDirtyChildrenOrder() { this.cachedBBox = void 0; } markDirty(property) { if (this.batchLevel > 0) { this.batchDirty = true; return; } if (property != null && this._debugDirtyProperties) { this.markDebugProperties(property); } this.cachedBBox = void 0; this.parentNode?.markDirty(); } markDebugProperties(property) { const sources = this._debugDirtyProperties?.get(property) ?? []; const caller = new Error().stack?.split("\n").filter((line) => { return line !== "Error" && !line.includes(".markDebugProperties") && !line.includes(".markDirty") && !line.includes("Object.assign ") && !line.includes(`${this.constructor.name}.`); }) ?? "unknown"; sources.push(caller[0].replace(" at ", "").trim()); this._debugDirtyProperties?.set(property, sources); } debugDirtyProperties() { if (this._debugDirtyProperties == null) return; if (!this._debugDirtyProperties.has("__first__")) { this._debugDirtyProperties.forEach((sources, property) => { if (sources.length > 1) { console.groupCollapsed( `Property changed multiple times before render: ${this.constructor.name}.${property} (${sources.length}x)` ); sources.forEach((source) => console.log(source)); console.groupEnd(); } }); } this._debugDirtyProperties.clear(); } onZIndexChange() { this.parentNode?.markDirtyChildrenOrder(); } toSVG() { return; } }; _Node._nextSerialNumber = 0; // eslint-disable-next-line sonarjs/public-static-readonly _Node._debugEnabled = false; __decorateClass([ SceneChangeDetection() ], _Node.prototype, "visible", 2); __decorateClass([ SceneObjectChangeDetection({ equals: objectsEqual, changeCb: (target) => target.onZIndexChange() }) ], _Node.prototype, "zIndex", 2); var Node = _Node; // packages/ag-charts-community/src/scene/shape/text.ts var import_ag_charts_core26 = require("ag-charts-core"); // packages/ag-charts-community/src/util/debug.ts var import_ag_charts_core5 = require("ag-charts-core"); var LONG_TIME_PERIOD_THRESHOLD = 2e3; var timeOfLastLog = Date.now(); var logTimeGap = () => { const timeSinceLastLog = Date.now() - timeOfLastLog; if (timeSinceLastLog > LONG_TIME_PERIOD_THRESHOLD) { const prettyDuration = (Math.floor(timeSinceLastLog / 100) / 10).toFixed(1); import_ag_charts_core5.Logger.log(`**** ${prettyDuration}s since last log message ****`); } timeOfLastLog = Date.now(); }; var Debug = { create(...debugSelectors) { const resultFn = (...logContent) => { if (Debug.check(...debugSelectors)) { if (typeof logContent[0] === "function") { logContent = (0, import_ag_charts_core5.toArray)(logContent[0]()); } logTimeGap(); import_ag_charts_core5.Logger.log(...logContent); } }; return Object.assign(resultFn, { check: () => Debug.check(...debugSelectors), group: (name, cb) => { if (Debug.check(...debugSelectors)) { return import_ag_charts_core5.Logger.logGroup(name, cb); } return cb(); } }); }, check(...debugSelectors) { if (debugSelectors.length === 0) { debugSelectors.push(true); } const chartDebug = (0, import_ag_charts_core5.toArray)((0, import_ag_charts_core5.getWindow)("agChartsDebug")); return chartDebug.some((selector) => debugSelectors.includes(selector)); }, inDevelopmentMode(fn) { if (Debug.check("dev")) { return fn(); } } }; // packages/ag-charts-community/src/util/canvas.util.ts function createCanvasContext(width = 0, height = 0) { return new OffscreenCanvas(width, height).getContext("2d"); } // packages/ag-charts-community/src/util/lruCache.ts var LRUCache = class { constructor(maxCacheSize = 5) { this.maxCacheSize = maxCacheSize; this.store = /* @__PURE__ */ new Map(); } get(key) { if (!this.store.has(key)) return void 0; const hit = this.store.get(key); this.store.delete(key); this.store.set(key, hit); return hit; } has(key) { return this.store.has(key); } set(key, value) { this.store.set(key, value); if (this.store.size > this.maxCacheSize) { const iterator = this.store.keys(); let evictCount = this.store.size - this.maxCacheSize; while (evictCount > 0) { const evictKeyIterator = iterator.next(); if (!evictKeyIterator.done) { this.store.delete(evictKeyIterator.value); } evictCount--; } } return value; } clear() { this.store.clear(); } }; // packages/ag-charts-community/src/util/textMeasurer.ts var CachedTextMeasurerPool = class { // Measures the dimensions of the provided text, handling multiline if needed. static measureText(text, options) { const textMeasurer = this.getMeasurer(options); return textMeasurer.measureText(text); } static measureLines(text, options) { const textMeasurer = this.getMeasurer(options); return textMeasurer.measureLines(text); } // Gets a TextMeasurer instance, configuring text alignment and baseline if provided. static getMeasurer(options) { const font = TextUtils.toFontString(options.font); const key = `${font}-${options.textAlign ?? "start"}-${options.textBaseline ?? "top"}`; return this.instanceMap.get(key) ?? this.createFontMeasurer(font, options, key); } static clear() { this.instanceMap.clear(); } // Creates or retrieves a TextMeasurer instance for a specific font. static createFontMeasurer(font, options, key) { const ctx = createCanvasContext(); ctx.font = font; ctx.textAlign = options.textAlign ?? "start"; ctx.textBaseline = options.textBaseline ?? "top"; const measurer = new CachedTextMeasurer(ctx, options); this.instanceMap.set(key, measurer); return measurer; } }; CachedTextMeasurerPool.instanceMap = new LRUCache(10); var CachedTextMeasurer = class { constructor(ctx, options) { this.ctx = ctx; // cached text measurements this.measureMap = new LRUCache(100); if (options.textAlign) { ctx.textAlign = options.textAlign; } if (options.textBaseline) { ctx.textBaseline = options.textBaseline; } ctx.font = TextUtils.toFontString(options.font); this.textMeasurer = new SimpleTextMeasurer( (t) => this.cachedCtxMeasureText(t), options.textBaseline ?? "alphabetic" ); } textWidth(text, estimate) { return this.textMeasurer.textWidth(text, estimate); } measureText(text) { return this.textMeasurer.measureText(text); } measureLines(text) { return this.textMeasurer.measureLines(text); } cachedCtxMeasureText(text) { if (!this.measureMap.has(text)) { const rawResult = this.ctx.measureText(text); this.measureMap.set(text, { actualBoundingBoxAscent: rawResult.actualBoundingBoxAscent, emHeightAscent: rawResult.emHeightAscent, emHeightDescent: rawResult.emHeightDescent, actualBoundingBoxDescent: rawResult.actualBoundingBoxDescent, actualBoundingBoxLeft: rawResult.actualBoundingBoxLeft, actualBoundingBoxRight: rawResult.actualBoundingBoxRight, alphabeticBaseline: rawResult.alphabeticBaseline, fontBoundingBoxAscent: rawResult.fontBoundingBoxAscent, fontBoundingBoxDescent: rawResult.fontBoundingBoxDescent, hangingBaseline: rawResult.hangingBaseline, ideographicBaseline: rawResult.ideographicBaseline, width: rawResult.width }); } return this.measureMap.get(text); } }; var TextUtils = class { static toFontString({ fontSize = 10, fontStyle, fontWeight, fontFamily }) { let fontString = ""; if (fontStyle && fontStyle !== "normal") { fontString += `${fontStyle} `; } if (fontWeight && fontWeight !== "normal" && fontWeight !== 400) { fontString += `${fontWeight} `; } fontString += `${fontSize}px`; fontString += ` ${fontFamily}`; return fontString.trim(); } static getLineHeight(fontSize) { return Math.ceil(fontSize * this.defaultLineHeight); } static getHorizontalModifier(textAlign) { switch (textAlign) { case "left": case "start": return 0; case "center": return 0.5; case "right": case "end": return 1; default: return 0; } } // Determines vertical offset modifier based on text baseline. static getVerticalModifier(textBaseline) { switch (textBaseline) { case "hanging": case "top": return 0; case "middle": return 0.5; case "alphabetic": case "bottom": case "ideographic": default: return 1; } } }; TextUtils.EllipsisChar = "\u2026"; // Representation for text clipping. TextUtils.defaultLineHeight = 1.15; // Normally between 1.1 and 1.2 TextUtils.lineSplitter = /\r?\n/g; var SimpleTextMeasurer = class { constructor(measureTextFn, textBaseline = "alphabetic") { this.measureTextFn = measureTextFn; this.textBaseline = textBaseline; // local chars width cache per TextMeasurer this.charMap = /* @__PURE__ */ new Map(); } // Measures metrics for a single line of text. getMetrics(text) { const m = this.measureTextFn(text); m.fontBoundingBoxAscent ?? (m.fontBoundingBoxAscent = m.emHeightAscent); m.fontBoundingBoxDescent ?? (m.fontBoundingBoxDescent = m.emHeightDescent); return { width: m.width, height: m.actualBoundingBoxAscent + m.actualBoundingBoxDescent, lineHeight: m.fontBoundingBoxAscent + m.fontBoundingBoxDescent }; } // Calculates aggregated metrics for multiline text. getMultilineMetrics(lines) { let width = 0; let height = 0; let offsetTop = 0; let offsetLeft = 0; let baselineDistance = 0; let alphabeticBaseline = 0; const verticalModifier = TextUtils.getVerticalModifier(this.textBaseline); const lineMetrics = []; let index = 0; const length = lines.length; for (const line of lines) { const m = this.measureTextFn(line); m.fontBoundingBoxAscent ?? (m.fontBoundingBoxAscent = m.emHeightAscent); m.fontBoundingBoxDescent ?? (m.fontBoundingBoxDescent = m.emHeightDescent); if (width < m.width) { width = m.width; } if (offsetLeft < m.actualBoundingBoxLeft) { offsetLeft = m.actualBoundingBoxLeft; } if (index === 0) { height += m.actualBoundingBoxAscent; offsetTop += m.actualBoundingBoxAscent; alphabeticBaseline = m.alphabeticBaseline; } else { baselineDistance += m.fontBoundingBoxAscent; } if (index === length - 1) { height += m.actualBoundingBoxDescent; } else { baselineDistance += m.fontBoundingBoxDescent; } lineMetrics.push({ text: line, width: m.width, height: m.actualBoundingBoxAscent + m.actualBoundingBoxDescent, lineHeight: m.fontBoundingBoxAscent + m.fontBoundingBoxDescent, offsetTop: m.actualBoundingBoxAscent, offsetLeft: m.actualBoundingBoxLeft }); index++; } height += baselineDistance; offsetTop += baselineDistance * verticalModifier; return { width, height, offsetTop, offsetLeft, alphabeticBaseline, lineMetrics }; } textWidth(text, estimate) { if (estimate) { let estimatedWidth = 0; for (let i = 0; i < text.length; i++) { estimatedWidth += this.textWidth(text.charAt(i)); } return estimatedWidth; } if (text.length > 1) { return this.measureTextFn(text).width; } return this.charMap.get(text) ?? this.charWidth(text); } measureText(text) { return this.getMetrics(text); } // Measures the dimensions of the provided text, handling multiline if needed. measureLines(text) { const lines = typeof text === "string" ? text.split(TextUtils.lineSplitter) : text; return this.getMultilineMetrics(lines); } charWidth(char) { const { width } = this.measureTextFn(char); this.charMap.set(char, width); return width; } }; // packages/ag-charts-community/src/scene/group.ts var import_ag_charts_core22 = require("ag-charts-core"); // packages/ag-charts-community/src/scene/canvas/canvasUtil.ts function clearContext({ context, pixelRatio, width, height }) { context.save(); try { context.resetTransform(); context.clearRect(0, 0, Math.ceil(width * pixelRatio), Math.ceil(height * pixelRatio)); } finally { context.restore(); } } function debugContext(ctx) { if (Debug.check("canvas")) { const save = ctx.save.bind(ctx); const restore = ctx.restore.bind(ctx); let depth = 0; Object.assign(ctx, { save() { save(); depth++; }, restore() { if (depth === 0) { throw new Error("AG Charts - Unable to restore() past depth 0"); } restore(); depth--; }, verifyDepthZero() { if (depth !== 0) { throw new Error(`AG Charts - Save/restore depth is non-zero: ${depth}`); } } }); } } // packages/ag-charts-community/src/scene/canvas/hdpiOffscreenCanvas.ts function canvasDimensions(width, height, pixelRatio) { return [Math.floor(width * pixelRatio), Math.floor(height * pixelRatio)]; } var HdpiOffscreenCanvas = class { constructor(options) { const { width, height, pixelRatio, willReadFrequently = false } = options; this.width = width; this.height = height; this.pixelRatio = pixelRatio; const [canvasWidth, canvasHeight] = canvasDimensions(width, height, pixelRatio); this.canvas = new OffscreenCanvas(canvasWidth, canvasHeight); this.context = this.canvas.getContext("2d", { willReadFrequently }); this.context.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0); debugContext(this.context); } drawImage(context, dx = 0, dy = 0) { return context.drawImage(this.canvas, dx, dy); } transferToImageBitmap() { return this.canvas.transferToImageBitmap(); } resize(width, height, pixelRatio) { if (!(width > 0 && height > 0)) return; const { canvas, context } = this; if (width !== this.width || height !== this.height || pixelRatio !== this.pixelRatio) { const [canvasWidth, canvasHeight] = canvasDimensions(width, height, pixelRatio); canvas.width = canvasWidth; canvas.height = canvasHeight; } context.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0); this.width = width; this.height = height; this.pixelRatio = pixelRatio; } clear() { clearContext(this); } destroy() { this.canvas.width = 0; this.canvas.height = 0; this.context.clearRect(0, 0, 0, 0); this.canvas = null; this.context = null; Object.freeze(this); } }; // packages/ag-charts-community/src/scene/shape/shape.ts var import_ag_charts_core19 = require("ag-charts-core"); // packages/ag-charts-community/src/scene/gradient/conicGradient.ts var import_ag_charts_core9 = require("ag-charts-core"); // packages/ag-charts-community/src/util/angle.ts var twoPi = Math.PI * 2; var halfPi = Math.PI / 2; function normalizeAngle360(radians) { radians %= twoPi; radians += twoPi; radians %= twoPi; return radians; } function normalizeAngle180(radians) { radians %= twoPi; if (radians < -Math.PI) { radians += twoPi; } else if (radians >= Math.PI) { radians -= twoPi; } return radians; } function isBetweenAngles(targetAngle, startAngle, endAngle) { const t = normalizeAngle360(targetAngle); const a0 = normalizeAngle360(startAngle); const a1 = normalizeAngle360(endAngle); if (a0 < a1) { return a0 <= t && t <= a1; } else if (a0 > a1) { return a0 <= t || t <= a1; } else { return startAngle !== endAngle; } } function toRadians(degrees) { return degrees / 180 * Math.PI; } function angleBetween(angle0, angle1) { angle0 = normalizeAngle360(angle0); angle1 = normalizeAngle360(angle1); return angle1 - angle0 + (angle0 > angle1 ? twoPi : 0); } function normalizeAngle360FromDegrees(degrees) { return degrees ? normalizeAngle360(toRadians(degrees)) : 0; } // packages/ag-charts-community/src/scene/gradient/gradient.ts var import_ag_charts_core8 = require("ag-charts-core"); // packages/ag-charts-community/src/scale/colorScale.ts var import_ag_charts_core7 = require("ag-charts-core"); // packages/ag-charts-community/src/util/color.ts var import_ag_charts_core6 = require("ag-charts-core"); var lerp = (x, y, t) => x * (1 - t) + y * t; var srgbToLinear = (value) => { const sign = value < 0 ? -1 : 1; const abs = Math.abs(value); if (abs <= 0.04045) return value / 12.92; return sign * ((abs + 0.055) / 1.055) ** 2.4; }; var srgbFromLinear = (value) => { const sign = value < 0 ? -1 : 1; const abs = Math.abs(value); if (abs > 31308e-7) { return sign * (1.055 * abs ** (1 / 2.4) - 0.055); } return 12.92 * value; }; var _Color = class _Color { /** * Every color component should be in the [0, 1] range. * Some easing functions (such as elastic easing) can overshoot the target value by some amount. * So, when animating colors, if the source or target color components are already near * or at the edge of the allowed [0, 1] range, it is possible for the intermediate color * component value to end up outside of that range mid-animation. For this reason the constructor * performs range checking/constraining. * @param r Red component. * @param g Green component. * @param b Blue component. * @param a Alpha (opacity) component. */ constructor(r, g, b, a = 1) { this.r = (0, import_ag_charts_core6.clamp)(0, r || 0, 1); this.g = (0, import_ag_charts_core6.clamp)(0, g || 0, 1); this.b = (0, import_ag_charts_core6.clamp)(0, b || 0, 1); this.a = (0, import_ag_charts_core6.clamp)(0, a || 0, 1); } /** * A color string can be in one of the following formats to be valid: * - #rgb * - #rrggbb * - rgb(r, g, b) * - rgba(r, g, b, a) * - CSS color name such as 'white', 'orange', 'cyan', etc. */ static validColorString(str) { if (str.indexOf("#") >= 0) { return !!_Color.parseHex(str); } if (str.indexOf("rgb") >= 0) { return !!_Color.stringToRgba(str); } return _Color.nameToHex.has(str.toLowerCase()); } /** * The given string can be in one of the following formats: * - #rgb * - #rrggbb * - rgb(r, g, b) * - rgba(r, g, b, a) * - CSS color name such as 'white', 'orange', 'cyan', etc. * @param str */ static fromString(str) { if (str.indexOf("#") >= 0) { return _Color.fromHexString(str); } const hex = _Color.nameToHex.get(str.toLowerCase()); if (hex) { return _Color.fromHexString(hex); } if (str.indexOf("rgb") >= 0) { return _Color.fromRgbaString(str); } throw new Error(`Invalid color string: '${str}'`); } // See https://drafts.csswg.org/css-color/#hex-notation static parseHex(input) { input = input.replace(/ /g, "").slice(1); let parts; switch (input.length) { case 6: case 8: parts = []; for (let i = 0; i < input.length; i += 2) { parts.push(parseInt(`${input[i]}${input[i + 1]}`, 16)); } break; case 3: case 4: parts = input.split("").map((p) => parseInt(p, 16)).map((p) => p + p * 16); break; } if (parts?.length >= 3 && parts.every((p) => p >= 0)) { if (parts.length === 3) { parts.push(255); } return parts; } } static fromHexString(str) { const values = _Color.parseHex(str); if (values) { const [r, g, b, a] = values; return new _Color(r / 255, g / 255, b / 255, a / 255); } throw new Error(`Malformed hexadecimal color string: '${str}'`); } static stringToRgba(str) { let po = -1; let pc = -1; for (let i = 0; i < str.length; i++) { const c = str[i]; if (po === -1 && c === "(") { po = i; } else if (c === ")") { pc = i; break; } } if (po === -1 || pc === -1) return; const contents = str.substring(po + 1, pc); const parts = contents.split(","); const rgba = []; for (let i = 0; i < parts.length; i++) { const part = parts[i]; let value = parseFloat(part); if (!Number.isFinite(value)) { return; } if (part.indexOf("%") >= 0) { value = (0, import_ag_charts_core6.clamp)(0, value, 100); value /= 100; } else if (i === 3) { value = (0, import_ag_charts_core6.clamp)(0, value, 1); } else { value = (0, import_ag_charts_core6.clamp)(0, value, 255); value /= 255; } rgba.push(value); } return rgba; } static fromRgbaString(str) { const rgba = _Color.stringToRgba(str); if (rgba) { if (rgba.length === 3) { return new _Color(rgba[0], rgba[1], rgba[2]); } else if (rgba.length === 4) { return new _Color(rgba[0], rgba[1], rgba[2], rgba[3]); } } throw new Error(`Malformed rgb/rgba color string: '${str}'`); } static fromArray(arr) { if (arr.length === 4) { return new _Color(arr[0], arr[1], arr[2], arr[3]); } if (arr.length === 3) { return new _Color(arr[0], arr[1], arr[2]); } throw new Error("The given array should contain 3 or 4 color components (numbers)."); } static fromHSB(h, s, b, alpha = 1) { const rgb = _Color.HSBtoRGB(h, s, b); return new _Color(rgb[0], rgb[1], rgb[2], alpha); } static fromHSL(h, s, l, alpha = 1) { const rgb = _Color.HSLtoRGB(h, s, l); return new _Color(rgb[0], rgb[1], rgb[2], alpha); } static fromOKLCH(l, c, h, alpha = 1) { const rgb = _Color.OKLCHtoRGB(l, c, h); return new _Color(rgb[0], rgb[1], rgb[2], alpha); } static padHex(str) { return str.length === 1 ? "0" + str : str; } toHexString() { let hex = "#" + _Color.padHex(Math.round(this.r * 255).toString(16)) + _Color.padHex(Math.round(this.g * 255).toString(16)) + _Color.padHex(Math.round(this.b * 255).toString(16)); if (this.a < 1) { hex += _Color.padHex(Math.round(this.a * 255).toString(16)); } return hex; } toRgbaString(fractionDigits = 3) { const components = [Math.round(this.r * 255), Math.round(this.g * 255), Math.round(this.b * 255)]; const k = Math.pow(10, fractionDigits); if (this.a !== 1) { components.push(Math.round(this.a * k) / k); return `rgba(${components.join(", ")})`; } return `rgb(${components.join(", ")})`; } toString() { if (this.a === 1) { return this.toHexString(); } return this.toRgbaString(); } toHSB() { return _Color.RGBtoHSB(this.r, this.g, this.b); } static RGBtoOKLCH(r, g, b) { const LSRGB0 = srgbToLinear(r); const LSRGB1 = srgbToLinear(g); const LSRGB2 = srgbToLinear(b); const LMS0 = Math.cbrt(0.4122214708 * LSRGB0 + 0.5363325363 * LSRGB1 + 0.0514459929 * LSRGB2); const LMS1 = Math.cbrt(0.2119034982 * LSRGB0 + 0.6806995451 * LSRGB1 + 0.1073969566 * LSRGB2); const LMS2 = Math.cbrt(0.0883024619 * LSRGB0 + 0.2817188376 * LSRGB1 + 0.6299787005 * LSRGB2); const OKLAB0 = 0.2104542553 * LMS0 + 0.793617785 * LMS1 - 0.0040720468 * LMS2; const OKLAB1 = 1.9779984951 * LMS0 - 2.428592205 * LMS1 + 0.4505937099 * LMS2; const OKLAB2 = 0.0259040371 * LMS0 + 0.7827717662 * LMS1 - 0.808675766 * LMS2; const hue = Math.atan2(OKLAB2, OKLAB1) * 180 / Math.PI; const OKLCH0 = OKLAB0; const OKLCH1 = Math.hypot(OKLAB1, OKLAB2); const OKLCH2 = hue >= 0 ? hue : hue + 360; return [OKLCH0, OKLCH1, OKLCH2]; } static OKLCHtoRGB(l, c, h) { const OKLAB0 = l; const OKLAB1 = c * Math.cos(h * Math.PI / 180); const OKLAB2 = c * Math.sin(h * Math.PI / 180); const LMS0 = (OKLAB0 + 0.3963377774 * OKLAB1 + 0.2158037573 * OKLAB2) ** 3; const LMS1 = (OKLAB0 - 0.1055613458 * OKLAB1 - 0.0638541728 * OKLAB2) ** 3; const LMS2 = (OKLAB0 - 0.0894841775 * OKLAB1 - 1.291485548 * OKLAB2) ** 3; const LSRGB0 = 4.0767416621 * LMS0 - 3.3077115913 * LMS1 + 0.2309699292 * LMS2; const LSRGB1 = -1.2684380046 * LMS0 + 2.6097574011 * LMS1 - 0.3413193965 * LMS2; const LSRGB2 = -0.0041960863 * LMS0 - 0.7034186147 * LMS1 + 1.707614701 * LMS2; const SRGB0 = srgbFromLinear(LSRGB0); const SRGB1 = srgbFromLinear(LSRGB1); const SRGB2 = srgbFromLinear(LSRGB2); return [SRGB0, SRGB1, SRGB2]; } static RGBtoHSL(r, g, b) { const min = Math.min(r, g, b); const max = Math.max(r, g, b); const l = (max + min) / 2; let h; let s; if (max === min) { h = 0; s = 0; } else { const delta3 = max - min; s = l > 0.5 ? delta3 / (2 - max - min) : delta3 / (max + min); if (max === r) { h = (g - b) / delta3 + (g < b ? 6 : 0); } else if (max === g) { h = (b - r) / delta3 + 2; } else { h = (r - g) / delta3 + 4; } h *= 360 / 6; } return [h, s, l]; } static HSLtoRGB(h, s, l) { h = (h % 360 + 360) % 360; if (s === 0) { return [l, l, l]; } const q = l < 0.5 ? l * (1 + s) : l + s - l * s; const p = 2 * l - q; function hueToRgb(t) { if (t < 0) t += 1; if (t > 1) t -= 1; if (t < 1 / 6) return p + (q - p) * 6 * t; if (t < 1 / 2) return q; if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; return p; } const r = hueToRgb(h / 360 + 1 / 3); const g = hueToRgb(h / 360); const b = hueToRgb(h / 360 - 1 / 3); return [r, g, b]; } /** * Converts the given RGB triple to an array of HSB (HSV) components. */ static RGBtoHSB(r, g, b) { const min = Math.min(r, g, b); const max = Math.max(r, g, b); const S = max === 0 ? 0 : (max - min) / max; let H = 0; if (min !== max) { const delta3 = max - min; const rc = (max - r) / delta3; const gc = (max - g) / delta3; const bc = (max - b) / delta3; if (r === max) { H = bc - gc; } else if (g === max) { H = 2 + rc - bc; } else { H = 4 + gc - rc; } H /= 6; if (H < 0) { H = H + 1; } } return [H * 360, S, max]; } /** * Converts the given HSB (HSV) triple to an array of RGB components. */ static HSBtoRGB(H, S, B) { H = (H % 360 + 360) % 360 / 360; let r = 0; let g = 0; let b = 0; if (S === 0) { r = g = b = B; } else { const h = (H - Math.floor(H)) * 6; const f = h - Math.floor(h); const p = B * (1 - S); const q = B * (1 - S * f); const t = B * (1 - S * (1 - f)); switch (h >> 0) { case 0: r = B; g = t; b = p; break; case 1: r = q; g = B; b = p; break; case 2: r = p; g = B; b = t; break; case 3: r = p; g = q; b = B; break; case 4: r = t; g = p; b = B; break; case 5: r = B; g = p; b = q; break; } } return [r, g, b]; } static mix(c0, c1, t) { return new _Color(lerp(c0.r, c1.r, t), lerp(c0.g, c1.g, t), lerp(c0.b, c1.b, t), lerp(c0.a, c1.a, t)); } static lighten(c, t) { const oklch = _Color.RGBtoOKLCH(c.r, c.g, c.b); return _Colo