UNPKG

maxlinekchart

Version:

Lightweight k-line chart built with html5 canvas

1,417 lines (1,356 loc) 641 kB
/** * @license * KLineChart v10.0.0-alpha9 * Copyright (c) 2019 lihu. * Licensed under Apache License 2.0 https://www.apache.org/licenses/LICENSE-2.0 */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.klinecharts = {})); })(this, (function (exports) { 'use strict'; /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function log(templateText, tagStyle, messageStyle, api, invalidParam, append) { { var apiStr = api !== '' ? "Call api `".concat(api, "`").concat(invalidParam !== '' || append !== '' ? ', ' : '.') : ''; var invalidParamStr = invalidParam !== '' ? "invalid parameter `".concat(invalidParam, "`").concat(append !== '' ? ', ' : '.') : ''; var appendStr = append !== '' ? append : ''; console.log(templateText, tagStyle, messageStyle, apiStr, invalidParamStr, appendStr); } } function logWarn(api, invalidParam, append) { log('%c😑 klinecharts warning%c %s%s%s', 'padding:3px 4px;border-radius:2px;color:#ffffff;background-color:#FF9600', 'color:#FF9600', api, invalidParam, append !== null && append !== void 0 ? append : ''); } function logError(api, invalidParam, append) { log('%c😟 klinecharts error%c %s%s%s', 'padding:3px 4px;border-radius:2px;color:#ffffff;background-color:#F92855;', 'color:#F92855;', api, invalidParam, append ); } function logTag() { log('%c❤️ Welcome to klinecharts. Version is 10.0.0-alpha9', 'border-radius:4px;border:dashed 1px #1677FF;line-height:70px;padding:0 20px;margin:16px 0;font-size:14px;color:#1677FF;', '', '', '', ''); } /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ignore function merge(target, source) { if ((!isObject(target) && !isObject(source))) { return; } for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access -- ignore var targetProp = target[key]; // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access -- ignore var sourceProp = source[key]; if (isObject(sourceProp) && isObject(targetProp)) { merge(targetProp, sourceProp); } else { // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access -- ignore if (isValid(source[key])) { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access -- ignore target[key] = clone(source[key]); } } } } } function clone(target) { if (!isObject(target)) { return target; } // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ignore var copy = null; if (isArray(target)) { copy = []; } else { copy = {}; } for (var key in target) { if (Object.prototype.hasOwnProperty.call(target, key)) { var v = target[key]; if (isObject(v)) { // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access -- ignore copy[key] = clone(v); } else { // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access -- ignore copy[key] = v; } } } // eslint-disable-next-line @typescript-eslint/no-unsafe-return -- ignore return copy; } function isArray(value) { return Object.prototype.toString.call(value) === '[object Array]'; } // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- ignore function isFunction(value) { return typeof value === 'function'; } function isObject(value) { return (typeof value === 'object') && isValid(value); } function isNumber(value) { return typeof value === 'number' && Number.isFinite(value); } function isValid(value) { return value !== null && value !== undefined; } function isBoolean(value) { return typeof value === 'boolean'; } function isString(value) { return typeof value === 'string'; } /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var reEscapeChar = /\\(\\)?/g; var rePropName = RegExp('[^.[\\]]+' + '|' + '\\[(?:' + '([^"\'][^[]*)' + '|' + '(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' + ')\\]' + '|' + '(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))', 'g'); function formatValue(data, key, defaultValue) { if (isValid(data)) { var path_1 = []; key.replace(rePropName, function (subString) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } var k = subString; if (isValid(args[1])) { k = args[2].replace(reEscapeChar, '$1'); } else if (isValid(args[0])) { k = args[0].trim(); } path_1.push(k); return ''; }); var value = data; var index = 0; var length_1 = path_1.length; while (isValid(value) && index < length_1) { value = value === null || value === void 0 ? void 0 : value[path_1[index++]]; } return isValid(value) ? value : (defaultValue !== null && defaultValue !== void 0 ? defaultValue : '--'); } return defaultValue !== null && defaultValue !== void 0 ? defaultValue : '--'; } function formatTimestampToDateTime(dateTimeFormat, timestamp) { var date = {}; dateTimeFormat.formatToParts(new Date(timestamp)).forEach(function (_a) { var type = _a.type, value = _a.value; switch (type) { case 'year': { date.YYYY = value; break; } case 'month': { date.MM = value; break; } case 'day': { date.DD = value; break; } case 'hour': { date.HH = value === '24' ? '00' : value; break; } case 'minute': { date.mm = value; break; } case 'second': { date.ss = value; break; } } }); return date; } function formatTimestampByTemplate(dateTimeFormat, timestamp, template) { var date = formatTimestampToDateTime(dateTimeFormat, timestamp); // eslint-disable-next-line @typescript-eslint/no-unsafe-return -- ignore return template.replace(/YYYY|MM|DD|HH|mm|ss/g, function (key) { return date[key]; }); } function formatPrecision(value, precision) { var v = +value; if (isNumber(v)) { return v.toFixed(precision !== null && precision !== void 0 ? precision : 2); } return "".concat(value); } function formatBigNumber(value) { var v = +value; if (isNumber(v)) { if (v > 1000000000) { return "".concat(+((v / 1000000000).toFixed(3)), "B"); } if (v > 1000000) { return "".concat(+((v / 1000000).toFixed(3)), "M"); } if (v > 1000) { return "".concat(+((v / 1000).toFixed(3)), "K"); } } return "".concat(value); } function formatThousands(value, sign) { var vl = "".concat(value); if (sign.length === 0) { return vl; } if (vl.includes('.')) { var arr = vl.split('.'); return "".concat(arr[0].replace(/(\d)(?=(\d{3})+$)/g, function ($1) { return "".concat($1).concat(sign); }), ".").concat(arr[1]); } return vl.replace(/(\d)(?=(\d{3})+$)/g, function ($1) { return "".concat($1).concat(sign); }); } function formatFoldDecimal(value, threshold) { var vl = "".concat(value); var reg = new RegExp('\\.0{' + threshold + ',}[1-9][0-9]*$'); if (reg.test(vl)) { var result = vl.split('.'); var lastIndex = result.length - 1; var v = result[lastIndex]; var match = /0*/.exec(v); if (isValid(match)) { var count = match[0].length; result[lastIndex] = v.replace(/0*/, "0{".concat(count, "}")); return result.join('.'); } } return vl; } function formatTemplateString(template, params) { return template.replace(/\{(\w+)\}/g, function (_, key) { var value = params[key]; if (isValid(value)) { return value; } return "{".concat(key, "}"); }); } /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var measureCtx = null; /** * Get pixel ratio * @param canvas * @returns {number} */ function getPixelRatio(canvas) { var _a, _b; return (_b = (_a = canvas.ownerDocument.defaultView) === null || _a === void 0 ? void 0 : _a.devicePixelRatio) !== null && _b !== void 0 ? _b : 1; } function createFont(size, weight, family) { return "".concat(weight !== null && weight !== void 0 ? weight : 'normal', " ").concat(size !== null && size !== void 0 ? size : 12, "px ").concat(family !== null && family !== void 0 ? family : 'Helvetica Neue'); } /** * Measure the width of text * @param text * @returns {number} */ function calcTextWidth(text, size, weight, family) { if (!isValid(measureCtx)) { var canvas = document.createElement('canvas'); var pixelRatio = getPixelRatio(canvas); measureCtx = canvas.getContext('2d'); measureCtx.scale(pixelRatio, pixelRatio); } measureCtx.font = createFont(size, weight, family); return Math.round(measureCtx.measureText(text).width); } /****************************************************************************** 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. ***************************************************************************** */ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; 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 __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()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); } typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function createDefaultBounding(bounding) { var defaultBounding = { width: 0, height: 0, left: 0, right: 0, top: 0, bottom: 0 }; if (isValid(bounding)) { merge(defaultBounding, bounding); } return defaultBounding; } /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var DEFAULT_REQUEST_ID = -1; function requestAnimationFrame(fn) { if (isFunction(window.requestAnimationFrame)) { return window.requestAnimationFrame(fn); } return window.setTimeout(fn, 20); } function cancelAnimationFrame(id) { if (isFunction(window.cancelAnimationFrame)) { window.cancelAnimationFrame(id); } else { window.clearTimeout(id); } } /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var Animation = /** @class */ (function () { function Animation(options) { this._options = { duration: 500, iterationCount: 1 }; this._currentIterationCount = 0; this._running = false; this._time = 0; merge(this._options, options); } Animation.prototype._loop = function () { var _this = this; this._running = true; var step = function () { var _a; if (_this._running) { var diffTime = new Date().getTime() - _this._time; if (diffTime < _this._options.duration) { (_a = _this._doFrameCallback) === null || _a === void 0 ? void 0 : _a.call(_this, diffTime); requestAnimationFrame(step); } else { _this.stop(); _this._currentIterationCount++; if (_this._currentIterationCount < _this._options.iterationCount) { _this.start(); } } } }; requestAnimationFrame(step); }; Animation.prototype.doFrame = function (callback) { this._doFrameCallback = callback; return this; }; Animation.prototype.setDuration = function (duration) { this._options.duration = duration; return this; }; Animation.prototype.setIterationCount = function (iterationCount) { this._options.iterationCount = iterationCount; return this; }; Animation.prototype.start = function () { if (!this._running) { this._time = new Date().getTime(); this._loop(); } }; Animation.prototype.stop = function () { var _a; if (this._running) { (_a = this._doFrameCallback) === null || _a === void 0 ? void 0 : _a.call(this, this._options.duration); } this._running = false; }; return Animation; }()); /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var baseId = 1; var prevIdTimestamp = new Date().getTime(); function createId(prefix) { var timestamp = new Date().getTime(); if (timestamp === prevIdTimestamp) { ++baseId; } else { baseId = 1; } prevIdTimestamp = timestamp; return "".concat(prefix !== null && prefix !== void 0 ? prefix : '').concat(timestamp, "_").concat(baseId); } /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Create dom * @param tagName * @param styles * @return {*} */ function createDom(tagName, styles) { var _a; var dom = document.createElement(tagName); var s = styles !== null && styles !== void 0 ? styles : {}; // eslint-disable-next-line guard-for-in -- ignore for (var key in s) { (dom.style)[key] = (_a = s[key]) !== null && _a !== void 0 ? _a : ''; } return dom; } /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Binary search for the nearest result * @param dataList * @param valueKey * @param targetValue * @return {number} */ function binarySearchNearest(dataList, valueKey, targetValue) { var left = 0; var right = 0; for (right = dataList.length - 1; left !== right;) { var midIndex = Math.floor((right + left) / 2); var mid = right - left; var midValue = dataList[midIndex][valueKey]; if (targetValue === dataList[left][valueKey]) { return left; } if (targetValue === dataList[right][valueKey]) { return right; } if (targetValue === midValue) { return midIndex; } if (targetValue > midValue) { left = midIndex; } else { right = midIndex; } if (mid <= 2) { break; } } return left; } /** * 优化数字 * @param value * @return {number|number} */ function nice(value) { var exponent = Math.floor(log10(value)); var exp10 = index10(exponent); var f = value / exp10; // 1 <= f < 10 var nf = 0; if (f < 1.5) { nf = 1; } else if (f < 2.5) { nf = 2; } else if (f < 3.5) { nf = 3; } else if (f < 4.5) { nf = 4; } else if (f < 5.5) { nf = 5; } else if (f < 6.5) { nf = 6; } else { nf = 8; } value = nf * exp10; return +value.toFixed(Math.abs(exponent)); } /** * Round * @param value * @param precision * @return {number} */ function round(value, precision) { precision = Math.max(0, precision !== null && precision !== void 0 ? precision : 0); var pow = Math.pow(10, precision); return Math.round(value * pow) / pow; } /** * Get precision * @param value * @return {number|number} */ function getPrecision(value) { var str = value.toString(); var eIndex = str.indexOf('e'); if (eIndex > 0) { var precision = +str.slice(eIndex + 1); return precision < 0 ? -precision : 0; } var dotIndex = str.indexOf('.'); return dotIndex < 0 ? 0 : str.length - 1 - dotIndex; } function getMaxMin(dataList, maxKey, minKey) { var _a, _b; var maxMin = [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER]; var dataLength = dataList.length; var index = 0; while (index < dataLength) { var data = dataList[index]; maxMin[0] = Math.max(((_a = data[maxKey]) !== null && _a !== void 0 ? _a : Number.MIN_SAFE_INTEGER), maxMin[0]); maxMin[1] = Math.min(((_b = data[minKey]) !== null && _b !== void 0 ? _b : Number.MAX_SAFE_INTEGER), maxMin[1]); ++index; } return maxMin; } /** * log10 * @param value * @return {number} */ function log10(value) { if (value === 0) { return 0; } return Math.log10(value); } /** * index 10 * @param value * @return {number} */ function index10(value) { return Math.pow(10, value); } /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function getDefaultVisibleRange() { return { from: 0, to: 0, realFrom: 0, realTo: 0 }; } /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function generateTaskId() { var params = []; for (var _i = 0; _i < arguments.length; _i++) { params[_i] = arguments[_i]; } return params.join('_'); } var DEFAULT_TASK_LIMIT = 5; var TaskScheduler = /** @class */ (function () { function TaskScheduler(limit) { this._running = 0; this._queue = []; this._taskMap = new Map(); this._limit = limit !== null && limit !== void 0 ? limit : DEFAULT_TASK_LIMIT; } TaskScheduler.prototype.add = function (task) { return __awaiter(this, void 0, void 0, function () { var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, new Promise(function (resolve, reject) { var id = task.id, handler = task.handler; var run = function () { _this._running++; handler().then(function (result) { resolve(result); }).catch(function () { // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors, prefer-promise-reject-errors -- ignore reject('failed'); }).finally(function () { _this._running--; _this._taskMap.delete(id); _this._next(); }); }; var oldTaskWrapper = _this._taskMap.get(id); if (isValid(oldTaskWrapper)) { oldTaskWrapper.reject('canceled'); var index = _this._queue.indexOf(oldTaskWrapper.run); if (index > -1) { _this._queue.splice(index, 1); } } _this._taskMap.set(id, { run: run, reject: reject }); _this._queue.push(run); _this._next(); })]; case 1: return [2 /*return*/, _a.sent()]; } }); }); }; TaskScheduler.prototype._next = function () { while (this._running < this._limit && this._queue.length > 0) { var fn = this._queue.shift(); fn === null || fn === void 0 ? void 0 : fn(); } }; TaskScheduler.prototype.remove = function (id) { var taskWrapper = this._taskMap.get(id); if (isValid(taskWrapper)) { this._taskMap.delete(id); var index = this._queue.indexOf(taskWrapper.run); if (index > -1) { this._queue.splice(index, 1); } taskWrapper.reject('canceled'); } }; TaskScheduler.prototype.clear = function () { var e_1, _a; try { for (var _b = __values(this._taskMap), _c = _b.next(); !_c.done; _c = _b.next()) { var _d = __read(_c.value, 2), reject = _d[1].reject; reject('canceled'); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_1) throw e_1.error; } } this._taskMap.clear(); this._queue = []; }; return TaskScheduler; }()); /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var SymbolDefaultPrecisionConstants = { PRICE: 2, VOLUME: 0 }; /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var Action = /** @class */ (function () { function Action() { this._callbacks = []; } Action.prototype.subscribe = function (callback) { var index = this._callbacks.indexOf(callback); if (index < 0) { this._callbacks.push(callback); } }; Action.prototype.unsubscribe = function (callback) { if (isFunction(callback)) { var index = this._callbacks.indexOf(callback); if (index > -1) { this._callbacks.splice(index, 1); } } else { this._callbacks = []; } }; Action.prototype.execute = function (data) { this._callbacks.forEach(function (callback) { callback(data); }); }; Action.prototype.isEmpty = function () { return this._callbacks.length === 0; }; return Action; }()); /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function isTransparent(color) { return color === 'transparent' || color === 'none' || /^[rR][gG][Bb][Aa]\(([\s]*(2[0-4][0-9]|25[0-5]|[01]?[0-9][0-9]?)[\s]*,){3}[\s]*0[\s]*\)$/.test(color) || /^[hH][Ss][Ll][Aa]\(([\s]*(360|3[0-5][0-9]|[012]?[0-9][0-9]?)[\s]*,)([\s]*((100|[0-9][0-9]?)%|0)[\s]*,){2}([\s]*0[\s]*)\)$/.test(color); } function hexToRgb(hex, alpha) { var h = hex.replace(/^#/, ''); var i = parseInt(h, 16); var r = (i >> 16) & 255; var g = (i >> 8) & 255; var b = i & 255; return "rgba(".concat(r, ", ").concat(g, ", ").concat(b, ", ").concat(alpha !== null && alpha !== void 0 ? alpha : 1, ")"); } /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var Color = { RED: '#F92855', GREEN: '#2DC08E', WHITE: '#FFFFFF', GREY: '#76808F', BLUE: '#1677FF' }; function getDefaultGridStyle() { return { show: true, horizontal: { show: true, size: 1, color: '#EDEDED', style: 'dashed', dashedValue: [2, 2] }, vertical: { show: true, size: 1, color: '#EDEDED', style: 'dashed', dashedValue: [2, 2] } }; } /** * Get default candle style * @type {{area: {backgroundColor: [{offset: number, color: string}, {offset: number, color: string}], lineColor: string, lineSize: number, value: string}, bar: {noChangeColor: string, upColor: string, downColor: string}, tooltip: {rect: {offsetTop: number, fillColor: string, borderColor: string, paddingBottom: number, borderRadius: number, paddingRight: number, borderSize: number, offsetLeft: number, paddingTop: number, paddingLeft: number, offsetRight: number}, showRule: string, values: null, showType: string, text: {marginRight: number, size: number, color: string, weight: string, marginBottom: number, family: string, marginTop: number, marginLeft: number}, labels: string[]}, type: string, priceMark: {high: {textMargin: number, textSize: number, color: string, textFamily: string, show: boolean, textWeight: string}, last: {noChangeColor: string, upColor: string, line: {dashValue: number[], size: number, show: boolean, style: string}, show: boolean, text: {paddingBottom: number, size: number, color: string, paddingRight: number, show: boolean, weight: string, paddingTop: number, family: string, paddingLeft: number}, downColor: string}, low: {textMargin: number, textSize: number, color: string, textFamily: string, show: boolean, textWeight: string}, show: boolean}}} */ function getDefaultCandleStyle() { var highLow = { show: true, color: Color.GREY, textOffset: 5, textSize: 10, textFamily: 'Helvetica Neue', textWeight: 'normal' }; return { type: 'candle_solid', bar: { compareRule: 'current_open', upColor: Color.GREEN, downColor: Color.RED, noChangeColor: Color.GREY, upBorderColor: Color.GREEN, downBorderColor: Color.RED, noChangeBorderColor: Color.GREY, upWickColor: Color.GREEN, downWickColor: Color.RED, noChangeWickColor: Color.GREY }, area: { lineSize: 2, lineColor: Color.BLUE, smooth: false, value: 'close', backgroundColor: [{ offset: 0, color: hexToRgb(Color.BLUE, 0.01) }, { offset: 1, color: hexToRgb(Color.BLUE, 0.2) }], point: { show: true, color: Color.BLUE, radius: 4, rippleColor: hexToRgb(Color.BLUE, 0.3), rippleRadius: 8, animation: true, animationDuration: 1000 } }, priceMark: { show: true, high: __assign({}, highLow), low: __assign({}, highLow), last: { show: true, compareRule: 'current_open', upColor: Color.GREEN, downColor: Color.RED, noChangeColor: Color.GREY, line: { show: true, style: 'dashed', dashedValue: [4, 4], size: 1 }, text: { show: true, style: 'fill', size: 12, paddingLeft: 4, paddingTop: 4, paddingRight: 4, paddingBottom: 4, borderColor: 'transparent', borderStyle: 'solid', borderSize: 0, borderDashedValue: [2, 2], color: Color.WHITE, family: 'Helvetica Neue', weight: 'normal', borderRadius: 2 }, extendTexts: [] } }, tooltip: { offsetLeft: 4, offsetTop: 6, offsetRight: 4, offsetBottom: 6, showRule: 'always', showType: 'standard', rect: { position: 'fixed', paddingLeft: 4, paddingRight: 4, paddingTop: 4, paddingBottom: 4, offsetLeft: 4, offsetTop: 4, offsetRight: 4, offsetBottom: 4, borderRadius: 4, borderSize: 1, borderColor: '#F2F3F5', color: '#FEFEFE' }, title: { show: true, size: 14, family: 'Helvetica Neue', weight: 'normal', color: Color.GREY, marginLeft: 8, marginTop: 4, marginRight: 8, marginBottom: 4, template: '{ticker} · {period}' }, legend: { size: 12, family: 'Helvetica Neue', weight: 'normal', color: Color.GREY, marginLeft: 8, marginTop: 4, marginRight: 8, marginBottom: 4, defaultValue: 'n/a', template: [ { title: 'time', value: '{time}' }, { title: 'open', value: '{open}' }, { title: 'high', value: '{high}' }, { title: 'low', value: '{low}' }, { title: 'close', value: '{close}' }, { title: 'volume', value: '{volume}' } ] }, features: [] } }; } /** * Get default indicator style */ function getDefaultIndicatorStyle() { var alphaGreen = hexToRgb(Color.GREEN, 0.7); var alphaRed = hexToRgb(Color.RED, 0.7); return { ohlc: { compareRule: 'current_open', upColor: alphaGreen, downColor: alphaRed, noChangeColor: Color.GREY }, bars: [{ style: 'fill', borderStyle: 'solid', borderSize: 1, borderDashedValue: [2, 2], upColor: alphaGreen, downColor: alphaRed, noChangeColor: Color.GREY }], lines: ['#FF9600', '#935EBD', Color.BLUE, '#E11D74', '#01C5C4'].map(function (color) { return ({ style: 'solid', smooth: false, size: 1, dashedValue: [2, 2], color: color }); }), circles: [{ style: 'fill', borderStyle: 'solid', borderSize: 1, borderDashedValue: [2, 2], upColor: alphaGreen, downColor: alphaRed, noChangeColor: Color.GREY }], lastValueMark: { show: false, text: { show: false, style: 'fill', color: Color.WHITE, size: 12, family: 'Helvetica Neue', weight: 'normal', borderStyle: 'solid', borderColor: 'transparent', borderSize: 0, borderDashedValue: [2, 2], paddingLeft: 4, paddingTop: 4, paddingRight: 4, paddingBottom: 4, borderRadius: 2 } }, tooltip: { offsetLeft: 4, offsetTop: 6, offsetRight: 4, offsetBottom: 6, showRule: 'always', showType: 'standard', title: { show: true, showName: true, showParams: true, size: 12, family: 'Helvetica Neue', weight: 'normal', color: Color.GREY, marginLeft: 8, marginTop: 4, marginRight: 8, marginBottom: 4 }, legend: { size: 12, family: 'Helvetica Neue', weight: 'normal', color: Color.GREY, marginLeft: 8, marginTop: 4, marginRight: 8, marginBottom: 4, defaultValue: 'n/a' }, features: [] } }; } function getDefaultAxisStyle() { return { show: true, size: 'auto', axisLine: { show: true, color: '#DDDDDD', size: 1 }, tickText: { show: true, color: Color.GREY, size: 12, family: 'Helvetica Neue', weight: 'normal', marginStart: 4, marginEnd: 6 }, tickLine: { show: true, size: 1, length: 3, color: '#DDDDDD' } }; } function getDefaultCrosshairStyle() { return { show: true, horizontal: { show: true, line: { show: true, style: 'dashed', dashedValue: [4, 2], size: 1, color: Color.GREY }, text: { show: true, style: 'fill', color: Color.WHITE, size: 12, family: 'Helvetica Neue', weight: 'normal', borderStyle: 'solid', borderDashedValue: [2, 2], borderSize: 1, borderColor: Color.GREY, borderRadius: 2, paddingLeft: 4, paddingRight: 4, paddingTop: 4, paddingBottom: 4, backgroundColor: Color.GREY }, features: [] }, vertical: { show: true, line: { show: true, style: 'dashed', dashedValue: [4, 2], size: 1, color: Color.GREY }, text: { show: true, style: 'fill', color: Color.WHITE, size: 12, family: 'Helvetica Neue', weight: 'normal', borderStyle: 'solid', borderDashedValue: [2, 2], borderSize: 1, borderColor: Color.GREY, borderRadius: 2, paddingLeft: 4, paddingRight: 4, paddingTop: 4, paddingBottom: 4, backgroundColor: Color.GREY } } }; } function getDefaultOverlayStyle() { var pointBorderColor = hexToRgb(Color.BLUE, 0.35); var alphaBg = hexToRgb(Color.BLUE, 0.25); function text() { return { style: 'fill', color: Color.WHITE, size: 12, family: 'Helvetica Neue', weight: 'normal', borderStyle: 'solid', borderDashedValue: [2, 2], borderSize: 1, borderRadius: 2, borderColor: Color.BLUE, paddingLeft: 4, paddingRight: 4, paddingTop: 4, paddingBottom: 4, backgroundColor: Color.BLUE }; } return { point: { color: Color.BLUE, borderColor: pointBorderColor, borderSize: 1, radius: 5, activeColor: Color.BLUE, activeBorderColor: pointBorderColor, activeBorderSize: 3, activeRadius: 5 }, line: { style: 'solid', smooth: false, color: Color.BLUE, size: 1, dashedValue: [2, 2] }, rect: { style: 'fill', color: alphaBg, borderColor: Color.BLUE, borderSize: 1, borderRadius: 0, borderStyle: 'solid', borderDashedValue: [2, 2] }, polygon: { style: 'fill', color: Color.BLUE, borderColor: Color.BLUE, borderSize: 1, borderStyle: 'solid', borderDashedValue: [2, 2] }, circle: { style: 'fill', color: alphaBg, borderColor: Color.BLUE, borderSize: 1, bo