!function(global1, factory) { 'object' == typeof exports && 'undefined' != typeof module ? factory(exports) : 'function' == typeof define && define.amd ? define([ 'exports' ], factory) : factory((global1 = 'undefined' != typeof globalThis ? globalThis : global1 || self).echarts = {}); }(this, function(exports1) { 'use strict'; var ua, env, browser, firefox, ie, edge, weChat, style, mouseHandlerNames, pointerEventNameMap, pointerHandlerNames, target, classAttr, target1, subTypeDefaulters, loadingFx, theme, _super, mainType, creator, _ctx, _cachedFont, requestAnimationFrame, reCreateSeriesIndices, assertSeriesInitialized, initBase, _a, _b, _c, providerMethods, mountMethods, seriesType, nodeParsers, prepare, prepareView, updateDirectly, updateMethods, doConvertPixel, updateStreamModes, doDispatchAction, flushPendingActions, triggerUpdatedEvent, bindRenderedEvent, bindMouseEvent, clearColorPalette, render, renderComponents, renderSeries, performPostUpdateFuncs, createExtensionAPI, enableConnect, setTransitionOpt, markStatusToUpdate, applyChangedStates, defaultDimValueGetters, prepareInvertedIndex, getIndicesCtor, prepareStorage, getRawIndexWithoutIndices, getRawIndexWithIndices, getId, getIdNameFromStore, makeIdFromName, normalizeDimensions, validateDimensions, cloneListForMapAndSample, getInitialExtent, setItemDataAndSeriesIndex, transferProperties, checkNonStyleTansitionRefer, checkTransformPropRefer, extendStatics = function(d, b) { return (extendStatics = Object.setPrototypeOf || ({ __proto__: [] }) instanceof Array && function(d, b) { d.__proto__ = b; } || function(d, b) { for(var p in b)Object.prototype.hasOwnProperty.call(b, p) && (d[p] = b[p]); })(d, b); }; function __extends(d, b) { function __() { this.constructor = d; } extendStatics(d, b), d.prototype = null === b ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { return (__assign = Object.assign || function(t) { for(var s, i = 1, n = arguments.length; i < n; i++)for(var p in s = arguments[i])Object.prototype.hasOwnProperty.call(s, p) && (t[p] = s[p]); return t; }).apply(this, arguments); }; function __spreadArrays() { for(var s = 0, i = 0, il = arguments.length; i < il; i++)s += arguments[i].length; for(var r = Array(s), k = 0, i = 0; i < il; i++)for(var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)r[k] = a[j]; return r; } var Browser = function() { this.firefox = !1, this.ie = !1, this.edge = !1, this.newEdge = !1, this.weChat = !1; }, env1 = new function() { this.browser = new Browser(), this.node = !1, this.wxa = !1, this.worker = !1, this.canvasSupported = !1, this.svgSupported = !1, this.touchEventsSupported = !1, this.pointerEventsSupported = !1, this.domSupported = !1, this.transformSupported = !1, this.transform3dSupported = !1; }(); 'object' == typeof wx && 'function' == typeof wx.getSystemInfoSync ? (env1.wxa = !0, env1.canvasSupported = !0, env1.touchEventsSupported = !0) : 'undefined' == typeof document && 'undefined' != typeof self ? (env1.worker = !0, env1.canvasSupported = !0) : 'undefined' == typeof navigator ? (env1.node = !0, env1.canvasSupported = !0, env1.svgSupported = !0) : (ua = navigator.userAgent, browser = (env = env1).browser, firefox = ua.match(/Firefox\/([\d.]+)/), ie = ua.match(/MSIE\s([\d.]+)/) || ua.match(/Trident\/.+?rv:(([\d.]+))/), edge = ua.match(/Edge?\/([\d.]+)/), weChat = /micromessenger/i.test(ua), firefox && (browser.firefox = !0, browser.version = firefox[1]), ie && (browser.ie = !0, browser.version = ie[1]), edge && (browser.edge = !0, browser.version = edge[1], browser.newEdge = +edge[1].split('.')[0] > 18), weChat && (browser.weChat = !0), env.canvasSupported = !!document.createElement('canvas').getContext, env.svgSupported = 'undefined' != typeof SVGRect, env.touchEventsSupported = 'ontouchstart' in window && !browser.ie && !browser.edge, env.pointerEventsSupported = 'onpointerdown' in window && (browser.edge || browser.ie && +browser.version >= 11), env.domSupported = 'undefined' != typeof document, style = document.documentElement.style, env.transform3dSupported = (browser.ie && 'transition' in style || browser.edge || 'WebKitCSSMatrix' in window && 'm11' in new WebKitCSSMatrix() || 'MozPerspective' in style) && !('OTransition' in style), env.transformSupported = env.transform3dSupported || browser.ie && +browser.version >= 9); var BUILTIN_OBJECT = { '[object Function]': !0, '[object RegExp]': !0, '[object Date]': !0, '[object Error]': !0, '[object CanvasGradient]': !0, '[object CanvasPattern]': !0, '[object Image]': !0, '[object Canvas]': !0 }, TYPED_ARRAY = { '[object Int8Array]': !0, '[object Uint8Array]': !0, '[object Uint8ClampedArray]': !0, '[object Int16Array]': !0, '[object Uint16Array]': !0, '[object Int32Array]': !0, '[object Uint32Array]': !0, '[object Float32Array]': !0, '[object Float64Array]': !0 }, objToString = Object.prototype.toString, arrayProto = Array.prototype, nativeForEach = arrayProto.forEach, nativeFilter = arrayProto.filter, nativeSlice = arrayProto.slice, nativeMap = arrayProto.map, ctorFunction = (function() {}).constructor, protoFunction = ctorFunction ? ctorFunction.prototype : null, methods = {}, idStart = 0x0907; function guid() { return idStart++; } function logError() { for(var args = [], _i = 0; _i < arguments.length; _i++)args[_i] = arguments[_i]; 'undefined' != typeof console && console.error.apply(console, args); } function clone(source) { if (null == source || 'object' != typeof source) return source; var result = source, typeStr = objToString.call(source); if ('[object Array]' === typeStr) { if (!source[primitiveKey]) { result = []; for(var i = 0, len = source.length; i < len; i++)result[i] = clone(source[i]); } } else if (TYPED_ARRAY[typeStr]) { if (!source[primitiveKey]) { var Ctor = source.constructor; if (Ctor.from) result = Ctor.from(source); else { result = new Ctor(source.length); for(var i = 0, len = source.length; i < len; i++)result[i] = clone(source[i]); } } } else if (!BUILTIN_OBJECT[typeStr] && !source[primitiveKey] && !isDom(source)) for(var key in result = {}, source)source.hasOwnProperty(key) && (result[key] = clone(source[key])); return result; } function merge(target, source, overwrite) { if (!isObject(source) || !isObject(target)) return overwrite ? clone(source) : target; for(var key in source)if (source.hasOwnProperty(key)) { var targetProp = target[key], sourceProp = source[key]; !(isObject(sourceProp) && isObject(targetProp)) || isArray(sourceProp) || isArray(targetProp) || isDom(sourceProp) || isDom(targetProp) || isBuiltInObject(sourceProp) || isBuiltInObject(targetProp) || sourceProp[primitiveKey] || targetProp[primitiveKey] ? !overwrite && key in target || (target[key] = clone(source[key])) : merge(targetProp, sourceProp, overwrite); } return target; } function mergeAll(targetAndSources, overwrite) { for(var result = targetAndSources[0], i = 1, len = targetAndSources.length; i < len; i++)result = merge(result, targetAndSources[i], overwrite); return result; } function extend(target, source) { if (Object.assign) Object.assign(target, source); else for(var key in source)source.hasOwnProperty(key) && (target[key] = source[key]); return target; } function defaults(target, source, overlay) { for(var keysArr = keys(source), i = 0; i < keysArr.length; i++){ var key = keysArr[i]; (overlay ? null != source[key] : null == target[key]) && (target[key] = source[key]); } return target; } var createCanvas = function() { return methods.createCanvas(); }; function indexOf(array, value) { if (array) { if (array.indexOf) return array.indexOf(value); for(var i = 0, len = array.length; i < len; i++)if (array[i] === value) return i; } return -1; } function inherits(clazz, baseClazz) { var clazzPrototype = clazz.prototype; function F() {} for(var prop in F.prototype = baseClazz.prototype, clazz.prototype = new F(), clazzPrototype)clazzPrototype.hasOwnProperty(prop) && (clazz.prototype[prop] = clazzPrototype[prop]); clazz.prototype.constructor = clazz, clazz.superClass = baseClazz; } function mixin(target, source, override) { if (target = 'prototype' in target ? target.prototype : target, source = 'prototype' in source ? source.prototype : source, Object.getOwnPropertyNames) for(var keyList = Object.getOwnPropertyNames(source), i = 0; i < keyList.length; i++){ var key = keyList[i]; 'constructor' !== key && (override ? null != source[key] : null == target[key]) && (target[key] = source[key]); } else defaults(target, source, override); } function isArrayLike(data) { return !!data && 'string' != typeof data && 'number' == typeof data.length; } function each(arr, cb, context) { if (arr && cb) { if (arr.forEach && arr.forEach === nativeForEach) arr.forEach(cb, context); else if (arr.length === +arr.length) for(var i = 0, len = arr.length; i < len; i++)cb.call(context, arr[i], i, arr); else for(var key in arr)arr.hasOwnProperty(key) && cb.call(context, arr[key], key, arr); } } function map(arr, cb, context) { if (!arr) return []; if (!cb) return slice(arr); if (arr.map && arr.map === nativeMap) return arr.map(cb, context); for(var result = [], i = 0, len = arr.length; i < len; i++)result.push(cb.call(context, arr[i], i, arr)); return result; } function reduce(arr, cb, memo, context) { if (arr && cb) { for(var i = 0, len = arr.length; i < len; i++)memo = cb.call(context, memo, arr[i], i, arr); return memo; } } function filter(arr, cb, context) { if (!arr) return []; if (!cb) return slice(arr); if (arr.filter && arr.filter === nativeFilter) return arr.filter(cb, context); for(var result = [], i = 0, len = arr.length; i < len; i++)cb.call(context, arr[i], i, arr) && result.push(arr[i]); return result; } function find(arr, cb, context) { if (arr && cb) { for(var i = 0, len = arr.length; i < len; i++)if (cb.call(context, arr[i], i, arr)) return arr[i]; } } function keys(obj) { if (!obj) return []; if (Object.keys) return Object.keys(obj); var keyList = []; for(var key in obj)obj.hasOwnProperty(key) && keyList.push(key); return keyList; } methods.createCanvas = function() { return document.createElement('canvas'); }; var bind = protoFunction && isFunction(protoFunction.bind) ? protoFunction.call.bind(protoFunction.bind) : function(func, context) { for(var args = [], _i = 2; _i < arguments.length; _i++)args[_i - 2] = arguments[_i]; return function() { return func.apply(context, args.concat(nativeSlice.call(arguments))); }; }; function curry(func) { for(var args = [], _i = 1; _i < arguments.length; _i++)args[_i - 1] = arguments[_i]; return function() { return func.apply(this, args.concat(nativeSlice.call(arguments))); }; } function isArray(value) { return Array.isArray ? Array.isArray(value) : '[object Array]' === objToString.call(value); } function isFunction(value) { return 'function' == typeof value; } function isString(value) { return 'string' == typeof value; } function isStringSafe(value) { return '[object String]' === objToString.call(value); } function isNumber(value) { return 'number' == typeof value; } function isObject(value) { var type = typeof value; return 'function' === type || !!value && 'object' === type; } function isBuiltInObject(value) { return !!BUILTIN_OBJECT[objToString.call(value)]; } function isTypedArray(value) { return !!TYPED_ARRAY[objToString.call(value)]; } function isDom(value) { return 'object' == typeof value && 'number' == typeof value.nodeType && 'object' == typeof value.ownerDocument; } function isGradientObject(value) { return null != value.colorStops; } function isPatternObject(value) { return null != value.image; } function isRegExp(value) { return '[object RegExp]' === objToString.call(value); } function retrieve() { for(var args = [], _i = 0; _i < arguments.length; _i++)args[_i] = arguments[_i]; for(var i = 0, len = args.length; i < len; i++)if (null != args[i]) return args[i]; } function retrieve2(value0, value1) { return null != value0 ? value0 : value1; } function retrieve3(value0, value1, value2) { return null != value0 ? value0 : null != value1 ? value1 : value2; } function slice(arr) { for(var args = [], _i = 1; _i < arguments.length; _i++)args[_i - 1] = arguments[_i]; return nativeSlice.apply(arr, args); } function normalizeCssArray(val) { if ('number' == typeof val) return [ val, val, val, val ]; var len = val.length; return 2 === len ? [ val[0], val[1], val[0], val[1] ] : 3 === len ? [ val[0], val[1], val[2], val[1] ] : val; } function assert(condition, message) { if (!condition) throw Error(message); } function trim(str) { return null == str ? null : 'function' == typeof str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); } var primitiveKey = '__ec_primitive__'; function setAsPrimitive(obj) { obj[primitiveKey] = !0; } var HashMap = function() { function HashMap(obj) { this.data = {}; var isArr = isArray(obj); this.data = {}; var thisMap = this; function visit(value, key) { isArr ? thisMap.set(value, key) : thisMap.set(key, value); } obj instanceof HashMap ? obj.each(visit) : obj && each(obj, visit); } return HashMap.prototype.get = function(key) { return this.data.hasOwnProperty(key) ? this.data[key] : null; }, HashMap.prototype.set = function(key, value) { return this.data[key] = value; }, HashMap.prototype.each = function(cb, context) { for(var key in this.data)this.data.hasOwnProperty(key) && cb.call(context, this.data[key], key); }, HashMap.prototype.keys = function() { return keys(this.data); }, HashMap.prototype.removeKey = function(key) { delete this.data[key]; }, HashMap; }(); function createHashMap(obj) { return new HashMap(obj); } function concatArray(a, b) { for(var newArray = new a.constructor(a.length + b.length), i = 0; i < a.length; i++)newArray[i] = a[i]; for(var offset = a.length, i = 0; i < b.length; i++)newArray[i + offset] = b[i]; return newArray; } function createObject(proto, properties) { var obj; if (Object.create) obj = Object.create(proto); else { var StyleCtor = function() {}; StyleCtor.prototype = proto, obj = new StyleCtor(); } return properties && extend(obj, properties), obj; } function hasOwn(own, prop) { return own.hasOwnProperty(prop); } function noop() {} var util = Object.freeze({ __proto__: null, $override: function(name, fn) { methods[name] = fn; }, guid: guid, logError: logError, clone: clone, merge: merge, mergeAll: mergeAll, extend: extend, defaults: defaults, createCanvas: createCanvas, indexOf: indexOf, inherits: inherits, mixin: mixin, isArrayLike: isArrayLike, each: each, map: map, reduce: reduce, filter: filter, find: find, keys: keys, bind: bind, curry: curry, isArray: isArray, isFunction: isFunction, isString: isString, isStringSafe: isStringSafe, isNumber: isNumber, isObject: isObject, isBuiltInObject: isBuiltInObject, isTypedArray: isTypedArray, isDom: isDom, isGradientObject: isGradientObject, isPatternObject: isPatternObject, isRegExp: isRegExp, eqNaN: function(value) { return value != value; }, retrieve: retrieve, retrieve2: retrieve2, retrieve3: retrieve3, slice: slice, normalizeCssArray: normalizeCssArray, assert: assert, trim: trim, setAsPrimitive: setAsPrimitive, isPrimitive: function(obj) { return obj[primitiveKey]; }, HashMap: HashMap, createHashMap: createHashMap, concatArray: concatArray, createObject: createObject, hasOwn: hasOwn, noop: noop }); function create(x, y) { return null == x && (x = 0), null == y && (y = 0), [ x, y ]; } function copy(out, v) { return out[0] = v[0], out[1] = v[1], out; } function clone$1(v) { return [ v[0], v[1] ]; } function set(out, a, b) { return out[0] = a, out[1] = b, out; } function add(out, v1, v2) { return out[0] = v1[0] + v2[0], out[1] = v1[1] + v2[1], out; } function scaleAndAdd(out, v1, v2, a) { return out[0] = v1[0] + v2[0] * a, out[1] = v1[1] + v2[1] * a, out; } function sub(out, v1, v2) { return out[0] = v1[0] - v2[0], out[1] = v1[1] - v2[1], out; } function len(v) { return Math.sqrt(lenSquare(v)); } function lenSquare(v) { return v[0] * v[0] + v[1] * v[1]; } function scale(out, v, s) { return out[0] = v[0] * s, out[1] = v[1] * s, out; } function normalize(out, v) { var d = len(v); return 0 === d ? (out[0] = 0, out[1] = 0) : (out[0] = v[0] / d, out[1] = v[1] / d), out; } function distance(v1, v2) { return Math.sqrt((v1[0] - v2[0]) * (v1[0] - v2[0]) + (v1[1] - v2[1]) * (v1[1] - v2[1])); } function distanceSquare(v1, v2) { return (v1[0] - v2[0]) * (v1[0] - v2[0]) + (v1[1] - v2[1]) * (v1[1] - v2[1]); } function lerp(out, v1, v2, t) { return out[0] = v1[0] + t * (v2[0] - v1[0]), out[1] = v1[1] + t * (v2[1] - v1[1]), out; } function applyTransform(out, v, m) { var x = v[0], y = v[1]; return out[0] = m[0] * x + m[2] * y + m[4], out[1] = m[1] * x + m[3] * y + m[5], out; } function min(out, v1, v2) { return out[0] = Math.min(v1[0], v2[0]), out[1] = Math.min(v1[1], v2[1]), out; } function max(out, v1, v2) { return out[0] = Math.max(v1[0], v2[0]), out[1] = Math.max(v1[1], v2[1]), out; } var vector = Object.freeze({ __proto__: null, create: create, copy: copy, clone: clone$1, set: set, add: add, scaleAndAdd: scaleAndAdd, sub: sub, len: len, length: len, lenSquare: lenSquare, lengthSquare: lenSquare, mul: function(out, v1, v2) { return out[0] = v1[0] * v2[0], out[1] = v1[1] * v2[1], out; }, div: function(out, v1, v2) { return out[0] = v1[0] / v2[0], out[1] = v1[1] / v2[1], out; }, dot: function(v1, v2) { return v1[0] * v2[0] + v1[1] * v2[1]; }, scale: scale, normalize: normalize, distance: distance, dist: distance, distanceSquare: distanceSquare, distSquare: distanceSquare, negate: function(out, v) { return out[0] = -v[0], out[1] = -v[1], out; }, lerp: lerp, applyTransform: applyTransform, min: min, max: max }), Param = function(target, e) { this.target = target, this.topTarget = e && e.topTarget; }, Draggable = function() { function Draggable(handler) { this.handler = handler, handler.on('mousedown', this._dragStart, this), handler.on('mousemove', this._drag, this), handler.on('mouseup', this._dragEnd, this); } return Draggable.prototype._dragStart = function(e) { for(var draggingTarget = e.target; draggingTarget && !draggingTarget.draggable;)draggingTarget = draggingTarget.parent; draggingTarget && (this._draggingTarget = draggingTarget, draggingTarget.dragging = !0, this._x = e.offsetX, this._y = e.offsetY, this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragstart', e.event)); }, Draggable.prototype._drag = function(e) { var draggingTarget = this._draggingTarget; if (draggingTarget) { var x = e.offsetX, y = e.offsetY, dx = x - this._x, dy = y - this._y; this._x = x, this._y = y, draggingTarget.drift(dx, dy, e), this.handler.dispatchToElement(new Param(draggingTarget, e), 'drag', e.event); var dropTarget = this.handler.findHover(x, y, draggingTarget).target, lastDropTarget = this._dropTarget; this._dropTarget = dropTarget, draggingTarget !== dropTarget && (lastDropTarget && dropTarget !== lastDropTarget && this.handler.dispatchToElement(new Param(lastDropTarget, e), 'dragleave', e.event), dropTarget && dropTarget !== lastDropTarget && this.handler.dispatchToElement(new Param(dropTarget, e), 'dragenter', e.event)); } }, Draggable.prototype._dragEnd = function(e) { var draggingTarget = this._draggingTarget; draggingTarget && (draggingTarget.dragging = !1), this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragend', e.event), this._dropTarget && this.handler.dispatchToElement(new Param(this._dropTarget, e), 'drop', e.event), this._draggingTarget = null, this._dropTarget = null; }, Draggable; }(), Eventful = function() { function Eventful(eventProcessors) { eventProcessors && (this._$eventProcessor = eventProcessors); } return Eventful.prototype.on = function(event, query, handler, context) { this._$handlers || (this._$handlers = {}); var _h = this._$handlers; if ('function' == typeof query && (context = handler, handler = query, query = null), !handler || !event) return this; var eventProcessor = this._$eventProcessor; null != query && eventProcessor && eventProcessor.normalizeQuery && (query = eventProcessor.normalizeQuery(query)), _h[event] || (_h[event] = []); for(var i = 0; i < _h[event].length; i++)if (_h[event][i].h === handler) return this; var wrap = { h: handler, query: query, ctx: context || this, callAtLast: handler.zrEventfulCallAtLast }, lastIndex = _h[event].length - 1, lastWrap = _h[event][lastIndex]; return lastWrap && lastWrap.callAtLast ? _h[event].splice(lastIndex, 0, wrap) : _h[event].push(wrap), this; }, Eventful.prototype.isSilent = function(eventName) { var _h = this._$handlers; return !_h || !_h[eventName] || !_h[eventName].length; }, Eventful.prototype.off = function(eventType, handler) { var _h = this._$handlers; if (!_h) return this; if (!eventType) return this._$handlers = {}, this; if (handler) { if (_h[eventType]) { for(var newList = [], i = 0, l = _h[eventType].length; i < l; i++)_h[eventType][i].h !== handler && newList.push(_h[eventType][i]); _h[eventType] = newList; } _h[eventType] && 0 === _h[eventType].length && delete _h[eventType]; } else delete _h[eventType]; return this; }, Eventful.prototype.trigger = function(eventType) { for(var args = [], _i = 1; _i < arguments.length; _i++)args[_i - 1] = arguments[_i]; if (!this._$handlers) return this; var _h = this._$handlers[eventType], eventProcessor = this._$eventProcessor; if (_h) for(var argLen = args.length, len = _h.length, i = 0; i < len; i++){ var hItem = _h[i]; if (!eventProcessor || !eventProcessor.filter || null == hItem.query || eventProcessor.filter(eventType, hItem.query)) switch(argLen){ case 0: hItem.h.call(hItem.ctx); break; case 1: hItem.h.call(hItem.ctx, args[0]); break; case 2: hItem.h.call(hItem.ctx, args[0], args[1]); break; default: hItem.h.apply(hItem.ctx, args); } } return eventProcessor && eventProcessor.afterTrigger && eventProcessor.afterTrigger(eventType), this; }, Eventful.prototype.triggerWithContext = function(type) { if (!this._$handlers) return this; var _h = this._$handlers[type], eventProcessor = this._$eventProcessor; if (_h) for(var args = arguments, argLen = args.length, ctx = args[argLen - 1], len = _h.length, i = 0; i < len; i++){ var hItem = _h[i]; if (!eventProcessor || !eventProcessor.filter || null == hItem.query || eventProcessor.filter(type, hItem.query)) switch(argLen){ case 0: hItem.h.call(ctx); break; case 1: hItem.h.call(ctx, args[0]); break; case 2: hItem.h.call(ctx, args[0], args[1]); break; default: hItem.h.apply(ctx, args.slice(1, argLen - 1)); } } return eventProcessor && eventProcessor.afterTrigger && eventProcessor.afterTrigger(type), this; }, Eventful; }(), LN2 = Math.log(2); function determinant(rows, rank, rowStart, rowMask, colMask, detCache) { var cacheKey = rowMask + '-' + colMask, fullRank = rows.length; if (detCache.hasOwnProperty(cacheKey)) return detCache[cacheKey]; if (1 === rank) return rows[rowStart][Math.round(Math.log((1 << fullRank) - 1 & ~colMask) / LN2)]; for(var subRowMask = rowMask | 1 << rowStart, subRowStart = rowStart + 1; rowMask & 1 << subRowStart;)subRowStart++; for(var sum = 0, j = 0, colLocalIdx = 0; j < fullRank; j++){ var colTag = 1 << j; !(colTag & colMask) && (sum += (colLocalIdx % 2 ? -1 : 1) * rows[rowStart][j] * determinant(rows, rank - 1, subRowStart, subRowMask, colMask | colTag, detCache), colLocalIdx++); } return detCache[cacheKey] = sum, sum; } function buildTransformer(src, dest) { var mA = [ [ src[0], src[1], 1, 0, 0, 0, -dest[0] * src[0], -dest[0] * src[1] ], [ 0, 0, 0, src[0], src[1], 1, -dest[1] * src[0], -dest[1] * src[1] ], [ src[2], src[3], 1, 0, 0, 0, -dest[2] * src[2], -dest[2] * src[3] ], [ 0, 0, 0, src[2], src[3], 1, -dest[3] * src[2], -dest[3] * src[3] ], [ src[4], src[5], 1, 0, 0, 0, -dest[4] * src[4], -dest[4] * src[5] ], [ 0, 0, 0, src[4], src[5], 1, -dest[5] * src[4], -dest[5] * src[5] ], [ src[6], src[7], 1, 0, 0, 0, -dest[6] * src[6], -dest[6] * src[7] ], [ 0, 0, 0, src[6], src[7], 1, -dest[7] * src[6], -dest[7] * src[7] ] ], detCache = {}, det = determinant(mA, 8, 0, 0, 0, detCache); if (0 !== det) { for(var vh = [], i = 0; i < 8; i++)for(var j = 0; j < 8; j++)null == vh[j] && (vh[j] = 0), vh[j] += ((i + j) % 2 ? -1 : 1) * determinant(mA, 7, 0 === i ? 1 : 0, 1 << i, 1 << j, detCache) / det * dest[i]; return function(out, srcPointX, srcPointY) { var pk = srcPointX * vh[6] + srcPointY * vh[7] + 1; out[0] = (srcPointX * vh[0] + srcPointY * vh[1] + vh[2]) / pk, out[1] = (srcPointX * vh[3] + srcPointY * vh[4] + vh[5]) / pk; }; } } var EVENT_SAVED_PROP = '___zrEVENTSAVED', _calcOut = []; function transformCoordWithViewport(out, el, inX, inY, inverse) { if (el.getBoundingClientRect && env1.domSupported && !isCanvasEl(el)) { var saved = el[EVENT_SAVED_PROP] || (el[EVENT_SAVED_PROP] = {}), transformer = function(markers, saved, inverse) { for(var transformerName = inverse ? 'invTrans' : 'trans', transformer = saved[transformerName], oldSrcCoords = saved.srcCoords, srcCoords = [], destCoords = [], oldCoordTheSame = !0, i = 0; i < 4; i++){ var rect = markers[i].getBoundingClientRect(), ii = 2 * i, x = rect.left, y = rect.top; srcCoords.push(x, y), oldCoordTheSame = oldCoordTheSame && oldSrcCoords && x === oldSrcCoords[ii] && y === oldSrcCoords[ii + 1], destCoords.push(markers[i].offsetLeft, markers[i].offsetTop); } return oldCoordTheSame && transformer ? transformer : (saved.srcCoords = srcCoords, saved[transformerName] = inverse ? buildTransformer(destCoords, srcCoords) : buildTransformer(srcCoords, destCoords)); }(function(el, saved) { var markers = saved.markers; if (markers) return markers; markers = saved.markers = []; for(var propLR = [ 'left', 'right' ], propTB = [ 'top', 'bottom' ], i = 0; i < 4; i++){ var marker = document.createElement('div'), stl = marker.style, idxLR = i % 2, idxTB = (i >> 1) % 2; stl.cssText = [ 'position: absolute', 'visibility: hidden', 'padding: 0', 'margin: 0', 'border-width: 0', 'user-select: none', 'width:0', 'height:0', propLR[idxLR] + ':0', propTB[idxTB] + ':0', propLR[1 - idxLR] + ':auto', propTB[1 - idxTB] + ':auto', '' ].join('!important;'), el.appendChild(marker), markers.push(marker); } return markers; }(el, saved), saved, inverse); if (transformer) return transformer(out, inX, inY), !0; } return !1; } function isCanvasEl(el) { return 'CANVAS' === el.nodeName.toUpperCase(); } var isDomLevel2 = 'undefined' != typeof window && !!window.addEventListener, MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, _calcOut$1 = []; function clientToLocal(el, e, out, calculate) { return out = out || {}, calculate || !env1.canvasSupported ? calculateZrXY(el, e, out) : env1.browser.firefox && null != e.layerX && e.layerX !== e.offsetX ? (out.zrX = e.layerX, out.zrY = e.layerY) : null != e.offsetX ? (out.zrX = e.offsetX, out.zrY = e.offsetY) : calculateZrXY(el, e, out), out; } function calculateZrXY(el, e, out) { if (env1.domSupported && el.getBoundingClientRect) { var ex = e.clientX, ey = e.clientY; if (isCanvasEl(el)) { var box = el.getBoundingClientRect(); out.zrX = ex - box.left, out.zrY = ey - box.top; return; } if (transformCoordWithViewport(_calcOut$1, el, ex, ey)) { out.zrX = _calcOut$1[0], out.zrY = _calcOut$1[1]; return; } } out.zrX = out.zrY = 0; } function getNativeEvent(e) { return e || window.event; } function normalizeEvent(el, e, calculate) { if (null != (e = getNativeEvent(e)).zrX) return e; var eventType = e.type; if (eventType && eventType.indexOf('touch') >= 0) { var touch = 'touchend' !== eventType ? e.targetTouches[0] : e.changedTouches[0]; touch && clientToLocal(el, touch, e, calculate); } else { clientToLocal(el, e, e, calculate); var wheelDelta = function(e) { var rawWheelDelta = e.wheelDelta; if (rawWheelDelta) return rawWheelDelta; var deltaX = e.deltaX, deltaY = e.deltaY; return null == deltaX || null == deltaY ? rawWheelDelta : 3 * (0 !== deltaY ? Math.abs(deltaY) : Math.abs(deltaX)) * (deltaY > 0 ? -1 : deltaY < 0 ? 1 : deltaX > 0 ? -1 : 1); }(e); e.zrDelta = wheelDelta ? wheelDelta / 120 : -(e.detail || 0) / 3; } var button = e.button; return null == e.which && void 0 !== button && MOUSE_EVENT_REG.test(e.type) && (e.which = 1 & button ? 1 : 2 & button ? 3 : 4 & button ? 2 : 0), e; } function addEventListener(el, name, handler, opt) { isDomLevel2 ? el.addEventListener(name, handler, opt) : el.attachEvent('on' + name, handler); } var stop = isDomLevel2 ? function(e) { e.preventDefault(), e.stopPropagation(), e.cancelBubble = !0; } : function(e) { e.returnValue = !1, e.cancelBubble = !0; }; function isMiddleOrRightButtonOnMouseUpDown(e) { return 2 === e.which || 3 === e.which; } var GestureMgr = function() { function GestureMgr() { this._track = []; } return GestureMgr.prototype.recognize = function(event, target, root) { return this._doTrack(event, target, root), this._recognize(event); }, GestureMgr.prototype.clear = function() { return this._track.length = 0, this; }, GestureMgr.prototype._doTrack = function(event, target, root) { var touches = event.touches; if (touches) { for(var trackItem = { points: [], touches: [], target: target, event: event }, i = 0, len = touches.length; i < len; i++){ var touch = touches[i], pos = clientToLocal(root, touch, {}); trackItem.points.push([ pos.zrX, pos.zrY ]), trackItem.touches.push(touch); } this._track.push(trackItem); } }, GestureMgr.prototype._recognize = function(event) { for(var eventName in recognizers)if (recognizers.hasOwnProperty(eventName)) { var gestureInfo = recognizers[eventName](this._track, event); if (gestureInfo) return gestureInfo; } }, GestureMgr; }(); function dist$1(pointPair) { var dx = pointPair[1][0] - pointPair[0][0], dy = pointPair[1][1] - pointPair[0][1]; return Math.sqrt(dx * dx + dy * dy); } var recognizers = { pinch: function(tracks, event) { var trackLen = tracks.length; if (trackLen) { var pinchEnd = (tracks[trackLen - 1] || {}).points, pinchPre = (tracks[trackLen - 2] || {}).points || pinchEnd; if (pinchPre && pinchPre.length > 1 && pinchEnd && pinchEnd.length > 1) { var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre); isFinite(pinchScale) || (pinchScale = 1), event.pinchScale = pinchScale; var pinchCenter = [ (pinchEnd[0][0] + pinchEnd[1][0]) / 2, (pinchEnd[0][1] + pinchEnd[1][1]) / 2 ]; return event.pinchX = pinchCenter[0], event.pinchY = pinchCenter[1], { type: 'pinch', target: tracks[0].target, event: event }; } } } }, SILENT = 'silent'; function stopEvent() { stop(this.event); } var EmptyProxy = function(_super) { function EmptyProxy() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.handler = null, _this; } return __extends(EmptyProxy, _super), EmptyProxy.prototype.dispose = function() {}, EmptyProxy.prototype.setCursor = function() {}, EmptyProxy; }(Eventful), HoveredResult = function(x, y) { this.x = x, this.y = y; }, handlerNames = [ 'click', 'dblclick', 'mousewheel', 'mouseout', 'mouseup', 'mousedown', 'mousemove', 'contextmenu' ], Handler = function(_super) { function Handler(storage, painter, proxy, painterRoot) { var _this = _super.call(this) || this; return _this._hovered = new HoveredResult(0, 0), _this.storage = storage, _this.painter = painter, _this.painterRoot = painterRoot, proxy = proxy || new EmptyProxy(), _this.proxy = null, _this.setHandlerProxy(proxy), _this._draggingMgr = new Draggable(_this), _this; } return __extends(Handler, _super), Handler.prototype.setHandlerProxy = function(proxy) { this.proxy && this.proxy.dispose(), proxy && (each(handlerNames, function(name) { proxy.on && proxy.on(name, this[name], this); }, this), proxy.handler = this), this.proxy = proxy; }, Handler.prototype.mousemove = function(event) { var x = event.zrX, y = event.zrY, isOutside = isOutsideBoundary(this, x, y), lastHovered = this._hovered, lastHoveredTarget = lastHovered.target; lastHoveredTarget && !lastHoveredTarget.__zr && (lastHoveredTarget = (lastHovered = this.findHover(lastHovered.x, lastHovered.y)).target); var hovered = this._hovered = isOutside ? new HoveredResult(x, y) : this.findHover(x, y), hoveredTarget = hovered.target, proxy = this.proxy; proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default'), lastHoveredTarget && hoveredTarget !== lastHoveredTarget && this.dispatchToElement(lastHovered, 'mouseout', event), this.dispatchToElement(hovered, 'mousemove', event), hoveredTarget && hoveredTarget !== lastHoveredTarget && this.dispatchToElement(hovered, 'mouseover', event); }, Handler.prototype.mouseout = function(event) { var eventControl = event.zrEventControl; 'only_globalout' !== eventControl && this.dispatchToElement(this._hovered, 'mouseout', event), 'no_globalout' !== eventControl && this.trigger('globalout', { type: 'globalout', event: event }); }, Handler.prototype.resize = function() { this._hovered = new HoveredResult(0, 0); }, Handler.prototype.dispatch = function(eventName, eventArgs) { var handler = this[eventName]; handler && handler.call(this, eventArgs); }, Handler.prototype.dispose = function() { this.proxy.dispose(), this.storage = null, this.proxy = null, this.painter = null; }, Handler.prototype.setCursorStyle = function(cursorStyle) { var proxy = this.proxy; proxy.setCursor && proxy.setCursor(cursorStyle); }, Handler.prototype.dispatchToElement = function(targetInfo, eventName, event) { var targetInfo1, el = (targetInfo = targetInfo || {}).target; if (!el || !el.silent) { for(var eventKey = 'on' + eventName, eventPacket = { type: eventName, event: event, target: (targetInfo1 = targetInfo).target, topTarget: targetInfo1.topTarget, cancelBubble: !1, offsetX: event.zrX, offsetY: event.zrY, gestureEvent: event.gestureEvent, pinchX: event.pinchX, pinchY: event.pinchY, pinchScale: event.pinchScale, wheelDelta: event.zrDelta, zrByTouch: event.zrByTouch, which: event.which, stop: stopEvent }; el && (el[eventKey] && (eventPacket.cancelBubble = !!el[eventKey].call(el, eventPacket)), el.trigger(eventName, eventPacket), el = el.__hostTarget ? el.__hostTarget : el.parent, !eventPacket.cancelBubble);); !eventPacket.cancelBubble && (this.trigger(eventName, eventPacket), this.painter && this.painter.eachOtherLayer && this.painter.eachOtherLayer(function(layer) { 'function' == typeof layer[eventKey] && layer[eventKey].call(layer, eventPacket), layer.trigger && layer.trigger(eventName, eventPacket); })); } }, Handler.prototype.findHover = function(x, y, exclude) { for(var list = this.storage.getDisplayList(), out = new HoveredResult(x, y), i = list.length - 1; i >= 0; i--){ var hoverCheckResult = void 0; if (list[i] !== exclude && !list[i].ignore && (hoverCheckResult = function(displayable, x, y) { if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) { for(var el = displayable, isSilent = void 0, ignoreClip = !1; el;){ if (el.ignoreClip && (ignoreClip = !0), !ignoreClip) { var clipPath = el.getClipPath(); if (clipPath && !clipPath.contain(x, y)) return !1; el.silent && (isSilent = !0); } el = el.__hostTarget || el.parent; } return !isSilent || SILENT; } return !1; }(list[i], x, y)) && (out.topTarget || (out.topTarget = list[i]), hoverCheckResult !== SILENT)) { out.target = list[i]; break; } } return out; }, Handler.prototype.processGesture = function(event, stage) { this._gestureMgr || (this._gestureMgr = new GestureMgr()); var gestureMgr = this._gestureMgr; 'start' === stage && gestureMgr.clear(); var gestureInfo = gestureMgr.recognize(event, this.findHover(event.zrX, event.zrY, null).target, this.proxy.dom); if ('end' === stage && gestureMgr.clear(), gestureInfo) { var type = gestureInfo.type; event.gestureEvent = type; var res = new HoveredResult(); res.target = gestureInfo.target, this.dispatchToElement(res, type, gestureInfo.event); } }, Handler; }(Eventful); function isOutsideBoundary(handlerInstance, x, y) { var painter = handlerInstance.painter; return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight(); } function create$1() { return [ 1, 0, 0, 1, 0, 0 ]; } function identity(out) { return out[0] = 1, out[1] = 0, out[2] = 0, out[3] = 1, out[4] = 0, out[5] = 0, out; } function copy$1(out, m) { return out[0] = m[0], out[1] = m[1], out[2] = m[2], out[3] = m[3], out[4] = m[4], out[5] = m[5], out; } function mul$1(out, m1, m2) { var out0 = m1[0] * m2[0] + m1[2] * m2[1], out1 = m1[1] * m2[0] + m1[3] * m2[1], out2 = m1[0] * m2[2] + m1[2] * m2[3], out3 = m1[1] * m2[2] + m1[3] * m2[3], out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4], out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5]; return out[0] = out0, out[1] = out1, out[2] = out2, out[3] = out3, out[4] = out4, out[5] = out5, out; } function translate(out, a, v) { return out[0] = a[0], out[1] = a[1], out[2] = a[2], out[3] = a[3], out[4] = a[4] + v[0], out[5] = a[5] + v[1], out; } function rotate(out, a, rad) { var aa = a[0], ac = a[2], atx = a[4], ab = a[1], ad = a[3], aty = a[5], st = Math.sin(rad), ct = Math.cos(rad); return out[0] = aa * ct + ab * st, out[1] = -aa * st + ab * ct, out[2] = ac * ct + ad * st, out[3] = -ac * st + ct * ad, out[4] = ct * atx + st * aty, out[5] = ct * aty - st * atx, out; } function scale$1(out, a, v) { var vx = v[0], vy = v[1]; return out[0] = a[0] * vx, out[1] = a[1] * vy, out[2] = a[2] * vx, out[3] = a[3] * vy, out[4] = a[4] * vx, out[5] = a[5] * vy, out; } function invert(out, a) { var aa = a[0], ac = a[2], atx = a[4], ab = a[1], ad = a[3], aty = a[5], det = aa * ad - ab * ac; return det ? (det = 1.0 / det, out[0] = ad * det, out[1] = -ab * det, out[2] = -ac * det, out[3] = aa * det, out[4] = (ac * aty - ad * atx) * det, out[5] = (ab * atx - aa * aty) * det, out) : null; } function clone$2(a) { var b = create$1(); return copy$1(b, a), b; } each([ 'click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu' ], function(name) { Handler.prototype[name] = function(event) { var hovered, hoveredTarget, x = event.zrX, y = event.zrY, isOutside = isOutsideBoundary(this, x, y); if ('mouseup' === name && isOutside || (hoveredTarget = (hovered = this.findHover(x, y)).target), 'mousedown' === name) this._downEl = hoveredTarget, this._downPoint = [ event.zrX, event.zrY ], this._upEl = hoveredTarget; else if ('mouseup' === name) this._upEl = hoveredTarget; else if ('click' === name) { if (this._downEl !== this._upEl || !this._downPoint || distance(this._downPoint, [ event.zrX, event.zrY ]) > 4) return; this._downPoint = null; } this.dispatchToElement(hovered, name, event); }; }); var matrix = Object.freeze({ __proto__: null, create: create$1, identity: identity, copy: copy$1, mul: mul$1, translate: translate, rotate: rotate, scale: scale$1, invert: invert, clone: clone$2 }); function isNotAroundZero(val) { return val > 5e-5 || val < -0.00005; } var scaleTmp = [], tmpTransform = [], originTransform = create$1(), abs = Math.abs, Transformable = function() { var proto; function Transformable() {} return Transformable.prototype.setPosition = function(arr) { this.x = arr[0], this.y = arr[1]; }, Transformable.prototype.setScale = function(arr) { this.scaleX = arr[0], this.scaleY = arr[1]; }, Transformable.prototype.setOrigin = function(arr) { this.originX = arr[0], this.originY = arr[1]; }, Transformable.prototype.needLocalTransform = function() { return isNotAroundZero(this.rotation) || isNotAroundZero(this.x) || isNotAroundZero(this.y) || isNotAroundZero(this.scaleX - 1) || isNotAroundZero(this.scaleY - 1); }, Transformable.prototype.updateTransform = function() { var parent = this.parent, parentHasTransform = parent && parent.transform, needLocalTransform = this.needLocalTransform(), m = this.transform; if (!(needLocalTransform || parentHasTransform)) { m && identity(m); return; } m = m || create$1(), needLocalTransform ? this.getLocalTransform(m) : identity(m), parentHasTransform && (needLocalTransform ? mul$1(m, parent.transform, m) : copy$1(m, parent.transform)), this.transform = m, this._resolveGlobalScaleRatio(m); }, Transformable.prototype._resolveGlobalScaleRatio = function(m) { var globalScaleRatio = this.globalScaleRatio; if (null != globalScaleRatio && 1 !== globalScaleRatio) { this.getGlobalScale(scaleTmp); var relX = scaleTmp[0] < 0 ? -1 : 1, relY = scaleTmp[1] < 0 ? -1 : 1, sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0, sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0; m[0] *= sx, m[1] *= sx, m[2] *= sy, m[3] *= sy; } this.invTransform = this.invTransform || create$1(), invert(this.invTransform, m); }, Transformable.prototype.getLocalTransform = function(m) { return Transformable.getLocalTransform(this, m); }, Transformable.prototype.getComputedTransform = function() { for(var transformNode = this, ancestors = []; transformNode;)ancestors.push(transformNode), transformNode = transformNode.parent; for(; transformNode = ancestors.pop();)transformNode.updateTransform(); return this.transform; }, Transformable.prototype.setLocalTransform = function(m) { if (m) { var sx = m[0] * m[0] + m[1] * m[1], sy = m[2] * m[2] + m[3] * m[3]; isNotAroundZero(sx - 1) && (sx = Math.sqrt(sx)), isNotAroundZero(sy - 1) && (sy = Math.sqrt(sy)), m[0] < 0 && (sx = -sx), m[3] < 0 && (sy = -sy), this.rotation = Math.atan2(-m[1] / sy, m[0] / sx), sx < 0 && sy < 0 && (this.rotation += Math.PI, sx = -sx, sy = -sy), this.x = m[4], this.y = m[5], this.scaleX = sx, this.scaleY = sy; } }, Transformable.prototype.decomposeTransform = function() { if (this.transform) { var parent = this.parent, m = this.transform; parent && parent.transform && (mul$1(tmpTransform, parent.invTransform, m), m = tmpTransform); var ox = this.originX, oy = this.originY; (ox || oy) && (originTransform[4] = ox, originTransform[5] = oy, mul$1(tmpTransform, m, originTransform), tmpTransform[4] -= ox, tmpTransform[5] -= oy, m = tmpTransform), this.setLocalTransform(m); } }, Transformable.prototype.getGlobalScale = function(out) { var m = this.transform; return (out = out || [], m) ? (out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]), out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]), m[0] < 0 && (out[0] = -out[0]), m[3] < 0 && (out[1] = -out[1]), out) : (out[0] = 1, out[1] = 1, out); }, Transformable.prototype.transformCoordToLocal = function(x, y) { var v2 = [ x, y ], invTransform = this.invTransform; return invTransform && applyTransform(v2, v2, invTransform), v2; }, Transformable.prototype.transformCoordToGlobal = function(x, y) { var v2 = [ x, y ], transform = this.transform; return transform && applyTransform(v2, v2, transform), v2; }, Transformable.prototype.getLineScale = function() { var m = this.transform; return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10 ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1])) : 1; }, Transformable.getLocalTransform = function(target, m) { identity(m = m || []); var ox = target.originX || 0, oy = target.originY || 0, sx = target.scaleX, sy = target.scaleY, rotation = target.rotation || 0, x = target.x, y = target.y; return m[4] -= ox, m[5] -= oy, m[0] *= sx, m[1] *= sy, m[2] *= sx, m[3] *= sy, m[4] *= sx, m[5] *= sy, rotation && rotate(m, m, rotation), m[4] += ox, m[5] += oy, m[4] += x, m[5] += y, m; }, Transformable.initDefaultProps = void ((proto = Transformable.prototype).x = 0, proto.y = 0, proto.scaleX = 1, proto.scaleY = 1, proto.originX = 0, proto.originY = 0, proto.rotation = 0, proto.globalScaleRatio = 1), Transformable; }(), easing = { linear: function(k) { return k; }, quadraticIn: function(k) { return k * k; }, quadraticOut: function(k) { return k * (2 - k); }, quadraticInOut: function(k) { return (k *= 2) < 1 ? 0.5 * k * k : -0.5 * (--k * (k - 2) - 1); }, cubicIn: function(k) { return k * k * k; }, cubicOut: function(k) { return --k * k * k + 1; }, cubicInOut: function(k) { return (k *= 2) < 1 ? 0.5 * k * k * k : 0.5 * ((k -= 2) * k * k + 2); }, quarticIn: function(k) { return k * k * k * k; }, quarticOut: function(k) { return 1 - --k * k * k * k; }, quarticInOut: function(k) { return (k *= 2) < 1 ? 0.5 * k * k * k * k : -0.5 * ((k -= 2) * k * k * k - 2); }, quinticIn: function(k) { return k * k * k * k * k; }, quinticOut: function(k) { return --k * k * k * k * k + 1; }, quinticInOut: function(k) { return (k *= 2) < 1 ? 0.5 * k * k * k * k * k : 0.5 * ((k -= 2) * k * k * k * k + 2); }, sinusoidalIn: function(k) { return 1 - Math.cos(k * Math.PI / 2); }, sinusoidalOut: function(k) { return Math.sin(k * Math.PI / 2); }, sinusoidalInOut: function(k) { return 0.5 * (1 - Math.cos(Math.PI * k)); }, exponentialIn: function(k) { return 0 === k ? 0 : Math.pow(1024, k - 1); }, exponentialOut: function(k) { return 1 === k ? 1 : 1 - Math.pow(2, -10 * k); }, exponentialInOut: function(k) { return 0 === k ? 0 : 1 === k ? 1 : (k *= 2) < 1 ? 0.5 * Math.pow(1024, k - 1) : 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2); }, circularIn: function(k) { return 1 - Math.sqrt(1 - k * k); }, circularOut: function(k) { return Math.sqrt(1 - --k * k); }, circularInOut: function(k) { return (k *= 2) < 1 ? -0.5 * (Math.sqrt(1 - k * k) - 1) : 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1); }, elasticIn: function(k) { var s, a = 0.1; return 0 === k ? 0 : 1 === k ? 1 : (!a || a < 1 ? (a = 1, s = 0.1) : s = 0.4 * Math.asin(1 / a) / (2 * Math.PI), -(a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / 0.4))); }, elasticOut: function(k) { var s, a = 0.1; return 0 === k ? 0 : 1 === k ? 1 : (!a || a < 1 ? (a = 1, s = 0.1) : s = 0.4 * Math.asin(1 / a) / (2 * Math.PI), a * Math.pow(2, -10 * k) * Math.sin((k - s) * (2 * Math.PI) / 0.4) + 1); }, elasticInOut: function(k) { var s, a = 0.1; return 0 === k ? 0 : 1 === k ? 1 : (!a || a < 1 ? (a = 1, s = 0.1) : s = 0.4 * Math.asin(1 / a) / (2 * Math.PI), (k *= 2) < 1) ? -0.5 * (a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / 0.4)) : a * Math.pow(2, -10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / 0.4) * 0.5 + 1; }, backIn: function(k) { return k * k * (2.70158 * k - 1.70158); }, backOut: function(k) { return --k * k * (2.70158 * k + 1.70158) + 1; }, backInOut: function(k) { return (k *= 2) < 1 ? 0.5 * (k * k * (3.5949095 * k - 2.5949095)) : 0.5 * ((k -= 2) * k * (3.5949095 * k + 2.5949095) + 2); }, bounceIn: function(k) { return 1 - easing.bounceOut(1 - k); }, bounceOut: function(k) { return k < 1 / 2.75 ? 7.5625 * k * k : k < 2 / 2.75 ? 7.5625 * (k -= 1.5 / 2.75) * k + 0.75 : k < 2.5 / 2.75 ? 7.5625 * (k -= 2.25 / 2.75) * k + 0.9375 : 7.5625 * (k -= 2.625 / 2.75) * k + 0.984375; }, bounceInOut: function(k) { return k < 0.5 ? 0.5 * easing.bounceIn(2 * k) : 0.5 * easing.bounceOut(2 * k - 1) + 0.5; } }, Clip = function() { function Clip(opts) { this._initialized = !1, this._startTime = 0, this._pausedTime = 0, this._paused = !1, this._life = opts.life || 1000, this._delay = opts.delay || 0, this.loop = null != opts.loop && opts.loop, this.gap = opts.gap || 0, this.easing = opts.easing || 'linear', this.onframe = opts.onframe, this.ondestroy = opts.ondestroy, this.onrestart = opts.onrestart; } return Clip.prototype.step = function(globalTime, deltaTime) { if (this._initialized || (this._startTime = globalTime + this._delay, this._initialized = !0), this._paused) { this._pausedTime += deltaTime; return; } var percent = (globalTime - this._startTime - this._pausedTime) / this._life; percent < 0 && (percent = 0), percent = Math.min(percent, 1); var easing$1 = this.easing, easingFunc = 'string' == typeof easing$1 ? easing[easing$1] : easing$1, schedule = 'function' == typeof easingFunc ? easingFunc(percent) : percent; if (this.onframe && this.onframe(schedule), 1 === percent) { if (!this.loop) return !0; this._restart(globalTime), this.onrestart && this.onrestart(); } return !1; }, Clip.prototype._restart = function(globalTime) { var remainder = (globalTime - this._startTime - this._pausedTime) % this._life; this._startTime = globalTime - remainder + this.gap, this._pausedTime = 0; }, Clip.prototype.pause = function() { this._paused = !0; }, Clip.prototype.resume = function() { this._paused = !1; }, Clip; }(), Entry = function(val) { this.value = val; }, LinkedList = function() { function LinkedList() { this._len = 0; } return LinkedList.prototype.insert = function(val) { var entry = new Entry(val); return this.insertEntry(entry), entry; }, LinkedList.prototype.insertEntry = function(entry) { this.head ? (this.tail.next = entry, entry.prev = this.tail, entry.next = null, this.tail = entry) : this.head = this.tail = entry, this._len++; }, LinkedList.prototype.remove = function(entry) { var prev = entry.prev, next = entry.next; prev ? prev.next = next : this.head = next, next ? next.prev = prev : this.tail = prev, entry.next = entry.prev = null, this._len--; }, LinkedList.prototype.len = function() { return this._len; }, LinkedList.prototype.clear = function() { this.head = this.tail = null, this._len = 0; }, LinkedList; }(), LRU = function() { function LRU(maxSize) { this._list = new LinkedList(), this._maxSize = 10, this._map = {}, this._maxSize = maxSize; } return LRU.prototype.put = function(key, value) { var list = this._list, map = this._map, removed = null; if (null == map[key]) { var len = list.len(), entry = this._lastRemovedEntry; if (len >= this._maxSize && len > 0) { var leastUsedEntry = list.head; list.remove(leastUsedEntry), delete map[leastUsedEntry.key], removed = leastUsedEntry.value, this._lastRemovedEntry = leastUsedEntry; } entry ? entry.value = value : entry = new Entry(value), entry.key = key, list.insertEntry(entry), map[key] = entry; } return removed; }, LRU.prototype.get = function(key) { var entry = this._map[key], list = this._list; if (null != entry) return entry !== list.tail && (list.remove(entry), list.insertEntry(entry)), entry.value; }, LRU.prototype.clear = function() { this._list.clear(), this._map = {}; }, LRU.prototype.len = function() { return this._list.len(); }, LRU; }(), kCSSColorTable = { transparent: [ 0, 0, 0, 0 ], aliceblue: [ 240, 248, 255, 1 ], antiquewhite: [ 250, 235, 215, 1 ], aqua: [ 0, 255, 255, 1 ], aquamarine: [ 127, 255, 212, 1 ], azure: [ 240, 255, 255, 1 ], beige: [ 245, 245, 220, 1 ], bisque: [ 255, 228, 196, 1 ], black: [ 0, 0, 0, 1 ], blanchedalmond: [ 255, 235, 205, 1 ], blue: [ 0, 0, 255, 1 ], blueviolet: [ 138, 43, 226, 1 ], brown: [ 165, 42, 42, 1 ], burlywood: [ 222, 184, 135, 1 ], cadetblue: [ 95, 158, 160, 1 ], chartreuse: [ 127, 255, 0, 1 ], chocolate: [ 210, 105, 30, 1 ], coral: [ 255, 127, 80, 1 ], cornflowerblue: [ 100, 149, 237, 1 ], cornsilk: [ 255, 248, 220, 1 ], crimson: [ 220, 20, 60, 1 ], cyan: [ 0, 255, 255, 1 ], darkblue: [ 0, 0, 139, 1 ], darkcyan: [ 0, 139, 139, 1 ], darkgoldenrod: [ 184, 134, 11, 1 ], darkgray: [ 169, 169, 169, 1 ], darkgreen: [ 0, 100, 0, 1 ], darkgrey: [ 169, 169, 169, 1 ], darkkhaki: [ 189, 183, 107, 1 ], darkmagenta: [ 139, 0, 139, 1 ], darkolivegreen: [ 85, 107, 47, 1 ], darkorange: [ 255, 140, 0, 1 ], darkorchid: [ 153, 50, 204, 1 ], darkred: [ 139, 0, 0, 1 ], darksalmon: [ 233, 150, 122, 1 ], darkseagreen: [ 143, 188, 143, 1 ], darkslateblue: [ 72, 61, 139, 1 ], darkslategray: [ 47, 79, 79, 1 ], darkslategrey: [ 47, 79, 79, 1 ], darkturquoise: [ 0, 206, 209, 1 ], darkviolet: [ 148, 0, 211, 1 ], deeppink: [ 255, 20, 147, 1 ], deepskyblue: [ 0, 191, 255, 1 ], dimgray: [ 105, 105, 105, 1 ], dimgrey: [ 105, 105, 105, 1 ], dodgerblue: [ 30, 144, 255, 1 ], firebrick: [ 178, 34, 34, 1 ], floralwhite: [ 255, 250, 240, 1 ], forestgreen: [ 34, 139, 34, 1 ], fuchsia: [ 255, 0, 255, 1 ], gainsboro: [ 220, 220, 220, 1 ], ghostwhite: [ 248, 248, 255, 1 ], gold: [ 255, 215, 0, 1 ], goldenrod: [ 218, 165, 32, 1 ], gray: [ 128, 128, 128, 1 ], green: [ 0, 128, 0, 1 ], greenyellow: [ 173, 255, 47, 1 ], grey: [ 128, 128, 128, 1 ], honeydew: [ 240, 255, 240, 1 ], hotpink: [ 255, 105, 180, 1 ], indianred: [ 205, 92, 92, 1 ], indigo: [ 75, 0, 130, 1 ], ivory: [ 255, 255, 240, 1 ], khaki: [ 240, 230, 140, 1 ], lavender: [ 230, 230, 250, 1 ], lavenderblush: [ 255, 240, 245, 1 ], lawngreen: [ 124, 252, 0, 1 ], lemonchiffon: [ 255, 250, 205, 1 ], lightblue: [ 173, 216, 230, 1 ], lightcoral: [ 240, 128, 128, 1 ], lightcyan: [ 224, 255, 255, 1 ], lightgoldenrodyellow: [ 250, 250, 210, 1 ], lightgray: [ 211, 211, 211, 1 ], lightgreen: [ 144, 238, 144, 1 ], lightgrey: [ 211, 211, 211, 1 ], lightpink: [ 255, 182, 193, 1 ], lightsalmon: [ 255, 160, 122, 1 ], lightseagreen: [ 32, 178, 170, 1 ], lightskyblue: [ 135, 206, 250, 1 ], lightslategray: [ 119, 136, 153, 1 ], lightslategrey: [ 119, 136, 153, 1 ], lightsteelblue: [ 176, 196, 222, 1 ], lightyellow: [ 255, 255, 224, 1 ], lime: [ 0, 255, 0, 1 ], limegreen: [ 50, 205, 50, 1 ], linen: [ 250, 240, 230, 1 ], magenta: [ 255, 0, 255, 1 ], maroon: [ 128, 0, 0, 1 ], mediumaquamarine: [ 102, 205, 170, 1 ], mediumblue: [ 0, 0, 205, 1 ], mediumorchid: [ 186, 85, 211, 1 ], mediumpurple: [ 147, 112, 219, 1 ], mediumseagreen: [ 60, 179, 113, 1 ], mediumslateblue: [ 123, 104, 238, 1 ], mediumspringgreen: [ 0, 250, 154, 1 ], mediumturquoise: [ 72, 209, 204, 1 ], mediumvioletred: [ 199, 21, 133, 1 ], midnightblue: [ 25, 25, 112, 1 ], mintcream: [ 245, 255, 250, 1 ], mistyrose: [ 255, 228, 225, 1 ], moccasin: [ 255, 228, 181, 1 ], navajowhite: [ 255, 222, 173, 1 ], navy: [ 0, 0, 128, 1 ], oldlace: [ 253, 245, 230, 1 ], olive: [ 128, 128, 0, 1 ], olivedrab: [ 107, 142, 35, 1 ], orange: [ 255, 165, 0, 1 ], orangered: [ 255, 69, 0, 1 ], orchid: [ 218, 112, 214, 1 ], palegoldenrod: [ 238, 232, 170, 1 ], palegreen: [ 152, 251, 152, 1 ], paleturquoise: [ 175, 238, 238, 1 ], palevioletred: [ 219, 112, 147, 1 ], papayawhip: [ 255, 239, 213, 1 ], peachpuff: [ 255, 218, 185, 1 ], peru: [ 205, 133, 63, 1 ], pink: [ 255, 192, 203, 1 ], plum: [ 221, 160, 221, 1 ], powderblue: [ 176, 224, 230, 1 ], purple: [ 128, 0, 128, 1 ], red: [ 255, 0, 0, 1 ], rosybrown: [ 188, 143, 143, 1 ], royalblue: [ 65, 105, 225, 1 ], saddlebrown: [ 139, 69, 19, 1 ], salmon: [ 250, 128, 114, 1 ], sandybrown: [ 244, 164, 96, 1 ], seagreen: [ 46, 139, 87, 1 ], seashell: [ 255, 245, 238, 1 ], sienna: [ 160, 82, 45, 1 ], silver: [ 192, 192, 192, 1 ], skyblue: [ 135, 206, 235, 1 ], slateblue: [ 106, 90, 205, 1 ], slategray: [ 112, 128, 144, 1 ], slategrey: [ 112, 128, 144, 1 ], snow: [ 255, 250, 250, 1 ], springgreen: [ 0, 255, 127, 1 ], steelblue: [ 70, 130, 180, 1 ], tan: [ 210, 180, 140, 1 ], teal: [ 0, 128, 128, 1 ], thistle: [ 216, 191, 216, 1 ], tomato: [ 255, 99, 71, 1 ], turquoise: [ 64, 224, 208, 1 ], violet: [ 238, 130, 238, 1 ], wheat: [ 245, 222, 179, 1 ], white: [ 255, 255, 255, 1 ], whitesmoke: [ 245, 245, 245, 1 ], yellow: [ 255, 255, 0, 1 ], yellowgreen: [ 154, 205, 50, 1 ] }; function clampCssByte(i) { return (i = Math.round(i)) < 0 ? 0 : i > 255 ? 255 : i; } function clampCssFloat(f) { return f < 0 ? 0 : f > 1 ? 1 : f; } function parseCssInt(val) { return val.length && '%' === val.charAt(val.length - 1) ? clampCssByte(parseFloat(val) / 100 * 255) : clampCssByte(parseInt(val, 10)); } function parseCssFloat(val) { return val.length && '%' === val.charAt(val.length - 1) ? clampCssFloat(parseFloat(val) / 100) : clampCssFloat(parseFloat(val)); } function cssHueToRgb(m1, m2, h) { return (h < 0 ? h += 1 : h > 1 && (h -= 1), 6 * h < 1) ? m1 + (m2 - m1) * h * 6 : 2 * h < 1 ? m2 : 3 * h < 2 ? m1 + (m2 - m1) * (2 / 3 - h) * 6 : m1; } function setRgba(out, r, g, b, a) { return out[0] = r, out[1] = g, out[2] = b, out[3] = a, out; } function copyRgba(out, a) { return out[0] = a[0], out[1] = a[1], out[2] = a[2], out[3] = a[3], out; } var colorCache = new LRU(20), lastRemovedArr = null; function putToCache(colorStr, rgbaArr) { lastRemovedArr && copyRgba(lastRemovedArr, rgbaArr), lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || rgbaArr.slice()); } function parse(colorStr, rgbaArr) { if (colorStr) { rgbaArr = rgbaArr || []; var cached = colorCache.get(colorStr); if (cached) return copyRgba(rgbaArr, cached); var str = (colorStr += '').replace(/ /g, '').toLowerCase(); if (str in kCSSColorTable) return copyRgba(rgbaArr, kCSSColorTable[str]), putToCache(colorStr, rgbaArr), rgbaArr; var strLen = str.length; if ('#' === str.charAt(0)) { if (4 === strLen || 5 === strLen) { var iv = parseInt(str.slice(1, 4), 16); if (!(iv >= 0 && iv <= 0xfff)) { setRgba(rgbaArr, 0, 0, 0, 1); return; } return setRgba(rgbaArr, (0xf00 & iv) >> 4 | (0xf00 & iv) >> 8, 0xf0 & iv | (0xf0 & iv) >> 4, 0xf & iv | (0xf & iv) << 4, 5 === strLen ? parseInt(str.slice(4), 16) / 0xf : 1), putToCache(colorStr, rgbaArr), rgbaArr; } if (7 === strLen || 9 === strLen) { var iv = parseInt(str.slice(1, 7), 16); if (!(iv >= 0 && iv <= 0xffffff)) { setRgba(rgbaArr, 0, 0, 0, 1); return; } return setRgba(rgbaArr, (0xff0000 & iv) >> 16, (0xff00 & iv) >> 8, 0xff & iv, 9 === strLen ? parseInt(str.slice(7), 16) / 0xff : 1), putToCache(colorStr, rgbaArr), rgbaArr; } return; } var op = str.indexOf('('), ep = str.indexOf(')'); if (-1 !== op && ep + 1 === strLen) { var fname = str.substr(0, op), params = str.substr(op + 1, ep - (op + 1)).split(','), alpha = 1; switch(fname){ case 'rgba': if (4 !== params.length) return 3 === params.length ? setRgba(rgbaArr, +params[0], +params[1], +params[2], 1) : setRgba(rgbaArr, 0, 0, 0, 1); alpha = parseCssFloat(params.pop()); case 'rgb': if (3 !== params.length) { setRgba(rgbaArr, 0, 0, 0, 1); return; } return setRgba(rgbaArr, parseCssInt(params[0]), parseCssInt(params[1]), parseCssInt(params[2]), alpha), putToCache(colorStr, rgbaArr), rgbaArr; case 'hsla': if (4 !== params.length) { setRgba(rgbaArr, 0, 0, 0, 1); return; } return params[3] = parseCssFloat(params[3]), hsla2rgba(params, rgbaArr), putToCache(colorStr, rgbaArr), rgbaArr; case 'hsl': if (3 !== params.length) { setRgba(rgbaArr, 0, 0, 0, 1); return; } return hsla2rgba(params, rgbaArr), putToCache(colorStr, rgbaArr), rgbaArr; default: return; } } setRgba(rgbaArr, 0, 0, 0, 1); } } function hsla2rgba(hsla, rgba) { var h = (parseFloat(hsla[0]) % 360 + 360) % 360 / 360, s = parseCssFloat(hsla[1]), l = parseCssFloat(hsla[2]), m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s, m1 = 2 * l - m2; return setRgba(rgba = rgba || [], clampCssByte(255 * cssHueToRgb(m1, m2, h + 1 / 3)), clampCssByte(255 * cssHueToRgb(m1, m2, h)), clampCssByte(255 * cssHueToRgb(m1, m2, h - 1 / 3)), 1), 4 === hsla.length && (rgba[3] = hsla[3]), rgba; } function lift(color, level) { var colorArr = parse(color); if (colorArr) { for(var i = 0; i < 3; i++)level < 0 ? colorArr[i] = colorArr[i] * (1 - level) | 0 : colorArr[i] = (255 - colorArr[i]) * level + colorArr[i] | 0, colorArr[i] > 255 ? colorArr[i] = 255 : colorArr[i] < 0 && (colorArr[i] = 0); return stringify(colorArr, 4 === colorArr.length ? 'rgba' : 'rgb'); } } function toHex(color) { var colorArr = parse(color); if (colorArr) return (16777216 + (colorArr[0] << 16) + (colorArr[1] << 8) + +colorArr[2]).toString(16).slice(1); } function fastLerp(normalizedValue, colors, out) { if (colors && colors.length && normalizedValue >= 0 && normalizedValue <= 1) { out = out || []; var a, a1, a2, a3, value = normalizedValue * (colors.length - 1), leftIndex = Math.floor(value), leftColor = colors[leftIndex], rightColor = colors[Math.ceil(value)], dv = value - leftIndex; return out[0] = clampCssByte((a = leftColor[0]) + (rightColor[0] - a) * dv), out[1] = clampCssByte((a1 = leftColor[1]) + (rightColor[1] - a1) * dv), out[2] = clampCssByte((a2 = leftColor[2]) + (rightColor[2] - a2) * dv), out[3] = clampCssFloat((a3 = leftColor[3]) + (rightColor[3] - a3) * dv), out; } } function lerp$1(normalizedValue, colors, fullOutput) { if (colors && colors.length && normalizedValue >= 0 && normalizedValue <= 1) { var a, a1, a2, a3, value = normalizedValue * (colors.length - 1), leftIndex = Math.floor(value), rightIndex = Math.ceil(value), leftColor = parse(colors[leftIndex]), rightColor = parse(colors[rightIndex]), dv = value - leftIndex, color = stringify([ clampCssByte((a = leftColor[0]) + (rightColor[0] - a) * dv), clampCssByte((a1 = leftColor[1]) + (rightColor[1] - a1) * dv), clampCssByte((a2 = leftColor[2]) + (rightColor[2] - a2) * dv), clampCssFloat((a3 = leftColor[3]) + (rightColor[3] - a3) * dv) ], 'rgba'); return fullOutput ? { color: color, leftIndex: leftIndex, rightIndex: rightIndex, value: value } : color; } } function modifyHSL(color, h, s, l) { var i, colorArr = parse(color); if (color) return colorArr = function(rgba) { if (rgba) { var H, S, R = rgba[0] / 255, G = rgba[1] / 255, B = rgba[2] / 255, vMin = Math.min(R, G, B), vMax = Math.max(R, G, B), delta = vMax - vMin, L = (vMax + vMin) / 2; if (0 === delta) H = 0, S = 0; else { S = L < 0.5 ? delta / (vMax + vMin) : delta / (2 - vMax - vMin); var deltaR = ((vMax - R) / 6 + delta / 2) / delta, deltaG = ((vMax - G) / 6 + delta / 2) / delta, deltaB = ((vMax - B) / 6 + delta / 2) / delta; R === vMax ? H = deltaB - deltaG : G === vMax ? H = 1 / 3 + deltaR - deltaB : B === vMax && (H = 2 / 3 + deltaG - deltaR), H < 0 && (H += 1), H > 1 && (H -= 1); } var hsla = [ 360 * H, S, L ]; return null != rgba[3] && hsla.push(rgba[3]), hsla; } }(colorArr), null != h && (colorArr[0] = (i = Math.round(i = h)) < 0 ? 0 : i > 360 ? 360 : i), null != s && (colorArr[1] = parseCssFloat(s)), null != l && (colorArr[2] = parseCssFloat(l)), stringify(hsla2rgba(colorArr), 'rgba'); } function modifyAlpha(color, alpha) { var colorArr = parse(color); if (colorArr && null != alpha) return colorArr[3] = clampCssFloat(alpha), stringify(colorArr, 'rgba'); } function stringify(arrColor, type) { if (arrColor && arrColor.length) { var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2]; return ('rgba' === type || 'hsva' === type || 'hsla' === type) && (colorStr += ',' + arrColor[3]), type + '(' + colorStr + ')'; } } function lum(color, backgroundLum) { var arr = parse(color); return arr ? (0.299 * arr[0] + 0.587 * arr[1] + 0.114 * arr[2]) * arr[3] / 255 + (1 - arr[3]) * backgroundLum : 0; } var color = Object.freeze({ __proto__: null, parse: parse, lift: lift, toHex: toHex, fastLerp: fastLerp, fastMapToColor: fastLerp, lerp: lerp$1, mapToColor: lerp$1, modifyHSL: modifyHSL, modifyAlpha: modifyAlpha, stringify: stringify, lum: lum, random: function() { return 'rgb(' + Math.round(255 * Math.random()) + ',' + Math.round(255 * Math.random()) + ',' + Math.round(255 * Math.random()) + ')'; } }), arraySlice = Array.prototype.slice; function interpolate1DArray(out, p0, p1, percent) { for(var p01, len = p0.length, i = 0; i < len; i++)out[i] = (p01 = p0[i], (p1[i] - p01) * percent + p01); } function add1DArray(out, p0, p1, sign) { for(var len = p0.length, i = 0; i < len; i++)out[i] = p0[i] + p1[i] * sign; return out; } function add2DArray(out, p0, p1, sign) { for(var len = p0.length, len2 = len && p0[0].length, i = 0; i < len; i++){ out[i] || (out[i] = []); for(var j = 0; j < len2; j++)out[i][j] = p0[i][j] + p1[i][j] * sign; } return out; } function is1DArraySame(arr0, arr1) { var len = arr0.length; if (len !== arr1.length) return !1; for(var i = 0; i < len; i++)if (arr0[i] !== arr1[i]) return !1; return !0; } function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) { var v0 = (p2 - p0) * 0.5, v1 = (p3 - p1) * 0.5; return (2 * (p1 - p2) + v0 + v1) * t3 + (-3 * (p1 - p2) - 2 * v0 - v1) * t2 + v0 * t + p1; } function catmullRomInterpolate1DArray(out, p0, p1, p2, p3, t, t2, t3) { for(var len = p0.length, i = 0; i < len; i++)out[i] = catmullRomInterpolate(p0[i], p1[i], p2[i], p3[i], t, t2, t3); } function cloneValue(value) { if (isArrayLike(value)) { var len = value.length; if (isArrayLike(value[0])) { for(var ret = [], i = 0; i < len; i++)ret.push(arraySlice.call(value[i])); return ret; } return arraySlice.call(value); } return value; } function rgba2String(rgba) { return rgba[0] = Math.floor(rgba[0]), rgba[1] = Math.floor(rgba[1]), rgba[2] = Math.floor(rgba[2]), 'rgba(' + rgba.join(',') + ')'; } var tmpRgba = [ 0, 0, 0, 0 ], Track = function() { function Track(propName) { this.keyframes = [], this.maxTime = 0, this.arrDim = 0, this.interpolable = !0, this._needsSort = !1, this._isAllValueEqual = !0, this._lastFrame = 0, this._lastFramePercent = 0, this.propName = propName; } return Track.prototype.isFinished = function() { return this._finished; }, Track.prototype.setFinished = function() { this._finished = !0, this._additiveTrack && this._additiveTrack.setFinished(); }, Track.prototype.needsAnimate = function() { return !this._isAllValueEqual && this.keyframes.length >= 2 && this.interpolable; }, Track.prototype.getAdditiveTrack = function() { return this._additiveTrack; }, Track.prototype.addKeyframe = function(time, value) { time >= this.maxTime ? this.maxTime = time : this._needsSort = !0; var keyframes = this.keyframes, len = keyframes.length; if (this.interpolable) { if (isArrayLike(value)) { var value1, arrayDim = isArrayLike((value1 = value) && value1[0]) ? 2 : 1; if (len > 0 && this.arrDim !== arrayDim || 1 === arrayDim && 'number' != typeof value[0] || 2 === arrayDim && 'number' != typeof value[0][0]) { this.interpolable = !1; return; } if (len > 0) { var lastFrame = keyframes[len - 1]; this._isAllValueEqual && (1 === arrayDim && is1DArraySame(value, lastFrame.value) || (this._isAllValueEqual = !1)); } this.arrDim = arrayDim; } else { if (this.arrDim > 0) { this.interpolable = !1; return; } if ('string' == typeof value) { var colorArray = parse(value); colorArray ? (value = colorArray, this.isValueColor = !0) : this.interpolable = !1; } else if ('number' != typeof value || isNaN(value)) { this.interpolable = !1; return; } if (this._isAllValueEqual && len > 0) { var lastFrame = keyframes[len - 1]; this.isValueColor && !is1DArraySame(lastFrame.value, value) ? this._isAllValueEqual = !1 : lastFrame.value !== value && (this._isAllValueEqual = !1); } } } var kf = { time: time, value: value, percent: 0 }; return this.keyframes.push(kf), kf; }, Track.prototype.prepare = function(additiveTrack) { var kfs = this.keyframes; this._needsSort && kfs.sort(function(a, b) { return a.time - b.time; }); for(var arrDim = this.arrDim, kfsLen = kfs.length, lastKf = kfs[kfsLen - 1], i = 0; i < kfsLen; i++)kfs[i].percent = kfs[i].time / this.maxTime, arrDim > 0 && i !== kfsLen - 1 && function(val0, val1, arrDim) { var arr0 = val0; if (arr0.push && val1.push) { var arr0Len = arr0.length, arr1Len = val1.length; if (arr0Len !== arr1Len) { if (arr0Len > arr1Len) arr0.length = arr1Len; else for(var i = arr0Len; i < arr1Len; i++)arr0.push(1 === arrDim ? val1[i] : arraySlice.call(val1[i])); } for(var len2 = arr0[0] && arr0[0].length, i = 0; i < arr0.length; i++)if (1 === arrDim) isNaN(arr0[i]) && (arr0[i] = val1[i]); else for(var j = 0; j < len2; j++)isNaN(arr0[i][j]) && (arr0[i][j] = val1[i][j]); } }(kfs[i].value, lastKf.value, arrDim); if (additiveTrack && this.needsAnimate() && additiveTrack.needsAnimate() && arrDim === additiveTrack.arrDim && this.isValueColor === additiveTrack.isValueColor && !additiveTrack._finished) { this._additiveTrack = additiveTrack; for(var startValue = kfs[0].value, i = 0; i < kfsLen; i++)0 === arrDim ? this.isValueColor ? kfs[i].additiveValue = add1DArray([], kfs[i].value, startValue, -1) : kfs[i].additiveValue = kfs[i].value - startValue : 1 === arrDim ? kfs[i].additiveValue = add1DArray([], kfs[i].value, startValue, -1) : 2 === arrDim && (kfs[i].additiveValue = add2DArray([], kfs[i].value, startValue, -1)); } }, Track.prototype.step = function(target, percent) { if (!this._finished) { this._additiveTrack && this._additiveTrack._finished && (this._additiveTrack = null); var frameIdx, isAdditive = null != this._additiveTrack, valueKey = isAdditive ? 'additiveValue' : 'value', keyframes = this.keyframes, kfsNum = this.keyframes.length, propName = this.propName, arrDim = this.arrDim, isValueColor = this.isValueColor; if (percent < 0) frameIdx = 0; else if (percent < this._lastFramePercent) { var start = Math.min(this._lastFrame + 1, kfsNum - 1); for(frameIdx = start; frameIdx >= 0 && !(keyframes[frameIdx].percent <= percent); frameIdx--); frameIdx = Math.min(frameIdx, kfsNum - 2); } else { for(frameIdx = this._lastFrame; frameIdx < kfsNum && !(keyframes[frameIdx].percent > percent); frameIdx++); frameIdx = Math.min(frameIdx - 1, kfsNum - 2); } var nextFrame = keyframes[frameIdx + 1], frame = keyframes[frameIdx]; if (frame && nextFrame) { this._lastFrame = frameIdx, this._lastFramePercent = percent; var range = nextFrame.percent - frame.percent; if (0 !== range) { var w = (percent - frame.percent) / range, targetArr = isAdditive ? this._additiveValue : isValueColor ? tmpRgba : target[propName]; if ((arrDim > 0 || isValueColor) && !targetArr && (targetArr = this._additiveValue = []), this.useSpline) { var p1 = keyframes[frameIdx][valueKey], p0 = keyframes[0 === frameIdx ? frameIdx : frameIdx - 1][valueKey], p2 = keyframes[frameIdx > kfsNum - 2 ? kfsNum - 1 : frameIdx + 1][valueKey], p3 = keyframes[frameIdx > kfsNum - 3 ? kfsNum - 1 : frameIdx + 2][valueKey]; if (arrDim > 0) 1 === arrDim ? catmullRomInterpolate1DArray(targetArr, p0, p1, p2, p3, w, w * w, w * w * w) : function(out, p0, p1, p2, p3, t, t2, t3) { for(var len = p0.length, len2 = p0[0].length, i = 0; i < len; i++){ out[i] || (out[1] = []); for(var j = 0; j < len2; j++)out[i][j] = catmullRomInterpolate(p0[i][j], p1[i][j], p2[i][j], p3[i][j], t, t2, t3); } }(targetArr, p0, p1, p2, p3, w, w * w, w * w * w); else if (isValueColor) catmullRomInterpolate1DArray(targetArr, p0, p1, p2, p3, w, w * w, w * w * w), isAdditive || (target[propName] = rgba2String(targetArr)); else { var value = void 0; value = this.interpolable ? catmullRomInterpolate(p0, p1, p2, p3, w, w * w, w * w * w) : p2, isAdditive ? this._additiveValue = value : target[propName] = value; } } else if (arrDim > 0) 1 === arrDim ? interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w) : function(out, p0, p1, percent) { for(var len = p0.length, len2 = len && p0[0].length, i = 0; i < len; i++){ out[i] || (out[i] = []); for(var p01, j = 0; j < len2; j++)out[i][j] = (p01 = p0[i][j], (p1[i][j] - p01) * percent + p01); } }(targetArr, frame[valueKey], nextFrame[valueKey], w); else if (isValueColor) interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w), isAdditive || (target[propName] = rgba2String(targetArr)); else { var p01, p02, p11, value = void 0; this.interpolable ? (p01 = frame[valueKey], value = (nextFrame[valueKey] - p01) * w + p01) : (p02 = frame[valueKey], p11 = nextFrame[valueKey], value = w > 0.5 ? p11 : p02), isAdditive ? this._additiveValue = value : target[propName] = value; } isAdditive && this._addToTarget(target); } } } }, Track.prototype._addToTarget = function(target) { var arrDim = this.arrDim, propName = this.propName, additiveValue = this._additiveValue; 0 === arrDim ? this.isValueColor ? (parse(target[propName], tmpRgba), add1DArray(tmpRgba, tmpRgba, additiveValue, 1), target[propName] = rgba2String(tmpRgba)) : target[propName] = target[propName] + additiveValue : 1 === arrDim ? add1DArray(target[propName], target[propName], additiveValue, 1) : 2 === arrDim && add2DArray(target[propName], target[propName], additiveValue, 1); }, Track; }(), Animator = function() { function Animator(target, loop, additiveTo) { if (this._tracks = {}, this._trackKeys = [], this._delay = 0, this._maxTime = 0, this._paused = !1, this._started = 0, this._clip = null, this._target = target, this._loop = loop, loop && additiveTo) { logError('Can\' use additive animation on looped animation.'); return; } this._additiveAnimators = additiveTo; } return Animator.prototype.getTarget = function() { return this._target; }, Animator.prototype.changeTarget = function(target) { this._target = target; }, Animator.prototype.when = function(time, props) { return this.whenWithKeys(time, props, keys(props)); }, Animator.prototype.whenWithKeys = function(time, props, propNames) { for(var tracks = this._tracks, i = 0; i < propNames.length; i++){ var propName = propNames[i], track = tracks[propName]; if (!track) { track = tracks[propName] = new Track(propName); var initialValue = void 0, additiveTrack = this._getAdditiveTrack(propName); if (additiveTrack) { var lastFinalKf = additiveTrack.keyframes[additiveTrack.keyframes.length - 1]; initialValue = lastFinalKf && lastFinalKf.value, additiveTrack.isValueColor && initialValue && (initialValue = rgba2String(initialValue)); } else initialValue = this._target[propName]; if (null == initialValue) continue; 0 !== time && track.addKeyframe(0, cloneValue(initialValue)), this._trackKeys.push(propName); } track.addKeyframe(time, cloneValue(props[propName])); } return this._maxTime = Math.max(this._maxTime, time), this; }, Animator.prototype.pause = function() { this._clip.pause(), this._paused = !0; }, Animator.prototype.resume = function() { this._clip.resume(), this._paused = !1; }, Animator.prototype.isPaused = function() { return !!this._paused; }, Animator.prototype._doneCallback = function() { this._setTracksFinished(), this._clip = null; var doneList = this._doneList; if (doneList) for(var len = doneList.length, i = 0; i < len; i++)doneList[i].call(this); }, Animator.prototype._abortedCallback = function() { this._setTracksFinished(); var animation = this.animation, abortedList = this._abortedList; if (animation && animation.removeClip(this._clip), this._clip = null, abortedList) for(var i = 0; i < abortedList.length; i++)abortedList[i].call(this); }, Animator.prototype._setTracksFinished = function() { for(var tracks = this._tracks, tracksKeys = this._trackKeys, i = 0; i < tracksKeys.length; i++)tracks[tracksKeys[i]].setFinished(); }, Animator.prototype._getAdditiveTrack = function(trackName) { var additiveTrack, additiveAnimators = this._additiveAnimators; if (additiveAnimators) for(var i = 0; i < additiveAnimators.length; i++){ var track = additiveAnimators[i].getTrack(trackName); track && (additiveTrack = track); } return additiveTrack; }, Animator.prototype.start = function(easing, forceAnimate) { if (!(this._started > 0)) { this._started = 1; for(var self1 = this, tracks = [], i = 0; i < this._trackKeys.length; i++){ var propName = this._trackKeys[i], track = this._tracks[propName], additiveTrack = this._getAdditiveTrack(propName), kfs = track.keyframes; if (track.prepare(additiveTrack), track.needsAnimate()) tracks.push(track); else if (!track.interpolable) { var lastKf = kfs[kfs.length - 1]; lastKf && (self1._target[track.propName] = lastKf.value); } } if (tracks.length || forceAnimate) { var clip = new Clip({ life: this._maxTime, loop: this._loop, delay: this._delay, onframe: function(percent) { self1._started = 2; var additiveAnimators = self1._additiveAnimators; if (additiveAnimators) { for(var stillHasAdditiveAnimator = !1, i = 0; i < additiveAnimators.length; i++)if (additiveAnimators[i]._clip) { stillHasAdditiveAnimator = !0; break; } stillHasAdditiveAnimator || (self1._additiveAnimators = null); } for(var i = 0; i < tracks.length; i++)tracks[i].step(self1._target, percent); var onframeList = self1._onframeList; if (onframeList) for(var i = 0; i < onframeList.length; i++)onframeList[i](self1._target, percent); }, ondestroy: function() { self1._doneCallback(); } }); this._clip = clip, this.animation && this.animation.addClip(clip), easing && 'spline' !== easing && (clip.easing = easing); } else this._doneCallback(); return this; } }, Animator.prototype.stop = function(forwardToLast) { if (this._clip) { var clip = this._clip; forwardToLast && clip.onframe(1), this._abortedCallback(); } }, Animator.prototype.delay = function(time) { return this._delay = time, this; }, Animator.prototype.during = function(cb) { return cb && (this._onframeList || (this._onframeList = []), this._onframeList.push(cb)), this; }, Animator.prototype.done = function(cb) { return cb && (this._doneList || (this._doneList = []), this._doneList.push(cb)), this; }, Animator.prototype.aborted = function(cb) { return cb && (this._abortedList || (this._abortedList = []), this._abortedList.push(cb)), this; }, Animator.prototype.getClip = function() { return this._clip; }, Animator.prototype.getTrack = function(propName) { return this._tracks[propName]; }, Animator.prototype.stopTracks = function(propNames, forwardToLast) { if (!propNames.length || !this._clip) return !0; for(var tracks = this._tracks, tracksKeys = this._trackKeys, i = 0; i < propNames.length; i++){ var track = tracks[propNames[i]]; track && (forwardToLast ? track.step(this._target, 1) : 1 === this._started && track.step(this._target, 0), track.setFinished()); } for(var allAborted = !0, i = 0; i < tracksKeys.length; i++)if (!tracks[tracksKeys[i]].isFinished()) { allAborted = !1; break; } return allAborted && this._abortedCallback(), allAborted; }, Animator.prototype.saveFinalToTarget = function(target, trackKeys) { if (target) { trackKeys = trackKeys || this._trackKeys; for(var i = 0; i < trackKeys.length; i++){ var propName = trackKeys[i], track = this._tracks[propName]; if (!(!track || track.isFinished())) { var kfs = track.keyframes, lastKf = kfs[kfs.length - 1]; if (lastKf) { var val = cloneValue(lastKf.value); track.isValueColor && (val = rgba2String(val)), target[propName] = val; } } } } }, Animator.prototype.__changeFinalValue = function(finalProps, trackKeys) { trackKeys = trackKeys || keys(finalProps); for(var i = 0; i < trackKeys.length; i++){ var propName = trackKeys[i], track = this._tracks[propName]; if (track) { var kfs = track.keyframes; if (kfs.length > 1) { var lastKf = kfs.pop(); track.addKeyframe(lastKf.time, finalProps[propName]), track.prepare(track.getAdditiveTrack()); } } } }, Animator; }(), Point = function() { function Point(x, y) { this.x = x || 0, this.y = y || 0; } return Point.prototype.copy = function(other) { return this.x = other.x, this.y = other.y, this; }, Point.prototype.clone = function() { return new Point(this.x, this.y); }, Point.prototype.set = function(x, y) { return this.x = x, this.y = y, this; }, Point.prototype.equal = function(other) { return other.x === this.x && other.y === this.y; }, Point.prototype.add = function(other) { return this.x += other.x, this.y += other.y, this; }, Point.prototype.scale = function(scalar) { this.x *= scalar, this.y *= scalar; }, Point.prototype.scaleAndAdd = function(other, scalar) { this.x += other.x * scalar, this.y += other.y * scalar; }, Point.prototype.sub = function(other) { return this.x -= other.x, this.y -= other.y, this; }, Point.prototype.dot = function(other) { return this.x * other.x + this.y * other.y; }, Point.prototype.len = function() { return Math.sqrt(this.x * this.x + this.y * this.y); }, Point.prototype.lenSquare = function() { return this.x * this.x + this.y * this.y; }, Point.prototype.normalize = function() { var len = this.len(); return this.x /= len, this.y /= len, this; }, Point.prototype.distance = function(other) { var dx = this.x - other.x, dy = this.y - other.y; return Math.sqrt(dx * dx + dy * dy); }, Point.prototype.distanceSquare = function(other) { var dx = this.x - other.x, dy = this.y - other.y; return dx * dx + dy * dy; }, Point.prototype.negate = function() { return this.x = -this.x, this.y = -this.y, this; }, Point.prototype.transform = function(m) { if (m) { var x = this.x, y = this.y; return this.x = m[0] * x + m[2] * y + m[4], this.y = m[1] * x + m[3] * y + m[5], this; } }, Point.prototype.toArray = function(out) { return out[0] = this.x, out[1] = this.y, out; }, Point.prototype.fromArray = function(input) { this.x = input[0], this.y = input[1]; }, Point.set = function(p, x, y) { p.x = x, p.y = y; }, Point.copy = function(p, p2) { p.x = p2.x, p.y = p2.y; }, Point.len = function(p) { return Math.sqrt(p.x * p.x + p.y * p.y); }, Point.lenSquare = function(p) { return p.x * p.x + p.y * p.y; }, Point.dot = function(p0, p1) { return p0.x * p1.x + p0.y * p1.y; }, Point.add = function(out, p0, p1) { out.x = p0.x + p1.x, out.y = p0.y + p1.y; }, Point.sub = function(out, p0, p1) { out.x = p0.x - p1.x, out.y = p0.y - p1.y; }, Point.scale = function(out, p0, scalar) { out.x = p0.x * scalar, out.y = p0.y * scalar; }, Point.scaleAndAdd = function(out, p0, p1, scalar) { out.x = p0.x + p1.x * scalar, out.y = p0.y + p1.y * scalar; }, Point.lerp = function(out, p0, p1, t) { var onet = 1 - t; out.x = onet * p0.x + t * p1.x, out.y = onet * p0.y + t * p1.y; }, Point; }(), mathMin = Math.min, mathMax = Math.max, lt = new Point(), rb = new Point(), lb = new Point(), rt = new Point(), minTv = new Point(), maxTv = new Point(), BoundingRect = function() { function BoundingRect(x, y, width, height) { width < 0 && isFinite(width) && (x += width, width = -width), height < 0 && isFinite(height) && (y += height, height = -height), this.x = x, this.y = y, this.width = width, this.height = height; } return BoundingRect.prototype.union = function(other) { var x = mathMin(other.x, this.x), y = mathMin(other.y, this.y); isFinite(this.x) && isFinite(this.width) ? this.width = mathMax(other.x + other.width, this.x + this.width) - x : this.width = other.width, isFinite(this.y) && isFinite(this.height) ? this.height = mathMax(other.y + other.height, this.y + this.height) - y : this.height = other.height, this.x = x, this.y = y; }, BoundingRect.prototype.applyTransform = function(m) { BoundingRect.applyTransform(this, this, m); }, BoundingRect.prototype.calculateTransform = function(b) { var sx = b.width / this.width, sy = b.height / this.height, m = create$1(); return translate(m, m, [ -this.x, -this.y ]), scale$1(m, m, [ sx, sy ]), translate(m, m, [ b.x, b.y ]), m; }, BoundingRect.prototype.intersect = function(b, mtv) { if (!b) return !1; b instanceof BoundingRect || (b = BoundingRect.create(b)); var ax0 = this.x, ax1 = this.x + this.width, ay0 = this.y, ay1 = this.y + this.height, bx0 = b.x, bx1 = b.x + b.width, by0 = b.y, by1 = b.y + b.height, overlap = !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0); if (mtv) { var dMin = 1 / 0, dMax = 0, d0 = Math.abs(ax1 - bx0), d1 = Math.abs(bx1 - ax0), d2 = Math.abs(ay1 - by0), d3 = Math.abs(by1 - ay0), dx = Math.min(d0, d1), dy = Math.min(d2, d3); ax1 < bx0 || bx1 < ax0 ? dx > dMax && (dMax = dx, d0 < d1 ? Point.set(maxTv, -d0, 0) : Point.set(maxTv, d1, 0)) : dx < dMin && (dMin = dx, d0 < d1 ? Point.set(minTv, d0, 0) : Point.set(minTv, -d1, 0)), ay1 < by0 || by1 < ay0 ? dy > dMax && (dMax = dy, d2 < d3 ? Point.set(maxTv, 0, -d2) : Point.set(maxTv, 0, d3)) : dx < dMin && (dMin = dx, d2 < d3 ? Point.set(minTv, 0, d2) : Point.set(minTv, 0, -d3)); } return mtv && Point.copy(mtv, overlap ? minTv : maxTv), overlap; }, BoundingRect.prototype.contain = function(x, y) { return x >= this.x && x <= this.x + this.width && y >= this.y && y <= this.y + this.height; }, BoundingRect.prototype.clone = function() { return new BoundingRect(this.x, this.y, this.width, this.height); }, BoundingRect.prototype.copy = function(other) { BoundingRect.copy(this, other); }, BoundingRect.prototype.plain = function() { return { x: this.x, y: this.y, width: this.width, height: this.height }; }, BoundingRect.prototype.isFinite = function() { return isFinite(this.x) && isFinite(this.y) && isFinite(this.width) && isFinite(this.height); }, BoundingRect.prototype.isZero = function() { return 0 === this.width || 0 === this.height; }, BoundingRect.create = function(rect) { return new BoundingRect(rect.x, rect.y, rect.width, rect.height); }, BoundingRect.copy = function(target, source) { target.x = source.x, target.y = source.y, target.width = source.width, target.height = source.height; }, BoundingRect.applyTransform = function(target, source, m) { if (!m) { target !== source && BoundingRect.copy(target, source); return; } if (m[1] < 1e-5 && m[1] > -0.00001 && m[2] < 1e-5 && m[2] > -0.00001) { var sx = m[0], sy = m[3], tx = m[4], ty = m[5]; target.x = source.x * sx + tx, target.y = source.y * sy + ty, target.width = source.width * sx, target.height = source.height * sy, target.width < 0 && (target.x += target.width, target.width = -target.width), target.height < 0 && (target.y += target.height, target.height = -target.height); return; } lt.x = lb.x = source.x, lt.y = rt.y = source.y, rb.x = rt.x = source.x + source.width, rb.y = lb.y = source.y + source.height, lt.transform(m), rt.transform(m), rb.transform(m), lb.transform(m), target.x = mathMin(lt.x, rb.x, lb.x, rt.x), target.y = mathMin(lt.y, rb.y, lb.y, rt.y); var maxX = mathMax(lt.x, rb.x, lb.x, rt.x), maxY = mathMax(lt.y, rb.y, lb.y, rt.y); target.width = maxX - target.x, target.height = maxY - target.y; }, BoundingRect; }(), textWidthCache = {}, DEFAULT_FONT = '12px sans-serif', methods$1 = { measureText: function(text, font) { return _ctx || (_ctx = createCanvas().getContext('2d')), _cachedFont !== font && (_cachedFont = _ctx.font = font || DEFAULT_FONT), _ctx.measureText(text); } }; function getWidth(text, font) { var cacheOfFont = textWidthCache[font = font || DEFAULT_FONT]; cacheOfFont || (cacheOfFont = textWidthCache[font] = new LRU(500)); var width = cacheOfFont.get(text); return null == width && (width = methods$1.measureText(text, font).width, cacheOfFont.put(text, width)), width; } function innerGetBoundingRect(text, font, textAlign, textBaseline) { var width = getWidth(text, font), height = getLineHeight(font), x = adjustTextX(0, width, textAlign), y = adjustTextY(0, height, textBaseline); return new BoundingRect(x, y, width, height); } function getBoundingRect(text, font, textAlign, textBaseline) { var textLines = ((text || '') + '').split('\n'); if (1 === textLines.length) return innerGetBoundingRect(textLines[0], font, textAlign, textBaseline); for(var uniondRect = new BoundingRect(0, 0, 0, 0), i = 0; i < textLines.length; i++){ var rect = innerGetBoundingRect(textLines[i], font, textAlign, textBaseline); 0 === i ? uniondRect.copy(rect) : uniondRect.union(rect); } return uniondRect; } function adjustTextX(x, width, textAlign) { return 'right' === textAlign ? x -= width : 'center' === textAlign && (x -= width / 2), x; } function adjustTextY(y, height, verticalAlign) { return 'middle' === verticalAlign ? y -= height / 2 : 'bottom' === verticalAlign && (y -= height), y; } function getLineHeight(font) { return getWidth('国', font); } function parsePercent(value, maxValue) { return 'string' == typeof value ? value.lastIndexOf('%') >= 0 ? parseFloat(value) / 100 * maxValue : parseFloat(value) : value; } function calculateTextPosition(out, opts, rect) { var textPosition = opts.position || 'inside', distance = null != opts.distance ? opts.distance : 5, height = rect.height, width = rect.width, halfHeight = height / 2, x = rect.x, y = rect.y, textAlign = 'left', textVerticalAlign = 'top'; if (textPosition instanceof Array) x += parsePercent(textPosition[0], rect.width), y += parsePercent(textPosition[1], rect.height), textAlign = null, textVerticalAlign = null; else switch(textPosition){ case 'left': x -= distance, y += halfHeight, textAlign = 'right', textVerticalAlign = 'middle'; break; case 'right': x += distance + width, y += halfHeight, textVerticalAlign = 'middle'; break; case 'top': x += width / 2, y -= distance, textAlign = 'center', textVerticalAlign = 'bottom'; break; case 'bottom': x += width / 2, y += height + distance, textAlign = 'center'; break; case 'inside': x += width / 2, y += halfHeight, textAlign = 'center', textVerticalAlign = 'middle'; break; case 'insideLeft': x += distance, y += halfHeight, textVerticalAlign = 'middle'; break; case 'insideRight': x += width - distance, y += halfHeight, textAlign = 'right', textVerticalAlign = 'middle'; break; case 'insideTop': x += width / 2, y += distance, textAlign = 'center'; break; case 'insideBottom': x += width / 2, y += height - distance, textAlign = 'center', textVerticalAlign = 'bottom'; break; case 'insideTopLeft': x += distance, y += distance; break; case 'insideTopRight': x += width - distance, y += distance, textAlign = 'right'; break; case 'insideBottomLeft': x += distance, y += height - distance, textVerticalAlign = 'bottom'; break; case 'insideBottomRight': x += width - distance, y += height - distance, textAlign = 'right', textVerticalAlign = 'bottom'; } return (out = out || {}).x = x, out.y = y, out.align = textAlign, out.verticalAlign = textVerticalAlign, out; } var dpr = 1; 'undefined' != typeof window && (dpr = Math.max(window.devicePixelRatio || window.screen && window.screen.deviceXDPI / window.screen.logicalXDPI || 1, 1)); var devicePixelRatio = dpr, DARK_LABEL_COLOR = '#333', LIGHT_LABEL_COLOR = '#ccc', PRESERVED_NORMAL_STATE = '__zr_normal__', PRIMARY_STATES_KEYS = [ 'x', 'y', 'scaleX', 'scaleY', 'originX', 'originY', 'rotation', 'ignore' ], DEFAULT_ANIMATABLE_MAP = { x: !0, y: !0, scaleX: !0, scaleY: !0, originX: !0, originY: !0, rotation: !0, ignore: !1 }, tmpTextPosCalcRes = {}, tmpBoundingRect = new BoundingRect(0, 0, 0, 0), Element = function() { function Element(props) { this.id = guid(), this.animators = [], this.currentStates = [], this.states = {}, this._init(props); } return Element.prototype._init = function(props) { this.attr(props); }, Element.prototype.drift = function(dx, dy, e) { switch(this.draggable){ case 'horizontal': dy = 0; break; case 'vertical': dx = 0; } var m = this.transform; m || (m = this.transform = [ 1, 0, 0, 1, 0, 0 ]), m[4] += dx, m[5] += dy, this.decomposeTransform(), this.markRedraw(); }, Element.prototype.beforeUpdate = function() {}, Element.prototype.afterUpdate = function() {}, Element.prototype.update = function() { this.updateTransform(), this.__dirty && this.updateInnerText(); }, Element.prototype.updateInnerText = function(forceUpdate) { var textEl = this._textContent; if (textEl && (!textEl.ignore || forceUpdate)) { this.textConfig || (this.textConfig = {}); var textConfig = this.textConfig, isLocal = textConfig.local, attachedTransform = textEl.attachedTransform, textAlign = void 0, textVerticalAlign = void 0, textStyleChanged = !1; isLocal ? attachedTransform.parent = this : attachedTransform.parent = null; var innerOrigin = !1; if (attachedTransform.x = textEl.x, attachedTransform.y = textEl.y, attachedTransform.originX = textEl.originX, attachedTransform.originY = textEl.originY, attachedTransform.rotation = textEl.rotation, attachedTransform.scaleX = textEl.scaleX, attachedTransform.scaleY = textEl.scaleY, null != textConfig.position) { textConfig.layoutRect ? tmpBoundingRect.copy(textConfig.layoutRect) : tmpBoundingRect.copy(this.getBoundingRect()), isLocal || tmpBoundingRect.applyTransform(this.transform), this.calculateTextPosition ? this.calculateTextPosition(tmpTextPosCalcRes, textConfig, tmpBoundingRect) : calculateTextPosition(tmpTextPosCalcRes, textConfig, tmpBoundingRect), attachedTransform.x = tmpTextPosCalcRes.x, attachedTransform.y = tmpTextPosCalcRes.y, textAlign = tmpTextPosCalcRes.align, textVerticalAlign = tmpTextPosCalcRes.verticalAlign; var textOrigin = textConfig.origin; if (textOrigin && null != textConfig.rotation) { var relOriginX = void 0, relOriginY = void 0; 'center' === textOrigin ? (relOriginX = 0.5 * tmpBoundingRect.width, relOriginY = 0.5 * tmpBoundingRect.height) : (relOriginX = parsePercent(textOrigin[0], tmpBoundingRect.width), relOriginY = parsePercent(textOrigin[1], tmpBoundingRect.height)), innerOrigin = !0, attachedTransform.originX = -attachedTransform.x + relOriginX + (isLocal ? 0 : tmpBoundingRect.x), attachedTransform.originY = -attachedTransform.y + relOriginY + (isLocal ? 0 : tmpBoundingRect.y); } } null != textConfig.rotation && (attachedTransform.rotation = textConfig.rotation); var textOffset = textConfig.offset; textOffset && (attachedTransform.x += textOffset[0], attachedTransform.y += textOffset[1], innerOrigin || (attachedTransform.originX = -textOffset[0], attachedTransform.originY = -textOffset[1])); var isInside = null == textConfig.inside ? 'string' == typeof textConfig.position && textConfig.position.indexOf('inside') >= 0 : textConfig.inside, innerTextDefaultStyle = this._innerTextDefaultStyle || (this._innerTextDefaultStyle = {}), textFill = void 0, textStroke = void 0, autoStroke = void 0; isInside && this.canBeInsideText() ? (textFill = textConfig.insideFill, textStroke = textConfig.insideStroke, (null == textFill || 'auto' === textFill) && (textFill = this.getInsideTextFill()), (null == textStroke || 'auto' === textStroke) && (textStroke = this.getInsideTextStroke(textFill), autoStroke = !0)) : (textFill = textConfig.outsideFill, textStroke = textConfig.outsideStroke, (null == textFill || 'auto' === textFill) && (textFill = this.getOutsideFill()), (null == textStroke || 'auto' === textStroke) && (textStroke = this.getOutsideStroke(textFill), autoStroke = !0)), ((textFill = textFill || '#000') !== innerTextDefaultStyle.fill || textStroke !== innerTextDefaultStyle.stroke || autoStroke !== innerTextDefaultStyle.autoStroke || textAlign !== innerTextDefaultStyle.align || textVerticalAlign !== innerTextDefaultStyle.verticalAlign) && (textStyleChanged = !0, innerTextDefaultStyle.fill = textFill, innerTextDefaultStyle.stroke = textStroke, innerTextDefaultStyle.autoStroke = autoStroke, innerTextDefaultStyle.align = textAlign, innerTextDefaultStyle.verticalAlign = textVerticalAlign, textEl.setDefaultTextStyle(innerTextDefaultStyle)), textStyleChanged && textEl.dirtyStyle(), textEl.markRedraw(); } }, Element.prototype.canBeInsideText = function() { return !0; }, Element.prototype.getInsideTextFill = function() { return '#fff'; }, Element.prototype.getInsideTextStroke = function(textFill) { return '#000'; }, Element.prototype.getOutsideFill = function() { return this.__zr && this.__zr.isDarkMode() ? LIGHT_LABEL_COLOR : DARK_LABEL_COLOR; }, Element.prototype.getOutsideStroke = function(textFill) { var backgroundColor = this.__zr && this.__zr.getBackgroundColor(), colorArr = 'string' == typeof backgroundColor && parse(backgroundColor); colorArr || (colorArr = [ 255, 255, 255, 1 ]); for(var alpha = colorArr[3], isDark = this.__zr.isDarkMode(), i = 0; i < 3; i++)colorArr[i] = colorArr[i] * alpha + (isDark ? 0 : 255) * (1 - alpha); return colorArr[3] = 1, stringify(colorArr, 'rgba'); }, Element.prototype.traverse = function(cb, context) {}, Element.prototype.attrKV = function(key, value) { 'textConfig' === key ? this.setTextConfig(value) : 'textContent' === key ? this.setTextContent(value) : 'clipPath' === key ? this.setClipPath(value) : 'extra' === key ? (this.extra = this.extra || {}, extend(this.extra, value)) : this[key] = value; }, Element.prototype.hide = function() { this.ignore = !0, this.markRedraw(); }, Element.prototype.show = function() { this.ignore = !1, this.markRedraw(); }, Element.prototype.attr = function(keyOrObj, value) { if ('string' == typeof keyOrObj) this.attrKV(keyOrObj, value); else if (isObject(keyOrObj)) for(var keysArr = keys(keyOrObj), i = 0; i < keysArr.length; i++){ var key = keysArr[i]; this.attrKV(key, keyOrObj[key]); } return this.markRedraw(), this; }, Element.prototype.saveCurrentToNormalState = function(toState) { this._innerSaveToNormal(toState); for(var normalState = this._normalState, i = 0; i < this.animators.length; i++){ var animator = this.animators[i], fromStateTransition = animator.__fromStateTransition; if (!fromStateTransition || fromStateTransition === PRESERVED_NORMAL_STATE) { var targetName = animator.targetName, target = targetName ? normalState[targetName] : normalState; animator.saveFinalToTarget(target); } } }, Element.prototype._innerSaveToNormal = function(toState) { var normalState = this._normalState; normalState || (normalState = this._normalState = {}), toState.textConfig && !normalState.textConfig && (normalState.textConfig = this.textConfig), this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS); }, Element.prototype._savePrimaryToNormal = function(toState, normalState, primaryKeys) { for(var i = 0; i < primaryKeys.length; i++){ var key = primaryKeys[i]; null == toState[key] || key in normalState || (normalState[key] = this[key]); } }, Element.prototype.hasState = function() { return this.currentStates.length > 0; }, Element.prototype.getState = function(name) { return this.states[name]; }, Element.prototype.ensureState = function(name) { var states = this.states; return states[name] || (states[name] = {}), states[name]; }, Element.prototype.clearStates = function(noAnimation) { this.useState(PRESERVED_NORMAL_STATE, !1, noAnimation); }, Element.prototype.useState = function(stateName, keepCurrentStates, noAnimation) { var state, toNormalState = stateName === PRESERVED_NORMAL_STATE; if (this.hasState() || !toNormalState) { var currentStates = this.currentStates, animationCfg = this.stateTransition; if (!(indexOf(currentStates, stateName) >= 0) || !keepCurrentStates && 1 !== currentStates.length) { if (this.stateProxy && !toNormalState && (state = this.stateProxy(stateName)), state || (state = this.states && this.states[stateName]), !state && !toNormalState) { logError("State " + stateName + " not exists."); return; } toNormalState || this.saveCurrentToNormalState(state); var useHoverLayer = !!(state && state.hoverLayer); return useHoverLayer && this._toggleHoverLayerFlag(!0), this._applyStateObj(stateName, state, this._normalState, keepCurrentStates, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg), this._textContent && this._textContent.useState(stateName, keepCurrentStates), this._textGuide && this._textGuide.useState(stateName, keepCurrentStates), toNormalState ? (this.currentStates = [], this._normalState = {}) : keepCurrentStates ? this.currentStates.push(stateName) : this.currentStates = [ stateName ], this._updateAnimationTargets(), this.markRedraw(), !useHoverLayer && this.__inHover && (this._toggleHoverLayerFlag(!1), this.__dirty &= ~Element.REDARAW_BIT), state; } } }, Element.prototype.useStates = function(states, noAnimation) { if (states.length) { var stateObjects = [], currentStates = this.currentStates, len = states.length, notChange = len === currentStates.length; if (notChange) { for(var i = 0; i < len; i++)if (states[i] !== currentStates[i]) { notChange = !1; break; } } if (!notChange) { for(var i = 0; i < len; i++){ var stateName = states[i], stateObj = void 0; this.stateProxy && (stateObj = this.stateProxy(stateName, states)), stateObj || (stateObj = this.states[stateName]), stateObj && stateObjects.push(stateObj); } var useHoverLayer = !!(stateObjects[len - 1] && stateObjects[len - 1].hoverLayer); useHoverLayer && this._toggleHoverLayerFlag(!0); var mergedState = this._mergeStates(stateObjects), animationCfg = this.stateTransition; this.saveCurrentToNormalState(mergedState), this._applyStateObj(states.join(','), mergedState, this._normalState, !1, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg), this._textContent && this._textContent.useStates(states), this._textGuide && this._textGuide.useStates(states), this._updateAnimationTargets(), this.currentStates = states.slice(), this.markRedraw(), !useHoverLayer && this.__inHover && (this._toggleHoverLayerFlag(!1), this.__dirty &= ~Element.REDARAW_BIT); } } else this.clearStates(); }, Element.prototype._updateAnimationTargets = function() { for(var i = 0; i < this.animators.length; i++){ var animator = this.animators[i]; animator.targetName && animator.changeTarget(this[animator.targetName]); } }, Element.prototype.removeState = function(state) { var idx = indexOf(this.currentStates, state); if (idx >= 0) { var currentStates = this.currentStates.slice(); currentStates.splice(idx, 1), this.useStates(currentStates); } }, Element.prototype.replaceState = function(oldState, newState, forceAdd) { var currentStates = this.currentStates.slice(), idx = indexOf(currentStates, oldState), newStateExists = indexOf(currentStates, newState) >= 0; idx >= 0 ? newStateExists ? currentStates.splice(idx, 1) : currentStates[idx] = newState : forceAdd && !newStateExists && currentStates.push(newState), this.useStates(currentStates); }, Element.prototype.toggleState = function(state, enable) { enable ? this.useState(state, !0) : this.removeState(state); }, Element.prototype._mergeStates = function(states) { for(var mergedTextConfig, mergedState = {}, i = 0; i < states.length; i++){ var state = states[i]; extend(mergedState, state), state.textConfig && extend(mergedTextConfig = mergedTextConfig || {}, state.textConfig); } return mergedTextConfig && (mergedState.textConfig = mergedTextConfig), mergedState; }, Element.prototype._applyStateObj = function(stateName, state, normalState, keepCurrentStates, transition, animationCfg) { var needsRestoreToNormal = !(state && keepCurrentStates); state && state.textConfig ? (this.textConfig = extend({}, keepCurrentStates ? this.textConfig : normalState.textConfig), extend(this.textConfig, state.textConfig)) : needsRestoreToNormal && normalState.textConfig && (this.textConfig = normalState.textConfig); for(var transitionTarget = {}, hasTransition = !1, i = 0; i < PRIMARY_STATES_KEYS.length; i++){ var key = PRIMARY_STATES_KEYS[i], propNeedsTransition = transition && DEFAULT_ANIMATABLE_MAP[key]; state && null != state[key] ? propNeedsTransition ? (hasTransition = !0, transitionTarget[key] = state[key]) : this[key] = state[key] : needsRestoreToNormal && null != normalState[key] && (propNeedsTransition ? (hasTransition = !0, transitionTarget[key] = normalState[key]) : this[key] = normalState[key]); } if (!transition) for(var i = 0; i < this.animators.length; i++){ var animator = this.animators[i], targetName = animator.targetName; animator.__changeFinalValue(targetName ? (state || normalState)[targetName] : state || normalState); } hasTransition && this._transitionState(stateName, transitionTarget, animationCfg); }, Element.prototype._attachComponent = function(componentEl) { if (componentEl.__zr && !componentEl.__hostTarget) throw Error('Text element has been added to zrender.'); if (componentEl === this) throw Error('Recursive component attachment.'); var zr = this.__zr; zr && componentEl.addSelfToZr(zr), componentEl.__zr = zr, componentEl.__hostTarget = this; }, Element.prototype._detachComponent = function(componentEl) { componentEl.__zr && componentEl.removeSelfFromZr(componentEl.__zr), componentEl.__zr = null, componentEl.__hostTarget = null; }, Element.prototype.getClipPath = function() { return this._clipPath; }, Element.prototype.setClipPath = function(clipPath) { this._clipPath && this._clipPath !== clipPath && this.removeClipPath(), this._attachComponent(clipPath), this._clipPath = clipPath, this.markRedraw(); }, Element.prototype.removeClipPath = function() { var clipPath = this._clipPath; clipPath && (this._detachComponent(clipPath), this._clipPath = null, this.markRedraw()); }, Element.prototype.getTextContent = function() { return this._textContent; }, Element.prototype.setTextContent = function(textEl) { var previousTextContent = this._textContent; if (previousTextContent !== textEl) { if (previousTextContent && previousTextContent !== textEl && this.removeTextContent(), textEl.__zr && !textEl.__hostTarget) throw Error('Text element has been added to zrender.'); textEl.attachedTransform = new Transformable(), this._attachComponent(textEl), this._textContent = textEl, this.markRedraw(); } }, Element.prototype.setTextConfig = function(cfg) { this.textConfig || (this.textConfig = {}), extend(this.textConfig, cfg), this.markRedraw(); }, Element.prototype.removeTextConfig = function() { this.textConfig = null, this.markRedraw(); }, Element.prototype.removeTextContent = function() { var textEl = this._textContent; textEl && (textEl.attachedTransform = null, this._detachComponent(textEl), this._textContent = null, this._innerTextDefaultStyle = null, this.markRedraw()); }, Element.prototype.getTextGuideLine = function() { return this._textGuide; }, Element.prototype.setTextGuideLine = function(guideLine) { this._textGuide && this._textGuide !== guideLine && this.removeTextGuideLine(), this._attachComponent(guideLine), this._textGuide = guideLine, this.markRedraw(); }, Element.prototype.removeTextGuideLine = function() { var textGuide = this._textGuide; textGuide && (this._detachComponent(textGuide), this._textGuide = null, this.markRedraw()); }, Element.prototype.markRedraw = function() { this.__dirty |= Element.REDARAW_BIT; var zr = this.__zr; zr && (this.__inHover ? zr.refreshHover() : zr.refresh()), this.__hostTarget && this.__hostTarget.markRedraw(); }, Element.prototype.dirty = function() { this.markRedraw(); }, Element.prototype._toggleHoverLayerFlag = function(inHover) { this.__inHover = inHover; var textContent = this._textContent, textGuide = this._textGuide; textContent && (textContent.__inHover = inHover), textGuide && (textGuide.__inHover = inHover); }, Element.prototype.addSelfToZr = function(zr) { this.__zr = zr; var animators = this.animators; if (animators) for(var i = 0; i < animators.length; i++)zr.animation.addAnimator(animators[i]); this._clipPath && this._clipPath.addSelfToZr(zr), this._textContent && this._textContent.addSelfToZr(zr), this._textGuide && this._textGuide.addSelfToZr(zr); }, Element.prototype.removeSelfFromZr = function(zr) { this.__zr = null; var animators = this.animators; if (animators) for(var i = 0; i < animators.length; i++)zr.animation.removeAnimator(animators[i]); this._clipPath && this._clipPath.removeSelfFromZr(zr), this._textContent && this._textContent.removeSelfFromZr(zr), this._textGuide && this._textGuide.removeSelfFromZr(zr); }, Element.prototype.animate = function(key, loop) { var target = key ? this[key] : this; if (!target) { logError('Property "' + key + '" is not existed in element ' + this.id); return; } var animator = new Animator(target, loop); return this.addAnimator(animator, key), animator; }, Element.prototype.addAnimator = function(animator, key) { var zr = this.__zr, el = this; animator.during(function() { el.updateDuringAnimation(key); }).done(function() { var animators = el.animators, idx = indexOf(animators, animator); idx >= 0 && animators.splice(idx, 1); }), this.animators.push(animator), zr && zr.animation.addAnimator(animator), zr && zr.wakeUp(); }, Element.prototype.updateDuringAnimation = function(key) { this.markRedraw(); }, Element.prototype.stopAnimation = function(scope, forwardToLast) { for(var animators = this.animators, len = animators.length, leftAnimators = [], i = 0; i < len; i++){ var animator = animators[i]; scope && scope !== animator.scope ? leftAnimators.push(animator) : animator.stop(forwardToLast); } return this.animators = leftAnimators, this; }, Element.prototype.animateTo = function(target, cfg, animationProps) { animateTo(this, target, cfg, animationProps); }, Element.prototype.animateFrom = function(target, cfg, animationProps) { animateTo(this, target, cfg, animationProps, !0); }, Element.prototype._transitionState = function(stateName, target, cfg, animationProps) { for(var animators = animateTo(this, target, cfg, animationProps), i = 0; i < animators.length; i++)animators[i].__fromStateTransition = stateName; }, Element.prototype.getBoundingRect = function() { return null; }, Element.prototype.getPaintRect = function() { return null; }, Element.REDARAW_BIT = 1, Element.initDefaultProps = function() { var elProto = Element.prototype; elProto.type = 'element', elProto.name = '', elProto.ignore = !1, elProto.silent = !1, elProto.isGroup = !1, elProto.draggable = !1, elProto.dragging = !1, elProto.ignoreClip = !1, elProto.__inHover = !1, elProto.__dirty = Element.REDARAW_BIT; var logs = {}; function logDeprecatedError(key, xKey, yKey) { logs[key + xKey + yKey] || (console.warn("DEPRECATED: '" + key + "' has been deprecated. use '" + xKey + "', '" + yKey + "' instead"), logs[key + xKey + yKey] = !0); } function createLegacyProperty(key, privateKey, xKey, yKey) { Object.defineProperty(elProto, key, { get: function() { return logDeprecatedError(key, xKey, yKey), this[privateKey] || enhanceArray(this, this[privateKey] = []), this[privateKey]; }, set: function(pos) { logDeprecatedError(key, xKey, yKey), this[xKey] = pos[0], this[yKey] = pos[1], this[privateKey] = pos, enhanceArray(this, pos); } }); function enhanceArray(self1, pos) { Object.defineProperty(pos, 0, { get: function() { return self1[xKey]; }, set: function(val) { self1[xKey] = val; } }), Object.defineProperty(pos, 1, { get: function() { return self1[yKey]; }, set: function(val) { self1[yKey] = val; } }); } } Object.defineProperty && (!env1.browser.ie || env1.browser.version > 8) && (createLegacyProperty('position', '_legacyPos', 'x', 'y'), createLegacyProperty('scale', '_legacyScale', 'scaleX', 'scaleY'), createLegacyProperty('origin', '_legacyOrigin', 'originX', 'originY')); }(), Element; }(); function animateTo(animatable, target, cfg, animationProps, reverse) { var animators = []; !function animateToShallow(animatable, topKey, source, target, cfg, animationProps, animators, reverse) { for(var animatableKeys = [], changedKeys = [], targetKeys = keys(target), duration = cfg.duration, delay = cfg.delay, additive = cfg.additive, setToFinal = cfg.setToFinal, animateAll = !isObject(animationProps), k = 0; k < targetKeys.length; k++){ var innerKey = targetKeys[k]; if (null != source[innerKey] && null != target[innerKey] && (animateAll || animationProps[innerKey])) { if (isObject(target[innerKey]) && !isArrayLike(target[innerKey])) { if (topKey) { reverse || (source[innerKey] = target[innerKey], animatable.updateDuringAnimation(topKey)); continue; } animateToShallow(animatable, innerKey, source[innerKey], target[innerKey], cfg, animationProps && animationProps[innerKey], animators, reverse); } else animatableKeys.push(innerKey), changedKeys.push(innerKey); } else reverse || (source[innerKey] = target[innerKey], animatable.updateDuringAnimation(topKey), changedKeys.push(innerKey)); } var keyLen = animatableKeys.length; if (keyLen > 0 || cfg.force && !animators.length) { for(var existsAnimators = animatable.animators, existsAnimatorsOnSameTarget = [], i = 0; i < existsAnimators.length; i++)existsAnimators[i].targetName === topKey && existsAnimatorsOnSameTarget.push(existsAnimators[i]); if (!additive && existsAnimatorsOnSameTarget.length) { for(var i = 0; i < existsAnimatorsOnSameTarget.length; i++)if (existsAnimatorsOnSameTarget[i].stopTracks(changedKeys)) { var idx = indexOf(existsAnimators, existsAnimatorsOnSameTarget[i]); existsAnimators.splice(idx, 1); } } var revertedSource = void 0, reversedTarget = void 0, sourceClone = void 0; if (reverse) { reversedTarget = {}, setToFinal && (revertedSource = {}); for(var i = 0; i < keyLen; i++){ var innerKey = animatableKeys[i]; reversedTarget[innerKey] = source[innerKey], setToFinal ? revertedSource[innerKey] = target[innerKey] : source[innerKey] = target[innerKey]; } } else if (setToFinal) { sourceClone = {}; for(var i = 0; i < keyLen; i++){ var innerKey = animatableKeys[i]; sourceClone[innerKey] = cloneValue(source[innerKey]), function(target, source, key) { if (isArrayLike(source[key])) { if (isArrayLike(target[key]) || (target[key] = []), isTypedArray(source[key])) { var len = source[key].length; target[key].length !== len && (target[key] = new source[key].constructor(len), copyArrShallow(target[key], source[key], len)); } else { var sourceArr = source[key], targetArr = target[key], len0 = sourceArr.length; if (isArrayLike(sourceArr[0])) for(var len1 = sourceArr[0].length, i = 0; i < len0; i++)targetArr[i] ? copyArrShallow(targetArr[i], sourceArr[i], len1) : targetArr[i] = Array.prototype.slice.call(sourceArr[i]); else copyArrShallow(targetArr, sourceArr, len0); targetArr.length = sourceArr.length; } } else target[key] = source[key]; }(source, target, innerKey); } } var animator = new Animator(source, !1, additive ? existsAnimatorsOnSameTarget : null); animator.targetName = topKey, cfg.scope && (animator.scope = cfg.scope), setToFinal && revertedSource && animator.whenWithKeys(0, revertedSource, animatableKeys), sourceClone && animator.whenWithKeys(0, sourceClone, animatableKeys), animator.whenWithKeys(null == duration ? 500 : duration, reverse ? reversedTarget : target, animatableKeys).delay(delay || 0), animatable.addAnimator(animator, topKey), animators.push(animator); } }(animatable, '', animatable, target, cfg = cfg || {}, animationProps, animators, reverse); var finishCount = animators.length, doneHappened = !1, cfgDone = cfg.done, cfgAborted = cfg.aborted, doneCb = function() { doneHappened = !0, --finishCount <= 0 && (doneHappened ? cfgDone && cfgDone() : cfgAborted && cfgAborted()); }, abortedCb = function() { --finishCount <= 0 && (doneHappened ? cfgDone && cfgDone() : cfgAborted && cfgAborted()); }; !finishCount && cfgDone && cfgDone(), animators.length > 0 && cfg.during && animators[0].during(function(target, percent) { cfg.during(percent); }); for(var i = 0; i < animators.length; i++){ var animator = animators[i]; doneCb && animator.done(doneCb), abortedCb && animator.aborted(abortedCb), animator.start(cfg.easing, cfg.force); } return animators; } function copyArrShallow(source, target, len) { for(var i = 0; i < len; i++)source[i] = target[i]; } function makeAscendingRun(array, lo, hi, compare) { var runHi = lo + 1; if (runHi === hi) return 1; if (0 > compare(array[runHi++], array[lo])) { for(; runHi < hi && 0 > compare(array[runHi], array[runHi - 1]);)runHi++; !function(array, lo, hi) { for(hi--; lo < hi;){ var t = array[lo]; array[lo++] = array[hi], array[hi--] = t; } }(array, lo, runHi); } else for(; runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0;)runHi++; return runHi - lo; } function binaryInsertionSort(array, lo, hi, start, compare) { for(start === lo && start++; start < hi; start++){ for(var mid, pivot = array[start], left = lo, right = start; left < right;)0 > compare(pivot, array[mid = left + right >>> 1]) ? right = mid : left = mid + 1; var n = start - left; switch(n){ case 3: array[left + 3] = array[left + 2]; case 2: array[left + 2] = array[left + 1]; case 1: array[left + 1] = array[left]; break; default: for(; n > 0;)array[left + n] = array[left + n - 1], n--; } array[left] = pivot; } } function gallopLeft(value, array, start, length, hint, compare) { var lastOffset = 0, maxOffset = 0, offset = 1; if (compare(value, array[start + hint]) > 0) { for(maxOffset = length - hint; offset < maxOffset && compare(value, array[start + hint + offset]) > 0;)lastOffset = offset, (offset = (offset << 1) + 1) <= 0 && (offset = maxOffset); offset > maxOffset && (offset = maxOffset), lastOffset += hint, offset += hint; } else { for(maxOffset = hint + 1; offset < maxOffset && 0 >= compare(value, array[start + hint - offset]);)lastOffset = offset, (offset = (offset << 1) + 1) <= 0 && (offset = maxOffset); offset > maxOffset && (offset = maxOffset); var tmp = lastOffset; lastOffset = hint - offset, offset = hint - tmp; } for(lastOffset++; lastOffset < offset;){ var m = lastOffset + (offset - lastOffset >>> 1); compare(value, array[start + m]) > 0 ? lastOffset = m + 1 : offset = m; } return offset; } function gallopRight(value, array, start, length, hint, compare) { var lastOffset = 0, maxOffset = 0, offset = 1; if (0 > compare(value, array[start + hint])) { for(maxOffset = hint + 1; offset < maxOffset && 0 > compare(value, array[start + hint - offset]);)lastOffset = offset, (offset = (offset << 1) + 1) <= 0 && (offset = maxOffset); offset > maxOffset && (offset = maxOffset); var tmp = lastOffset; lastOffset = hint - offset, offset = hint - tmp; } else { for(maxOffset = length - hint; offset < maxOffset && compare(value, array[start + hint + offset]) >= 0;)lastOffset = offset, (offset = (offset << 1) + 1) <= 0 && (offset = maxOffset); offset > maxOffset && (offset = maxOffset), lastOffset += hint, offset += hint; } for(lastOffset++; lastOffset < offset;){ var m = lastOffset + (offset - lastOffset >>> 1); 0 > compare(value, array[start + m]) ? offset = m : lastOffset = m + 1; } return offset; } function sort(array, compare, lo, hi) { lo || (lo = 0), hi || (hi = array.length); var remaining = hi - lo; if (!(remaining < 2)) { var runLength = 0; if (remaining < 32) { runLength = makeAscendingRun(array, lo, hi, compare), binaryInsertionSort(array, lo, hi, lo + runLength, compare); return; } var ts = function(array, compare) { var runStart, runLength, minGallop = 7, stackSize = 0; array.length; var tmp = []; function mergeAt(i) { var start1 = runStart[i], length1 = runLength[i], start2 = runStart[i + 1], length2 = runLength[i + 1]; runLength[i] = length1 + length2, i === stackSize - 3 && (runStart[i + 1] = runStart[i + 2], runLength[i + 1] = runLength[i + 2]), stackSize--; var k = gallopRight(array[start2], array, start1, length1, 0, compare); start1 += k, 0 != (length1 -= k) && 0 !== (length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare)) && (length1 <= length2 ? function(start1, length1, start2, length2) { var count1, count2, exit, i = 0; for(i = 0; i < length1; i++)tmp[i] = array[start1 + i]; var cursor1 = 0, cursor2 = start2, dest = start1; if (array[dest++] = array[cursor2++], 0 == --length2) { for(i = 0; i < length1; i++)array[dest + i] = tmp[cursor1 + i]; return; } if (1 === length1) { for(i = 0; i < length2; i++)array[dest + i] = array[cursor2 + i]; array[dest + length2] = tmp[cursor1]; return; } for(var _minGallop = minGallop;;){ count1 = 0, count2 = 0, exit = !1; do if (0 > compare(array[cursor2], tmp[cursor1])) { if (array[dest++] = array[cursor2++], count2++, count1 = 0, 0 == --length2) { exit = !0; break; } } else if (array[dest++] = tmp[cursor1++], count1++, count2 = 0, 1 == --length1) { exit = !0; break; } while ((count1 | count2) < _minGallop) if (exit) break; do { if (0 !== (count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare))) { for(i = 0; i < count1; i++)array[dest + i] = tmp[cursor1 + i]; if (dest += count1, cursor1 += count1, (length1 -= count1) <= 1) { exit = !0; break; } } if (array[dest++] = array[cursor2++], 0 == --length2) { exit = !0; break; } if (0 !== (count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare))) { for(i = 0; i < count2; i++)array[dest + i] = array[cursor2 + i]; if (dest += count2, cursor2 += count2, 0 == (length2 -= count2)) { exit = !0; break; } } if (array[dest++] = tmp[cursor1++], 1 == --length1) { exit = !0; break; } _minGallop--; }while (count1 >= 7 || count2 >= 7) if (exit) break; _minGallop < 0 && (_minGallop = 0), _minGallop += 2; } if ((minGallop = _minGallop) < 1 && (minGallop = 1), 1 === length1) { for(i = 0; i < length2; i++)array[dest + i] = array[cursor2 + i]; array[dest + length2] = tmp[cursor1]; } else if (0 === length1) throw Error(); else for(i = 0; i < length1; i++)array[dest + i] = tmp[cursor1 + i]; }(start1, length1, start2, length2) : function(start1, length1, start2, length2) { var i = 0; for(i = 0; i < length2; i++)tmp[i] = array[start2 + i]; var cursor1 = start1 + length1 - 1, cursor2 = length2 - 1, dest = start2 + length2 - 1, customCursor = 0, customDest = 0; if (array[dest--] = array[cursor1--], 0 == --length1) { for(i = 0, customCursor = dest - (length2 - 1); i < length2; i++)array[customCursor + i] = tmp[i]; return; } if (1 === length2) { for(dest -= length1, cursor1 -= length1, customDest = dest + 1, customCursor = cursor1 + 1, i = length1 - 1; i >= 0; i--)array[customDest + i] = array[customCursor + i]; array[dest] = tmp[cursor2]; return; } for(var _minGallop = minGallop;;){ var count1 = 0, count2 = 0, exit = !1; do if (0 > compare(tmp[cursor2], array[cursor1])) { if (array[dest--] = array[cursor1--], count1++, count2 = 0, 0 == --length1) { exit = !0; break; } } else if (array[dest--] = tmp[cursor2--], count2++, count1 = 0, 1 == --length2) { exit = !0; break; } while ((count1 | count2) < _minGallop) if (exit) break; do { if (0 != (count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare))) { for(dest -= count1, cursor1 -= count1, length1 -= count1, customDest = dest + 1, customCursor = cursor1 + 1, i = count1 - 1; i >= 0; i--)array[customDest + i] = array[customCursor + i]; if (0 === length1) { exit = !0; break; } } if (array[dest--] = tmp[cursor2--], 1 == --length2) { exit = !0; break; } if (0 != (count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare))) { for(dest -= count2, cursor2 -= count2, length2 -= count2, customDest = dest + 1, customCursor = cursor2 + 1, i = 0; i < count2; i++)array[customDest + i] = tmp[customCursor + i]; if (length2 <= 1) { exit = !0; break; } } if (array[dest--] = array[cursor1--], 0 == --length1) { exit = !0; break; } _minGallop--; }while (count1 >= 7 || count2 >= 7) if (exit) break; _minGallop < 0 && (_minGallop = 0), _minGallop += 2; } if ((minGallop = _minGallop) < 1 && (minGallop = 1), 1 === length2) { for(dest -= length1, cursor1 -= length1, customDest = dest + 1, customCursor = cursor1 + 1, i = length1 - 1; i >= 0; i--)array[customDest + i] = array[customCursor + i]; array[dest] = tmp[cursor2]; } else if (0 === length2) throw Error(); else for(i = 0, customCursor = dest - (length2 - 1); i < length2; i++)array[customCursor + i] = tmp[i]; }(start1, length1, start2, length2)); } return runStart = [], runLength = [], { mergeRuns: function() { for(; stackSize > 1;){ var n = stackSize - 2; if (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1] || n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1]) runLength[n - 1] < runLength[n + 1] && n--; else if (runLength[n] > runLength[n + 1]) break; mergeAt(n); } }, forceMergeRuns: function() { for(; stackSize > 1;){ var n = stackSize - 2; n > 0 && runLength[n - 1] < runLength[n + 1] && n--, mergeAt(n); } }, pushRun: function(_runStart, _runLength) { runStart[stackSize] = _runStart, runLength[stackSize] = _runLength, stackSize += 1; } }; }(array, compare), minRun = function(n) { for(var r = 0; n >= 32;)r |= 1 & n, n >>= 1; return n + r; }(remaining); do { if ((runLength = makeAscendingRun(array, lo, hi, compare)) < minRun) { var force = remaining; force > minRun && (force = minRun), binaryInsertionSort(array, lo, lo + force, lo + runLength, compare), runLength = force; } ts.pushRun(lo, runLength), ts.mergeRuns(), remaining -= runLength, lo += runLength; }while (0 !== remaining) ts.forceMergeRuns(); } } mixin(Element, Eventful), mixin(Element, Transformable); var invalidZErrorLogged = !1; function logInvalidZError() { invalidZErrorLogged || (invalidZErrorLogged = !0, console.warn('z / z2 / zlevel of displayable is invalid, which may cause unexpected errors')); } function shapeCompareFunc(a, b) { return a.zlevel === b.zlevel ? a.z === b.z ? a.z2 - b.z2 : a.z - b.z : a.zlevel - b.zlevel; } var Storage = function() { function Storage() { this._roots = [], this._displayList = [], this._displayListLen = 0, this.displayableSortFunc = shapeCompareFunc; } return Storage.prototype.traverse = function(cb, context) { for(var i = 0; i < this._roots.length; i++)this._roots[i].traverse(cb, context); }, Storage.prototype.getDisplayList = function(update, includeIgnore) { includeIgnore = includeIgnore || !1; var displayList = this._displayList; return (update || !displayList.length) && this.updateDisplayList(includeIgnore), displayList; }, Storage.prototype.updateDisplayList = function(includeIgnore) { this._displayListLen = 0; for(var roots = this._roots, displayList = this._displayList, i = 0, len = roots.length; i < len; i++)this._updateAndAddDisplayable(roots[i], null, includeIgnore); displayList.length = this._displayListLen, env1.canvasSupported && sort(displayList, shapeCompareFunc); }, Storage.prototype._updateAndAddDisplayable = function(el, clipPaths, includeIgnore) { if (!el.ignore || includeIgnore) { el.beforeUpdate(), el.update(), el.afterUpdate(); var userSetClipPath = el.getClipPath(); if (el.ignoreClip) clipPaths = null; else if (userSetClipPath) { clipPaths = clipPaths ? clipPaths.slice() : []; for(var currentClipPath = userSetClipPath, parentClipPath = el; currentClipPath;)currentClipPath.parent = parentClipPath, currentClipPath.updateTransform(), clipPaths.push(currentClipPath), parentClipPath = currentClipPath, currentClipPath = currentClipPath.getClipPath(); } if (el.childrenRef) { for(var children = el.childrenRef(), i = 0; i < children.length; i++){ var child = children[i]; el.__dirty && (child.__dirty |= Element.REDARAW_BIT), this._updateAndAddDisplayable(child, clipPaths, includeIgnore); } el.__dirty = 0; } else { var disp = el; clipPaths && clipPaths.length ? disp.__clipPaths = clipPaths : disp.__clipPaths && disp.__clipPaths.length > 0 && (disp.__clipPaths = []), isNaN(disp.z) && (logInvalidZError(), disp.z = 0), isNaN(disp.z2) && (logInvalidZError(), disp.z2 = 0), isNaN(disp.zlevel) && (logInvalidZError(), disp.zlevel = 0), this._displayList[this._displayListLen++] = disp; } var decalEl = el.getDecalElement && el.getDecalElement(); decalEl && this._updateAndAddDisplayable(decalEl, clipPaths, includeIgnore); var textGuide = el.getTextGuideLine(); textGuide && this._updateAndAddDisplayable(textGuide, clipPaths, includeIgnore); var textEl = el.getTextContent(); textEl && this._updateAndAddDisplayable(textEl, clipPaths, includeIgnore); } }, Storage.prototype.addRoot = function(el) { el.__zr && el.__zr.storage === this || this._roots.push(el); }, Storage.prototype.delRoot = function(el) { if (el instanceof Array) { for(var i = 0, l = el.length; i < l; i++)this.delRoot(el[i]); return; } var idx = indexOf(this._roots, el); idx >= 0 && this._roots.splice(idx, 1); }, Storage.prototype.delAllRoots = function() { this._roots = [], this._displayList = [], this._displayListLen = 0; }, Storage.prototype.getRoots = function() { return this._roots; }, Storage.prototype.dispose = function() { this._displayList = null, this._roots = null; }, Storage; }(); requestAnimationFrame = 'undefined' != typeof window && (window.requestAnimationFrame && window.requestAnimationFrame.bind(window) || window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window) || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame) || function(func) { return setTimeout(func, 16); }; var Animation = function(_super) { function Animation(opts) { var _this = _super.call(this) || this; return _this._running = !1, _this._time = 0, _this._pausedTime = 0, _this._pauseStart = 0, _this._paused = !1, opts = opts || {}, _this.stage = opts.stage || {}, _this.onframe = opts.onframe || function() {}, _this; } return __extends(Animation, _super), Animation.prototype.addClip = function(clip) { clip.animation && this.removeClip(clip), this._clipsHead ? (this._clipsTail.next = clip, clip.prev = this._clipsTail, clip.next = null, this._clipsTail = clip) : this._clipsHead = this._clipsTail = clip, clip.animation = this; }, Animation.prototype.addAnimator = function(animator) { animator.animation = this; var clip = animator.getClip(); clip && this.addClip(clip); }, Animation.prototype.removeClip = function(clip) { if (clip.animation) { var prev = clip.prev, next = clip.next; prev ? prev.next = next : this._clipsHead = next, next ? next.prev = prev : this._clipsTail = prev, clip.next = clip.prev = clip.animation = null; } }, Animation.prototype.removeAnimator = function(animator) { var clip = animator.getClip(); clip && this.removeClip(clip), animator.animation = null; }, Animation.prototype.update = function(notTriggerFrameAndStageUpdate) { for(var time = new Date().getTime() - this._pausedTime, delta = time - this._time, clip = this._clipsHead; clip;){ var nextClip = clip.next; clip.step(time, delta) && (clip.ondestroy && clip.ondestroy(), this.removeClip(clip)), clip = nextClip; } this._time = time, !notTriggerFrameAndStageUpdate && (this.onframe(delta), this.trigger('frame', delta), this.stage.update && this.stage.update()); }, Animation.prototype._startLoop = function() { var self1 = this; this._running = !0, requestAnimationFrame(function step() { self1._running && (requestAnimationFrame(step), self1._paused || self1.update()); }); }, Animation.prototype.start = function() { this._running || (this._time = new Date().getTime(), this._pausedTime = 0, this._startLoop()); }, Animation.prototype.stop = function() { this._running = !1; }, Animation.prototype.pause = function() { this._paused || (this._pauseStart = new Date().getTime(), this._paused = !0); }, Animation.prototype.resume = function() { this._paused && (this._pausedTime += new Date().getTime() - this._pauseStart, this._paused = !1); }, Animation.prototype.clear = function() { for(var clip = this._clipsHead; clip;){ var nextClip = clip.next; clip.prev = clip.next = clip.animation = null, clip = nextClip; } this._clipsHead = this._clipsTail = null; }, Animation.prototype.isFinished = function() { return null == this._clipsHead; }, Animation.prototype.animate = function(target, options) { options = options || {}, this.start(); var animator = new Animator(target, options.loop); return this.addAnimator(animator), animator; }, Animation; }(Eventful), globalEventSupported = env1.domSupported, localNativeListenerNames = (pointerEventNameMap = { pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1 }, pointerHandlerNames = map(mouseHandlerNames = [ 'click', 'dblclick', 'mousewheel', 'wheel', 'mouseout', 'mouseup', 'mousedown', 'mousemove', 'contextmenu' ], function(name) { var nm = name.replace('mouse', 'pointer'); return pointerEventNameMap.hasOwnProperty(nm) ? nm : name; }), { mouse: mouseHandlerNames, touch: [ 'touchstart', 'touchend', 'touchmove' ], pointer: pointerHandlerNames }), globalNativeListenerNames = { mouse: [ 'mousemove', 'mouseup' ], pointer: [ 'pointermove', 'pointerup' ] }, wheelEventSupported = !1; function isPointerFromTouch(event) { var pointerType = event.pointerType; return 'pen' === pointerType || 'touch' === pointerType; } function markTouch(event) { event && (event.zrByTouch = !0); } function isLocalEl(instance, el) { for(var elTmp = el, isLocal = !1; elTmp && 9 !== elTmp.nodeType && !(isLocal = elTmp.domBelongToZr || elTmp !== el && elTmp === instance.painterRoot);)elTmp = elTmp.parentNode; return isLocal; } var FakeGlobalEvent = function(instance, event) { this.stopPropagation = noop, this.stopImmediatePropagation = noop, this.preventDefault = noop, this.type = event.type, this.target = this.currentTarget = instance.dom, this.pointerType = event.pointerType, this.clientX = event.clientX, this.clientY = event.clientY; }, localDOMHandlers = { mousedown: function(event) { event = normalizeEvent(this.dom, event), this.__mayPointerCapture = [ event.zrX, event.zrY ], this.trigger('mousedown', event); }, mousemove: function(event) { event = normalizeEvent(this.dom, event); var downPoint = this.__mayPointerCapture; downPoint && (event.zrX !== downPoint[0] || event.zrY !== downPoint[1]) && this.__togglePointerCapture(!0), this.trigger('mousemove', event); }, mouseup: function(event) { event = normalizeEvent(this.dom, event), this.__togglePointerCapture(!1), this.trigger('mouseup', event); }, mouseout: function(event) { isLocalEl(this, (event = normalizeEvent(this.dom, event)).toElement || event.relatedTarget) || (this.__pointerCapturing && (event.zrEventControl = 'no_globalout'), this.trigger('mouseout', event)); }, wheel: function(event) { wheelEventSupported = !0, event = normalizeEvent(this.dom, event), this.trigger('mousewheel', event); }, mousewheel: function(event) { wheelEventSupported || (event = normalizeEvent(this.dom, event), this.trigger('mousewheel', event)); }, touchstart: function(event) { markTouch(event = normalizeEvent(this.dom, event)), this.__lastTouchMoment = new Date(), this.handler.processGesture(event, 'start'), localDOMHandlers.mousemove.call(this, event), localDOMHandlers.mousedown.call(this, event); }, touchmove: function(event) { markTouch(event = normalizeEvent(this.dom, event)), this.handler.processGesture(event, 'change'), localDOMHandlers.mousemove.call(this, event); }, touchend: function(event) { markTouch(event = normalizeEvent(this.dom, event)), this.handler.processGesture(event, 'end'), localDOMHandlers.mouseup.call(this, event), +new Date() - +this.__lastTouchMoment < 300 && localDOMHandlers.click.call(this, event); }, pointerdown: function(event) { localDOMHandlers.mousedown.call(this, event); }, pointermove: function(event) { isPointerFromTouch(event) || localDOMHandlers.mousemove.call(this, event); }, pointerup: function(event) { localDOMHandlers.mouseup.call(this, event); }, pointerout: function(event) { isPointerFromTouch(event) || localDOMHandlers.mouseout.call(this, event); } }; each([ 'click', 'dblclick', 'contextmenu' ], function(name) { localDOMHandlers[name] = function(event) { event = normalizeEvent(this.dom, event), this.trigger(name, event); }; }); var globalDOMHandlers = { pointermove: function(event) { isPointerFromTouch(event) || globalDOMHandlers.mousemove.call(this, event); }, pointerup: function(event) { globalDOMHandlers.mouseup.call(this, event); }, mousemove: function(event) { this.trigger('mousemove', event); }, mouseup: function(event) { var pointerCaptureReleasing = this.__pointerCapturing; this.__togglePointerCapture(!1), this.trigger('mouseup', event), pointerCaptureReleasing && (event.zrEventControl = 'only_globalout', this.trigger('mouseout', event)); } }; function mountSingleDOMEventListener(scope, nativeEventName, listener, opt) { scope.mounted[nativeEventName] = listener, scope.listenerOpts[nativeEventName] = opt, addEventListener(scope.domTarget, nativeEventName, listener, opt); } function unmountDOMEventListeners(scope) { var el, name, handler, opt, mounted = scope.mounted; for(var nativeEventName in mounted)mounted.hasOwnProperty(nativeEventName) && (el = scope.domTarget, name = nativeEventName, handler = mounted[nativeEventName], opt = scope.listenerOpts[nativeEventName], isDomLevel2 ? el.removeEventListener(name, handler, opt) : el.detachEvent('on' + name, handler)); scope.mounted = {}; } var DOMHandlerScope = function(domTarget, domHandlers) { this.mounted = {}, this.listenerOpts = {}, this.touching = !1, this.domTarget = domTarget, this.domHandlers = domHandlers; }, HandlerDomProxy = function(_super) { function HandlerDomProxy(dom, painterRoot) { var scope, domHandlers, _this = _super.call(this) || this; return _this.__pointerCapturing = !1, _this.dom = dom, _this.painterRoot = painterRoot, _this._localHandlerScope = new DOMHandlerScope(dom, localDOMHandlers), globalEventSupported && (_this._globalHandlerScope = new DOMHandlerScope(document, globalDOMHandlers)), domHandlers = (scope = _this._localHandlerScope).domHandlers, env1.pointerEventsSupported ? each(localNativeListenerNames.pointer, function(nativeEventName) { mountSingleDOMEventListener(scope, nativeEventName, function(event) { domHandlers[nativeEventName].call(_this, event); }); }) : (env1.touchEventsSupported && each(localNativeListenerNames.touch, function(nativeEventName) { mountSingleDOMEventListener(scope, nativeEventName, function(event) { var scope1; domHandlers[nativeEventName].call(_this, event), (scope1 = scope).touching = !0, null != scope1.touchTimer && (clearTimeout(scope1.touchTimer), scope1.touchTimer = null), scope1.touchTimer = setTimeout(function() { scope1.touching = !1, scope1.touchTimer = null; }, 700); }); }), each(localNativeListenerNames.mouse, function(nativeEventName) { mountSingleDOMEventListener(scope, nativeEventName, function(event) { event = getNativeEvent(event), scope.touching || domHandlers[nativeEventName].call(_this, event); }); })), _this; } return __extends(HandlerDomProxy, _super), HandlerDomProxy.prototype.dispose = function() { unmountDOMEventListeners(this._localHandlerScope), globalEventSupported && unmountDOMEventListeners(this._globalHandlerScope); }, HandlerDomProxy.prototype.setCursor = function(cursorStyle) { this.dom.style && (this.dom.style.cursor = cursorStyle || 'default'); }, HandlerDomProxy.prototype.__togglePointerCapture = function(isPointerCapturing) { if (this.__mayPointerCapture = null, globalEventSupported && +this.__pointerCapturing ^ +isPointerCapturing) { this.__pointerCapturing = isPointerCapturing; var globalHandlerScope = this._globalHandlerScope; isPointerCapturing ? function(instance, scope) { env1.pointerEventsSupported ? each(globalNativeListenerNames.pointer, mount) : env1.touchEventsSupported || each(globalNativeListenerNames.mouse, mount); function mount(nativeEventName) { mountSingleDOMEventListener(scope, nativeEventName, function(event) { if (event = getNativeEvent(event), !isLocalEl(instance, event.target)) { var event1; event1 = event, event = normalizeEvent(instance.dom, new FakeGlobalEvent(instance, event1), !0), scope.domHandlers[nativeEventName].call(instance, event); } }, { capture: !0 }); } }(this, globalHandlerScope) : unmountDOMEventListeners(globalHandlerScope); } }, HandlerDomProxy; }(Eventful), Group = function(_super) { function Group(opts) { var _this = _super.call(this) || this; return _this.isGroup = !0, _this._children = [], _this.attr(opts), _this; } return __extends(Group, _super), Group.prototype.childrenRef = function() { return this._children; }, Group.prototype.children = function() { return this._children.slice(); }, Group.prototype.childAt = function(idx) { return this._children[idx]; }, Group.prototype.childOfName = function(name) { for(var children = this._children, i = 0; i < children.length; i++)if (children[i].name === name) return children[i]; }, Group.prototype.childCount = function() { return this._children.length; }, Group.prototype.add = function(child) { if (child && (child !== this && child.parent !== this && (this._children.push(child), this._doAdd(child)), child.__hostTarget)) throw 'This elemenet has been used as an attachment'; return this; }, Group.prototype.addBefore = function(child, nextSibling) { if (child && child !== this && child.parent !== this && nextSibling && nextSibling.parent === this) { var children = this._children, idx = children.indexOf(nextSibling); idx >= 0 && (children.splice(idx, 0, child), this._doAdd(child)); } return this; }, Group.prototype.replaceAt = function(child, index) { var children = this._children, old = children[index]; if (child && child !== this && child.parent !== this && child !== old) { children[index] = child, old.parent = null; var zr = this.__zr; zr && old.removeSelfFromZr(zr), this._doAdd(child); } return this; }, Group.prototype._doAdd = function(child) { child.parent && child.parent.remove(child), child.parent = this; var zr = this.__zr; zr && zr !== child.__zr && child.addSelfToZr(zr), zr && zr.refresh(); }, Group.prototype.remove = function(child) { var zr = this.__zr, children = this._children, idx = indexOf(children, child); return idx < 0 || (children.splice(idx, 1), child.parent = null, zr && child.removeSelfFromZr(zr), zr && zr.refresh()), this; }, Group.prototype.removeAll = function() { for(var children = this._children, zr = this.__zr, i = 0; i < children.length; i++){ var child = children[i]; zr && child.removeSelfFromZr(zr), child.parent = null; } return children.length = 0, this; }, Group.prototype.eachChild = function(cb, context) { for(var children = this._children, i = 0; i < children.length; i++){ var child = children[i]; cb.call(context, child, i); } return this; }, Group.prototype.traverse = function(cb, context) { for(var i = 0; i < this._children.length; i++){ var child = this._children[i], stopped = cb.call(context, child); child.isGroup && !stopped && child.traverse(cb, context); } return this; }, Group.prototype.addSelfToZr = function(zr) { _super.prototype.addSelfToZr.call(this, zr); for(var i = 0; i < this._children.length; i++)this._children[i].addSelfToZr(zr); }, Group.prototype.removeSelfFromZr = function(zr) { _super.prototype.removeSelfFromZr.call(this, zr); for(var i = 0; i < this._children.length; i++)this._children[i].removeSelfFromZr(zr); }, Group.prototype.getBoundingRect = function(includeChildren) { for(var tmpRect = new BoundingRect(0, 0, 0, 0), children = includeChildren || this._children, tmpMat = [], rect = null, i = 0; i < children.length; i++){ var child = children[i]; if (!child.ignore && !child.invisible) { var childRect = child.getBoundingRect(), transform = child.getLocalTransform(tmpMat); transform ? (BoundingRect.applyTransform(tmpRect, childRect, transform), (rect = rect || tmpRect.clone()).union(tmpRect)) : (rect = rect || childRect.clone()).union(childRect); } } return rect || tmpRect; }, Group; }(Element); Group.prototype.type = 'group'; var useVML = !env1.canvasSupported, painterCtors = {}, instances = {}, ZRender = function() { function ZRender(id, dom, opts) { var _this = this; this._sleepAfterStill = 10, this._stillFrameAccum = 0, this._needsRefresh = !0, this._needsRefreshHover = !0, this._darkMode = !1, opts = opts || {}, this.dom = dom, this.id = id; var storage = new Storage(), rendererType = opts.renderer || 'canvas'; if (useVML) throw Error('IE8 support has been dropped since 5.0'); if (painterCtors[rendererType] || (rendererType = keys(painterCtors)[0]), !painterCtors[rendererType]) throw Error("Renderer '" + rendererType + "' is not imported. Please import it first."); opts.useDirtyRect = null != opts.useDirtyRect && opts.useDirtyRect; var painter = new painterCtors[rendererType](dom, storage, opts, id); this.storage = storage, this.painter = painter; var handerProxy = env1.node || env1.worker ? null : new HandlerDomProxy(painter.getViewportRoot(), painter.root); this.handler = new Handler(storage, painter, handerProxy, painter.root), this.animation = new Animation({ stage: { update: function() { return _this._flush(!0); } } }), this.animation.start(); } return ZRender.prototype.add = function(el) { el && (this.storage.addRoot(el), el.addSelfToZr(this), this.refresh()); }, ZRender.prototype.remove = function(el) { el && (this.storage.delRoot(el), el.removeSelfFromZr(this), this.refresh()); }, ZRender.prototype.configLayer = function(zLevel, config) { this.painter.configLayer && this.painter.configLayer(zLevel, config), this.refresh(); }, ZRender.prototype.setBackgroundColor = function(backgroundColor) { this.painter.setBackgroundColor && this.painter.setBackgroundColor(backgroundColor), this.refresh(), this._backgroundColor = backgroundColor, this._darkMode = function(backgroundColor) { if (!backgroundColor) return !1; if ('string' == typeof backgroundColor) return 0.4 > lum(backgroundColor, 1); if (backgroundColor.colorStops) { for(var colorStops = backgroundColor.colorStops, totalLum = 0, len = colorStops.length, i = 0; i < len; i++)totalLum += lum(colorStops[i].color, 1); return (totalLum /= len) < 0.4; } return !1; }(backgroundColor); }, ZRender.prototype.getBackgroundColor = function() { return this._backgroundColor; }, ZRender.prototype.setDarkMode = function(darkMode) { this._darkMode = darkMode; }, ZRender.prototype.isDarkMode = function() { return this._darkMode; }, ZRender.prototype.refreshImmediately = function(fromInside) { fromInside || this.animation.update(!0), this._needsRefresh = !1, this.painter.refresh(), this._needsRefresh = !1; }, ZRender.prototype.refresh = function() { this._needsRefresh = !0, this.animation.start(); }, ZRender.prototype.flush = function() { this._flush(!1); }, ZRender.prototype._flush = function(fromInside) { var triggerRendered, start = new Date().getTime(); this._needsRefresh && (triggerRendered = !0, this.refreshImmediately(fromInside)), this._needsRefreshHover && (triggerRendered = !0, this.refreshHoverImmediately()); var end = new Date().getTime(); triggerRendered ? (this._stillFrameAccum = 0, this.trigger('rendered', { elapsedTime: end - start })) : this._sleepAfterStill > 0 && (this._stillFrameAccum++, this._stillFrameAccum > this._sleepAfterStill && this.animation.stop()); }, ZRender.prototype.setSleepAfterStill = function(stillFramesCount) { this._sleepAfterStill = stillFramesCount; }, ZRender.prototype.wakeUp = function() { this.animation.start(), this._stillFrameAccum = 0; }, ZRender.prototype.addHover = function(el) {}, ZRender.prototype.removeHover = function(el) {}, ZRender.prototype.clearHover = function() {}, ZRender.prototype.refreshHover = function() { this._needsRefreshHover = !0; }, ZRender.prototype.refreshHoverImmediately = function() { this._needsRefreshHover = !1, this.painter.refreshHover && 'canvas' === this.painter.getType() && this.painter.refreshHover(); }, ZRender.prototype.resize = function(opts) { opts = opts || {}, this.painter.resize(opts.width, opts.height), this.handler.resize(); }, ZRender.prototype.clearAnimation = function() { this.animation.clear(); }, ZRender.prototype.getWidth = function() { return this.painter.getWidth(); }, ZRender.prototype.getHeight = function() { return this.painter.getHeight(); }, ZRender.prototype.pathToImage = function(e, dpr) { if (this.painter.pathToImage) return this.painter.pathToImage(e, dpr); }, ZRender.prototype.setCursorStyle = function(cursorStyle) { this.handler.setCursorStyle(cursorStyle); }, ZRender.prototype.findHover = function(x, y) { return this.handler.findHover(x, y); }, ZRender.prototype.on = function(eventName, eventHandler, context) { return this.handler.on(eventName, eventHandler, context), this; }, ZRender.prototype.off = function(eventName, eventHandler) { this.handler.off(eventName, eventHandler); }, ZRender.prototype.trigger = function(eventName, event) { this.handler.trigger(eventName, event); }, ZRender.prototype.clear = function() { for(var roots = this.storage.getRoots(), i = 0; i < roots.length; i++)roots[i] instanceof Group && roots[i].removeSelfFromZr(this); this.storage.delAllRoots(), this.painter.clear(); }, ZRender.prototype.dispose = function() { this.animation.stop(), this.clear(), this.storage.dispose(), this.painter.dispose(), this.handler.dispose(), this.animation = this.storage = this.painter = this.handler = null, delete instances[this.id]; }, ZRender; }(); function init(dom, opts) { var zr = new ZRender(guid(), dom, opts); return instances[zr.id] = zr, zr; } var zrender = Object.freeze({ __proto__: null, init: init, dispose: function(zr) { zr.dispose(); }, disposeAll: function() { for(var key in instances)instances.hasOwnProperty(key) && instances[key].dispose(); instances = {}; }, getInstance: function(id) { return instances[id]; }, registerPainter: function(name, Ctor) { painterCtors[name] = Ctor; }, version: '5.1.0' }); function linearMap(val, domain, range, clamp) { var subDomain = domain[1] - domain[0], subRange = range[1] - range[0]; if (0 === subDomain) return 0 === subRange ? range[0] : (range[0] + range[1]) / 2; if (clamp) { if (subDomain > 0) { if (val <= domain[0]) return range[0]; if (val >= domain[1]) return range[1]; } else { if (val >= domain[0]) return range[0]; if (val <= domain[1]) return range[1]; } } else { if (val === domain[0]) return range[0]; if (val === domain[1]) return range[1]; } return (val - domain[0]) / subDomain * subRange + range[0]; } function parsePercent$1(percent, all) { switch(percent){ case 'center': case 'middle': percent = '50%'; break; case 'left': case 'top': percent = '0%'; break; case 'right': case 'bottom': percent = '100%'; } return 'string' == typeof percent ? percent.replace(/^\s+|\s+$/g, '').match(/%$/) ? parseFloat(percent) / 100 * all : parseFloat(percent) : null == percent ? NaN : +percent; } function round(x, precision, returnStr) { return null == precision && (precision = 10), precision = Math.min(Math.max(0, precision), 20), x = (+x).toFixed(precision), returnStr ? x : +x; } function asc(arr) { return arr.sort(function(a, b) { return a - b; }), arr; } function getPrecision(val) { if (isNaN(val = +val)) return 0; for(var e = 1, count = 0; Math.round(val * e) / e !== val;)e *= 10, count++; return count; } function getPrecisionSafe(val) { var str = val.toString(), 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 getPixelPrecision(dataExtent, pixelExtent) { var log = Math.log, LN10 = Math.LN10, precision = Math.min(Math.max(-Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10) + Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10), 0), 20); return isFinite(precision) ? precision : 20; } function getPercentWithPrecision(valueList, idx, precision) { if (!valueList[idx]) return 0; var sum = reduce(valueList, function(acc, val) { return acc + (isNaN(val) ? 0 : val); }, 0); if (0 === sum) return 0; for(var digits = Math.pow(10, precision), votesPerQuota = map(valueList, function(val) { return (isNaN(val) ? 0 : val) / sum * digits * 100; }), targetSeats = 100 * digits, seats = map(votesPerQuota, function(votes) { return Math.floor(votes); }), currentSum = reduce(seats, function(acc, val) { return acc + val; }, 0), remainder = map(votesPerQuota, function(votes, idx) { return votes - seats[idx]; }); currentSum < targetSeats;){ for(var max = Number.NEGATIVE_INFINITY, maxId = null, i = 0, len = remainder.length; i < len; ++i)remainder[i] > max && (max = remainder[i], maxId = i); ++seats[maxId], remainder[maxId] = 0, ++currentSum; } return seats[idx] / digits; } function remRadian(radian) { var pi2 = 2 * Math.PI; return (radian % pi2 + pi2) % pi2; } function isRadianAroundZero(val) { return val > -0.0001 && val < 1e-4; } var TIME_REG = /^(?:(\d{4})(?:[-\/](\d{1,2})(?:[-\/](\d{1,2})(?:[T ](\d{1,2})(?::(\d{1,2})(?::(\d{1,2})(?:[.,](\d+))?)?)?(Z|[\+\-]\d\d:?\d\d)?)?)?)?)?$/; function parseDate(value) { if (value instanceof Date) return value; if ('string' == typeof value) { var match = TIME_REG.exec(value); if (!match) return new Date(NaN); if (!match[8]) return new Date(+match[1], +(match[2] || 1) - 1, +match[3] || 1, +match[4] || 0, +(match[5] || 0), +match[6] || 0, +match[7] || 0); var hour = +match[4] || 0; return 'Z' !== match[8].toUpperCase() && (hour -= +match[8].slice(0, 3)), new Date(Date.UTC(+match[1], +(match[2] || 1) - 1, +match[3] || 1, hour, +(match[5] || 0), +match[6] || 0, +match[7] || 0)); } return new Date(null == value ? NaN : Math.round(value)); } function quantity(val) { return Math.pow(10, quantityExponent(val)); } function quantityExponent(val) { if (0 === val) return 0; var exp = Math.floor(Math.log(val) / Math.LN10); return val / Math.pow(10, exp) >= 10 && exp++, exp; } function nice(val, round) { var exponent = quantityExponent(val), exp10 = Math.pow(10, exponent), f = val / exp10; return val = (round ? f < 1.5 ? 1 : f < 2.5 ? 2 : f < 4 ? 3 : f < 7 ? 5 : 10 : f < 1 ? 1 : f < 2 ? 2 : f < 3 ? 3 : f < 5 ? 5 : 10) * exp10, exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val; } function quantile(ascArr, p) { var H = (ascArr.length - 1) * p + 1, h = Math.floor(H), v = +ascArr[h - 1], e = H - h; return e ? v + e * (ascArr[h] - v) : v; } function reformIntervals(list) { list.sort(function(a, b) { return !function littleThan(a, b, lg) { return a.interval[lg] < b.interval[lg] || a.interval[lg] === b.interval[lg] && (a.close[lg] - b.close[lg] == (lg ? -1 : 1) || !lg && littleThan(a, b, 1)); }(a, b, 0) ? 1 : -1; }); for(var curr = -1 / 0, currClose = 1, i = 0; i < list.length;){ for(var interval = list[i].interval, close_1 = list[i].close, lg = 0; lg < 2; lg++)interval[lg] <= curr && (interval[lg] = curr, close_1[lg] = lg ? 1 : 1 - currClose), curr = interval[lg], currClose = close_1[lg]; interval[0] === interval[1] && close_1[0] * close_1[1] != 1 ? list.splice(i, 1) : i++; } return list; } function numericToNumber(val) { var valFloat = parseFloat(val); return valFloat == val && (0 !== valFloat || 'string' != typeof val || 0 >= val.indexOf('x')) ? valFloat : NaN; } function isNumeric(val) { return !isNaN(numericToNumber(val)); } function getRandomIdBase() { return Math.round(9 * Math.random()); } function getLeastCommonMultiple(a, b) { return null == a ? b : null == b ? a : a * b / function getGreatestCommonDividor(a, b) { return 0 === b ? a : getGreatestCommonDividor(b, a % b); }(a, b); } var ECHARTS_PREFIX = '[ECharts] ', storedLogs = {}, hasConsole = 'undefined' != typeof console && console.warn && console.log; function warn(str) { hasConsole && console.warn(ECHARTS_PREFIX + str); } function error(str) { hasConsole && console.error(ECHARTS_PREFIX + str); } function deprecateLog(str) { !storedLogs[str] && hasConsole && (storedLogs[str] = !0, console.warn(ECHARTS_PREFIX + 'DEPRECATED: ' + str)); } function deprecateReplaceLog(oldOpt, newOpt, scope) { deprecateLog((scope ? "[" + scope + "]" : '') + oldOpt + " is deprecated, use " + newOpt + " instead."); } function makePrintable() { for(var hintInfo = [], _i = 0; _i < arguments.length; _i++)hintInfo[_i] = arguments[_i]; var makePrintableStringIfPossible_1 = function(val) { return void 0 === val ? 'undefined' : val === 1 / 0 ? 'Infinity' : val === -1 / 0 ? '-Infinity' : val != val ? 'NaN' : val instanceof Date ? 'Date(' + val.toISOString() + ')' : isFunction(val) ? 'function () { ... }' : isRegExp(val) ? val + '' : null; }; return map(hintInfo, function(arg) { if (isString(arg)) return arg; var printableStr = makePrintableStringIfPossible_1(arg); if (null != printableStr) return printableStr; if ('undefined' == typeof JSON || !JSON.stringify) return '?'; try { return JSON.stringify(arg, function(n, val) { var printableStr = makePrintableStringIfPossible_1(val); return null == printableStr ? val : printableStr; }); } catch (err) { return '?'; } }).join(' '); } function throwError(msg) { throw Error(msg); } var DUMMY_COMPONENT_NAME_PREFIX = 'series\0', INTERNAL_COMPONENT_ID_PREFIX = '\0_ec_\0'; function normalizeToArray(value) { return value instanceof Array ? value : null == value ? [] : [ value ]; } function defaultEmphasis(opt, key, subOpts) { if (opt) { opt[key] = opt[key] || {}, opt.emphasis = opt.emphasis || {}, opt.emphasis[key] = opt.emphasis[key] || {}; for(var i = 0, len = subOpts.length; i < len; i++){ var subOptName = subOpts[i]; !opt.emphasis[key].hasOwnProperty(subOptName) && opt[key].hasOwnProperty(subOptName) && (opt.emphasis[key][subOptName] = opt[key][subOptName]); } } } var TEXT_STYLE_OPTIONS = [ 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth', 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY', 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY', 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding' ]; function getDataItemValue(dataItem) { return !isObject(dataItem) || isArray(dataItem) || dataItem instanceof Date ? dataItem : dataItem.value; } function mappingToExists(existings, newCmptOptions, mode) { var existings1, newCmptOptions1, result, newCmptOptions2, idMap, isNormalMergeMode = 'normalMerge' === mode, isReplaceMergeMode = 'replaceMerge' === mode; existings = existings || [], newCmptOptions = (newCmptOptions || []).slice(); var existingIdIdxMap = createHashMap(); each(newCmptOptions, function(cmptOption, index) { var idOrName, idOrName1; if (!isObject(cmptOption)) { newCmptOptions[index] = null; return; } null == cmptOption.id || isStringSafe(idOrName = cmptOption.id) || isNumeric(idOrName) || warnInvalidateIdOrName(cmptOption.id), null == cmptOption.name || isStringSafe(idOrName1 = cmptOption.name) || isNumeric(idOrName1) || warnInvalidateIdOrName(cmptOption.name); }); var result1 = function(existings, existingIdIdxMap, mode) { var result = []; if ('replaceAll' === mode) return result; for(var index = 0; index < existings.length; index++){ var existing = existings[index]; existing && null != existing.id && existingIdIdxMap.set(existing.id, index), result.push({ existing: 'replaceMerge' === mode || isComponentIdInternal(existing) ? null : existing, newOption: null, keyInfo: null, brandNew: null }); } return result; }(existings, existingIdIdxMap, mode); return (isNormalMergeMode || isReplaceMergeMode) && (existings1 = existings, each(newCmptOptions1 = newCmptOptions, function(cmptOption, index) { if (cmptOption && null != cmptOption.id) { var optionId = makeComparableKey(cmptOption.id), existingIdx = existingIdIdxMap.get(optionId); if (null != existingIdx) { var resultItem = result1[existingIdx]; assert(!resultItem.newOption, 'Duplicated option on id "' + optionId + '".'), resultItem.newOption = cmptOption, resultItem.existing = existings1[existingIdx], newCmptOptions1[index] = null; } } })), isNormalMergeMode && (result = result1, each(newCmptOptions2 = newCmptOptions, function(cmptOption, index) { if (cmptOption && null != cmptOption.name) for(var i = 0; i < result.length; i++){ var existing = result[i].existing; if (!result[i].newOption && existing && (null == existing.id || null == cmptOption.id) && !isComponentIdInternal(cmptOption) && !isComponentIdInternal(existing) && keyExistAndEqual('name', existing, cmptOption)) { result[i].newOption = cmptOption, newCmptOptions2[index] = null; return; } } })), isNormalMergeMode || isReplaceMergeMode ? each(newCmptOptions, function(cmptOption) { if (cmptOption) { for(var resultItem, nextIdx = 0; (resultItem = result1[nextIdx]) && (resultItem.newOption || isComponentIdInternal(resultItem.existing) || resultItem.existing && null != cmptOption.id && !keyExistAndEqual('id', cmptOption, resultItem.existing));)nextIdx++; resultItem ? (resultItem.newOption = cmptOption, resultItem.brandNew = isReplaceMergeMode) : result1.push({ newOption: cmptOption, brandNew: isReplaceMergeMode, existing: null, keyInfo: null }), nextIdx++; } }) : 'replaceAll' === mode && each(newCmptOptions, function(cmptOption) { result1.push({ newOption: cmptOption, brandNew: !0, existing: null, keyInfo: null }); }), idMap = createHashMap(), each(result1, function(item) { var existing = item.existing; existing && idMap.set(existing.id, item); }), each(result1, function(item) { var opt = item.newOption; assert(!opt || null == opt.id || !idMap.get(opt.id) || idMap.get(opt.id) === item, 'id duplicates: ' + (opt && opt.id)), opt && null != opt.id && idMap.set(opt.id, item), item.keyInfo || (item.keyInfo = {}); }), each(result1, function(item, index) { var existing = item.existing, opt = item.newOption, keyInfo = item.keyInfo; if (isObject(opt)) { if (keyInfo.name = null != opt.name ? makeComparableKey(opt.name) : existing ? existing.name : DUMMY_COMPONENT_NAME_PREFIX + index, existing) keyInfo.id = makeComparableKey(existing.id); else if (null != opt.id) keyInfo.id = makeComparableKey(opt.id); else { var idNum = 0; do keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++; while (idMap.get(keyInfo.id)) } idMap.set(keyInfo.id, item); } }), result1; } function keyExistAndEqual(attr, obj1, obj2) { var key1 = convertOptionIdName(obj1[attr], null), key2 = convertOptionIdName(obj2[attr], null); return null != key1 && null != key2 && key1 === key2; } function makeComparableKey(val) { if (null == val) throw Error(); return convertOptionIdName(val, ''); } function convertOptionIdName(idOrName, defaultValue) { if (null == idOrName) return defaultValue; var type = typeof idOrName; return 'string' === type ? idOrName : 'number' === type || isStringSafe(idOrName) ? idOrName + '' : defaultValue; } function warnInvalidateIdOrName(idOrName) { warn('`' + idOrName + '` is invalid id or name. Must be a string or number.'); } function isNameSpecified(componentModel) { var name = componentModel.name; return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX)); } function isComponentIdInternal(cmptOption) { return cmptOption && null != cmptOption.id && 0 === makeComparableKey(cmptOption.id).indexOf(INTERNAL_COMPONENT_ID_PREFIX); } function queryDataIndex(data, payload) { return null != payload.dataIndexInside ? payload.dataIndexInside : null != payload.dataIndex ? isArray(payload.dataIndex) ? map(payload.dataIndex, function(value) { return data.indexOfRawIndex(value); }) : data.indexOfRawIndex(payload.dataIndex) : null != payload.name ? isArray(payload.name) ? map(payload.name, function(value) { return data.indexOfName(value); }) : data.indexOfName(payload.name) : void 0; } function makeInner() { var key = '__ec_inner_' + innerUniqueIndex++; return function(hostObj) { return hostObj[key] || (hostObj[key] = {}); }; } var innerUniqueIndex = getRandomIdBase(); function parseFinder(ecModel, finderInput, opt) { var _a = preParseFinder(finderInput, opt), mainTypeSpecified = _a.mainTypeSpecified, queryOptionMap = _a.queryOptionMap, result = _a.others, defaultMainType = opt ? opt.defaultMainType : null; return !mainTypeSpecified && defaultMainType && queryOptionMap.set(defaultMainType, {}), queryOptionMap.each(function(queryOption, mainType) { var queryResult = queryReferringComponents(ecModel, mainType, queryOption, { useDefault: defaultMainType === mainType, enableAll: !opt || null == opt.enableAll || opt.enableAll, enableNone: !opt || null == opt.enableNone || opt.enableNone }); result[mainType + 'Models'] = queryResult.models, result[mainType + 'Model'] = queryResult.models[0]; }), result; } function preParseFinder(finderInput, opt) { if (isString(finderInput)) { var finder, obj = {}; obj[finderInput + 'Index'] = 0, finder = obj; } else finder = finderInput; var queryOptionMap = createHashMap(), others = {}, mainTypeSpecified = !1; return each(finder, function(value, key) { if ('dataIndex' === key || 'dataIndexInside' === key) { others[key] = value; return; } var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [], mainType = parsedKey[1], queryType = (parsedKey[2] || '').toLowerCase(); !mainType || !queryType || opt && opt.includeMainTypes && 0 > indexOf(opt.includeMainTypes, mainType) || (mainTypeSpecified = mainTypeSpecified || !!mainType, (queryOptionMap.get(mainType) || queryOptionMap.set(mainType, {}))[queryType] = value); }), { mainTypeSpecified: mainTypeSpecified, queryOptionMap: queryOptionMap, others: others }; } var SINGLE_REFERRING = { useDefault: !0, enableAll: !1, enableNone: !1 }, MULTIPLE_REFERRING = { useDefault: !1, enableAll: !0, enableNone: !0 }; function queryReferringComponents(ecModel, mainType, userOption, opt) { opt = opt || SINGLE_REFERRING; var indexOption = userOption.index, idOption = userOption.id, nameOption = userOption.name, result = { models: null, specified: null != indexOption || null != idOption || null != nameOption }; if (!result.specified) { var firstCmpt = void 0; return result.models = opt.useDefault && (firstCmpt = ecModel.getComponent(mainType)) ? [ firstCmpt ] : [], result; } return 'none' === indexOption || !1 === indexOption ? (assert(opt.enableNone, '`"none"` or `false` is not a valid value on index option.'), result.models = [], result) : ('all' === indexOption && (assert(opt.enableAll, '`"all"` is not a valid value on index option.'), indexOption = idOption = nameOption = null), result.models = ecModel.queryComponents({ mainType: mainType, index: indexOption, id: idOption, name: nameOption }), result); } function setAttribute(dom, key, value) { dom.setAttribute ? dom.setAttribute(key, value) : dom[key] = value; } function groupData(array, getKey) { var buckets = createHashMap(), keys = []; return each(array, function(item) { var key = getKey(item); (buckets.get(key) || (keys.push(key), buckets.set(key, []))).push(item); }), { keys: keys, buckets: buckets }; } function interpolateRawValues(data, precision, sourceValue, targetValue, percent) { var isAutoPrecision = null == precision || 'auto' === precision; if (null == targetValue) return targetValue; if ('number' == typeof targetValue) { var p0, value = (targetValue - (p0 = sourceValue || 0)) * percent + p0; return round(value, isAutoPrecision ? Math.max(getPrecisionSafe(sourceValue || 0), getPrecisionSafe(targetValue)) : precision); } if ('string' == typeof targetValue) return percent < 1 ? sourceValue : targetValue; for(var interpolated = [], length_1 = Math.max(sourceValue ? sourceValue.length : 0, targetValue.length), i = 0; i < length_1; ++i)if ('ordinal' === data.getDimensionInfo(i).type) interpolated[i] = (percent < 1 && sourceValue ? sourceValue : targetValue)[i]; else { var leftVal = sourceValue && sourceValue[i] ? sourceValue[i] : 0, rightVal = targetValue[i], value = (rightVal - leftVal) * percent + leftVal; interpolated[i] = round(value, isAutoPrecision ? Math.max(getPrecisionSafe(leftVal), getPrecisionSafe(rightVal)) : precision); } return interpolated; } var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___', IS_EXTENDED_CLASS = '___EC__EXTENDED_CLASS___'; function parseClassType(componentType) { var ret = { main: '', sub: '' }; if (componentType) { var typeArr = componentType.split('.'); ret.main = typeArr[0] || '', ret.sub = typeArr[1] || ''; } return ret; } function enableClassExtend(rootClz, mandatoryMethods) { rootClz.$constructor = rootClz, rootClz.extend = function(proto) { each(mandatoryMethods, function(method) { proto[method] || console.warn('Method `' + method + '` should be implemented' + (proto.type ? ' in ' + proto.type : '') + '.'); }); var superClass = this; function ExtendedClass() { for(var args = [], _i = 0; _i < arguments.length; _i++)args[_i] = arguments[_i]; if (proto.$constructor) proto.$constructor.apply(this, arguments); else { if ('function' == typeof superClass && /^class\s/.test(Function.prototype.toString.call(superClass))) return createObject(ExtendedClass.prototype, new (superClass.bind.apply(superClass, __spreadArrays([ void 0 ], args)))()); superClass.apply(this, arguments); } } return ExtendedClass[IS_EXTENDED_CLASS] = !0, extend(ExtendedClass.prototype, proto), ExtendedClass.extend = this.extend, ExtendedClass.superCall = superCall, ExtendedClass.superApply = superApply, inherits(ExtendedClass, this), ExtendedClass.superClass = superClass, ExtendedClass; }; } function mountExtend(SubClz, SupperClz) { SubClz.extend = SupperClz.extend; } var classBase = Math.round(10 * Math.random()); function superCall(context, methodName) { for(var args = [], _i = 2; _i < arguments.length; _i++)args[_i - 2] = arguments[_i]; return this.superClass.prototype[methodName].apply(context, args); } function superApply(context, methodName, args) { return this.superClass.prototype[methodName].apply(context, args); } function enableClassManagement(target) { var storage = {}; target.registerClass = function(clz) { var componentFullType = clz.type || clz.prototype.type; if (componentFullType) { assert(/^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentFullType), 'componentType "' + componentFullType + '" illegal'), clz.prototype.type = componentFullType; var componentTypeInfo, container, componentTypeInfo1 = parseClassType(componentFullType); componentTypeInfo1.sub ? componentTypeInfo1.sub !== IS_CONTAINER && (((container = storage[(componentTypeInfo = componentTypeInfo1).main]) && container[IS_CONTAINER] || ((container = storage[componentTypeInfo.main] = {})[IS_CONTAINER] = !0), container)[componentTypeInfo1.sub] = clz) : (storage[componentTypeInfo1.main] && console.warn(componentTypeInfo1.main + ' exists.'), storage[componentTypeInfo1.main] = clz); } return clz; }, target.getClass = function(mainType, subType, throwWhenNotFound) { var clz = storage[mainType]; if (clz && clz[IS_CONTAINER] && (clz = subType ? clz[subType] : null), throwWhenNotFound && !clz) throw Error(subType ? 'Component ' + mainType + '.' + (subType || '') + ' is used but not imported.' : mainType + ".type should be specified."); return clz; }, target.getClassesByMainType = function(componentType) { var componentTypeInfo = parseClassType(componentType), result = [], obj = storage[componentTypeInfo.main]; return obj && obj[IS_CONTAINER] ? each(obj, function(o, type) { type !== IS_CONTAINER && result.push(o); }) : result.push(obj), result; }, target.hasClass = function(componentType) { return !!storage[parseClassType(componentType).main]; }, target.getAllClassMainTypes = function() { var types = []; return each(storage, function(obj, type) { types.push(type); }), types; }, target.hasSubTypes = function(componentType) { var obj = storage[parseClassType(componentType).main]; return obj && obj[IS_CONTAINER]; }; } function makeStyleMapper(properties, ignoreParent) { for(var i = 0; i < properties.length; i++)properties[i][1] || (properties[i][1] = properties[i][0]); return ignoreParent = ignoreParent || !1, function(model, excludes, includes) { for(var style = {}, i = 0; i < properties.length; i++){ var propName = properties[i][1]; if (!(excludes && indexOf(excludes, propName) >= 0 || includes && 0 > indexOf(includes, propName))) { var val = model.getShallow(propName, ignoreParent); null != val && (style[properties[i][0]] = val); } } return style; }; } var getAreaStyle = makeStyleMapper([ [ 'fill', 'color' ], [ 'shadowBlur' ], [ 'shadowOffsetX' ], [ 'shadowOffsetY' ], [ 'opacity' ], [ 'shadowColor' ] ]), AreaStyleMixin = function() { function AreaStyleMixin() {} return AreaStyleMixin.prototype.getAreaStyle = function(excludes, includes) { return getAreaStyle(this, excludes, includes); }, AreaStyleMixin; }(), globalImageCache = new LRU(50); function createOrUpdateImage(newImageOrSrc, image, hostEl, onload, cbPayload) { if (!newImageOrSrc) return image; if ('string' != typeof newImageOrSrc) return newImageOrSrc; if (image && image.__zrImageSrc === newImageOrSrc || !hostEl) return image; var cachedImgObj = globalImageCache.get(newImageOrSrc), pendingWrap = { hostEl: hostEl, cb: onload, cbPayload: cbPayload }; return cachedImgObj ? isImageReady(image = cachedImgObj.image) || cachedImgObj.pending.push(pendingWrap) : ((image = new Image()).onload = image.onerror = imageOnLoad, globalImageCache.put(newImageOrSrc, image.__cachedImgObj = { image: image, pending: [ pendingWrap ] }), image.src = image.__zrImageSrc = newImageOrSrc), image; } function imageOnLoad() { var cachedImgObj = this.__cachedImgObj; this.onload = this.onerror = this.__cachedImgObj = null; for(var i = 0; i < cachedImgObj.pending.length; i++){ var pendingWrap = cachedImgObj.pending[i], cb = pendingWrap.cb; cb && cb(this, pendingWrap.cbPayload), pendingWrap.hostEl.dirty(); } cachedImgObj.pending.length = 0; } function isImageReady(image) { return image && image.width && image.height; } var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g; function truncateText(text, containerWidth, font, ellipsis, options) { if (!containerWidth) return ''; var textLines = (text + '').split('\n'); options = prepareTruncateOptions(containerWidth, font, ellipsis, options); for(var i = 0, len = textLines.length; i < len; i++)textLines[i] = truncateSingleLine(textLines[i], options); return textLines.join('\n'); } function prepareTruncateOptions(containerWidth, font, ellipsis, options) { var preparedOpts = extend({}, options = options || {}); preparedOpts.font = font, ellipsis = retrieve2(ellipsis, '...'), preparedOpts.maxIterations = retrieve2(options.maxIterations, 2); var minChar = preparedOpts.minChar = retrieve2(options.minChar, 0); preparedOpts.cnCharWidth = getWidth('国', font); var ascCharWidth = preparedOpts.ascCharWidth = getWidth('a', font); preparedOpts.placeholder = retrieve2(options.placeholder, ''); for(var contentWidth = containerWidth = Math.max(0, containerWidth - 1), i = 0; i < minChar && contentWidth >= ascCharWidth; i++)contentWidth -= ascCharWidth; var ellipsisWidth = getWidth(ellipsis, font); return ellipsisWidth > contentWidth && (ellipsis = '', ellipsisWidth = 0), contentWidth = containerWidth - ellipsisWidth, preparedOpts.ellipsis = ellipsis, preparedOpts.ellipsisWidth = ellipsisWidth, preparedOpts.contentWidth = contentWidth, preparedOpts.containerWidth = containerWidth, preparedOpts; } function truncateSingleLine(textLine, options) { var containerWidth = options.containerWidth, font = options.font, contentWidth = options.contentWidth; if (!containerWidth) return ''; var lineWidth = getWidth(textLine, font); if (lineWidth <= containerWidth) return textLine; for(var j = 0;; j++){ if (lineWidth <= contentWidth || j >= options.maxIterations) { textLine += options.ellipsis; break; } var subLength = 0 === j ? function(text, contentWidth, ascCharWidth, cnCharWidth) { for(var width = 0, i = 0, len = text.length; i < len && width < contentWidth; i++){ var charCode = text.charCodeAt(i); width += 0 <= charCode && charCode <= 127 ? ascCharWidth : cnCharWidth; } return i; }(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth) : lineWidth > 0 ? Math.floor(textLine.length * contentWidth / lineWidth) : 0; lineWidth = getWidth(textLine = textLine.substr(0, subLength), font); } return '' === textLine && (textLine = options.placeholder), textLine; } var RichTextToken = function() {}, RichTextLine = function(tokens) { this.tokens = [], tokens && (this.tokens = tokens); }, RichTextContentBlock = function() { this.width = 0, this.height = 0, this.contentWidth = 0, this.contentHeight = 0, this.outerWidth = 0, this.outerHeight = 0, this.lines = []; }; function pushTokens(block, str, style, wrapInfo, styleName) { var strLines, linesWidths, isEmptyStr = '' === str, tokenStyle = styleName && style.rich[styleName] || {}, lines = block.lines, font = tokenStyle.font || style.font, newLine = !1; if (wrapInfo) { var tokenPadding = tokenStyle.padding, tokenPaddingH = tokenPadding ? tokenPadding[1] + tokenPadding[3] : 0; if (null != tokenStyle.width && 'auto' !== tokenStyle.width) { var outerWidth_1 = parsePercent(tokenStyle.width, wrapInfo.width) + tokenPaddingH; lines.length > 0 && outerWidth_1 + wrapInfo.accumWidth > wrapInfo.width && (strLines = str.split('\n'), newLine = !0), wrapInfo.accumWidth = outerWidth_1; } else { var res = wrapText(str, font, wrapInfo.width, wrapInfo.breakAll, wrapInfo.accumWidth); wrapInfo.accumWidth = res.accumWidth + tokenPaddingH, linesWidths = res.linesWidths, strLines = res.lines; } } else strLines = str.split('\n'); for(var i = 0; i < strLines.length; i++){ var text = strLines[i], token = new RichTextToken(); if (token.styleName = styleName, token.text = text, token.isLineHolder = !text && !isEmptyStr, 'number' == typeof tokenStyle.width ? token.width = tokenStyle.width : token.width = linesWidths ? linesWidths[i] : getWidth(text, font), i || newLine) lines.push(new RichTextLine([ token ])); else { var tokens = (lines[lines.length - 1] || (lines[0] = new RichTextLine())).tokens, tokensLen = tokens.length; 1 === tokensLen && tokens[0].isLineHolder ? tokens[0] = token : (text || !tokensLen || isEmptyStr) && tokens.push(token); } } } var breakCharMap = reduce(',&?/;] '.split(''), function(obj, ch) { return obj[ch] = !0, obj; }, {}); function wrapText(text, font, lineWidth, isBreakAll, lastAccumWidth) { for(var lines = [], linesWidths = [], line = '', currentWord = '', currentWordWidth = 0, accumWidth = 0, i = 0; i < text.length; i++){ var ch = text.charAt(i); if ('\n' === ch) { currentWord && (line += currentWord, accumWidth += currentWordWidth), lines.push(line), linesWidths.push(accumWidth), line = '', currentWord = '', currentWordWidth = 0, accumWidth = 0; continue; } var chWidth = getWidth(ch, font), inWord = !isBreakAll && !function(ch) { var code; return !((code = ch.charCodeAt(0)) >= 0x21) || !(code <= 0xFF) || !!breakCharMap[ch]; }(ch); if (lines.length ? accumWidth + chWidth > lineWidth : lastAccumWidth + accumWidth + chWidth > lineWidth) { accumWidth ? (line || currentWord) && (inWord ? (line || (line = currentWord, currentWord = '', accumWidth = currentWordWidth = 0), lines.push(line), linesWidths.push(accumWidth - currentWordWidth), currentWord += ch, currentWordWidth += chWidth, line = '', accumWidth = currentWordWidth) : (currentWord && (line += currentWord, accumWidth += currentWordWidth, currentWord = '', currentWordWidth = 0), lines.push(line), linesWidths.push(accumWidth), line = ch, accumWidth = chWidth)) : inWord ? (lines.push(currentWord), linesWidths.push(currentWordWidth), currentWord = ch, currentWordWidth = chWidth) : (lines.push(ch), linesWidths.push(chWidth)); continue; } accumWidth += chWidth, inWord ? (currentWord += ch, currentWordWidth += chWidth) : (currentWord && (line += currentWord, currentWord = '', currentWordWidth = 0), line += ch); } return lines.length || line || (line = text, currentWord = '', currentWordWidth = 0), currentWord && (line += currentWord), line && (lines.push(line), linesWidths.push(accumWidth)), 1 === lines.length && (accumWidth += lastAccumWidth), { accumWidth: accumWidth, lines: lines, linesWidths: linesWidths }; } var STYLE_MAGIC_KEY = '__zr_style_' + Math.round(10 * Math.random()), DEFAULT_COMMON_STYLE = { shadowBlur: 0, shadowOffsetX: 0, shadowOffsetY: 0, shadowColor: '#000', opacity: 1, blend: 'source-over' }, DEFAULT_COMMON_ANIMATION_PROPS = { style: { shadowBlur: !0, shadowOffsetX: !0, shadowOffsetY: !0, shadowColor: !0, opacity: !0 } }; DEFAULT_COMMON_STYLE[STYLE_MAGIC_KEY] = !0; var PRIMARY_STATES_KEYS$1 = [ 'z', 'z2', 'invisible' ], Displayable = function(_super) { var dispProto; function Displayable(props) { return _super.call(this, props) || this; } return __extends(Displayable, _super), Displayable.prototype._init = function(props) { for(var keysArr = keys(props), i = 0; i < keysArr.length; i++){ var key = keysArr[i]; 'style' === key ? this.useStyle(props[key]) : _super.prototype.attrKV.call(this, key, props[key]); } this.style || this.useStyle({}); }, Displayable.prototype.beforeBrush = function() {}, Displayable.prototype.afterBrush = function() {}, Displayable.prototype.innerBeforeBrush = function() {}, Displayable.prototype.innerAfterBrush = function() {}, Displayable.prototype.shouldBePainted = function(viewWidth, viewHeight, considerClipPath, considerAncestors) { var m = this.transform; if (this.ignore || this.invisible || 0 === this.style.opacity || this.culling && (tmpRect.copy(this.getBoundingRect()), this.transform && tmpRect.applyTransform(this.transform), viewRect.width = viewWidth, viewRect.height = viewHeight, !tmpRect.intersect(viewRect)) || m && !m[0] && !m[3]) return !1; if (considerClipPath && this.__clipPaths) { for(var i = 0; i < this.__clipPaths.length; ++i)if (this.__clipPaths[i].isZeroArea()) return !1; } if (considerAncestors && this.parent) for(var parent_1 = this.parent; parent_1;){ if (parent_1.ignore) return !1; parent_1 = parent_1.parent; } return !0; }, Displayable.prototype.contain = function(x, y) { return this.rectContain(x, y); }, Displayable.prototype.traverse = function(cb, context) { cb.call(context, this); }, Displayable.prototype.rectContain = function(x, y) { var coord = this.transformCoordToLocal(x, y); return this.getBoundingRect().contain(coord[0], coord[1]); }, Displayable.prototype.getPaintRect = function() { var rect = this._paintRect; if (!this._paintRect || this.__dirty) { var transform = this.transform, elRect = this.getBoundingRect(), style = this.style, shadowSize = style.shadowBlur || 0, shadowOffsetX = style.shadowOffsetX || 0, shadowOffsetY = style.shadowOffsetY || 0; rect = this._paintRect || (this._paintRect = new BoundingRect(0, 0, 0, 0)), transform ? BoundingRect.applyTransform(rect, elRect, transform) : rect.copy(elRect), (shadowSize || shadowOffsetX || shadowOffsetY) && (rect.width += 2 * shadowSize + Math.abs(shadowOffsetX), rect.height += 2 * shadowSize + Math.abs(shadowOffsetY), rect.x = Math.min(rect.x, rect.x + shadowOffsetX - shadowSize), rect.y = Math.min(rect.y, rect.y + shadowOffsetY - shadowSize)); var tolerance = this.dirtyRectTolerance; rect.isZero() || (rect.x = Math.floor(rect.x - tolerance), rect.y = Math.floor(rect.y - tolerance), rect.width = Math.ceil(rect.width + 1 + 2 * tolerance), rect.height = Math.ceil(rect.height + 1 + 2 * tolerance)); } return rect; }, Displayable.prototype.setPrevPaintRect = function(paintRect) { paintRect ? (this._prevPaintRect = this._prevPaintRect || new BoundingRect(0, 0, 0, 0), this._prevPaintRect.copy(paintRect)) : this._prevPaintRect = null; }, Displayable.prototype.getPrevPaintRect = function() { return this._prevPaintRect; }, Displayable.prototype.animateStyle = function(loop) { return this.animate('style', loop); }, Displayable.prototype.updateDuringAnimation = function(targetKey) { 'style' === targetKey ? this.dirtyStyle() : this.markRedraw(); }, Displayable.prototype.attrKV = function(key, value) { 'style' !== key ? _super.prototype.attrKV.call(this, key, value) : this.style ? this.setStyle(value) : this.useStyle(value); }, Displayable.prototype.setStyle = function(keyOrObj, value) { return 'string' == typeof keyOrObj ? this.style[keyOrObj] = value : extend(this.style, keyOrObj), this.dirtyStyle(), this; }, Displayable.prototype.dirtyStyle = function() { this.markRedraw(), this.__dirty |= Displayable.STYLE_CHANGED_BIT, this._rect && (this._rect = null); }, Displayable.prototype.dirty = function() { this.dirtyStyle(); }, Displayable.prototype.styleChanged = function() { return !!(this.__dirty & Displayable.STYLE_CHANGED_BIT); }, Displayable.prototype.styleUpdated = function() { this.__dirty &= ~Displayable.STYLE_CHANGED_BIT; }, Displayable.prototype.createStyle = function(obj) { return createObject(DEFAULT_COMMON_STYLE, obj); }, Displayable.prototype.useStyle = function(obj) { obj[STYLE_MAGIC_KEY] || (obj = this.createStyle(obj)), this.__inHover ? this.__hoverStyle = obj : this.style = obj, this.dirtyStyle(); }, Displayable.prototype.isStyleObject = function(obj) { return obj[STYLE_MAGIC_KEY]; }, Displayable.prototype._innerSaveToNormal = function(toState) { _super.prototype._innerSaveToNormal.call(this, toState); var normalState = this._normalState; toState.style && !normalState.style && (normalState.style = this._mergeStyle(this.createStyle(), this.style)), this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS$1); }, Displayable.prototype._applyStateObj = function(stateName, state, normalState, keepCurrentStates, transition, animationCfg) { _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg); var targetStyle, needsRestoreToNormal = !(state && keepCurrentStates); if (state && state.style ? transition ? keepCurrentStates ? targetStyle = state.style : (targetStyle = this._mergeStyle(this.createStyle(), normalState.style), this._mergeStyle(targetStyle, state.style)) : (targetStyle = this._mergeStyle(this.createStyle(), keepCurrentStates ? this.style : normalState.style), this._mergeStyle(targetStyle, state.style)) : needsRestoreToNormal && (targetStyle = normalState.style), targetStyle) { if (transition) { var sourceStyle = this.style; if (this.style = this.createStyle(needsRestoreToNormal ? {} : sourceStyle), needsRestoreToNormal) for(var changedKeys = keys(sourceStyle), i = 0; i < changedKeys.length; i++){ var key = changedKeys[i]; key in targetStyle && (targetStyle[key] = targetStyle[key], this.style[key] = sourceStyle[key]); } for(var targetKeys = keys(targetStyle), i = 0; i < targetKeys.length; i++){ var key = targetKeys[i]; this.style[key] = this.style[key]; } this._transitionState(stateName, { style: targetStyle }, animationCfg, this.getAnimationStyleProps()); } else this.useStyle(targetStyle); } for(var i = 0; i < PRIMARY_STATES_KEYS$1.length; i++){ var key = PRIMARY_STATES_KEYS$1[i]; state && null != state[key] ? this[key] = state[key] : needsRestoreToNormal && null != normalState[key] && (this[key] = normalState[key]); } }, Displayable.prototype._mergeStates = function(states) { for(var mergedStyle, mergedState = _super.prototype._mergeStates.call(this, states), i = 0; i < states.length; i++){ var state = states[i]; state.style && (mergedStyle = mergedStyle || {}, this._mergeStyle(mergedStyle, state.style)); } return mergedStyle && (mergedState.style = mergedStyle), mergedState; }, Displayable.prototype._mergeStyle = function(targetStyle, sourceStyle) { return extend(targetStyle, sourceStyle), targetStyle; }, Displayable.prototype.getAnimationStyleProps = function() { return DEFAULT_COMMON_ANIMATION_PROPS; }, Displayable.STYLE_CHANGED_BIT = 2, Displayable.initDefaultProps = void ((dispProto = Displayable.prototype).type = 'displayable', dispProto.invisible = !1, dispProto.z = 0, dispProto.z2 = 0, dispProto.zlevel = 0, dispProto.culling = !1, dispProto.cursor = 'pointer', dispProto.rectHover = !1, dispProto.incremental = !1, dispProto._rect = null, dispProto.dirtyRectTolerance = 0, dispProto.__dirty = Element.REDARAW_BIT | Displayable.STYLE_CHANGED_BIT), Displayable; }(Element), tmpRect = new BoundingRect(0, 0, 0, 0), viewRect = new BoundingRect(0, 0, 0, 0), mathPow = Math.pow, mathSqrt = Math.sqrt, THREE_SQRT = mathSqrt(3), ONE_THIRD = 1 / 3, _v0 = create(), _v1 = create(), _v2 = create(); function isAroundZero(val) { return val > -0.00000001 && val < 1e-8; } function isNotAroundZero$1(val) { return val > 1e-8 || val < -0.00000001; } function cubicAt(p0, p1, p2, p3, t) { var onet = 1 - t; return onet * onet * (onet * p0 + 3 * t * p1) + t * t * (t * p3 + 3 * onet * p2); } function cubicDerivativeAt(p0, p1, p2, p3, t) { var onet = 1 - t; return 3 * (((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet + (p3 - p2) * t * t); } function cubicRootAt(p0, p1, p2, p3, val, roots) { var a = p3 + 3 * (p1 - p2) - p0, b = 3 * (p2 - 2 * p1 + p0), c = 3 * (p1 - p0), d = p0 - val, A = b * b - 3 * a * c, B = b * c - 9 * a * d, n = 0; if (isAroundZero(A) && isAroundZero(B)) { if (isAroundZero(b)) roots[0] = 0; else { var t1 = -c / b; t1 >= 0 && t1 <= 1 && (roots[n++] = t1); } } else { var disc = B * B - 4 * A * (c * c - 3 * b * d); if (isAroundZero(disc)) { var K = B / A, t1 = -b / a + K, t2 = -K / 2; t1 >= 0 && t1 <= 1 && (roots[n++] = t1), t2 >= 0 && t2 <= 1 && (roots[n++] = t2); } else if (disc > 0) { var discSqrt = mathSqrt(disc), Y1 = A * b + 1.5 * a * (-B + discSqrt), Y2 = A * b + 1.5 * a * (-B - discSqrt), t1 = (-b - ((Y1 = Y1 < 0 ? -mathPow(-Y1, ONE_THIRD) : mathPow(Y1, ONE_THIRD)) + (Y2 = Y2 < 0 ? -mathPow(-Y2, ONE_THIRD) : mathPow(Y2, ONE_THIRD)))) / (3 * a); t1 >= 0 && t1 <= 1 && (roots[n++] = t1); } else { var theta = Math.acos((2 * A * b - 3 * a * B) / (2 * mathSqrt(A * A * A))) / 3, ASqrt = mathSqrt(A), tmp = Math.cos(theta), t1 = (-b - 2 * ASqrt * tmp) / (3 * a), t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a), t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a); t1 >= 0 && t1 <= 1 && (roots[n++] = t1), t2 >= 0 && t2 <= 1 && (roots[n++] = t2), t3 >= 0 && t3 <= 1 && (roots[n++] = t3); } } return n; } function cubicExtrema(p0, p1, p2, p3, extrema) { var b = 6 * p2 - 12 * p1 + 6 * p0, a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2, c = 3 * p1 - 3 * p0, n = 0; if (isAroundZero(a)) { if (isNotAroundZero$1(b)) { var t1 = -c / b; t1 >= 0 && t1 <= 1 && (extrema[n++] = t1); } } else { var disc = b * b - 4 * a * c; if (isAroundZero(disc)) extrema[0] = -b / (2 * a); else if (disc > 0) { var discSqrt = mathSqrt(disc), t1 = (-b + discSqrt) / (2 * a), t2 = (-b - discSqrt) / (2 * a); t1 >= 0 && t1 <= 1 && (extrema[n++] = t1), t2 >= 0 && t2 <= 1 && (extrema[n++] = t2); } } return n; } function cubicSubdivide(p0, p1, p2, p3, t, out) { var p01 = (p1 - p0) * t + p0, p12 = (p2 - p1) * t + p1, p23 = (p3 - p2) * t + p2, p012 = (p12 - p01) * t + p01, p123 = (p23 - p12) * t + p12, p0123 = (p123 - p012) * t + p012; out[0] = p0, out[1] = p01, out[2] = p012, out[3] = p0123, out[4] = p0123, out[5] = p123, out[6] = p23, out[7] = p3; } function cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, out) { var t, prev, next, d1, d2, interval = 0.005, d = 1 / 0; _v0[0] = x, _v0[1] = y; for(var _t = 0; _t < 1; _t += 0.05)_v1[0] = cubicAt(x0, x1, x2, x3, _t), _v1[1] = cubicAt(y0, y1, y2, y3, _t), (d1 = distanceSquare(_v0, _v1)) < d && (t = _t, d = d1); d = 1 / 0; for(var i = 0; i < 32 && !(interval < 1e-4); i++)prev = t - interval, next = t + interval, _v1[0] = cubicAt(x0, x1, x2, x3, prev), _v1[1] = cubicAt(y0, y1, y2, y3, prev), d1 = distanceSquare(_v1, _v0), prev >= 0 && d1 < d ? (t = prev, d = d1) : (_v2[0] = cubicAt(x0, x1, x2, x3, next), _v2[1] = cubicAt(y0, y1, y2, y3, next), d2 = distanceSquare(_v2, _v0), next <= 1 && d2 < d ? (t = next, d = d2) : interval *= 0.5); return out && (out[0] = cubicAt(x0, x1, x2, x3, t), out[1] = cubicAt(y0, y1, y2, y3, t)), mathSqrt(d); } function quadraticAt(p0, p1, p2, t) { var onet = 1 - t; return onet * (onet * p0 + 2 * t * p1) + t * t * p2; } function quadraticDerivativeAt(p0, p1, p2, t) { return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1)); } function quadraticExtremum(p0, p1, p2) { var divider = p0 + p2 - 2 * p1; return 0 === divider ? 0.5 : (p0 - p1) / divider; } function quadraticSubdivide(p0, p1, p2, t, out) { var p01 = (p1 - p0) * t + p0, p12 = (p2 - p1) * t + p1, p012 = (p12 - p01) * t + p01; out[0] = p0, out[1] = p01, out[2] = p012, out[3] = p012, out[4] = p12, out[5] = p2; } function quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, out) { var t, interval = 0.005, d = 1 / 0; _v0[0] = x, _v0[1] = y; for(var _t = 0; _t < 1; _t += 0.05){ _v1[0] = quadraticAt(x0, x1, x2, _t), _v1[1] = quadraticAt(y0, y1, y2, _t); var d1 = distanceSquare(_v0, _v1); d1 < d && (t = _t, d = d1); } d = 1 / 0; for(var i = 0; i < 32 && !(interval < 1e-4); i++){ var prev = t - interval, next = t + interval; _v1[0] = quadraticAt(x0, x1, x2, prev), _v1[1] = quadraticAt(y0, y1, y2, prev); var d1 = distanceSquare(_v1, _v0); if (prev >= 0 && d1 < d) t = prev, d = d1; else { _v2[0] = quadraticAt(x0, x1, x2, next), _v2[1] = quadraticAt(y0, y1, y2, next); var d2 = distanceSquare(_v2, _v0); next <= 1 && d2 < d ? (t = next, d = d2) : interval *= 0.5; } } return out && (out[0] = quadraticAt(x0, x1, x2, t), out[1] = quadraticAt(y0, y1, y2, t)), mathSqrt(d); } var mathMin$1 = Math.min, mathMax$1 = Math.max, mathSin = Math.sin, mathCos = Math.cos, PI2 = 2 * Math.PI, start = create(), end = create(), extremity = create(); function fromPoints(points, min, max) { if (0 !== points.length) { for(var p = points[0], left = p[0], right = p[0], top = p[1], bottom = p[1], i = 1; i < points.length; i++)left = mathMin$1(left, (p = points[i])[0]), right = mathMax$1(right, p[0]), top = mathMin$1(top, p[1]), bottom = mathMax$1(bottom, p[1]); min[0] = left, min[1] = top, max[0] = right, max[1] = bottom; } } function fromLine(x0, y0, x1, y1, min, max) { min[0] = mathMin$1(x0, x1), min[1] = mathMin$1(y0, y1), max[0] = mathMax$1(x0, x1), max[1] = mathMax$1(y0, y1); } var xDim = [], yDim = [], CMD = { M: 1, L: 2, C: 3, Q: 4, A: 5, Z: 6, R: 7 }, tmpOutX = [], tmpOutY = [], min$1 = [], max$1 = [], min2 = [], max2 = [], mathMin$2 = Math.min, mathMax$2 = Math.max, mathCos$1 = Math.cos, mathSin$1 = Math.sin, mathSqrt$1 = Math.sqrt, mathAbs = Math.abs, PI = Math.PI, PI2$1 = 2 * PI, hasTypedArray = 'undefined' != typeof Float32Array, tmpAngles = []; function modPI2(radian) { return Math.round(radian / PI * 1e8) / 1e8 % 2 * PI; } function normalizeArcAngles(angles, anticlockwise) { var newStartAngle = modPI2(angles[0]); newStartAngle < 0 && (newStartAngle += PI2$1); var delta = newStartAngle - angles[0], newEndAngle = angles[1]; newEndAngle += delta, !anticlockwise && newEndAngle - newStartAngle >= PI2$1 ? newEndAngle = newStartAngle + PI2$1 : anticlockwise && newStartAngle - newEndAngle >= PI2$1 ? newEndAngle = newStartAngle - PI2$1 : !anticlockwise && newStartAngle > newEndAngle ? newEndAngle = newStartAngle + (PI2$1 - modPI2(newStartAngle - newEndAngle)) : anticlockwise && newStartAngle < newEndAngle && (newEndAngle = newStartAngle - (PI2$1 - modPI2(newEndAngle - newStartAngle))), angles[0] = newStartAngle, angles[1] = newEndAngle; } var PathProxy = function() { var proto; function PathProxy(notSaveData) { this.dpr = 1, this._version = 0, this._xi = 0, this._yi = 0, this._x0 = 0, this._y0 = 0, this._len = 0, notSaveData && (this._saveData = !1), this._saveData && (this.data = []); } return PathProxy.prototype.increaseVersion = function() { this._version++; }, PathProxy.prototype.getVersion = function() { return this._version; }, PathProxy.prototype.setScale = function(sx, sy, segmentIgnoreThreshold) { (segmentIgnoreThreshold = segmentIgnoreThreshold || 0) > 0 && (this._ux = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sx) || 0, this._uy = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sy) || 0); }, PathProxy.prototype.setDPR = function(dpr) { this.dpr = dpr; }, PathProxy.prototype.setContext = function(ctx) { this._ctx = ctx; }, PathProxy.prototype.getContext = function() { return this._ctx; }, PathProxy.prototype.beginPath = function() { return this._ctx && this._ctx.beginPath(), this.reset(), this; }, PathProxy.prototype.reset = function() { this._saveData && (this._len = 0), this._lineDash && (this._lineDash = null, this._dashOffset = 0), this._pathSegLen && (this._pathSegLen = null, this._pathLen = 0), this._version++; }, PathProxy.prototype.moveTo = function(x, y) { return this.addData(CMD.M, x, y), this._ctx && this._ctx.moveTo(x, y), this._x0 = x, this._y0 = y, this._xi = x, this._yi = y, this; }, PathProxy.prototype.lineTo = function(x, y) { var exceedUnit = mathAbs(x - this._xi) > this._ux || mathAbs(y - this._yi) > this._uy || this._len < 5; return this.addData(CMD.L, x, y), this._ctx && exceedUnit && (this._needsDash ? this._dashedLineTo(x, y) : this._ctx.lineTo(x, y)), exceedUnit && (this._xi = x, this._yi = y), this; }, PathProxy.prototype.bezierCurveTo = function(x1, y1, x2, y2, x3, y3) { return this.addData(CMD.C, x1, y1, x2, y2, x3, y3), this._ctx && (this._needsDash ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3) : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3)), this._xi = x3, this._yi = y3, this; }, PathProxy.prototype.quadraticCurveTo = function(x1, y1, x2, y2) { return this.addData(CMD.Q, x1, y1, x2, y2), this._ctx && (this._needsDash ? this._dashedQuadraticTo(x1, y1, x2, y2) : this._ctx.quadraticCurveTo(x1, y1, x2, y2)), this._xi = x2, this._yi = y2, this; }, PathProxy.prototype.arc = function(cx, cy, r, startAngle, endAngle, anticlockwise) { tmpAngles[0] = startAngle, tmpAngles[1] = endAngle, normalizeArcAngles(tmpAngles, anticlockwise), startAngle = tmpAngles[0]; var delta = (endAngle = tmpAngles[1]) - startAngle; return this.addData(CMD.A, cx, cy, r, r, startAngle, delta, 0, anticlockwise ? 0 : 1), this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise), this._xi = mathCos$1(endAngle) * r + cx, this._yi = mathSin$1(endAngle) * r + cy, this; }, PathProxy.prototype.arcTo = function(x1, y1, x2, y2, radius) { return this._ctx && this._ctx.arcTo(x1, y1, x2, y2, radius), this; }, PathProxy.prototype.rect = function(x, y, w, h) { return this._ctx && this._ctx.rect(x, y, w, h), this.addData(CMD.R, x, y, w, h), this; }, PathProxy.prototype.closePath = function() { this.addData(CMD.Z); var ctx = this._ctx, x0 = this._x0, y0 = this._y0; return ctx && (this._needsDash && this._dashedLineTo(x0, y0), ctx.closePath()), this._xi = x0, this._yi = y0, this; }, PathProxy.prototype.fill = function(ctx) { ctx && ctx.fill(), this.toStatic(); }, PathProxy.prototype.stroke = function(ctx) { ctx && ctx.stroke(), this.toStatic(); }, PathProxy.prototype.setLineDash = function(lineDash) { if (lineDash instanceof Array) { this._lineDash = lineDash, this._dashIdx = 0; for(var lineDashSum = 0, i = 0; i < lineDash.length; i++)lineDashSum += lineDash[i]; this._dashSum = lineDashSum, this._needsDash = !0; } else this._lineDash = null, this._needsDash = !1; return this; }, PathProxy.prototype.setLineDashOffset = function(offset) { return this._dashOffset = offset, this; }, PathProxy.prototype.len = function() { return this._len; }, PathProxy.prototype.setData = function(data) { var len = data.length; !(this.data && this.data.length === len) && hasTypedArray && (this.data = new Float32Array(len)); for(var i = 0; i < len; i++)this.data[i] = data[i]; this._len = len; }, PathProxy.prototype.appendPath = function(path) { path instanceof Array || (path = [ path ]); for(var len = path.length, appendSize = 0, offset = this._len, i = 0; i < len; i++)appendSize += path[i].len(); hasTypedArray && this.data instanceof Float32Array && (this.data = new Float32Array(offset + appendSize)); for(var i = 0; i < len; i++)for(var appendPathData = path[i].data, k = 0; k < appendPathData.length; k++)this.data[offset++] = appendPathData[k]; this._len = offset; }, PathProxy.prototype.addData = function(cmd, a, b, c, d, e, f, g, h) { if (this._saveData) { var data = this.data; this._len + arguments.length > data.length && (this._expandData(), data = this.data); for(var i = 0; i < arguments.length; i++)data[this._len++] = arguments[i]; } }, PathProxy.prototype._expandData = function() { if (!(this.data instanceof Array)) { for(var newData = [], i = 0; i < this._len; i++)newData[i] = this.data[i]; this.data = newData; } }, PathProxy.prototype._dashedLineTo = function(x1, y1) { var dash, idx, dashSum = this._dashSum, lineDash = this._lineDash, ctx = this._ctx, offset = this._dashOffset, x0 = this._xi, y0 = this._yi, dx = x1 - x0, dy = y1 - y0, dist = mathSqrt$1(dx * dx + dy * dy), x = x0, y = y0, nDash = lineDash.length; for(dx /= dist, dy /= dist, offset < 0 && (offset = dashSum + offset), offset %= dashSum, x -= offset * dx, y -= offset * dy; dx > 0 && x <= x1 || dx < 0 && x >= x1 || 0 === dx && (dy > 0 && y <= y1 || dy < 0 && y >= y1);)x += dx * (dash = lineDash[idx = this._dashIdx]), y += dy * dash, this._dashIdx = (idx + 1) % nDash, dx > 0 && x < x0 || dx < 0 && x > x0 || dy > 0 && y < y0 || dy < 0 && y > y0 || ctx[idx % 2 ? 'moveTo' : 'lineTo'](dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1), dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1)); dx = x - x1, dy = y - y1, this._dashOffset = -mathSqrt$1(dx * dx + dy * dy); }, PathProxy.prototype._dashedBezierTo = function(x1, y1, x2, y2, x3, y3) { var t, dx, dy, x, y, ctx = this._ctx, dashSum = this._dashSum, offset = this._dashOffset, lineDash = this._lineDash, x0 = this._xi, y0 = this._yi, bezierLen = 0, idx = this._dashIdx, nDash = lineDash.length, tmpLen = 0; for(offset < 0 && (offset = dashSum + offset), offset %= dashSum, t = 0; t < 1; t += 0.1)bezierLen += mathSqrt$1((dx = cubicAt(x0, x1, x2, x3, t + 0.1) - cubicAt(x0, x1, x2, x3, t)) * dx + (dy = cubicAt(y0, y1, y2, y3, t + 0.1) - cubicAt(y0, y1, y2, y3, t)) * dy); for(; idx < nDash && !((tmpLen += lineDash[idx]) > offset); idx++); for(t = (tmpLen - offset) / bezierLen; t <= 1;)x = cubicAt(x0, x1, x2, x3, t), y = cubicAt(y0, y1, y2, y3, t), idx % 2 ? ctx.moveTo(x, y) : ctx.lineTo(x, y), t += lineDash[idx] / bezierLen, idx = (idx + 1) % nDash; idx % 2 != 0 && ctx.lineTo(x3, y3), dx = x3 - x, dy = y3 - y, this._dashOffset = -mathSqrt$1(dx * dx + dy * dy); }, PathProxy.prototype._dashedQuadraticTo = function(x1, y1, x2, y2) { var x3 = x2, y3 = y2; x2 = (x2 + 2 * x1) / 3, y2 = (y2 + 2 * y1) / 3, x1 = (this._xi + 2 * x1) / 3, y1 = (this._yi + 2 * y1) / 3, this._dashedBezierTo(x1, y1, x2, y2, x3, y3); }, PathProxy.prototype.toStatic = function() { if (this._saveData) { var data = this.data; data instanceof Array && (data.length = this._len, hasTypedArray && this._len > 11 && (this.data = new Float32Array(data))); } }, PathProxy.prototype.getBoundingRect = function() { min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE, max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE; var i, data = this.data, xi = 0, yi = 0, x0 = 0, y0 = 0; for(i = 0; i < this._len;){ var cmd = data[i++], isFirst = 1 === i; switch(isFirst && (xi = data[i], yi = data[i + 1], x0 = xi, y0 = yi), cmd){ case CMD.M: xi = x0 = data[i++], yi = y0 = data[i++], min2[0] = x0, min2[1] = y0, max2[0] = x0, max2[1] = y0; break; case CMD.L: fromLine(xi, yi, data[i], data[i + 1], min2, max2), xi = data[i++], yi = data[i++]; break; case CMD.C: (function(x0, y0, x1, y1, x2, y2, x3, y3, min, max) { var n = cubicExtrema(x0, x1, x2, x3, xDim); min[0] = 1 / 0, min[1] = 1 / 0, max[0] = -1 / 0, max[1] = -1 / 0; for(var i = 0; i < n; i++){ var x = cubicAt(x0, x1, x2, x3, xDim[i]); min[0] = mathMin$1(x, min[0]), max[0] = mathMax$1(x, max[0]); } n = cubicExtrema(y0, y1, y2, y3, yDim); for(var i = 0; i < n; i++){ var y = cubicAt(y0, y1, y2, y3, yDim[i]); min[1] = mathMin$1(y, min[1]), max[1] = mathMax$1(y, max[1]); } min[0] = mathMin$1(x0, min[0]), max[0] = mathMax$1(x0, max[0]), min[0] = mathMin$1(x3, min[0]), max[0] = mathMax$1(x3, max[0]), min[1] = mathMin$1(y0, min[1]), max[1] = mathMax$1(y0, max[1]), min[1] = mathMin$1(y3, min[1]), max[1] = mathMax$1(y3, max[1]); })(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], min2, max2), xi = data[i++], yi = data[i++]; break; case CMD.Q: (function(x0, y0, x1, y1, x2, y2, min, max) { var tx = mathMax$1(mathMin$1(quadraticExtremum(x0, x1, x2), 1), 0), ty = mathMax$1(mathMin$1(quadraticExtremum(y0, y1, y2), 1), 0), x = quadraticAt(x0, x1, x2, tx), y = quadraticAt(y0, y1, y2, ty); min[0] = mathMin$1(x0, x2, x), min[1] = mathMin$1(y0, y2, y), max[0] = mathMax$1(x0, x2, x), max[1] = mathMax$1(y0, y2, y); })(xi, yi, data[i++], data[i++], data[i], data[i + 1], min2, max2), xi = data[i++], yi = data[i++]; break; case CMD.A: var cx = data[i++], cy = data[i++], rx = data[i++], ry = data[i++], startAngle = data[i++], endAngle = data[i++] + startAngle; i += 1; var anticlockwise = !data[i++]; isFirst && (x0 = mathCos$1(startAngle) * rx + cx, y0 = mathSin$1(startAngle) * ry + cy), function(x, y, rx, ry, startAngle, endAngle, anticlockwise, min$1, max$1) { var diff = Math.abs(startAngle - endAngle); if (diff % PI2 < 1e-4 && diff > 1e-4) { min$1[0] = x - rx, min$1[1] = y - ry, max$1[0] = x + rx, max$1[1] = y + ry; return; } if (start[0] = mathCos(startAngle) * rx + x, start[1] = mathSin(startAngle) * ry + y, end[0] = mathCos(endAngle) * rx + x, end[1] = mathSin(endAngle) * ry + y, min(min$1, start, end), max(max$1, start, end), (startAngle %= PI2) < 0 && (startAngle += PI2), (endAngle %= PI2) < 0 && (endAngle += PI2), startAngle > endAngle && !anticlockwise ? endAngle += PI2 : startAngle < endAngle && anticlockwise && (startAngle += PI2), anticlockwise) { var tmp = endAngle; endAngle = startAngle, startAngle = tmp; } for(var angle = 0; angle < endAngle; angle += Math.PI / 2)angle > startAngle && (extremity[0] = mathCos(angle) * rx + x, extremity[1] = mathSin(angle) * ry + y, min(min$1, extremity, min$1), max(max$1, extremity, max$1)); }(cx, cy, rx, ry, startAngle, endAngle, anticlockwise, min2, max2), xi = mathCos$1(endAngle) * rx + cx, yi = mathSin$1(endAngle) * ry + cy; break; case CMD.R: fromLine(x0 = xi = data[i++], y0 = yi = data[i++], x0 + data[i++], y0 + data[i++], min2, max2); break; case CMD.Z: xi = x0, yi = y0; } min(min$1, min$1, min2), max(max$1, max$1, max2); } return 0 === i && (min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0), new BoundingRect(min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]); }, PathProxy.prototype._calculateLength = function() { var data = this.data, len = this._len, ux = this._ux, uy = this._uy, xi = 0, yi = 0, x0 = 0, y0 = 0; this._pathSegLen || (this._pathSegLen = []); for(var pathSegLen = this._pathSegLen, pathTotalLen = 0, segCount = 0, i = 0; i < len;){ var cmd = data[i++], isFirst = 1 === i; isFirst && (xi = data[i], yi = data[i + 1], x0 = xi, y0 = yi); var l = -1; switch(cmd){ case CMD.M: xi = x0 = data[i++], yi = y0 = data[i++]; break; case CMD.L: var x2 = data[i++], y2 = data[i++], dx = x2 - xi, dy = y2 - yi; (mathAbs(dx) > ux || mathAbs(dy) > uy || i === len - 1) && (l = Math.sqrt(dx * dx + dy * dy), xi = x2, yi = y2); break; case CMD.C: var x1 = data[i++], y1 = data[i++], x2 = data[i++], y2 = data[i++], x3 = data[i++], y3 = data[i++]; l = function(x0, y0, x1, y1, x2, y2, x3, y3, iteration) { for(var px = x0, py = y0, d = 0, step = 1 / iteration, i = 1; i <= iteration; i++){ var t = i * step, x = cubicAt(x0, x1, x2, x3, t), y = cubicAt(y0, y1, y2, y3, t), dx = x - px, dy = y - py; d += Math.sqrt(dx * dx + dy * dy), px = x, py = y; } return d; }(xi, yi, x1, y1, x2, y2, x3, y3, 10), xi = x3, yi = y3; break; case CMD.Q: var x1 = data[i++], y1 = data[i++], x2 = data[i++], y2 = data[i++]; l = function(x0, y0, x1, y1, x2, y2, iteration) { for(var px = x0, py = y0, d = 0, step = 1 / iteration, i = 1; i <= iteration; i++){ var t = i * step, x = quadraticAt(x0, x1, x2, t), y = quadraticAt(y0, y1, y2, t), dx = x - px, dy = y - py; d += Math.sqrt(dx * dx + dy * dy), px = x, py = y; } return d; }(xi, yi, x1, y1, x2, y2, 10), xi = x2, yi = y2; break; case CMD.A: var cx = data[i++], cy = data[i++], rx = data[i++], ry = data[i++], startAngle = data[i++], delta = data[i++], endAngle = delta + startAngle; i += 1, data[i++], isFirst && (x0 = mathCos$1(startAngle) * rx + cx, y0 = mathSin$1(startAngle) * ry + cy), l = mathMax$2(rx, ry) * mathMin$2(PI2$1, Math.abs(delta)), xi = mathCos$1(endAngle) * rx + cx, yi = mathSin$1(endAngle) * ry + cy; break; case CMD.R: x0 = xi = data[i++], y0 = yi = data[i++], l = 2 * data[i++] + 2 * data[i++]; break; case CMD.Z: var dx = x0 - xi, dy = y0 - yi; l = Math.sqrt(dx * dx + dy * dy), xi = x0, yi = y0; } l >= 0 && (pathSegLen[segCount++] = l, pathTotalLen += l); } return this._pathLen = pathTotalLen, pathTotalLen; }, PathProxy.prototype.rebuildPath = function(ctx, percent) { var x0, y0, xi, yi, x, y, pathSegLen, displayedLength, d = this.data, ux = this._ux, uy = this._uy, len = this._len, drawPart = percent < 1, accumLength = 0, segCount = 0; if (!drawPart || (this._pathSegLen || this._calculateLength(), pathSegLen = this._pathSegLen, displayedLength = percent * this._pathLen)) lo: for(var i = 0; i < len;){ var cmd = d[i++], isFirst = 1 === i; switch(isFirst && (xi = d[i], yi = d[i + 1], x0 = xi, y0 = yi), cmd){ case CMD.M: x0 = xi = d[i++], y0 = yi = d[i++], ctx.moveTo(xi, yi); break; case CMD.L: if (x = d[i++], y = d[i++], mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len - 1) { if (drawPart) { var l = pathSegLen[segCount++]; if (accumLength + l > displayedLength) { var t = (displayedLength - accumLength) / l; ctx.lineTo(xi * (1 - t) + x * t, yi * (1 - t) + y * t); break lo; } accumLength += l; } ctx.lineTo(x, y), xi = x, yi = y; } break; case CMD.C: var x1 = d[i++], y1 = d[i++], x2 = d[i++], y2 = d[i++], x3 = d[i++], y3 = d[i++]; if (drawPart) { var l = pathSegLen[segCount++]; if (accumLength + l > displayedLength) { var t = (displayedLength - accumLength) / l; cubicSubdivide(xi, x1, x2, x3, t, tmpOutX), cubicSubdivide(yi, y1, y2, y3, t, tmpOutY), ctx.bezierCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2], tmpOutX[3], tmpOutY[3]); break lo; } accumLength += l; } ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3), xi = x3, yi = y3; break; case CMD.Q: var x1 = d[i++], y1 = d[i++], x2 = d[i++], y2 = d[i++]; if (drawPart) { var l = pathSegLen[segCount++]; if (accumLength + l > displayedLength) { var t = (displayedLength - accumLength) / l; quadraticSubdivide(xi, x1, x2, t, tmpOutX), quadraticSubdivide(yi, y1, y2, t, tmpOutY), ctx.quadraticCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2]); break lo; } accumLength += l; } ctx.quadraticCurveTo(x1, y1, x2, y2), xi = x2, yi = y2; break; case CMD.A: var cx = d[i++], cy = d[i++], rx = d[i++], ry = d[i++], startAngle = d[i++], delta = d[i++], psi = d[i++], anticlockwise = !d[i++], r = rx > ry ? rx : ry, isEllipse = mathAbs(rx - ry) > 1e-3, endAngle = startAngle + delta, breakBuild = !1; if (drawPart) { var l = pathSegLen[segCount++]; accumLength + l > displayedLength && (endAngle = startAngle + delta * (displayedLength - accumLength) / l, breakBuild = !0), accumLength += l; } if (isEllipse && ctx.ellipse ? ctx.ellipse(cx, cy, rx, ry, psi, startAngle, endAngle, anticlockwise) : ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise), breakBuild) break lo; isFirst && (x0 = mathCos$1(startAngle) * rx + cx, y0 = mathSin$1(startAngle) * ry + cy), xi = mathCos$1(endAngle) * rx + cx, yi = mathSin$1(endAngle) * ry + cy; break; case CMD.R: x0 = xi = d[i], y0 = yi = d[i + 1], x = d[i++], y = d[i++]; var width = d[i++], height = d[i++]; if (drawPart) { var l = pathSegLen[segCount++]; if (accumLength + l > displayedLength) { var d_1 = displayedLength - accumLength; ctx.moveTo(x, y), ctx.lineTo(x + mathMin$2(d_1, width), y), (d_1 -= width) > 0 && ctx.lineTo(x + width, y + mathMin$2(d_1, height)), (d_1 -= height) > 0 && ctx.lineTo(x + mathMax$2(width - d_1, 0), y + height), (d_1 -= width) > 0 && ctx.lineTo(x, y + mathMax$2(height - d_1, 0)); break lo; } accumLength += l; } ctx.rect(x, y, width, height); break; case CMD.Z: if (drawPart) { var l = pathSegLen[segCount++]; if (accumLength + l > displayedLength) { var t = (displayedLength - accumLength) / l; ctx.lineTo(xi * (1 - t) + x0 * t, yi * (1 - t) + y0 * t); break lo; } accumLength += l; } ctx.closePath(), xi = x0, yi = y0; } } }, PathProxy.CMD = CMD, PathProxy.initDefaultProps = void ((proto = PathProxy.prototype)._saveData = !0, proto._needsDash = !1, proto._dashOffset = 0, proto._dashIdx = 0, proto._dashSum = 0, proto._ux = 0, proto._uy = 0), PathProxy; }(); function containStroke(x0, y0, x1, y1, lineWidth, x, y) { if (0 === lineWidth) return !1; var _a = 0, _b = x0; if (y > y0 + lineWidth && y > y1 + lineWidth || y < y0 - lineWidth && y < y1 - lineWidth || x > x0 + lineWidth && x > x1 + lineWidth || x < x0 - lineWidth && x < x1 - lineWidth) return !1; if (x0 === x1) return Math.abs(x - x0) <= lineWidth / 2; var tmp = (_a = (y0 - y1) / (x0 - x1)) * x - y + (x0 * y1 - x1 * y0) / (x0 - x1); return tmp * tmp / (_a * _a + 1) <= lineWidth / 2 * lineWidth / 2; } function containStroke$2(x0, y0, x1, y1, x2, y2, lineWidth, x, y) { return 0 !== lineWidth && (!(y > y0 + lineWidth) || !(y > y1 + lineWidth) || !(y > y2 + lineWidth)) && (!(y < y0 - lineWidth) || !(y < y1 - lineWidth) || !(y < y2 - lineWidth)) && (!(x > x0 + lineWidth) || !(x > x1 + lineWidth) || !(x > x2 + lineWidth)) && (!(x < x0 - lineWidth) || !(x < x1 - lineWidth) || !(x < x2 - lineWidth)) && quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, null) <= lineWidth / 2; } var PI2$2 = 2 * Math.PI; function normalizeRadian(angle) { return (angle %= PI2$2) < 0 && (angle += PI2$2), angle; } var PI2$3 = 2 * Math.PI; function windingLine(x0, y0, x1, y1, x, y) { if (y > y0 && y > y1 || y < y0 && y < y1 || y1 === y0) return 0; var t = (y - y0) / (y1 - y0), dir = y1 < y0 ? 1 : -1; (1 === t || 0 === t) && (dir = y1 < y0 ? 0.5 : -0.5); var x_ = t * (x1 - x0) + x0; return x_ === x ? 1 / 0 : x_ > x ? dir : 0; } var CMD$1 = PathProxy.CMD, PI2$4 = 2 * Math.PI, roots = [ -1, -1, -1 ], extrema = [ -1, -1 ]; function containPath(path, lineWidth, isStroke, x, y) { for(var x1, y1, data = path.data, len = path.len(), w = 0, xi = 0, yi = 0, x0 = 0, y0 = 0, i = 0; i < len;){ var x01, y01, x11, y11, x2, y2, x3, y3, cmd = data[i++], isFirst = 1 === i; switch(cmd === CMD$1.M && i > 1 && !isStroke && (w += windingLine(xi, yi, x0, y0, x, y)), isFirst && (xi = data[i], yi = data[i + 1], x0 = xi, y0 = yi), cmd){ case CMD$1.M: x0 = data[i++], y0 = data[i++], xi = x0, yi = y0; break; case CMD$1.L: if (isStroke) { if (containStroke(xi, yi, data[i], data[i + 1], lineWidth, x, y)) return !0; } else w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0; xi = data[i++], yi = data[i++]; break; case CMD$1.C: if (isStroke) { if (x01 = xi, y01 = yi, x11 = data[i++], y11 = data[i++], x2 = data[i++], y2 = data[i++], x3 = data[i], y3 = data[i + 1], 0 !== lineWidth && (!(y > y01 + lineWidth) || !(y > y11 + lineWidth) || !(y > y2 + lineWidth) || !(y > y3 + lineWidth)) && (!(y < y01 - lineWidth) || !(y < y11 - lineWidth) || !(y < y2 - lineWidth) || !(y < y3 - lineWidth)) && (!(x > x01 + lineWidth) || !(x > x11 + lineWidth) || !(x > x2 + lineWidth) || !(x > x3 + lineWidth)) && (!(x < x01 - lineWidth) || !(x < x11 - lineWidth) || !(x < x2 - lineWidth) || !(x < x3 - lineWidth)) && cubicProjectPoint(x01, y01, x11, y11, x2, y2, x3, y3, x, y, null) <= lineWidth / 2) return !0; } else w += function(x0, y0, x1, y1, x2, y2, x3, y3, x, y) { if (y > y0 && y > y1 && y > y2 && y > y3 || y < y0 && y < y1 && y < y2 && y < y3) return 0; var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots); if (0 === nRoots) return 0; for(var w = 0, nExtrema = -1, y0_ = void 0, y1_ = void 0, i = 0; i < nRoots; i++){ var t = roots[i], unit = 0 === t || 1 === t ? 0.5 : 1; cubicAt(x0, x1, x2, x3, t) < x || (nExtrema < 0 && (nExtrema = cubicExtrema(y0, y1, y2, y3, extrema), extrema[1] < extrema[0] && nExtrema > 1 && function() { var tmp = extrema[0]; extrema[0] = extrema[1], extrema[1] = tmp; }(), y0_ = cubicAt(y0, y1, y2, y3, extrema[0]), nExtrema > 1 && (y1_ = cubicAt(y0, y1, y2, y3, extrema[1]))), 2 === nExtrema ? t < extrema[0] ? w += y0_ < y0 ? unit : -unit : t < extrema[1] ? w += y1_ < y0_ ? unit : -unit : w += y3 < y1_ ? unit : -unit : t < extrema[0] ? w += y0_ < y0 ? unit : -unit : w += y3 < y0_ ? unit : -unit); } return w; }(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], x, y) || 0; xi = data[i++], yi = data[i++]; break; case CMD$1.Q: if (isStroke) { if (containStroke$2(xi, yi, data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) return !0; } else w += function(x0, y0, x1, y1, x2, y2, x, y) { if (y > y0 && y > y1 && y > y2 || y < y0 && y < y1 && y < y2) return 0; var nRoots = function(p0, p1, p2, val, roots) { var a = p0 - 2 * p1 + p2, b = 2 * (p1 - p0), c = p0 - val, n = 0; if (isAroundZero(a)) { if (isNotAroundZero$1(b)) { var t1 = -c / b; t1 >= 0 && t1 <= 1 && (roots[n++] = t1); } } else { var disc = b * b - 4 * a * c; if (isAroundZero(disc)) { var t1 = -b / (2 * a); t1 >= 0 && t1 <= 1 && (roots[n++] = t1); } else if (disc > 0) { var discSqrt = mathSqrt(disc), t1 = (-b + discSqrt) / (2 * a), t2 = (-b - discSqrt) / (2 * a); t1 >= 0 && t1 <= 1 && (roots[n++] = t1), t2 >= 0 && t2 <= 1 && (roots[n++] = t2); } } return n; }(y0, y1, y2, y, roots); if (0 === nRoots) return 0; var t = quadraticExtremum(y0, y1, y2); if (t >= 0 && t <= 1) { for(var w = 0, y_ = quadraticAt(y0, y1, y2, t), i = 0; i < nRoots; i++){ var unit = 0 === roots[i] || 1 === roots[i] ? 0.5 : 1, x_ = quadraticAt(x0, x1, x2, roots[i]); x_ < x || (roots[i] < t ? w += y_ < y0 ? unit : -unit : w += y2 < y_ ? unit : -unit); } return w; } var unit = 0 === roots[0] || 1 === roots[0] ? 0.5 : 1, x_ = quadraticAt(x0, x1, x2, roots[0]); return x_ < x ? 0 : y2 < y0 ? unit : -unit; }(xi, yi, data[i++], data[i++], data[i], data[i + 1], x, y) || 0; xi = data[i++], yi = data[i++]; break; case CMD$1.A: var cx = data[i++], cy = data[i++], rx = data[i++], ry = data[i++], theta = data[i++], dTheta = data[i++]; i += 1; var anticlockwise = !!(1 - data[i++]); x1 = Math.cos(theta) * rx + cx, y1 = Math.sin(theta) * ry + cy, isFirst ? (x0 = x1, y0 = y1) : w += windingLine(xi, yi, x1, y1, x, y); var _x = (x - cx) * ry / rx + cx; if (isStroke) { if (function(cx, cy, r, startAngle, endAngle, anticlockwise, lineWidth, x, y) { if (0 === lineWidth) return !1; var d = Math.sqrt((x -= cx) * x + (y -= cy) * y); if (d - lineWidth > r || d + lineWidth < r) return !1; if (Math.abs(startAngle - endAngle) % PI2$3 < 1e-4) return !0; if (anticlockwise) { var tmp = startAngle; startAngle = normalizeRadian(endAngle), endAngle = normalizeRadian(tmp); } else startAngle = normalizeRadian(startAngle), endAngle = normalizeRadian(endAngle); startAngle > endAngle && (endAngle += PI2$3); var angle = Math.atan2(y, x); return angle < 0 && (angle += PI2$3), angle >= startAngle && angle <= endAngle || angle + PI2$3 >= startAngle && angle + PI2$3 <= endAngle; }(cx, cy, ry, theta, theta + dTheta, anticlockwise, lineWidth, _x, y)) return !0; } else w += function(cx, cy, r, startAngle, endAngle, anticlockwise, x, y) { if ((y -= cy) > r || y < -r) return 0; var tmp = Math.sqrt(r * r - y * y); roots[0] = -tmp, roots[1] = tmp; var dTheta = Math.abs(startAngle - endAngle); if (dTheta < 1e-4) return 0; if (dTheta >= PI2$4 - 1e-4) { startAngle = 0, endAngle = PI2$4; var dir = anticlockwise ? 1 : -1; return x >= roots[0] + cx && x <= roots[1] + cx ? dir : 0; } if (startAngle > endAngle) { var tmp_1 = startAngle; startAngle = endAngle, endAngle = tmp_1; } startAngle < 0 && (startAngle += PI2$4, endAngle += PI2$4); for(var w = 0, i = 0; i < 2; i++){ var x_ = roots[i]; if (x_ + cx > x) { var angle = Math.atan2(y, x_), dir = anticlockwise ? 1 : -1; angle < 0 && (angle = PI2$4 + angle), (angle >= startAngle && angle <= endAngle || angle + PI2$4 >= startAngle && angle + PI2$4 <= endAngle) && (angle > Math.PI / 2 && angle < 1.5 * Math.PI && (dir = -dir), w += dir); } } return w; }(cx, cy, ry, theta, theta + dTheta, anticlockwise, _x, y); xi = Math.cos(theta + dTheta) * rx + cx, yi = Math.sin(theta + dTheta) * ry + cy; break; case CMD$1.R: x0 = xi = data[i++], y0 = yi = data[i++]; var width = data[i++], height = data[i++]; if (x1 = x0 + width, y1 = y0 + height, isStroke) { if (containStroke(x0, y0, x1, y0, lineWidth, x, y) || containStroke(x1, y0, x1, y1, lineWidth, x, y) || containStroke(x1, y1, x0, y1, lineWidth, x, y) || containStroke(x0, y1, x0, y0, lineWidth, x, y)) return !0; } else w += windingLine(x1, y0, x1, y1, x, y), w += windingLine(x0, y1, x0, y0, x, y); break; case CMD$1.Z: if (isStroke) { if (containStroke(xi, yi, x0, y0, lineWidth, x, y)) return !0; } else w += windingLine(xi, yi, x0, y0, x, y); xi = x0, yi = y0; } } return isStroke || 1e-4 > Math.abs(yi - y0) || (w += windingLine(xi, yi, x0, y0, x, y) || 0), 0 !== w; } var DEFAULT_PATH_STYLE = defaults({ fill: '#000', stroke: null, strokePercent: 1, fillOpacity: 1, strokeOpacity: 1, lineDashOffset: 0, lineWidth: 1, lineCap: 'butt', miterLimit: 10, strokeNoScale: !1, strokeFirst: !1 }, DEFAULT_COMMON_STYLE), DEFAULT_PATH_ANIMATION_PROPS = { style: defaults({ fill: !0, stroke: !0, strokePercent: !0, fillOpacity: !0, strokeOpacity: !0, lineDashOffset: !0, lineWidth: !0, miterLimit: !0 }, DEFAULT_COMMON_ANIMATION_PROPS.style) }, pathCopyParams = [ 'x', 'y', 'rotation', 'scaleX', 'scaleY', 'originX', 'originY', 'invisible', 'culling', 'z', 'z2', 'zlevel', 'parent' ], Path = function(_super) { var pathProto; function Path(opts) { return _super.call(this, opts) || this; } return __extends(Path, _super), Path.prototype.update = function() { var _this = this; _super.prototype.update.call(this); var style = this.style; if (style.decal) { var decalEl = this._decalEl = this._decalEl || new Path(); decalEl.buildPath === Path.prototype.buildPath && (decalEl.buildPath = function(ctx) { _this.buildPath(ctx, _this.shape); }), decalEl.silent = !0; var decalElStyle = decalEl.style; for(var key in style)decalElStyle[key] !== style[key] && (decalElStyle[key] = style[key]); decalElStyle.fill = style.fill ? style.decal : null, decalElStyle.decal = null, decalElStyle.shadowColor = null, style.strokeFirst && (decalElStyle.stroke = null); for(var i = 0; i < pathCopyParams.length; ++i)decalEl[pathCopyParams[i]] = this[pathCopyParams[i]]; decalEl.__dirty |= Element.REDARAW_BIT; } else this._decalEl && (this._decalEl = null); }, Path.prototype.getDecalElement = function() { return this._decalEl; }, Path.prototype._init = function(props) { var keysArr = keys(props); this.shape = this.getDefaultShape(); var defaultStyle = this.getDefaultStyle(); defaultStyle && this.useStyle(defaultStyle); for(var i = 0; i < keysArr.length; i++){ var key = keysArr[i], value = props[key]; 'style' === key ? this.style ? extend(this.style, value) : this.useStyle(value) : 'shape' === key ? extend(this.shape, value) : _super.prototype.attrKV.call(this, key, value); } this.style || this.useStyle({}); }, Path.prototype.getDefaultStyle = function() { return null; }, Path.prototype.getDefaultShape = function() { return {}; }, Path.prototype.canBeInsideText = function() { return this.hasFill(); }, Path.prototype.getInsideTextFill = function() { var pathFill = this.style.fill; if ('none' !== pathFill) { if (isString(pathFill)) { var fillLum = lum(pathFill, 0); return fillLum > 0.5 ? DARK_LABEL_COLOR : fillLum > 0.2 ? '#eee' : LIGHT_LABEL_COLOR; } if (pathFill) return LIGHT_LABEL_COLOR; } return DARK_LABEL_COLOR; }, Path.prototype.getInsideTextStroke = function(textFill) { var pathFill = this.style.fill; if (isString(pathFill)) { var zr = this.__zr; if (!!(zr && zr.isDarkMode()) == 0.4 > lum(textFill, 0)) return pathFill; } }, Path.prototype.buildPath = function(ctx, shapeCfg, inBundle) {}, Path.prototype.pathUpdated = function() { this.__dirty &= ~Path.SHAPE_CHANGED_BIT; }, Path.prototype.createPathProxy = function() { this.path = new PathProxy(!1); }, Path.prototype.hasStroke = function() { var style = this.style, stroke = style.stroke; return !(null == stroke || 'none' === stroke || !(style.lineWidth > 0)); }, Path.prototype.hasFill = function() { var fill = this.style.fill; return null != fill && 'none' !== fill; }, Path.prototype.getBoundingRect = function() { var rect = this._rect, style = this.style, needsUpdateRect = !rect; if (needsUpdateRect) { var firstInvoke = !1; this.path || (firstInvoke = !0, this.createPathProxy()); var path = this.path; (firstInvoke || this.__dirty & Path.SHAPE_CHANGED_BIT) && (path.beginPath(), this.buildPath(path, this.shape, !1), this.pathUpdated()), rect = path.getBoundingRect(); } if (this._rect = rect, this.hasStroke() && this.path && this.path.len() > 0) { var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone()); if (this.__dirty || needsUpdateRect) { rectWithStroke.copy(rect); var lineScale = style.strokeNoScale ? this.getLineScale() : 1, w = style.lineWidth; if (!this.hasFill()) { var strokeContainThreshold = this.strokeContainThreshold; w = Math.max(w, null == strokeContainThreshold ? 4 : strokeContainThreshold); } lineScale > 1e-10 && (rectWithStroke.width += w / lineScale, rectWithStroke.height += w / lineScale, rectWithStroke.x -= w / lineScale / 2, rectWithStroke.y -= w / lineScale / 2); } return rectWithStroke; } return rect; }, Path.prototype.contain = function(x, y) { var localPos = this.transformCoordToLocal(x, y), rect = this.getBoundingRect(), style = this.style; if (x = localPos[0], y = localPos[1], rect.contain(x, y)) { var pathProxy = this.path; if (this.hasStroke()) { var lineWidth = style.lineWidth, lineScale = style.strokeNoScale ? this.getLineScale() : 1; if (lineScale > 1e-10 && (this.hasFill() || (lineWidth = Math.max(lineWidth, this.strokeContainThreshold)), containPath(pathProxy, lineWidth / lineScale, !0, x, y))) return !0; } if (this.hasFill()) return containPath(pathProxy, 0, !1, x, y); } return !1; }, Path.prototype.dirtyShape = function() { this.__dirty |= Path.SHAPE_CHANGED_BIT, this._rect && (this._rect = null), this._decalEl && this._decalEl.dirtyShape(), this.markRedraw(); }, Path.prototype.dirty = function() { this.dirtyStyle(), this.dirtyShape(); }, Path.prototype.animateShape = function(loop) { return this.animate('shape', loop); }, Path.prototype.updateDuringAnimation = function(targetKey) { 'style' === targetKey ? this.dirtyStyle() : 'shape' === targetKey ? this.dirtyShape() : this.markRedraw(); }, Path.prototype.attrKV = function(key, value) { 'shape' === key ? this.setShape(value) : _super.prototype.attrKV.call(this, key, value); }, Path.prototype.setShape = function(keyOrObj, value) { var shape = this.shape; return shape || (shape = this.shape = {}), 'string' == typeof keyOrObj ? shape[keyOrObj] = value : extend(shape, keyOrObj), this.dirtyShape(), this; }, Path.prototype.shapeChanged = function() { return !!(this.__dirty & Path.SHAPE_CHANGED_BIT); }, Path.prototype.createStyle = function(obj) { return createObject(DEFAULT_PATH_STYLE, obj); }, Path.prototype._innerSaveToNormal = function(toState) { _super.prototype._innerSaveToNormal.call(this, toState); var normalState = this._normalState; toState.shape && !normalState.shape && (normalState.shape = extend({}, this.shape)); }, Path.prototype._applyStateObj = function(stateName, state, normalState, keepCurrentStates, transition, animationCfg) { var targetShape; if (_super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg), state && state.shape ? transition ? keepCurrentStates ? targetShape = state.shape : (targetShape = extend({}, normalState.shape), extend(targetShape, state.shape)) : (targetShape = extend({}, keepCurrentStates ? this.shape : normalState.shape), extend(targetShape, state.shape)) : state && keepCurrentStates || (targetShape = normalState.shape), targetShape) { if (transition) { this.shape = extend({}, this.shape); for(var targetShapePrimaryProps = {}, shapeKeys = keys(targetShape), i = 0; i < shapeKeys.length; i++){ var key = shapeKeys[i]; 'object' == typeof targetShape[key] ? this.shape[key] = targetShape[key] : targetShapePrimaryProps[key] = targetShape[key]; } this._transitionState(stateName, { shape: targetShapePrimaryProps }, animationCfg); } else this.shape = targetShape, this.dirtyShape(); } }, Path.prototype._mergeStates = function(states) { for(var mergedShape, mergedState = _super.prototype._mergeStates.call(this, states), i = 0; i < states.length; i++){ var state = states[i]; state.shape && (mergedShape = mergedShape || {}, this._mergeStyle(mergedShape, state.shape)); } return mergedShape && (mergedState.shape = mergedShape), mergedState; }, Path.prototype.getAnimationStyleProps = function() { return DEFAULT_PATH_ANIMATION_PROPS; }, Path.prototype.isZeroArea = function() { return !1; }, Path.extend = function(defaultProps) { var Sub = function(_super) { function Sub(opts) { var _this = _super.call(this, opts) || this; return defaultProps.init && defaultProps.init.call(_this, opts), _this; } return __extends(Sub, _super), Sub.prototype.getDefaultStyle = function() { return clone(defaultProps.style); }, Sub.prototype.getDefaultShape = function() { return clone(defaultProps.shape); }, Sub; }(Path); for(var key in defaultProps)'function' == typeof defaultProps[key] && (Sub.prototype[key] = defaultProps[key]); return Sub; }, Path.SHAPE_CHANGED_BIT = 4, Path.initDefaultProps = void ((pathProto = Path.prototype).type = 'path', pathProto.strokeContainThreshold = 5, pathProto.segmentIgnoreThreshold = 0, pathProto.subPixelOptimize = !1, pathProto.autoBatch = !1, pathProto.__dirty = Element.REDARAW_BIT | Displayable.STYLE_CHANGED_BIT | Path.SHAPE_CHANGED_BIT), Path; }(Displayable), DEFAULT_TSPAN_STYLE = defaults({ strokeFirst: !0, font: DEFAULT_FONT, x: 0, y: 0, textAlign: 'left', textBaseline: 'top', miterLimit: 2 }, DEFAULT_PATH_STYLE), TSpan = function(_super) { function TSpan() { return null !== _super && _super.apply(this, arguments) || this; } return __extends(TSpan, _super), TSpan.prototype.hasStroke = function() { var style = this.style, stroke = style.stroke; return null != stroke && 'none' !== stroke && style.lineWidth > 0; }, TSpan.prototype.hasFill = function() { var fill = this.style.fill; return null != fill && 'none' !== fill; }, TSpan.prototype.createStyle = function(obj) { return createObject(DEFAULT_TSPAN_STYLE, obj); }, TSpan.prototype.setBoundingRect = function(rect) { this._rect = rect; }, TSpan.prototype.getBoundingRect = function() { var style = this.style; if (!this._rect) { var text = style.text; null != text ? text += '' : text = ''; var rect = getBoundingRect(text, style.font, style.textAlign, style.textBaseline); if (rect.x += style.x || 0, rect.y += style.y || 0, this.hasStroke()) { var w = style.lineWidth; rect.x -= w / 2, rect.y -= w / 2, rect.width += w, rect.height += w; } this._rect = rect; } return this._rect; }, TSpan.initDefaultProps = void (TSpan.prototype.dirtyRectTolerance = 10), TSpan; }(Displayable); TSpan.prototype.type = 'tspan'; var DEFAULT_IMAGE_STYLE = defaults({ x: 0, y: 0 }, DEFAULT_COMMON_STYLE), DEFAULT_IMAGE_ANIMATION_PROPS = { style: defaults({ x: !0, y: !0, width: !0, height: !0, sx: !0, sy: !0, sWidth: !0, sHeight: !0 }, DEFAULT_COMMON_ANIMATION_PROPS.style) }, ZRImage = function(_super) { function ZRImage() { return null !== _super && _super.apply(this, arguments) || this; } return __extends(ZRImage, _super), ZRImage.prototype.createStyle = function(obj) { return createObject(DEFAULT_IMAGE_STYLE, obj); }, ZRImage.prototype._getSize = function(dim) { var source, style = this.style, size = style[dim]; if (null != size) return size; var imageSource = (source = style.image) && 'string' != typeof source && source.width && source.height ? style.image : this.__image; if (!imageSource) return 0; var otherDim = 'width' === dim ? 'height' : 'width', otherDimSize = style[otherDim]; return null == otherDimSize ? imageSource[dim] : imageSource[dim] / imageSource[otherDim] * otherDimSize; }, ZRImage.prototype.getWidth = function() { return this._getSize('width'); }, ZRImage.prototype.getHeight = function() { return this._getSize('height'); }, ZRImage.prototype.getAnimationStyleProps = function() { return DEFAULT_IMAGE_ANIMATION_PROPS; }, ZRImage.prototype.getBoundingRect = function() { var style = this.style; return this._rect || (this._rect = new BoundingRect(style.x || 0, style.y || 0, this.getWidth(), this.getHeight())), this._rect; }, ZRImage; }(Displayable); ZRImage.prototype.type = 'image'; var round$1 = Math.round; function subPixelOptimizeLine(outputShape, inputShape, style) { if (inputShape) { var x1 = inputShape.x1, x2 = inputShape.x2, y1 = inputShape.y1, y2 = inputShape.y2; outputShape.x1 = x1, outputShape.x2 = x2, outputShape.y1 = y1, outputShape.y2 = y2; var lineWidth = style && style.lineWidth; return lineWidth && (round$1(2 * x1) === round$1(2 * x2) && (outputShape.x1 = outputShape.x2 = subPixelOptimize(x1, lineWidth, !0)), round$1(2 * y1) === round$1(2 * y2) && (outputShape.y1 = outputShape.y2 = subPixelOptimize(y1, lineWidth, !0))), outputShape; } } function subPixelOptimizeRect(outputShape, inputShape, style) { if (inputShape) { var originX = inputShape.x, originY = inputShape.y, originWidth = inputShape.width, originHeight = inputShape.height; outputShape.x = originX, outputShape.y = originY, outputShape.width = originWidth, outputShape.height = originHeight; var lineWidth = style && style.lineWidth; return lineWidth && (outputShape.x = subPixelOptimize(originX, lineWidth, !0), outputShape.y = subPixelOptimize(originY, lineWidth, !0), outputShape.width = Math.max(subPixelOptimize(originX + originWidth, lineWidth, !1) - outputShape.x, 0 === originWidth ? 0 : 1), outputShape.height = Math.max(subPixelOptimize(originY + originHeight, lineWidth, !1) - outputShape.y, 0 === originHeight ? 0 : 1)), outputShape; } } function subPixelOptimize(position, lineWidth, positiveOrNegative) { if (!lineWidth) return position; var doubledPosition = round$1(2 * position); return (doubledPosition + round$1(lineWidth)) % 2 == 0 ? doubledPosition / 2 : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2; } var RectShape = function() { this.x = 0, this.y = 0, this.width = 0, this.height = 0; }, subPixelOptimizeOutputShape = {}, Rect = function(_super) { function Rect(opts) { return _super.call(this, opts) || this; } return __extends(Rect, _super), Rect.prototype.getDefaultShape = function() { return new RectShape(); }, Rect.prototype.buildPath = function(ctx, shape) { if (this.subPixelOptimize) { var shape1, r1, r2, r3, r4, total, x, y, width, height, r, x1, y1, width1, height1, optimizedShape = subPixelOptimizeRect(subPixelOptimizeOutputShape, shape, this.style); x1 = optimizedShape.x, y1 = optimizedShape.y, width1 = optimizedShape.width, height1 = optimizedShape.height, optimizedShape.r = shape.r, shape = optimizedShape; } else x1 = shape.x, y1 = shape.y, width1 = shape.width, height1 = shape.height; shape.r ? (x = (shape1 = shape).x, y = shape1.y, width = shape1.width, height = shape1.height, r = shape1.r, width < 0 && (x += width, width = -width), height < 0 && (y += height, height = -height), 'number' == typeof r ? r1 = r2 = r3 = r4 = r : r instanceof Array ? 1 === r.length ? r1 = r2 = r3 = r4 = r[0] : 2 === r.length ? (r1 = r3 = r[0], r2 = r4 = r[1]) : 3 === r.length ? (r1 = r[0], r2 = r4 = r[1], r3 = r[2]) : (r1 = r[0], r2 = r[1], r3 = r[2], r4 = r[3]) : r1 = r2 = r3 = r4 = 0, r1 + r2 > width && (total = r1 + r2, r1 *= width / total, r2 *= width / total), r3 + r4 > width && (total = r3 + r4, r3 *= width / total, r4 *= width / total), r2 + r3 > height && (total = r2 + r3, r2 *= height / total, r3 *= height / total), r1 + r4 > height && (total = r1 + r4, r1 *= height / total, r4 *= height / total), ctx.moveTo(x + r1, y), ctx.lineTo(x + width - r2, y), 0 !== r2 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0), ctx.lineTo(x + width, y + height - r3), 0 !== r3 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2), ctx.lineTo(x + r4, y + height), 0 !== r4 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI), ctx.lineTo(x, y + r1), 0 !== r1 && ctx.arc(x + r1, y + r1, r1, Math.PI, 1.5 * Math.PI)) : ctx.rect(x1, y1, width1, height1); }, Rect.prototype.isZeroArea = function() { return !this.shape.width || !this.shape.height; }, Rect; }(Path); Rect.prototype.type = 'rect'; var DEFAULT_RICH_TEXT_COLOR = { fill: '#000' }, DEFAULT_TEXT_ANIMATION_PROPS = { style: defaults({ fill: !0, stroke: !0, fillOpacity: !0, strokeOpacity: !0, lineWidth: !0, fontSize: !0, lineHeight: !0, width: !0, height: !0, textShadowColor: !0, textShadowBlur: !0, textShadowOffsetX: !0, textShadowOffsetY: !0, backgroundColor: !0, padding: !0, borderColor: !0, borderWidth: !0, borderRadius: !0 }, DEFAULT_COMMON_ANIMATION_PROPS.style) }, ZRText = function(_super) { function ZRText(opts) { var _this = _super.call(this) || this; return _this.type = 'text', _this._children = [], _this._defaultStyle = DEFAULT_RICH_TEXT_COLOR, _this.attr(opts), _this; } return __extends(ZRText, _super), ZRText.prototype.childrenRef = function() { return this._children; }, ZRText.prototype.update = function() { this.styleChanged() && this._updateSubTexts(); for(var i = 0; i < this._children.length; i++){ var child = this._children[i]; child.zlevel = this.zlevel, child.z = this.z, child.z2 = this.z2, child.culling = this.culling, child.cursor = this.cursor, child.invisible = this.invisible; } var attachedTransform = this.attachedTransform; if (attachedTransform) { attachedTransform.updateTransform(); var m = attachedTransform.transform; m ? (this.transform = this.transform || [], copy$1(this.transform, m)) : this.transform = null; } else _super.prototype.update.call(this); }, ZRText.prototype.getComputedTransform = function() { return this.__hostTarget && (this.__hostTarget.getComputedTransform(), this.__hostTarget.updateInnerText(!0)), this.attachedTransform ? this.attachedTransform.getComputedTransform() : _super.prototype.getComputedTransform.call(this); }, ZRText.prototype._updateSubTexts = function() { var style; this._childCursor = 0, normalizeStyle(style = this.style), each(style.rich, normalizeStyle), this.style.rich ? this._updateRichTexts() : this._updatePlainTexts(), this._children.length = this._childCursor, this.styleUpdated(); }, ZRText.prototype.addSelfToZr = function(zr) { _super.prototype.addSelfToZr.call(this, zr); for(var i = 0; i < this._children.length; i++)this._children[i].__zr = zr; }, ZRText.prototype.removeSelfFromZr = function(zr) { _super.prototype.removeSelfFromZr.call(this, zr); for(var i = 0; i < this._children.length; i++)this._children[i].__zr = null; }, ZRText.prototype.getBoundingRect = function() { if (this.styleChanged() && this._updateSubTexts(), !this._rect) { for(var tmpRect = new BoundingRect(0, 0, 0, 0), children = this._children, tmpMat = [], rect = null, i = 0; i < children.length; i++){ var child = children[i], childRect = child.getBoundingRect(), transform = child.getLocalTransform(tmpMat); transform ? (tmpRect.copy(childRect), tmpRect.applyTransform(transform), (rect = rect || tmpRect.clone()).union(tmpRect)) : (rect = rect || childRect.clone()).union(childRect); } this._rect = rect || tmpRect; } return this._rect; }, ZRText.prototype.setDefaultTextStyle = function(defaultTextStyle) { this._defaultStyle = defaultTextStyle || DEFAULT_RICH_TEXT_COLOR; }, ZRText.prototype.setTextContent = function(textContent) { throw Error('Can\'t attach text on another text'); }, ZRText.prototype._mergeStyle = function(targetStyle, sourceStyle) { if (!sourceStyle) return targetStyle; var sourceRich = sourceStyle.rich, targetRich = targetStyle.rich || sourceRich && {}; return extend(targetStyle, sourceStyle), sourceRich && targetRich ? (this._mergeRich(targetRich, sourceRich), targetStyle.rich = targetRich) : targetRich && (targetStyle.rich = targetRich), targetStyle; }, ZRText.prototype._mergeRich = function(targetRich, sourceRich) { for(var richNames = keys(sourceRich), i = 0; i < richNames.length; i++){ var richName = richNames[i]; targetRich[richName] = targetRich[richName] || {}, extend(targetRich[richName], sourceRich[richName]); } }, ZRText.prototype.getAnimationStyleProps = function() { return DEFAULT_TEXT_ANIMATION_PROPS; }, ZRText.prototype._getOrCreateChild = function(Ctor) { var child = this._children[this._childCursor]; return child && child instanceof Ctor || (child = new Ctor()), this._children[this._childCursor++] = child, child.__zr = this.__zr, child.parent = this, child; }, ZRText.prototype._updatePlainTexts = function() { var fill, style = this.style, textFont = style.font || DEFAULT_FONT, textPadding = style.padding, contentBlock = function(text, style) { null != text && (text += ''); var lines, overflow = style.overflow, padding = style.padding, font = style.font, calculatedLineHeight = getLineHeight(font), lineHeight = retrieve2(style.lineHeight, calculatedLineHeight), truncateLineOverflow = 'truncate' === style.lineOverflow, width = style.width, contentHeight = (lines = null != width && 'break' === overflow || 'breakAll' === overflow ? text ? wrapText(text, style.font, width, 'breakAll' === overflow, 0).lines : [] : text ? text.split('\n') : []).length * lineHeight, height = retrieve2(style.height, contentHeight); contentHeight > height && truncateLineOverflow && (lines = lines.slice(0, Math.floor(height / lineHeight))); var outerHeight = height, outerWidth = width; if (padding && (outerHeight += padding[0] + padding[2], null != outerWidth && (outerWidth += padding[1] + padding[3])), text && 'truncate' === overflow && null != outerWidth) for(var options = prepareTruncateOptions(width, font, style.ellipsis, { minChar: style.truncateMinChar, placeholder: style.placeholder }), i = 0; i < lines.length; i++)lines[i] = truncateSingleLine(lines[i], options); if (null == width) { for(var maxWidth = 0, i = 0; i < lines.length; i++)maxWidth = Math.max(getWidth(lines[i], font), maxWidth); width = maxWidth; } return { lines: lines, height: height, outerHeight: outerHeight, lineHeight: lineHeight, calculatedLineHeight: calculatedLineHeight, contentHeight: contentHeight, width: width }; }(getStyleText(style), style), needDrawBg = needDrawBackground(style), bgColorDrawn = !!style.backgroundColor, outerHeight = contentBlock.outerHeight, textLines = contentBlock.lines, lineHeight = contentBlock.lineHeight, defaultStyle = this._defaultStyle, baseX = style.x || 0, baseY = style.y || 0, textAlign = style.align || defaultStyle.align || 'left', verticalAlign = style.verticalAlign || defaultStyle.verticalAlign || 'top', textX = baseX, textY = adjustTextY(baseY, contentBlock.contentHeight, verticalAlign); if (needDrawBg || textPadding) { var outerWidth_1 = contentBlock.width; textPadding && (outerWidth_1 += textPadding[1] + textPadding[3]); var boxX = adjustTextX(baseX, outerWidth_1, textAlign), boxY = adjustTextY(baseY, outerHeight, verticalAlign); needDrawBg && this._renderBackground(style, style, boxX, boxY, outerWidth_1, outerHeight); } textY += lineHeight / 2, textPadding && (textX = getTextXForPadding(baseX, textAlign, textPadding), 'top' === verticalAlign ? textY += textPadding[0] : 'bottom' === verticalAlign && (textY -= textPadding[2])); for(var defaultLineWidth = 0, useDefaultFill = !1, textFill = null == (fill = ('fill' in style) ? style.fill : (useDefaultFill = !0, defaultStyle.fill)) || 'none' === fill ? null : fill.image || fill.colorStops ? '#000' : fill, textStroke = getStroke(('stroke' in style) ? style.stroke : bgColorDrawn || defaultStyle.autoStroke && !useDefaultFill ? null : (defaultLineWidth = 2, defaultStyle.stroke)), hasShadow = style.textShadowBlur > 0, fixedBoundingRect = null != style.width && ('truncate' === style.overflow || 'break' === style.overflow || 'breakAll' === style.overflow), calculatedLineHeight = contentBlock.calculatedLineHeight, i = 0; i < textLines.length; i++){ var el = this._getOrCreateChild(TSpan), subElStyle = el.createStyle(); el.useStyle(subElStyle), subElStyle.text = textLines[i], subElStyle.x = textX, subElStyle.y = textY, textAlign && (subElStyle.textAlign = textAlign), subElStyle.textBaseline = 'middle', subElStyle.opacity = style.opacity, subElStyle.strokeFirst = !0, hasShadow && (subElStyle.shadowBlur = style.textShadowBlur || 0, subElStyle.shadowColor = style.textShadowColor || 'transparent', subElStyle.shadowOffsetX = style.textShadowOffsetX || 0, subElStyle.shadowOffsetY = style.textShadowOffsetY || 0), textStroke && (subElStyle.stroke = textStroke, subElStyle.lineWidth = style.lineWidth || defaultLineWidth, subElStyle.lineDash = style.lineDash, subElStyle.lineDashOffset = style.lineDashOffset || 0), textFill && (subElStyle.fill = textFill), subElStyle.font = textFont, textY += lineHeight, fixedBoundingRect && el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, style.width, subElStyle.textAlign), adjustTextY(subElStyle.y, calculatedLineHeight, subElStyle.textBaseline), style.width, calculatedLineHeight)); } }, ZRText.prototype._updateRichTexts = function() { var style = this.style, contentBlock = function(text, style) { var result, contentBlock = new RichTextContentBlock(); if (null != text && (text += ''), !text) return contentBlock; for(var topWidth = style.width, topHeight = style.height, overflow = style.overflow, wrapInfo = ('break' === overflow || 'breakAll' === overflow) && null != topWidth ? { width: topWidth, accumWidth: 0, breakAll: 'breakAll' === overflow } : null, lastIndex = STYLE_REG.lastIndex = 0; null != (result = STYLE_REG.exec(text));){ var matchedIndex = result.index; matchedIndex > lastIndex && pushTokens(contentBlock, text.substring(lastIndex, matchedIndex), style, wrapInfo), pushTokens(contentBlock, result[2], style, wrapInfo, result[1]), lastIndex = STYLE_REG.lastIndex; } lastIndex < text.length && pushTokens(contentBlock, text.substring(lastIndex, text.length), style, wrapInfo); var pendingList = [], calculatedHeight = 0, calculatedWidth = 0, stlPadding = style.padding, truncate = 'truncate' === overflow, truncateLine = 'truncate' === style.lineOverflow; function finishLine(line, lineWidth, lineHeight) { line.width = lineWidth, line.lineHeight = lineHeight, calculatedHeight += lineHeight, calculatedWidth = Math.max(calculatedWidth, lineWidth); } outer: for(var i = 0; i < contentBlock.lines.length; i++){ for(var line = contentBlock.lines[i], lineHeight = 0, lineWidth = 0, j = 0; j < line.tokens.length; j++){ var token = line.tokens[j], tokenStyle = token.styleName && style.rich[token.styleName] || {}, textPadding = token.textPadding = tokenStyle.padding, paddingH = textPadding ? textPadding[1] + textPadding[3] : 0, font = token.font = tokenStyle.font || style.font; token.contentHeight = getLineHeight(font); var tokenHeight = retrieve2(tokenStyle.height, token.contentHeight); if (token.innerHeight = tokenHeight, textPadding && (tokenHeight += textPadding[0] + textPadding[2]), token.height = tokenHeight, token.lineHeight = retrieve3(tokenStyle.lineHeight, style.lineHeight, tokenHeight), token.align = tokenStyle && tokenStyle.align || style.align, token.verticalAlign = tokenStyle && tokenStyle.verticalAlign || 'middle', truncateLine && null != topHeight && calculatedHeight + token.lineHeight > topHeight) { j > 0 ? (line.tokens = line.tokens.slice(0, j), finishLine(line, lineWidth, lineHeight), contentBlock.lines = contentBlock.lines.slice(0, i + 1)) : contentBlock.lines = contentBlock.lines.slice(0, i); break outer; } var styleTokenWidth = tokenStyle.width, tokenWidthNotSpecified = null == styleTokenWidth || 'auto' === styleTokenWidth; if ('string' == typeof styleTokenWidth && '%' === styleTokenWidth.charAt(styleTokenWidth.length - 1)) token.percentWidth = styleTokenWidth, pendingList.push(token), token.contentWidth = getWidth(token.text, font); else { if (tokenWidthNotSpecified) { var textBackgroundColor = tokenStyle.backgroundColor, bgImg = textBackgroundColor && textBackgroundColor.image; bgImg && isImageReady(bgImg = function(newImageOrSrc) { if ('string' != typeof newImageOrSrc) return newImageOrSrc; var cachedImgObj = globalImageCache.get(newImageOrSrc); return cachedImgObj && cachedImgObj.image; }(bgImg)) && (token.width = Math.max(token.width, bgImg.width * tokenHeight / bgImg.height)); } var remainTruncWidth = truncate && null != topWidth ? topWidth - lineWidth : null; null != remainTruncWidth && remainTruncWidth < token.width ? !tokenWidthNotSpecified || remainTruncWidth < paddingH ? (token.text = '', token.width = token.contentWidth = 0) : (token.text = truncateText(token.text, remainTruncWidth - paddingH, font, style.ellipsis, { minChar: style.truncateMinChar }), token.width = token.contentWidth = getWidth(token.text, font)) : token.contentWidth = getWidth(token.text, font); } token.width += paddingH, lineWidth += token.width, tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight)); } finishLine(line, lineWidth, lineHeight); } contentBlock.outerWidth = contentBlock.width = retrieve2(topWidth, calculatedWidth), contentBlock.outerHeight = contentBlock.height = retrieve2(topHeight, calculatedHeight), contentBlock.contentHeight = calculatedHeight, contentBlock.contentWidth = calculatedWidth, stlPadding && (contentBlock.outerWidth += stlPadding[1] + stlPadding[3], contentBlock.outerHeight += stlPadding[0] + stlPadding[2]); for(var i = 0; i < pendingList.length; i++){ var token = pendingList[i], percentWidth = token.percentWidth; token.width = parseInt(percentWidth, 10) / 100 * contentBlock.width; } return contentBlock; }(getStyleText(style), style), contentWidth = contentBlock.width, outerWidth = contentBlock.outerWidth, outerHeight = contentBlock.outerHeight, textPadding = style.padding, baseX = style.x || 0, baseY = style.y || 0, defaultStyle = this._defaultStyle, textAlign = style.align || defaultStyle.align, verticalAlign = style.verticalAlign || defaultStyle.verticalAlign, boxX = adjustTextX(baseX, outerWidth, textAlign), boxY = adjustTextY(baseY, outerHeight, verticalAlign), xLeft = boxX, lineTop = boxY; textPadding && (xLeft += textPadding[3], lineTop += textPadding[0]); var xRight = xLeft + contentWidth; needDrawBackground(style) && this._renderBackground(style, style, boxX, boxY, outerWidth, outerHeight); for(var bgColorDrawn = !!style.backgroundColor, i = 0; i < contentBlock.lines.length; i++){ for(var line = contentBlock.lines[i], tokens = line.tokens, tokenCount = tokens.length, lineHeight = line.lineHeight, remainedWidth = line.width, leftIndex = 0, lineXLeft = xLeft, lineXRight = xRight, rightIndex = tokenCount - 1, token = void 0; leftIndex < tokenCount && (!(token = tokens[leftIndex]).align || 'left' === token.align);)this._placeToken(token, style, lineHeight, lineTop, lineXLeft, 'left', bgColorDrawn), remainedWidth -= token.width, lineXLeft += token.width, leftIndex++; for(; rightIndex >= 0 && 'right' === (token = tokens[rightIndex]).align;)this._placeToken(token, style, lineHeight, lineTop, lineXRight, 'right', bgColorDrawn), remainedWidth -= token.width, lineXRight -= token.width, rightIndex--; for(lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - remainedWidth) / 2; leftIndex <= rightIndex;)token = tokens[leftIndex], this._placeToken(token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center', bgColorDrawn), lineXLeft += token.width, leftIndex++; lineTop += lineHeight; } }, ZRText.prototype._placeToken = function(token, style, lineHeight, lineTop, x, textAlign, parentBgColorDrawn) { var tokenStyle = style.rich[token.styleName] || {}; tokenStyle.text = token.text; var verticalAlign = token.verticalAlign, y = lineTop + lineHeight / 2; 'top' === verticalAlign ? y = lineTop + token.height / 2 : 'bottom' === verticalAlign && (y = lineTop + lineHeight - token.height / 2), !token.isLineHolder && needDrawBackground(tokenStyle) && this._renderBackground(tokenStyle, style, 'right' === textAlign ? x - token.width : 'center' === textAlign ? x - token.width / 2 : x, y - token.height / 2, token.width, token.height); var bgColorDrawn = !!tokenStyle.backgroundColor, textPadding = token.textPadding; textPadding && (x = getTextXForPadding(x, textAlign, textPadding), y -= token.height / 2 - textPadding[0] - token.innerHeight / 2); var el = this._getOrCreateChild(TSpan), subElStyle = el.createStyle(); el.useStyle(subElStyle); var defaultStyle = this._defaultStyle, useDefaultFill = !1, defaultLineWidth = 0, textFill = getStroke('fill' in tokenStyle ? tokenStyle.fill : 'fill' in style ? style.fill : (useDefaultFill = !0, defaultStyle.fill)), textStroke = getStroke('stroke' in tokenStyle ? tokenStyle.stroke : 'stroke' in style ? style.stroke : bgColorDrawn || parentBgColorDrawn || defaultStyle.autoStroke && !useDefaultFill ? null : (defaultLineWidth = 2, defaultStyle.stroke)), hasShadow = tokenStyle.textShadowBlur > 0 || style.textShadowBlur > 0; subElStyle.text = token.text, subElStyle.x = x, subElStyle.y = y, hasShadow && (subElStyle.shadowBlur = tokenStyle.textShadowBlur || style.textShadowBlur || 0, subElStyle.shadowColor = tokenStyle.textShadowColor || style.textShadowColor || 'transparent', subElStyle.shadowOffsetX = tokenStyle.textShadowOffsetX || style.textShadowOffsetX || 0, subElStyle.shadowOffsetY = tokenStyle.textShadowOffsetY || style.textShadowOffsetY || 0), subElStyle.textAlign = textAlign, subElStyle.textBaseline = 'middle', subElStyle.font = token.font || DEFAULT_FONT, subElStyle.opacity = retrieve3(tokenStyle.opacity, style.opacity, 1), textStroke && (subElStyle.lineWidth = retrieve3(tokenStyle.lineWidth, style.lineWidth, defaultLineWidth), subElStyle.lineDash = retrieve2(tokenStyle.lineDash, style.lineDash), subElStyle.lineDashOffset = style.lineDashOffset || 0, subElStyle.stroke = textStroke), textFill && (subElStyle.fill = textFill); var textWidth = token.contentWidth, textHeight = token.contentHeight; el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, textWidth, subElStyle.textAlign), adjustTextY(subElStyle.y, textHeight, subElStyle.textBaseline), textWidth, textHeight)); }, ZRText.prototype._renderBackground = function(style, topStyle, x, y, width, height) { var rectEl, imgEl, textBackgroundColor = style.backgroundColor, textBorderWidth = style.borderWidth, textBorderColor = style.borderColor, isPlainBg = isString(textBackgroundColor), textBorderRadius = style.borderRadius, self1 = this; if (isPlainBg || textBorderWidth && textBorderColor) { (rectEl = this._getOrCreateChild(Rect)).useStyle(rectEl.createStyle()), rectEl.style.fill = null; var rectShape = rectEl.shape; rectShape.x = x, rectShape.y = y, rectShape.width = width, rectShape.height = height, rectShape.r = textBorderRadius, rectEl.dirtyShape(); } if (isPlainBg) { var rectStyle = rectEl.style; rectStyle.fill = textBackgroundColor || null, rectStyle.fillOpacity = retrieve2(style.fillOpacity, 1); } else if (textBackgroundColor && textBackgroundColor.image) { (imgEl = this._getOrCreateChild(ZRImage)).onload = function() { self1.dirtyStyle(); }; var imgStyle = imgEl.style; imgStyle.image = textBackgroundColor.image, imgStyle.x = x, imgStyle.y = y, imgStyle.width = width, imgStyle.height = height; } if (textBorderWidth && textBorderColor) { var rectStyle = rectEl.style; rectStyle.lineWidth = textBorderWidth, rectStyle.stroke = textBorderColor, rectStyle.strokeOpacity = retrieve2(style.strokeOpacity, 1), rectStyle.lineDash = style.borderDash, rectStyle.lineDashOffset = style.borderDashOffset || 0, rectEl.strokeContainThreshold = 0, rectEl.hasFill() && rectEl.hasStroke() && (rectStyle.strokeFirst = !0, rectStyle.lineWidth *= 2); } var commonStyle = (rectEl || imgEl).style; commonStyle.shadowBlur = style.shadowBlur || 0, commonStyle.shadowColor = style.shadowColor || 'transparent', commonStyle.shadowOffsetX = style.shadowOffsetX || 0, commonStyle.shadowOffsetY = style.shadowOffsetY || 0, commonStyle.opacity = retrieve3(style.opacity, topStyle.opacity, 1); }, ZRText.makeFont = function(style) { var font = ''; if (style.fontSize || style.fontFamily || style.fontWeight) { var fontSize = ''; fontSize = 'string' == typeof style.fontSize && (-1 !== style.fontSize.indexOf('px') || -1 !== style.fontSize.indexOf('rem') || -1 !== style.fontSize.indexOf('em')) ? style.fontSize : isNaN(+style.fontSize) ? '12px' : style.fontSize + 'px', font = [ style.fontStyle, style.fontWeight, fontSize, style.fontFamily || 'sans-serif' ].join(' '); } return font && trim(font) || style.textFont || style.font; }, ZRText; }(Displayable), VALID_TEXT_ALIGN = { left: !0, right: 1, center: 1 }, VALID_TEXT_VERTICAL_ALIGN = { top: 1, bottom: 1, middle: 1 }; function normalizeStyle(style) { if (style) { style.font = ZRText.makeFont(style); var textAlign = style.align; 'middle' === textAlign && (textAlign = 'center'), style.align = null == textAlign || VALID_TEXT_ALIGN[textAlign] ? textAlign : 'left'; var verticalAlign = style.verticalAlign; 'center' === verticalAlign && (verticalAlign = 'middle'), style.verticalAlign = null == verticalAlign || VALID_TEXT_VERTICAL_ALIGN[verticalAlign] ? verticalAlign : 'top', style.padding && (style.padding = normalizeCssArray(style.padding)); } } function getStroke(stroke, lineWidth) { return null == stroke || lineWidth <= 0 || 'transparent' === stroke || 'none' === stroke ? null : stroke.image || stroke.colorStops ? '#000' : stroke; } function getTextXForPadding(x, textAlign, textPadding) { return 'right' === textAlign ? x - textPadding[1] : 'center' === textAlign ? x + textPadding[3] / 2 - textPadding[1] / 2 : x + textPadding[3]; } function getStyleText(style) { var text = style.text; return null != text && (text += ''), text; } function needDrawBackground(style) { return !!(style.backgroundColor || style.borderWidth && style.borderColor); } var getECData = makeInner(), _highlightNextDigit = 1, _highlightKeyMap = {}, getSavedStates = makeInner(), SPECIAL_STATES = [ 'emphasis', 'blur', 'select' ], DISPLAY_STATES = [ 'normal', 'emphasis', 'blur', 'select' ], HIGHLIGHT_ACTION_TYPE = 'highlight', DOWNPLAY_ACTION_TYPE = 'downplay', SELECT_ACTION_TYPE = 'select', UNSELECT_ACTION_TYPE = 'unselect', TOGGLE_SELECT_ACTION_TYPE = 'toggleSelect'; function hasFillOrStroke(fillOrStroke) { return null != fillOrStroke && 'none' !== fillOrStroke; } var liftedColorCache = new LRU(100); function liftColor(color$1) { if ('string' != typeof color$1) return color$1; var liftedColor = liftedColorCache.get(color$1); return liftedColor || (liftedColor = lift(color$1, -0.1), liftedColorCache.put(color$1, liftedColor)), liftedColor; } function doChangeHoverState(el, stateName, hoverStateEnum) { el.onHoverStateChange && (el.hoverState || 0) !== hoverStateEnum && el.onHoverStateChange(stateName), el.hoverState = hoverStateEnum; } function singleEnterEmphasis(el) { doChangeHoverState(el, 'emphasis', 2); } function singleLeaveEmphasis(el) { 2 === el.hoverState && doChangeHoverState(el, 'normal', 0); } function singleEnterBlur(el) { doChangeHoverState(el, 'blur', 1); } function singleLeaveBlur(el) { 1 === el.hoverState && doChangeHoverState(el, 'normal', 0); } function singleEnterSelect(el) { el.selected = !0; } function singleLeaveSelect(el) { el.selected = !1; } function traverseUpdateState(el, updater, commonParam) { updater(el, commonParam), el.isGroup && el.traverse(function(child) { updater(child, commonParam); }); } function setStatesFlag(el, stateName) { switch(stateName){ case 'emphasis': el.hoverState = 2; break; case 'normal': el.hoverState = 0; break; case 'blur': el.hoverState = 1; break; case 'select': el.selected = !0; } } function elementStateProxy(stateName, targetStates) { var state, hasBlur, currentOpacity, fromState, blurStyle, state1 = this.states[stateName]; if (this.style) { if ('emphasis' === stateName) return function(el, stateName, targetStates, state) { var hasSelect = targetStates && indexOf(targetStates, 'select') >= 0, cloned = !1; if (el instanceof Path) { var store = getSavedStates(el), fromFill = hasSelect && store.selectFill || store.normalFill, fromStroke = hasSelect && store.selectStroke || store.normalStroke; if (hasFillOrStroke(fromFill) || hasFillOrStroke(fromStroke)) { var emphasisStyle = (state = state || {}).style || {}; !hasFillOrStroke(emphasisStyle.fill) && hasFillOrStroke(fromFill) ? (cloned = !0, state = extend({}, state), (emphasisStyle = extend({}, emphasisStyle)).fill = liftColor(fromFill)) : !hasFillOrStroke(emphasisStyle.stroke) && hasFillOrStroke(fromStroke) && (cloned || (state = extend({}, state), emphasisStyle = extend({}, emphasisStyle)), emphasisStyle.stroke = liftColor(fromStroke)), state.style = emphasisStyle; } } if (state && null == state.z2) { cloned || (state = extend({}, state)); var z2EmphasisLift = el.z2EmphasisLift; state.z2 = el.z2 + (null != z2EmphasisLift ? z2EmphasisLift : 10); } return state; }(this, 0, targetStates, state1); if ('blur' === stateName) return state = state1, hasBlur = indexOf(this.currentStates, stateName) >= 0, currentOpacity = this.style.opacity, fromState = hasBlur ? null : function(el, props, toStateName, defaultValue) { for(var style = el.style, fromState = {}, i = 0; i < props.length; i++){ var propName = props[i], val = style[propName]; fromState[propName] = null == val ? defaultValue && defaultValue[propName] : val; } for(var i = 0; i < el.animators.length; i++){ var animator = el.animators[i]; animator.__fromStateTransition && 0 > animator.__fromStateTransition.indexOf(toStateName) && 'style' === animator.targetName && animator.saveFinalToTarget(fromState, props); } return fromState; }(this, [ 'opacity' ], stateName, { opacity: 1 }), null == (blurStyle = (state = state || {}).style || {}).opacity && (state = extend({}, state), blurStyle = extend({ opacity: hasBlur ? currentOpacity : 0.1 * fromState.opacity }, blurStyle), state.style = blurStyle), state; if ('select' === stateName) return function(el, stateName, state) { if (state && null == state.z2) { state = extend({}, state); var z2SelectLift = el.z2SelectLift; state.z2 = el.z2 + (null != z2SelectLift ? z2SelectLift : 9); } return state; }(this, 0, state1); } return state1; } function setDefaultStateProxy(el) { el.stateProxy = elementStateProxy; var textContent = el.getTextContent(), textGuide = el.getTextGuideLine(); textContent && (textContent.stateProxy = elementStateProxy), textGuide && (textGuide.stateProxy = elementStateProxy); } function enterEmphasisWhenMouseOver(el, e) { shouldSilent(el, e) || el.__highByOuter || traverseUpdateState(el, singleEnterEmphasis); } function leaveEmphasisWhenMouseOut(el, e) { shouldSilent(el, e) || el.__highByOuter || traverseUpdateState(el, singleLeaveEmphasis); } function enterEmphasis(el, highlightDigit) { el.__highByOuter |= 1 << (highlightDigit || 0), traverseUpdateState(el, singleEnterEmphasis); } function leaveEmphasis(el, highlightDigit) { (el.__highByOuter &= ~(1 << (highlightDigit || 0))) || traverseUpdateState(el, singleLeaveEmphasis); } function shouldSilent(el, e) { return el.__highDownSilentOnTouch && e.zrByTouch; } function allLeaveBlur(api) { api.getModel().eachComponent(function(componentType, componentModel) { ('series' === componentType ? api.getViewOfSeriesModel(componentModel) : api.getViewOfComponentModel(componentModel)).group.traverse(function(child) { singleLeaveBlur(child); }); }); } function blurSeries(targetSeriesIndex, focus, blurScope, api) { var ecModel = api.getModel(); function leaveBlurOfIndices(data, dataIndices) { for(var i = 0; i < dataIndices.length; i++){ var itemEl = data.getItemGraphicEl(dataIndices[i]); itemEl && traverseUpdateState(itemEl, singleLeaveBlur); } } if (blurScope = blurScope || 'coordinateSystem', null != targetSeriesIndex && focus && 'none' !== focus) { var targetSeriesModel = ecModel.getSeriesByIndex(targetSeriesIndex), targetCoordSys = targetSeriesModel.coordinateSystem; targetCoordSys && targetCoordSys.master && (targetCoordSys = targetCoordSys.master); var blurredSeries = []; ecModel.eachSeries(function(seriesModel) { var sameSeries = targetSeriesModel === seriesModel, coordSys = seriesModel.coordinateSystem; coordSys && coordSys.master && (coordSys = coordSys.master); var sameCoordSys = coordSys && targetCoordSys ? coordSys === targetCoordSys : sameSeries; if (!('series' === blurScope && !sameSeries || 'coordinateSystem' === blurScope && !sameCoordSys || 'series' === focus && sameSeries)) { if (api.getViewOfSeriesModel(seriesModel).group.traverse(function(child) { singleEnterBlur(child); }), isArrayLike(focus)) leaveBlurOfIndices(seriesModel.getData(), focus); else if (isObject(focus)) for(var dataTypes = keys(focus), d = 0; d < dataTypes.length; d++)leaveBlurOfIndices(seriesModel.getData(dataTypes[d]), focus[dataTypes[d]]); blurredSeries.push(seriesModel); } }), ecModel.eachComponent(function(componentType, componentModel) { if ('series' !== componentType) { var view = api.getViewOfComponentModel(componentModel); view && view.blurSeries && view.blurSeries(blurredSeries, ecModel); } }); } } function blurComponent(componentMainType, componentIndex, api) { if (null != componentMainType && null != componentIndex) { var componentModel = api.getModel().getComponent(componentMainType, componentIndex); if (componentModel) { var view = api.getViewOfComponentModel(componentModel); view && view.focusBlurEnabled && view.group.traverse(function(child) { singleEnterBlur(child); }); } } } function findComponentHighDownDispatchers(componentMainType, componentIndex, name, api) { var focusSelf, ret = { focusSelf: !1, dispatchers: null }; if (null == componentMainType || 'series' === componentMainType || null == componentIndex || null == name) return ret; var componentModel = api.getModel().getComponent(componentMainType, componentIndex); if (!componentModel) return ret; var view = api.getViewOfComponentModel(componentModel); if (!view || !view.findHighDownDispatchers) return ret; for(var dispatchers = view.findHighDownDispatchers(name), i = 0; i < dispatchers.length; i++)if (isHighDownDispatcher(dispatchers[i]) || error('param should be highDownDispatcher'), 'self' === getECData(dispatchers[i]).focus) { focusSelf = !0; break; } return { focusSelf: focusSelf, dispatchers: dispatchers }; } function updateSeriesElementSelection(seriesModel) { each(seriesModel.getAllData(), function(_a) { var data = _a.data, type = _a.type; data.eachItemGraphicEl(function(el, idx) { seriesModel.isSelected(idx, type) ? traverseUpdateState(el, singleEnterSelect) : traverseUpdateState(el, singleLeaveSelect); }); }); } function enableHoverEmphasis(el, focus, blurScope) { setAsHighDownDispatcher(el, !0), traverseUpdateState(el, setDefaultStateProxy), enableHoverFocus(el, focus, blurScope); } function enableHoverFocus(el, focus, blurScope) { var ecData = getECData(el); null != focus ? (ecData.focus = focus, ecData.blurScope = blurScope) : ecData.focus && (ecData.focus = null); } var OTHER_STATES = [ 'emphasis', 'blur', 'select' ], defaultStyleGetterMap = { itemStyle: 'getItemStyle', lineStyle: 'getLineStyle', areaStyle: 'getAreaStyle' }; function setStatesStylesFromModel(el, itemModel, styleType, getter) { styleType = styleType || 'itemStyle'; for(var i = 0; i < OTHER_STATES.length; i++){ var stateName = OTHER_STATES[i], model = itemModel.getModel([ stateName, styleType ]); el.ensureState(stateName).style = getter ? getter(model) : model[defaultStyleGetterMap[styleType]](); } } function setAsHighDownDispatcher(el, asDispatcher) { var disable = !1 === asDispatcher, extendedEl = el; el.highDownSilentOnTouch && (extendedEl.__highDownSilentOnTouch = el.highDownSilentOnTouch), (!disable || extendedEl.__highDownDispatcher) && (extendedEl.__highByOuter = extendedEl.__highByOuter || 0, extendedEl.__highDownDispatcher = !disable); } function isHighDownDispatcher(el) { return !!(el && el.__highDownDispatcher); } function isSelectChangePayload(payload) { var payloadType = payload.type; return payloadType === SELECT_ACTION_TYPE || payloadType === UNSELECT_ACTION_TYPE || payloadType === TOGGLE_SELECT_ACTION_TYPE; } function isHighDownPayload(payload) { var payloadType = payload.type; return payloadType === HIGHLIGHT_ACTION_TYPE || payloadType === DOWNPLAY_ACTION_TYPE; } var CMD$2 = PathProxy.CMD, points = [ [], [], [] ], mathSqrt$2 = Math.sqrt, mathAtan2 = Math.atan2, mathSqrt$3 = Math.sqrt, mathSin$2 = Math.sin, mathCos$2 = Math.cos, PI$1 = Math.PI; function vMag(v) { return Math.sqrt(v[0] * v[0] + v[1] * v[1]); } function vRatio(u, v) { return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v)); } function vAngle(u, v) { return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(vRatio(u, v)); } function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) { var psi = psiDeg * (PI$1 / 180.0), xp = mathCos$2(psi) * (x1 - x2) / 2.0 + mathSin$2(psi) * (y1 - y2) / 2.0, yp = -1 * mathSin$2(psi) * (x1 - x2) / 2.0 + mathCos$2(psi) * (y1 - y2) / 2.0, lambda = xp * xp / (rx * rx) + yp * yp / (ry * ry); lambda > 1 && (rx *= mathSqrt$3(lambda), ry *= mathSqrt$3(lambda)); var f = (fa === fs ? -1 : 1) * mathSqrt$3((rx * rx * (ry * ry) - rx * rx * (yp * yp) - ry * ry * (xp * xp)) / (rx * rx * (yp * yp) + ry * ry * (xp * xp))) || 0, cxp = f * rx * yp / ry, cyp = -(f * ry) * xp / rx, cx = (x1 + x2) / 2.0 + mathCos$2(psi) * cxp - mathSin$2(psi) * cyp, cy = (y1 + y2) / 2.0 + mathSin$2(psi) * cxp + mathCos$2(psi) * cyp, theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]), u = [ (xp - cxp) / rx, (yp - cyp) / ry ], v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ], dTheta = vAngle(u, v); if (-1 >= vRatio(u, v) && (dTheta = PI$1), vRatio(u, v) >= 1 && (dTheta = 0), dTheta < 0) { var n = Math.round(dTheta / PI$1 * 1e6) / 1e6; dTheta = 2 * PI$1 + n % 2 * PI$1; } path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs); } var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig, numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g, SVGPath = function(_super) { function SVGPath() { return null !== _super && _super.apply(this, arguments) || this; } return __extends(SVGPath, _super), SVGPath.prototype.applyTransform = function(m) {}, SVGPath; }(Path); function isPathProxy(path) { return null != path.setData; } function createPathOptions(str, opts) { var pathProxy = function(data) { var prevCmd, path = new PathProxy(); if (!data) return path; var cpx = 0, cpy = 0, subpathX = 0, subpathY = 0, CMD = PathProxy.CMD, cmdList = data.match(commandReg); if (!cmdList) return path; for(var l = 0; l < cmdList.length; l++){ for(var cmdText = cmdList[l], cmdStr = cmdText.charAt(0), cmd = void 0, p = cmdText.match(numberReg) || [], pLen = p.length, i = 0; i < pLen; i++)p[i] = parseFloat(p[i]); for(var off = 0; off < pLen;){ var ctlPtx = void 0, ctlPty = void 0, rx = void 0, ry = void 0, psi = void 0, fa = void 0, fs = void 0, x1 = cpx, y1 = cpy, len = void 0, pathData = void 0; switch(cmdStr){ case 'l': cpx += p[off++], cpy += p[off++], cmd = CMD.L, path.addData(cmd, cpx, cpy); break; case 'L': cpx = p[off++], cpy = p[off++], cmd = CMD.L, path.addData(cmd, cpx, cpy); break; case 'm': cpx += p[off++], cpy += p[off++], cmd = CMD.M, path.addData(cmd, cpx, cpy), subpathX = cpx, subpathY = cpy, cmdStr = 'l'; break; case 'M': cpx = p[off++], cpy = p[off++], cmd = CMD.M, path.addData(cmd, cpx, cpy), subpathX = cpx, subpathY = cpy, cmdStr = 'L'; break; case 'h': cpx += p[off++], cmd = CMD.L, path.addData(cmd, cpx, cpy); break; case 'H': cpx = p[off++], cmd = CMD.L, path.addData(cmd, cpx, cpy); break; case 'v': cpy += p[off++], cmd = CMD.L, path.addData(cmd, cpx, cpy); break; case 'V': cpy = p[off++], cmd = CMD.L, path.addData(cmd, cpx, cpy); break; case 'C': cmd = CMD.C, path.addData(cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]), cpx = p[off - 2], cpy = p[off - 1]; break; case 'c': cmd = CMD.C, path.addData(cmd, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy), cpx += p[off - 2], cpy += p[off - 1]; break; case 'S': ctlPtx = cpx, ctlPty = cpy, len = path.len(), pathData = path.data, prevCmd === CMD.C && (ctlPtx += cpx - pathData[len - 4], ctlPty += cpy - pathData[len - 3]), cmd = CMD.C, x1 = p[off++], y1 = p[off++], cpx = p[off++], cpy = p[off++], path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy); break; case 's': ctlPtx = cpx, ctlPty = cpy, len = path.len(), pathData = path.data, prevCmd === CMD.C && (ctlPtx += cpx - pathData[len - 4], ctlPty += cpy - pathData[len - 3]), cmd = CMD.C, x1 = cpx + p[off++], y1 = cpy + p[off++], cpx += p[off++], cpy += p[off++], path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy); break; case 'Q': x1 = p[off++], y1 = p[off++], cpx = p[off++], cpy = p[off++], cmd = CMD.Q, path.addData(cmd, x1, y1, cpx, cpy); break; case 'q': x1 = p[off++] + cpx, y1 = p[off++] + cpy, cpx += p[off++], cpy += p[off++], cmd = CMD.Q, path.addData(cmd, x1, y1, cpx, cpy); break; case 'T': ctlPtx = cpx, ctlPty = cpy, len = path.len(), pathData = path.data, prevCmd === CMD.Q && (ctlPtx += cpx - pathData[len - 4], ctlPty += cpy - pathData[len - 3]), cpx = p[off++], cpy = p[off++], cmd = CMD.Q, path.addData(cmd, ctlPtx, ctlPty, cpx, cpy); break; case 't': ctlPtx = cpx, ctlPty = cpy, len = path.len(), pathData = path.data, prevCmd === CMD.Q && (ctlPtx += cpx - pathData[len - 4], ctlPty += cpy - pathData[len - 3]), cpx += p[off++], cpy += p[off++], cmd = CMD.Q, path.addData(cmd, ctlPtx, ctlPty, cpx, cpy); break; case 'A': rx = p[off++], ry = p[off++], psi = p[off++], fa = p[off++], fs = p[off++], processArc(x1 = cpx, y1 = cpy, cpx = p[off++], cpy = p[off++], fa, fs, rx, ry, psi, cmd = CMD.A, path); break; case 'a': rx = p[off++], ry = p[off++], psi = p[off++], fa = p[off++], fs = p[off++], processArc(x1 = cpx, y1 = cpy, cpx += p[off++], cpy += p[off++], fa, fs, rx, ry, psi, cmd = CMD.A, path); } } ('z' === cmdStr || 'Z' === cmdStr) && (cmd = CMD.Z, path.addData(cmd), cpx = subpathX, cpy = subpathY), prevCmd = cmd; } return path.toStatic(), path; }(str), innerOpts = extend({}, opts); return innerOpts.buildPath = function(path) { if (isPathProxy(path)) { path.setData(pathProxy.data); var ctx = path.getContext(); ctx && path.rebuildPath(ctx, 1); } else { var ctx = path; pathProxy.rebuildPath(ctx, 1); } }, innerOpts.applyTransform = function(m) { (function(path, m) { var cmd, nPoint, i, j, k, p, data = path.data, len = path.len(), M = CMD$2.M, C = CMD$2.C, L = CMD$2.L, R = CMD$2.R, A = CMD$2.A, Q = CMD$2.Q; for(i = 0, j = 0; i < len;){ switch(cmd = data[i++], j = i, nPoint = 0, cmd){ case M: case L: nPoint = 1; break; case C: nPoint = 3; break; case Q: nPoint = 2; break; case A: var x = m[4], y = m[5], sx = mathSqrt$2(m[0] * m[0] + m[1] * m[1]), sy = mathSqrt$2(m[2] * m[2] + m[3] * m[3]), angle = mathAtan2(-m[1] / sy, m[0] / sx); data[i] *= sx, data[i++] += x, data[i] *= sy, data[i++] += y, data[i++] *= sx, data[i++] *= sy, data[i++] += angle, data[i++] += angle, i += 2, j = i; break; case R: p[0] = data[i++], p[1] = data[i++], applyTransform(p, p, m), data[j++] = p[0], data[j++] = p[1], p[0] += data[i++], p[1] += data[i++], applyTransform(p, p, m), data[j++] = p[0], data[j++] = p[1]; } for(k = 0; k < nPoint; k++){ var p_1 = points[k]; p_1[0] = data[i++], p_1[1] = data[i++], applyTransform(p_1, p_1, m), data[j++] = p_1[0], data[j++] = p_1[1]; } } path.increaseVersion(); })(pathProxy, m), this.dirtyShape(); }, innerOpts; } var CircleShape = function() { this.cx = 0, this.cy = 0, this.r = 0; }, Circle = function(_super) { function Circle(opts) { return _super.call(this, opts) || this; } return __extends(Circle, _super), Circle.prototype.getDefaultShape = function() { return new CircleShape(); }, Circle.prototype.buildPath = function(ctx, shape, inBundle) { inBundle && ctx.moveTo(shape.cx + shape.r, shape.cy), ctx.arc(shape.cx, shape.cy, shape.r, 0, 2 * Math.PI); }, Circle; }(Path); Circle.prototype.type = 'circle'; var EllipseShape = function() { this.cx = 0, this.cy = 0, this.rx = 0, this.ry = 0; }, Ellipse = function(_super) { function Ellipse(opts) { return _super.call(this, opts) || this; } return __extends(Ellipse, _super), Ellipse.prototype.getDefaultShape = function() { return new EllipseShape(); }, Ellipse.prototype.buildPath = function(ctx, shape) { var x = shape.cx, y = shape.cy, a = shape.rx, b = shape.ry, ox = 0.5522848 * a, oy = 0.5522848 * b; ctx.moveTo(x - a, y), ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b), ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y), ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b), ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y), ctx.closePath(); }, Ellipse; }(Path); Ellipse.prototype.type = 'ellipse'; var PI$2 = Math.PI, PI2$5 = 2 * PI$2, mathSin$3 = Math.sin, mathCos$3 = Math.cos, mathACos = Math.acos, mathATan2 = Math.atan2, mathAbs$1 = Math.abs, mathSqrt$4 = Math.sqrt, mathMax$3 = Math.max, mathMin$3 = Math.min; function computeCornerTangents(x0, y0, x1, y1, radius, cr, clockwise) { var x01 = x0 - x1, y01 = y0 - y1, lo = (clockwise ? cr : -cr) / mathSqrt$4(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x11 = x0 + ox, y11 = y0 + oy, x10 = x1 + ox, y10 = y1 + oy, x00 = (x11 + x10) / 2, y00 = (y11 + y10) / 2, dx = x10 - x11, dy = y10 - y11, d2 = dx * dx + dy * dy, r = radius - cr, s = x11 * y10 - x10 * y11, d = (dy < 0 ? -1 : 1) * mathSqrt$4(mathMax$3(0, r * r * d2 - s * s)), cx0 = (s * dy - dx * d) / d2, cy0 = (-s * dx - dy * d) / d2, cx1 = (s * dy + dx * d) / d2, cy1 = (-s * dx + dy * d) / d2, dx0 = cx0 - x00, dy0 = cy0 - y00, dx1 = cx1 - x00, dy1 = cy1 - y00; return dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1 && (cx0 = cx1, cy0 = cy1), { cx: cx0, cy: cy0, x01: -ox, y01: -oy, x11: cx0 * (radius / r - 1), y11: cy0 * (radius / r - 1) }; } var SectorShape = function() { this.cx = 0, this.cy = 0, this.r0 = 0, this.r = 0, this.startAngle = 0, this.endAngle = 2 * Math.PI, this.clockwise = !0, this.cornerRadius = 0, this.innerCornerRadius = 0; }, Sector = function(_super) { function Sector(opts) { return _super.call(this, opts) || this; } return __extends(Sector, _super), Sector.prototype.getDefaultShape = function() { return new SectorShape(); }, Sector.prototype.buildPath = function(ctx, shape) { !function(ctx, shape) { var arc, radius = mathMax$3(shape.r, 0), innerRadius = mathMax$3(shape.r0 || 0, 0), hasRadius = radius > 0, hasInnerRadius = innerRadius > 0; if (hasRadius || hasInnerRadius) { if (hasRadius || (radius = innerRadius, innerRadius = 0), innerRadius > radius) { var tmp = radius; radius = innerRadius, innerRadius = tmp; } var clockwise = !!shape.clockwise, startAngle = shape.startAngle, endAngle = shape.endAngle; if (startAngle === endAngle) arc = 0; else { var tmpAngles = [ startAngle, endAngle ]; normalizeArcAngles(tmpAngles, !clockwise), arc = mathAbs$1(tmpAngles[0] - tmpAngles[1]); } var x = shape.cx, y = shape.cy, cornerRadius = shape.cornerRadius || 0, innerCornerRadius = shape.innerCornerRadius || 0; if (radius > 1e-4) { if (arc > PI2$5 - 1e-4) ctx.moveTo(x + radius * mathCos$3(startAngle), y + radius * mathSin$3(startAngle)), ctx.arc(x, y, radius, startAngle, endAngle, !clockwise), innerRadius > 1e-4 && (ctx.moveTo(x + innerRadius * mathCos$3(endAngle), y + innerRadius * mathSin$3(endAngle)), ctx.arc(x, y, innerRadius, endAngle, startAngle, clockwise)); else { var halfRd = mathAbs$1(radius - innerRadius) / 2, cr = mathMin$3(halfRd, cornerRadius), icr = mathMin$3(halfRd, innerCornerRadius), cr0 = icr, cr1 = cr, xrs = radius * mathCos$3(startAngle), yrs = radius * mathSin$3(startAngle), xire = innerRadius * mathCos$3(endAngle), yire = innerRadius * mathSin$3(endAngle), xre = void 0, yre = void 0, xirs = void 0, yirs = void 0; if ((cr > 1e-4 || icr > 1e-4) && (xre = radius * mathCos$3(endAngle), yre = radius * mathSin$3(endAngle), xirs = innerRadius * mathCos$3(startAngle), yirs = innerRadius * mathSin$3(startAngle), arc < PI$2)) { var it_1 = function(x0, y0, x1, y1, x2, y2, x3, y3) { var x10 = x1 - x0, y10 = y1 - y0, x32 = x3 - x2, y32 = y3 - y2, t = y32 * x10 - x32 * y10; if (!(t * t < 1e-4)) return t = (x32 * (y0 - y2) - y32 * (x0 - x2)) / t, [ x0 + t * x10, y0 + t * y10 ]; }(xrs, yrs, xirs, yirs, xre, yre, xire, yire); if (it_1) { var x0 = xrs - it_1[0], y0 = yrs - it_1[1], x1 = xre - it_1[0], y1 = yre - it_1[1], a = 1 / mathSin$3(mathACos((x0 * x1 + y0 * y1) / (mathSqrt$4(x0 * x0 + y0 * y0) * mathSqrt$4(x1 * x1 + y1 * y1))) / 2), b = mathSqrt$4(it_1[0] * it_1[0] + it_1[1] * it_1[1]); cr0 = mathMin$3(icr, (innerRadius - b) / (a - 1)), cr1 = mathMin$3(cr, (radius - b) / (a + 1)); } } if (arc > 1e-4) { if (cr1 > 1e-4) { var ct0 = computeCornerTangents(xirs, yirs, xrs, yrs, radius, cr1, clockwise), ct1 = computeCornerTangents(xre, yre, xire, yire, radius, cr1, clockwise); ctx.moveTo(x + ct0.cx + ct0.x01, y + ct0.cy + ct0.y01), cr1 < cr ? ctx.arc(x + ct0.cx, y + ct0.cy, cr1, mathATan2(ct0.y01, ct0.x01), mathATan2(ct1.y01, ct1.x01), !clockwise) : (ctx.arc(x + ct0.cx, y + ct0.cy, cr1, mathATan2(ct0.y01, ct0.x01), mathATan2(ct0.y11, ct0.x11), !clockwise), ctx.arc(x, y, radius, mathATan2(ct0.cy + ct0.y11, ct0.cx + ct0.x11), mathATan2(ct1.cy + ct1.y11, ct1.cx + ct1.x11), !clockwise), ctx.arc(x + ct1.cx, y + ct1.cy, cr1, mathATan2(ct1.y11, ct1.x11), mathATan2(ct1.y01, ct1.x01), !clockwise)); } else ctx.moveTo(x + xrs, y + yrs), ctx.arc(x, y, radius, startAngle, endAngle, !clockwise); } else ctx.moveTo(x + xrs, y + yrs); if (innerRadius > 1e-4 && arc > 1e-4) { if (cr0 > 1e-4) { var ct0 = computeCornerTangents(xire, yire, xre, yre, innerRadius, -cr0, clockwise), ct1 = computeCornerTangents(xrs, yrs, xirs, yirs, innerRadius, -cr0, clockwise); ctx.lineTo(x + ct0.cx + ct0.x01, y + ct0.cy + ct0.y01), cr0 < icr ? ctx.arc(x + ct0.cx, y + ct0.cy, cr0, mathATan2(ct0.y01, ct0.x01), mathATan2(ct1.y01, ct1.x01), !clockwise) : (ctx.arc(x + ct0.cx, y + ct0.cy, cr0, mathATan2(ct0.y01, ct0.x01), mathATan2(ct0.y11, ct0.x11), !clockwise), ctx.arc(x, y, innerRadius, mathATan2(ct0.cy + ct0.y11, ct0.cx + ct0.x11), mathATan2(ct1.cy + ct1.y11, ct1.cx + ct1.x11), clockwise), ctx.arc(x + ct1.cx, y + ct1.cy, cr0, mathATan2(ct1.y11, ct1.x11), mathATan2(ct1.y01, ct1.x01), !clockwise)); } else ctx.lineTo(x + xire, y + yire), ctx.arc(x, y, innerRadius, endAngle, startAngle, clockwise); } else ctx.lineTo(x + xire, y + yire); } } else ctx.moveTo(x, y); ctx.closePath(); } }(ctx, shape); }, Sector.prototype.isZeroArea = function() { return this.shape.startAngle === this.shape.endAngle || this.shape.r === this.shape.r0; }, Sector; }(Path); Sector.prototype.type = 'sector'; var RingShape = function() { this.cx = 0, this.cy = 0, this.r = 0, this.r0 = 0; }, Ring = function(_super) { function Ring(opts) { return _super.call(this, opts) || this; } return __extends(Ring, _super), Ring.prototype.getDefaultShape = function() { return new RingShape(); }, Ring.prototype.buildPath = function(ctx, shape) { var x = shape.cx, y = shape.cy, PI2 = 2 * Math.PI; ctx.moveTo(x + shape.r, y), ctx.arc(x, y, shape.r, 0, PI2, !1), ctx.moveTo(x + shape.r0, y), ctx.arc(x, y, shape.r0, 0, PI2, !0); }, Ring; }(Path); function interpolate(p0, p1, p2, p3, t, t2, t3) { var v0 = (p2 - p0) * 0.5, v1 = (p3 - p1) * 0.5; return (2 * (p1 - p2) + v0 + v1) * t3 + (-3 * (p1 - p2) - 2 * v0 - v1) * t2 + v0 * t + p1; } function buildPath$2(ctx, shape, closePath) { var smooth = shape.smooth, points = shape.points; if (points && points.length >= 2) { if (smooth && 'spline' !== smooth) { var controlPoints = function(points, smooth, isLoop, constraint) { var prevPoint, nextPoint, min$1, max$1, cps = [], v = [], v1 = [], v2 = []; if (constraint) { min$1 = [ 1 / 0, 1 / 0 ], max$1 = [ -1 / 0, -1 / 0 ]; for(var i = 0, len = points.length; i < len; i++)min(min$1, min$1, points[i]), max(max$1, max$1, points[i]); min(min$1, min$1, constraint[0]), max(max$1, max$1, constraint[1]); } for(var i = 0, len = points.length; i < len; i++){ var point = points[i]; if (isLoop) prevPoint = points[i ? i - 1 : len - 1], nextPoint = points[(i + 1) % len]; else { if (0 === i || i === len - 1) { cps.push(clone$1(points[i])); continue; } prevPoint = points[i - 1], nextPoint = points[i + 1]; } sub(v, nextPoint, prevPoint), scale(v, v, smooth); var d0 = distance(point, prevPoint), d1 = distance(point, nextPoint), sum = d0 + d1; 0 !== sum && (d0 /= sum, d1 /= sum), scale(v1, v, -d0), scale(v2, v, d1); var cp0 = add([], point, v1), cp1 = add([], point, v2); constraint && (max(cp0, cp0, min$1), min(cp0, cp0, max$1), max(cp1, cp1, min$1), min(cp1, cp1, max$1)), cps.push(cp0), cps.push(cp1); } return isLoop && cps.push(cps.shift()), cps; }(points, smooth, closePath, shape.smoothConstraint); ctx.moveTo(points[0][0], points[0][1]); for(var len = points.length, i = 0; i < (closePath ? len : len - 1); i++){ var cp1 = controlPoints[2 * i], cp2 = controlPoints[2 * i + 1], p = points[(i + 1) % len]; ctx.bezierCurveTo(cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]); } } else { 'spline' === smooth && (points = function(points, isLoop) { for(var len = points.length, ret = [], distance$1 = 0, i = 1; i < len; i++)distance$1 += distance(points[i - 1], points[i]); var segs = distance$1 / 2; segs = segs < len ? len : segs; for(var i = 0; i < segs; i++){ var pos = i / (segs - 1) * (isLoop ? len : len - 1), idx = Math.floor(pos), w = pos - idx, p0 = void 0, p1 = points[idx % len], p2 = void 0, p3 = void 0; isLoop ? (p0 = points[(idx - 1 + len) % len], p2 = points[(idx + 1) % len], p3 = points[(idx + 2) % len]) : (p0 = points[0 === idx ? idx : idx - 1], p2 = points[idx > len - 2 ? len - 1 : idx + 1], p3 = points[idx > len - 3 ? len - 1 : idx + 2]); var w2 = w * w, w3 = w * w2; ret.push([ interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3), interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3) ]); } return ret; }(points, closePath)), ctx.moveTo(points[0][0], points[0][1]); for(var i = 1, l = points.length; i < l; i++)ctx.lineTo(points[i][0], points[i][1]); } closePath && ctx.closePath(); } } Ring.prototype.type = 'ring'; var PolygonShape = function() { this.points = null, this.smooth = 0, this.smoothConstraint = null; }, Polygon = function(_super) { function Polygon(opts) { return _super.call(this, opts) || this; } return __extends(Polygon, _super), Polygon.prototype.getDefaultShape = function() { return new PolygonShape(); }, Polygon.prototype.buildPath = function(ctx, shape) { buildPath$2(ctx, shape, !0); }, Polygon; }(Path); Polygon.prototype.type = 'polygon'; var PolylineShape = function() { this.points = null, this.percent = 1, this.smooth = 0, this.smoothConstraint = null; }, Polyline = function(_super) { function Polyline(opts) { return _super.call(this, opts) || this; } return __extends(Polyline, _super), Polyline.prototype.getDefaultStyle = function() { return { stroke: '#000', fill: null }; }, Polyline.prototype.getDefaultShape = function() { return new PolylineShape(); }, Polyline.prototype.buildPath = function(ctx, shape) { buildPath$2(ctx, shape, !1); }, Polyline; }(Path); Polyline.prototype.type = 'polyline'; var subPixelOptimizeOutputShape$1 = {}, LineShape = function() { this.x1 = 0, this.y1 = 0, this.x2 = 0, this.y2 = 0, this.percent = 1; }, Line = function(_super) { function Line(opts) { return _super.call(this, opts) || this; } return __extends(Line, _super), Line.prototype.getDefaultStyle = function() { return { stroke: '#000', fill: null }; }, Line.prototype.getDefaultShape = function() { return new LineShape(); }, Line.prototype.buildPath = function(ctx, shape) { if (this.subPixelOptimize) { var x1, y1, x2, y2, optimizedShape = subPixelOptimizeLine(subPixelOptimizeOutputShape$1, shape, this.style); x1 = optimizedShape.x1, y1 = optimizedShape.y1, x2 = optimizedShape.x2, y2 = optimizedShape.y2; } else x1 = shape.x1, y1 = shape.y1, x2 = shape.x2, y2 = shape.y2; var percent = shape.percent; 0 !== percent && (ctx.moveTo(x1, y1), percent < 1 && (x2 = x1 * (1 - percent) + x2 * percent, y2 = y1 * (1 - percent) + y2 * percent), ctx.lineTo(x2, y2)); }, Line.prototype.pointAt = function(p) { var shape = this.shape; return [ shape.x1 * (1 - p) + shape.x2 * p, shape.y1 * (1 - p) + shape.y2 * p ]; }, Line; }(Path); Line.prototype.type = 'line'; var out = [], BezierCurveShape = function() { this.x1 = 0, this.y1 = 0, this.x2 = 0, this.y2 = 0, this.cpx1 = 0, this.cpy1 = 0, this.percent = 1; }; function someVectorAt(shape, t, isTangent) { var cpx2 = shape.cpx2, cpy2 = shape.cpy2; return null === cpx2 || null === cpy2 ? [ (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t), (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t) ] : [ (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t), (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t) ]; } var BezierCurve = function(_super) { function BezierCurve(opts) { return _super.call(this, opts) || this; } return __extends(BezierCurve, _super), BezierCurve.prototype.getDefaultStyle = function() { return { stroke: '#000', fill: null }; }, BezierCurve.prototype.getDefaultShape = function() { return new BezierCurveShape(); }, BezierCurve.prototype.buildPath = function(ctx, shape) { var x1 = shape.x1, y1 = shape.y1, x2 = shape.x2, y2 = shape.y2, cpx1 = shape.cpx1, cpy1 = shape.cpy1, cpx2 = shape.cpx2, cpy2 = shape.cpy2, percent = shape.percent; 0 !== percent && (ctx.moveTo(x1, y1), null == cpx2 || null == cpy2 ? (percent < 1 && (quadraticSubdivide(x1, cpx1, x2, percent, out), cpx1 = out[1], x2 = out[2], quadraticSubdivide(y1, cpy1, y2, percent, out), cpy1 = out[1], y2 = out[2]), ctx.quadraticCurveTo(cpx1, cpy1, x2, y2)) : (percent < 1 && (cubicSubdivide(x1, cpx1, cpx2, x2, percent, out), cpx1 = out[1], cpx2 = out[2], x2 = out[3], cubicSubdivide(y1, cpy1, cpy2, y2, percent, out), cpy1 = out[1], cpy2 = out[2], y2 = out[3]), ctx.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x2, y2))); }, BezierCurve.prototype.pointAt = function(t) { return someVectorAt(this.shape, t, !1); }, BezierCurve.prototype.tangentAt = function(t) { var p = someVectorAt(this.shape, t, !0); return normalize(p, p); }, BezierCurve; }(Path); BezierCurve.prototype.type = 'bezier-curve'; var ArcShape = function() { this.cx = 0, this.cy = 0, this.r = 0, this.startAngle = 0, this.endAngle = 2 * Math.PI, this.clockwise = !0; }, Arc = function(_super) { function Arc(opts) { return _super.call(this, opts) || this; } return __extends(Arc, _super), Arc.prototype.getDefaultStyle = function() { return { stroke: '#000', fill: null }; }, Arc.prototype.getDefaultShape = function() { return new ArcShape(); }, Arc.prototype.buildPath = function(ctx, shape) { var x = shape.cx, y = shape.cy, r = Math.max(shape.r, 0), startAngle = shape.startAngle, endAngle = shape.endAngle, clockwise = shape.clockwise; ctx.moveTo(Math.cos(startAngle) * r + x, Math.sin(startAngle) * r + y), ctx.arc(x, y, r, startAngle, endAngle, !clockwise); }, Arc; }(Path); Arc.prototype.type = 'arc'; var CompoundPath = function(_super) { function CompoundPath() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = 'compound', _this; } return __extends(CompoundPath, _super), CompoundPath.prototype._updatePathDirty = function() { for(var paths = this.shape.paths, dirtyPath = this.shapeChanged(), i = 0; i < paths.length; i++)dirtyPath = dirtyPath || paths[i].shapeChanged(); dirtyPath && this.dirtyShape(); }, CompoundPath.prototype.beforeBrush = function() { this._updatePathDirty(); for(var paths = this.shape.paths || [], scale = this.getGlobalScale(), i = 0; i < paths.length; i++)paths[i].path || paths[i].createPathProxy(), paths[i].path.setScale(scale[0], scale[1], paths[i].segmentIgnoreThreshold); }, CompoundPath.prototype.buildPath = function(ctx, shape) { for(var paths = shape.paths || [], i = 0; i < paths.length; i++)paths[i].buildPath(ctx, paths[i].shape, !0); }, CompoundPath.prototype.afterBrush = function() { for(var paths = this.shape.paths || [], i = 0; i < paths.length; i++)paths[i].pathUpdated(); }, CompoundPath.prototype.getBoundingRect = function() { return this._updatePathDirty.call(this), Path.prototype.getBoundingRect.call(this); }, CompoundPath; }(Path), Gradient = function() { function Gradient(colorStops) { this.colorStops = colorStops || []; } return Gradient.prototype.addColorStop = function(offset, color) { this.colorStops.push({ offset: offset, color: color }); }, Gradient; }(), LinearGradient = function(_super) { function LinearGradient(x, y, x2, y2, colorStops, globalCoord) { var _this = _super.call(this, colorStops) || this; return _this.x = null == x ? 0 : x, _this.y = null == y ? 0 : y, _this.x2 = null == x2 ? 1 : x2, _this.y2 = null == y2 ? 0 : y2, _this.type = 'linear', _this.global = globalCoord || !1, _this; } return __extends(LinearGradient, _super), LinearGradient; }(Gradient), RadialGradient = function(_super) { function RadialGradient(x, y, r, colorStops, globalCoord) { var _this = _super.call(this, colorStops) || this; return _this.x = null == x ? 0.5 : x, _this.y = null == y ? 0.5 : y, _this.r = null == r ? 0.5 : r, _this.type = 'radial', _this.global = globalCoord || !1, _this; } return __extends(RadialGradient, _super), RadialGradient; }(Gradient), extent = [ 0, 0 ], extent2 = [ 0, 0 ], minTv$1 = new Point(), maxTv$1 = new Point(), OrientedBoundingRect = function() { function OrientedBoundingRect(rect, transform) { this._corners = [], this._axes = [], this._origin = [ 0, 0 ]; for(var i = 0; i < 4; i++)this._corners[i] = new Point(); for(var i = 0; i < 2; i++)this._axes[i] = new Point(); rect && this.fromBoundingRect(rect, transform); } return OrientedBoundingRect.prototype.fromBoundingRect = function(rect, transform) { var corners = this._corners, axes = this._axes, x = rect.x, y = rect.y, x2 = x + rect.width, y2 = y + rect.height; if (corners[0].set(x, y), corners[1].set(x2, y), corners[2].set(x2, y2), corners[3].set(x, y2), transform) for(var i = 0; i < 4; i++)corners[i].transform(transform); Point.sub(axes[0], corners[1], corners[0]), Point.sub(axes[1], corners[3], corners[0]), axes[0].normalize(), axes[1].normalize(); for(var i = 0; i < 2; i++)this._origin[i] = axes[i].dot(corners[0]); }, OrientedBoundingRect.prototype.intersect = function(other, mtv) { var overlapped = !0, noMtv = !mtv; return minTv$1.set(1 / 0, 1 / 0), maxTv$1.set(0, 0), !this._intersectCheckOneSide(this, other, minTv$1, maxTv$1, noMtv, 1) && (overlapped = !1, noMtv) || !this._intersectCheckOneSide(other, this, minTv$1, maxTv$1, noMtv, -1) && (overlapped = !1, noMtv) || noMtv || Point.copy(mtv, overlapped ? minTv$1 : maxTv$1), overlapped; }, OrientedBoundingRect.prototype._intersectCheckOneSide = function(self1, other, minTv, maxTv, noMtv, inverse) { for(var overlapped = !0, i = 0; i < 2; i++){ var axis = this._axes[i]; if (this._getProjMinMaxOnAxis(i, self1._corners, extent), this._getProjMinMaxOnAxis(i, other._corners, extent2), extent[1] < extent2[0] || extent[0] > extent2[1]) { if (overlapped = !1, noMtv) return overlapped; var dist0 = Math.abs(extent2[0] - extent[1]), dist1 = Math.abs(extent[0] - extent2[1]); Math.min(dist0, dist1) > maxTv.len() && (dist0 < dist1 ? Point.scale(maxTv, axis, -dist0 * inverse) : Point.scale(maxTv, axis, dist1 * inverse)); } else if (minTv) { var dist0 = Math.abs(extent2[0] - extent[1]), dist1 = Math.abs(extent[0] - extent2[1]); Math.min(dist0, dist1) < minTv.len() && (dist0 < dist1 ? Point.scale(minTv, axis, dist0 * inverse) : Point.scale(minTv, axis, -dist1 * inverse)); } } return overlapped; }, OrientedBoundingRect.prototype._getProjMinMaxOnAxis = function(dim, corners, out) { for(var axis = this._axes[dim], origin = this._origin, proj = corners[0].dot(axis) + origin[dim], min = proj, max = proj, i = 1; i < corners.length; i++){ var proj_1 = corners[i].dot(axis) + origin[dim]; min = Math.min(proj_1, min), max = Math.max(proj_1, max); } out[0] = min, out[1] = max; }, OrientedBoundingRect; }(), m = [], IncrementalDisplayable = function(_super) { function IncrementalDisplayable() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.notClear = !0, _this.incremental = !0, _this._displayables = [], _this._temporaryDisplayables = [], _this._cursor = 0, _this; } return __extends(IncrementalDisplayable, _super), IncrementalDisplayable.prototype.traverse = function(cb, context) { cb.call(context, this); }, IncrementalDisplayable.prototype.useStyle = function() { this.style = {}; }, IncrementalDisplayable.prototype.getCursor = function() { return this._cursor; }, IncrementalDisplayable.prototype.innerAfterBrush = function() { this._cursor = this._displayables.length; }, IncrementalDisplayable.prototype.clearDisplaybles = function() { this._displayables = [], this._temporaryDisplayables = [], this._cursor = 0, this.markRedraw(), this.notClear = !1; }, IncrementalDisplayable.prototype.clearTemporalDisplayables = function() { this._temporaryDisplayables = []; }, IncrementalDisplayable.prototype.addDisplayable = function(displayable, notPersistent) { notPersistent ? this._temporaryDisplayables.push(displayable) : this._displayables.push(displayable), this.markRedraw(); }, IncrementalDisplayable.prototype.addDisplayables = function(displayables, notPersistent) { notPersistent = notPersistent || !1; for(var i = 0; i < displayables.length; i++)this.addDisplayable(displayables[i], notPersistent); }, IncrementalDisplayable.prototype.getDisplayables = function() { return this._displayables; }, IncrementalDisplayable.prototype.getTemporalDisplayables = function() { return this._temporaryDisplayables; }, IncrementalDisplayable.prototype.eachPendingDisplayable = function(cb) { for(var i = this._cursor; i < this._displayables.length; i++)cb && cb(this._displayables[i]); for(var i = 0; i < this._temporaryDisplayables.length; i++)cb && cb(this._temporaryDisplayables[i]); }, IncrementalDisplayable.prototype.update = function() { this.updateTransform(); for(var i = this._cursor; i < this._displayables.length; i++){ var displayable = this._displayables[i]; displayable.parent = this, displayable.update(), displayable.parent = null; } for(var i = 0; i < this._temporaryDisplayables.length; i++){ var displayable = this._temporaryDisplayables[i]; displayable.parent = this, displayable.update(), displayable.parent = null; } }, IncrementalDisplayable.prototype.getBoundingRect = function() { if (!this._rect) { for(var rect = new BoundingRect(1 / 0, 1 / 0, -1 / 0, -1 / 0), i = 0; i < this._displayables.length; i++){ var displayable = this._displayables[i], childRect = displayable.getBoundingRect().clone(); displayable.needLocalTransform() && childRect.applyTransform(displayable.getLocalTransform(m)), rect.union(childRect); } this._rect = rect; } return this._rect; }, IncrementalDisplayable.prototype.contain = function(x, y) { var localPos = this.transformCoordToLocal(x, y); if (this.getBoundingRect().contain(localPos[0], localPos[1])) { for(var i = 0; i < this._displayables.length; i++)if (this._displayables[i].contain(x, y)) return !0; } return !1; }, IncrementalDisplayable; }(Displayable), mathMax$4 = Math.max, mathMin$4 = Math.min, _customShapeMap = {}; function extendShape(opts) { return Path.extend(opts); } var extendPathFromString = function(str, defaultOpts) { var innerOpts = createPathOptions(str, defaultOpts); return function(_super) { function Sub(opts) { var _this = _super.call(this, opts) || this; return _this.applyTransform = innerOpts.applyTransform, _this.buildPath = innerOpts.buildPath, _this; } return __extends(Sub, _super), Sub; }(SVGPath); }; function extendPath(pathData, opts) { return extendPathFromString(pathData, opts); } function registerShape(name, ShapeClass) { _customShapeMap[name] = ShapeClass; } function getShapeClass(name) { if (_customShapeMap.hasOwnProperty(name)) return _customShapeMap[name]; } function makePath(pathData, opts, rect, layout) { var path = new SVGPath(createPathOptions(pathData, opts)); return rect && ('center' === layout && (rect = centerGraphic(rect, path.getBoundingRect())), resizePath(path, rect)), path; } function makeImage(imageUrl, rect, layout) { var zrImg = new ZRImage({ style: { image: imageUrl, x: rect.x, y: rect.y, width: rect.width, height: rect.height }, onload: function(img) { if ('center' === layout) { var boundingRect = { width: img.width, height: img.height }; zrImg.setStyle(centerGraphic(rect, boundingRect)); } } }); return zrImg; } function centerGraphic(rect, boundingRect) { var height, aspect = boundingRect.width / boundingRect.height, width = rect.height * aspect; return height = width <= rect.width ? rect.height : (width = rect.width) / aspect, { x: rect.x + rect.width / 2 - width / 2, y: rect.y + rect.height / 2 - height / 2, width: width, height: height }; } var mergePath$1 = function(pathEls, opts) { for(var pathList = [], len = pathEls.length, i = 0; i < len; i++){ var pathEl = pathEls[i]; pathEl.path || pathEl.createPathProxy(), pathEl.shapeChanged() && pathEl.buildPath(pathEl.path, pathEl.shape, !0), pathList.push(pathEl.path); } var pathBundle = new Path(opts); return pathBundle.createPathProxy(), pathBundle.buildPath = function(path) { if (isPathProxy(path)) { path.appendPath(pathList); var ctx = path.getContext(); ctx && path.rebuildPath(ctx, 1); } }, pathBundle; }; function resizePath(path, rect) { if (path.applyTransform) { var m = path.getBoundingRect().calculateTransform(rect); path.applyTransform(m); } } function animateOrSetProps(animationType, el, props, animatableModel, dataIndex, cb, during) { var removeOpt, animationPayload, isFrom = !1; 'function' == typeof dataIndex ? (during = cb, cb = dataIndex, dataIndex = null) : isObject(dataIndex) && (cb = dataIndex.cb, during = dataIndex.during, isFrom = dataIndex.isFrom, removeOpt = dataIndex.removeOpt, dataIndex = dataIndex.dataIndex); var isUpdate = 'update' === animationType, isRemove = 'remove' === animationType; if (animatableModel && animatableModel.ecModel) { var updatePayload = animatableModel.ecModel.getUpdatePayload(); animationPayload = updatePayload && updatePayload.animation; } var animationEnabled = animatableModel && animatableModel.isAnimationEnabled(); if (isRemove || el.stopAnimation('remove'), animationEnabled) { var duration = void 0, animationEasing = void 0, animationDelay = void 0; animationPayload ? (duration = animationPayload.duration || 0, animationEasing = animationPayload.easing || 'cubicOut', animationDelay = animationPayload.delay || 0) : isRemove ? (duration = retrieve2((removeOpt = removeOpt || {}).duration, 200), animationEasing = retrieve2(removeOpt.easing, 'cubicOut'), animationDelay = 0) : (duration = animatableModel.getShallow(isUpdate ? 'animationDurationUpdate' : 'animationDuration'), animationEasing = animatableModel.getShallow(isUpdate ? 'animationEasingUpdate' : 'animationEasing'), animationDelay = animatableModel.getShallow(isUpdate ? 'animationDelayUpdate' : 'animationDelay')), 'function' == typeof animationDelay && (animationDelay = animationDelay(dataIndex, animatableModel.getAnimationDelayParams ? animatableModel.getAnimationDelayParams(el, dataIndex) : null)), 'function' == typeof duration && (duration = duration(dataIndex)), duration > 0 ? isFrom ? el.animateFrom(props, { duration: duration, delay: animationDelay || 0, easing: animationEasing, done: cb, force: !!cb || !!during, scope: animationType, during: during }) : el.animateTo(props, { duration: duration, delay: animationDelay || 0, easing: animationEasing, done: cb, force: !!cb || !!during, setToFinal: !0, scope: animationType, during: during }) : (el.stopAnimation(), isFrom || el.attr(props), cb && cb()); } else el.stopAnimation(), isFrom || el.attr(props), during && during(1), cb && cb(); } function updateProps(el, props, animatableModel, dataIndex, cb, during) { animateOrSetProps('update', el, props, animatableModel, dataIndex, cb, during); } function initProps(el, props, animatableModel, dataIndex, cb, during) { animateOrSetProps('init', el, props, animatableModel, dataIndex, cb, during); } function removeElement(el, props, animatableModel, dataIndex, cb, during) { isElementRemoved(el) || animateOrSetProps('remove', el, props, animatableModel, dataIndex, cb, during); } function fadeOutDisplayable(el, animatableModel, dataIndex, done) { el.removeTextContent(), el.removeTextGuideLine(), removeElement(el, { style: { opacity: 0 } }, animatableModel, dataIndex, done); } function removeElementWithFadeOut(el, animatableModel, dataIndex) { function doRemove() { el.parent && el.parent.remove(el); } el.isGroup ? el.traverse(function(disp) { disp.isGroup || fadeOutDisplayable(disp, animatableModel, dataIndex, doRemove); }) : fadeOutDisplayable(el, animatableModel, dataIndex, doRemove); } function isElementRemoved(el) { if (!el.__zr) return !0; for(var i = 0; i < el.animators.length; i++)if ('remove' === el.animators[i].scope) return !0; return !1; } function getTransform(target, ancestor) { for(var mat = identity([]); target && target !== ancestor;)mul$1(mat, target.getLocalTransform(), mat), target = target.parent; return mat; } function applyTransform$1(target, transform, invert$1) { return transform && !isArrayLike(transform) && (transform = Transformable.getLocalTransform(transform)), invert$1 && (transform = invert([], transform)), applyTransform([], target, transform); } function transformDirection(direction, transform, invert) { var hBase = 0 === transform[4] || 0 === transform[5] || 0 === transform[0] ? 1 : Math.abs(2 * transform[4] / transform[0]), vBase = 0 === transform[4] || 0 === transform[5] || 0 === transform[2] ? 1 : Math.abs(2 * transform[4] / transform[2]), vertex = [ 'left' === direction ? -hBase : 'right' === direction ? hBase : 0, 'top' === direction ? -vBase : 'bottom' === direction ? vBase : 0 ]; return Math.abs((vertex = applyTransform$1(vertex, transform, invert))[0]) > Math.abs(vertex[1]) ? vertex[0] > 0 ? 'right' : 'left' : vertex[1] > 0 ? 'bottom' : 'top'; } function groupTransition(g1, g2, animatableModel) { if (g1 && g2) { var elMap, elMap1 = (elMap = {}, g1.traverse(function(el) { !el.isGroup && el.anid && (elMap[el.anid] = el); }), elMap); g2.traverse(function(el) { if (!el.isGroup && el.anid) { var oldEl = elMap1[el.anid]; if (oldEl) { var newProp = getAnimatableProps(el); el.attr(getAnimatableProps(oldEl)), updateProps(el, newProp, animatableModel, getECData(el).dataIndex); } } }); } function getAnimatableProps(el) { var obj = { x: el.x, y: el.y, rotation: el.rotation }; return null != el.shape && (obj.shape = extend({}, el.shape)), obj; } } function clipPointsByRect(points, rect) { return map(points, function(point) { var x = point[0]; x = mathMin$4(x = mathMax$4(x, rect.x), rect.x + rect.width); var y = point[1]; return [ x, y = mathMin$4(y = mathMax$4(y, rect.y), rect.y + rect.height) ]; }); } function clipRectByRect(targetRect, rect) { var x = mathMax$4(targetRect.x, rect.x), x2 = mathMin$4(targetRect.x + targetRect.width, rect.x + rect.width), y = mathMax$4(targetRect.y, rect.y), y2 = mathMin$4(targetRect.y + targetRect.height, rect.y + rect.height); if (x2 >= x && y2 >= y) return { x: x, y: y, width: x2 - x, height: y2 - y }; } function createIcon(iconStr, opt, rect) { var innerOpts = extend({ rectHover: !0 }, opt), style = innerOpts.style = { strokeNoScale: !0 }; if (rect = rect || { x: -1, y: -1, width: 2, height: 2 }, iconStr) return 0 === iconStr.indexOf('image://') ? (style.image = iconStr.slice(8), defaults(style, rect), new ZRImage(innerOpts)) : makePath(iconStr.replace('path://', ''), innerOpts, rect, 'center'); } function linePolygonIntersect(a1x, a1y, a2x, a2y, points) { for(var i = 0, p2 = points[points.length - 1]; i < points.length; i++){ var p = points[i]; if (lineLineIntersect(a1x, a1y, a2x, a2y, p[0], p[1], p2[0], p2[1])) return !0; p2 = p; } } function lineLineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) { var mx = a2x - a1x, my = a2y - a1y, nx = b2x - b1x, ny = b2y - b1y, nmCrossProduct = nx * my - mx * ny; if (nmCrossProduct <= 1e-6 && nmCrossProduct >= -0.000001) return !1; var b1a1x = a1x - b1x, b1a1y = a1y - b1y, q = (b1a1x * my - mx * b1a1y) / nmCrossProduct; if (q < 0 || q > 1) return !1; var p = (b1a1x * ny - nx * b1a1y) / nmCrossProduct; return !(p < 0) && !(p > 1); } function setTooltipConfig(opt) { var itemTooltipOption = opt.itemTooltipOption, componentModel = opt.componentModel, itemName = opt.itemName, itemTooltipOptionObj = isString(itemTooltipOption) ? { formatter: itemTooltipOption } : itemTooltipOption, mainType = componentModel.mainType, componentIndex = componentModel.componentIndex, formatterParams = { componentType: mainType, name: itemName, $vars: [ 'name' ] }; formatterParams[mainType + 'Index'] = componentIndex; var formatterParamsExtra = opt.formatterParamsExtra; formatterParamsExtra && each(keys(formatterParamsExtra), function(key) { hasOwn(formatterParams, key) || (formatterParams[key] = formatterParamsExtra[key], formatterParams.$vars.push(key)); }); var ecData = getECData(opt.el); ecData.componentMainType = mainType, ecData.componentIndex = componentIndex, ecData.tooltipConfig = { name: itemName, option: defaults({ content: itemName, formatterParams: formatterParams }, itemTooltipOptionObj) }; } _customShapeMap.circle = Circle, _customShapeMap.ellipse = Ellipse, _customShapeMap.sector = Sector, _customShapeMap.ring = Ring, _customShapeMap.polygon = Polygon, _customShapeMap.polyline = Polyline, _customShapeMap.rect = Rect, _customShapeMap.line = Line, _customShapeMap.bezierCurve = BezierCurve, _customShapeMap.arc = Arc; var graphic = Object.freeze({ __proto__: null, extendShape: extendShape, extendPath: extendPath, registerShape: registerShape, getShapeClass: getShapeClass, makePath: makePath, makeImage: makeImage, mergePath: mergePath$1, resizePath: resizePath, subPixelOptimizeLine: function(param) { return subPixelOptimizeLine(param.shape, param.shape, param.style), param; }, subPixelOptimizeRect: function(param) { return subPixelOptimizeRect(param.shape, param.shape, param.style), param; }, subPixelOptimize: subPixelOptimize, updateProps: updateProps, initProps: initProps, removeElement: removeElement, removeElementWithFadeOut: removeElementWithFadeOut, isElementRemoved: isElementRemoved, getTransform: getTransform, applyTransform: applyTransform$1, transformDirection: transformDirection, groupTransition: groupTransition, clipPointsByRect: clipPointsByRect, clipRectByRect: clipRectByRect, createIcon: createIcon, linePolygonIntersect: linePolygonIntersect, lineLineIntersect: lineLineIntersect, setTooltipConfig: setTooltipConfig, Group: Group, Image: ZRImage, Text: ZRText, Circle: Circle, Ellipse: Ellipse, Sector: Sector, Ring: Ring, Polygon: Polygon, Polyline: Polyline, Rect: Rect, Line: Line, BezierCurve: BezierCurve, Arc: Arc, IncrementalDisplayable: IncrementalDisplayable, CompoundPath: CompoundPath, LinearGradient: LinearGradient, RadialGradient: RadialGradient, BoundingRect: BoundingRect, OrientedBoundingRect: OrientedBoundingRect, Point: Point, Path: Path }), EMPTY_OBJ = {}; function setLabelText(label, labelTexts) { for(var i = 0; i < SPECIAL_STATES.length; i++){ var stateName = SPECIAL_STATES[i], text = labelTexts[stateName], state = label.ensureState(stateName); state.style = state.style || {}, state.style.text = text; } var oldStates = label.currentStates.slice(); label.clearStates(!0), label.setStyle({ text: labelTexts.normal }), label.useStates(oldStates, !0); } function getLabelText(opt, stateModels, interpolatedValue) { var baseText, labelFetcher = opt.labelFetcher, labelDataIndex = opt.labelDataIndex, labelDimIndex = opt.labelDimIndex, normalModel = stateModels.normal; labelFetcher && (baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex, normalModel && normalModel.get('formatter'), null != interpolatedValue ? { interpolatedValue: interpolatedValue } : null)), null == baseText && (baseText = isFunction(opt.defaultText) ? opt.defaultText(labelDataIndex, opt, interpolatedValue) : opt.defaultText); for(var statesText = { normal: baseText }, i = 0; i < SPECIAL_STATES.length; i++){ var stateName = SPECIAL_STATES[i], stateModel = stateModels[stateName]; statesText[stateName] = retrieve2(labelFetcher ? labelFetcher.getFormattedLabel(labelDataIndex, stateName, null, labelDimIndex, stateModel && stateModel.get('formatter')) : null, baseText); } return statesText; } function setLabelStyle(targetEl, labelStatesModels, opt, stateSpecified) { opt = opt || EMPTY_OBJ; for(var isSetOnText = targetEl instanceof ZRText, needsCreateText = !1, i = 0; i < DISPLAY_STATES.length; i++){ var stateModel = labelStatesModels[DISPLAY_STATES[i]]; if (stateModel && stateModel.getShallow('show')) { needsCreateText = !0; break; } } var textContent = isSetOnText ? targetEl : targetEl.getTextContent(); if (needsCreateText) { !isSetOnText && (textContent || (textContent = new ZRText(), targetEl.setTextContent(textContent)), targetEl.stateProxy && (textContent.stateProxy = targetEl.stateProxy)); var labelStatesTexts = getLabelText(opt, labelStatesModels), normalModel = labelStatesModels.normal, showNormal = !!normalModel.getShallow('show'), normalStyle = createTextStyle(normalModel, stateSpecified && stateSpecified.normal, opt, !1, !isSetOnText); normalStyle.text = labelStatesTexts.normal, isSetOnText || targetEl.setTextConfig(createTextConfig(normalModel, opt, !1)); for(var i = 0; i < SPECIAL_STATES.length; i++){ var stateName = SPECIAL_STATES[i], stateModel = labelStatesModels[stateName]; if (stateModel) { var stateObj = textContent.ensureState(stateName), stateShow = !!retrieve2(stateModel.getShallow('show'), showNormal); stateShow !== showNormal && (stateObj.ignore = !stateShow), stateObj.style = createTextStyle(stateModel, stateSpecified && stateSpecified[stateName], opt, !0, !isSetOnText), stateObj.style.text = labelStatesTexts[stateName], isSetOnText || (targetEl.ensureState(stateName).textConfig = createTextConfig(stateModel, opt, !0)); } } textContent.silent = !!normalModel.getShallow('silent'), null != textContent.style.x && (normalStyle.x = textContent.style.x), null != textContent.style.y && (normalStyle.y = textContent.style.y), textContent.ignore = !showNormal, textContent.useStyle(normalStyle), textContent.dirty(), opt.enableTextSetter && (labelInner(textContent).setLabelText = function(interpolatedValue) { setLabelText(textContent, getLabelText(opt, labelStatesModels, interpolatedValue)); }); } else textContent && (textContent.ignore = !0); targetEl.dirty(); } function getLabelStatesModels(itemModel, labelName) { labelName = labelName || 'label'; for(var statesModels = { normal: itemModel.getModel(labelName) }, i = 0; i < SPECIAL_STATES.length; i++){ var stateName = SPECIAL_STATES[i]; statesModels[stateName] = itemModel.getModel([ stateName, labelName ]); } return statesModels; } function createTextStyle(textStyleModel, specifiedTextStyle, opt, isNotNormal, isAttached) { var textStyle = {}; return function(textStyle, textStyleModel, opt, isNotNormal, isAttached) { opt = opt || EMPTY_OBJ; var richResult, ecModel = textStyleModel.ecModel, globalTextStyle = ecModel && ecModel.option.textStyle, richItemNames = function(textStyleModel) { for(var richItemNameMap; textStyleModel && textStyleModel !== textStyleModel.ecModel;){ var rich = (textStyleModel.option || EMPTY_OBJ).rich; if (rich) { richItemNameMap = richItemNameMap || {}; for(var richKeys = keys(rich), i = 0; i < richKeys.length; i++)richItemNameMap[richKeys[i]] = 1; } textStyleModel = textStyleModel.parentModel; } return richItemNameMap; }(textStyleModel); if (richItemNames) { for(var name_1 in richResult = {}, richItemNames)if (richItemNames.hasOwnProperty(name_1)) { var richTextStyle = textStyleModel.getModel([ 'rich', name_1 ]); setTokenTextStyle(richResult[name_1] = {}, richTextStyle, globalTextStyle, opt, isNotNormal, isAttached, !1, !0); } } richResult && (textStyle.rich = richResult); var overflow = textStyleModel.get('overflow'); overflow && (textStyle.overflow = overflow); var margin = textStyleModel.get('minMargin'); null != margin && (textStyle.margin = margin), setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, !0, !1); }(textStyle, textStyleModel, opt, isNotNormal, isAttached), specifiedTextStyle && extend(textStyle, specifiedTextStyle), textStyle; } function createTextConfig(textStyleModel, opt, isNotNormal) { opt = opt || {}; var labelPosition, textConfig = {}, labelRotate = textStyleModel.getShallow('rotate'), labelDistance = retrieve2(textStyleModel.getShallow('distance'), isNotNormal ? null : 5), labelOffset = textStyleModel.getShallow('offset'); return 'outside' === (labelPosition = textStyleModel.getShallow('position') || (isNotNormal ? null : 'inside')) && (labelPosition = opt.defaultOutsidePosition || 'top'), null != labelPosition && (textConfig.position = labelPosition), null != labelOffset && (textConfig.offset = labelOffset), null != labelRotate && (labelRotate *= Math.PI / 180, textConfig.rotation = labelRotate), null != labelDistance && (textConfig.distance = labelDistance), textConfig.outsideFill = 'inherit' === textStyleModel.get('color') ? opt.inheritColor || null : 'auto', textConfig; } var TEXT_PROPS_WITH_GLOBAL = [ 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY' ], TEXT_PROPS_SELF = [ 'align', 'lineHeight', 'width', 'height', 'tag', 'verticalAlign' ], TEXT_PROPS_BOX = [ 'padding', 'borderWidth', 'borderRadius', 'borderDashOffset', 'backgroundColor', 'borderColor', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY' ]; function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, isBlock, inRich) { globalTextStyle = !isNotNormal && globalTextStyle || EMPTY_OBJ; var inheritColor = opt && opt.inheritColor, fillColor = textStyleModel.getShallow('color'), strokeColor = textStyleModel.getShallow('textBorderColor'), opacity = retrieve2(textStyleModel.getShallow('opacity'), globalTextStyle.opacity); ('inherit' === fillColor || 'auto' === fillColor) && ('auto' === fillColor && deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\''), fillColor = inheritColor || null), ('inherit' === strokeColor || 'auto' === strokeColor) && ('auto' === strokeColor && deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\''), strokeColor = inheritColor || null), isAttached || (fillColor = fillColor || globalTextStyle.color, strokeColor = strokeColor || globalTextStyle.textBorderColor), null != fillColor && (textStyle.fill = fillColor), null != strokeColor && (textStyle.stroke = strokeColor); var textBorderWidth = retrieve2(textStyleModel.getShallow('textBorderWidth'), globalTextStyle.textBorderWidth); null != textBorderWidth && (textStyle.lineWidth = textBorderWidth); var textBorderType = retrieve2(textStyleModel.getShallow('textBorderType'), globalTextStyle.textBorderType); null != textBorderType && (textStyle.lineDash = textBorderType); var textBorderDashOffset = retrieve2(textStyleModel.getShallow('textBorderDashOffset'), globalTextStyle.textBorderDashOffset); null != textBorderDashOffset && (textStyle.lineDashOffset = textBorderDashOffset), isNotNormal || null != opacity || inRich || (opacity = opt && opt.defaultOpacity), null != opacity && (textStyle.opacity = opacity), isNotNormal || isAttached || null != textStyle.fill || !opt.inheritColor || (textStyle.fill = opt.inheritColor); for(var i = 0; i < TEXT_PROPS_WITH_GLOBAL.length; i++){ var key = TEXT_PROPS_WITH_GLOBAL[i], val = retrieve2(textStyleModel.getShallow(key), globalTextStyle[key]); null != val && (textStyle[key] = val); } for(var i = 0; i < TEXT_PROPS_SELF.length; i++){ var key = TEXT_PROPS_SELF[i], val = textStyleModel.getShallow(key); null != val && (textStyle[key] = val); } if (null == textStyle.verticalAlign) { var baseline = textStyleModel.getShallow('baseline'); null != baseline && (textStyle.verticalAlign = baseline); } if (!isBlock || !opt.disableBox) { for(var i = 0; i < TEXT_PROPS_BOX.length; i++){ var key = TEXT_PROPS_BOX[i], val = textStyleModel.getShallow(key); null != val && (textStyle[key] = val); } var borderType = textStyleModel.getShallow('borderType'); null != borderType && (textStyle.borderDash = borderType), ('auto' === textStyle.backgroundColor || 'inherit' === textStyle.backgroundColor) && inheritColor && ('auto' === textStyle.backgroundColor && deprecateReplaceLog('backgroundColor: \'auto\'', 'backgroundColor: \'inherit\''), textStyle.backgroundColor = inheritColor), ('auto' === textStyle.borderColor || 'inherit' === textStyle.borderColor) && inheritColor && ('auto' === textStyle.borderColor && deprecateReplaceLog('borderColor: \'auto\'', 'borderColor: \'inherit\''), textStyle.borderColor = inheritColor); } } function getFont(opt, ecModel) { var gTextStyleModel = ecModel && ecModel.getModel('textStyle'); return trim([ opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '', opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '', (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px', opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif' ].join(' ')); } var labelInner = makeInner(); function setLabelValueAnimation(label, labelStatesModels, value, getDefaultText) { if (label) { var obj = labelInner(label); obj.prevValue = obj.value, obj.value = value; var normalLabelModel = labelStatesModels.normal; obj.valueAnimation = normalLabelModel.get('valueAnimation'), obj.valueAnimation && (obj.precision = normalLabelModel.get('precision'), obj.defaultInterpolatedText = getDefaultText, obj.statesModels = labelStatesModels); } } function animateLabelValue(textEl, dataIndex, data, animatableModel, labelFetcher) { var labelInnerStore = labelInner(textEl); if (labelInnerStore.valueAnimation) { var defaultInterpolatedText = labelInnerStore.defaultInterpolatedText, currValue = retrieve2(labelInnerStore.interpolatedValue, labelInnerStore.prevValue), targetValue = labelInnerStore.value; (null == currValue ? initProps : updateProps)(textEl, {}, animatableModel, dataIndex, null, function(percent) { var interpolated = interpolateRawValues(data, labelInnerStore.precision, currValue, targetValue, percent); labelInnerStore.interpolatedValue = 1 === percent ? null : interpolated; var labelText = getLabelText({ labelDataIndex: dataIndex, labelFetcher: labelFetcher, defaultText: defaultInterpolatedText ? defaultInterpolatedText(interpolated) : interpolated + '' }, labelInnerStore.statesModels, interpolated); setLabelText(textEl, labelText); }); } } var PATH_COLOR = [ 'textStyle', 'color' ], tmpRichText = new ZRText(), TextStyleMixin = function() { function TextStyleMixin() {} return TextStyleMixin.prototype.getTextColor = function(isEmphasis) { var ecModel = this.ecModel; return this.getShallow('color') || (!isEmphasis && ecModel ? ecModel.get(PATH_COLOR) : null); }, TextStyleMixin.prototype.getFont = function() { return getFont({ fontStyle: this.getShallow('fontStyle'), fontWeight: this.getShallow('fontWeight'), fontSize: this.getShallow('fontSize'), fontFamily: this.getShallow('fontFamily') }, this.ecModel); }, TextStyleMixin.prototype.getTextRect = function(text) { return tmpRichText.useStyle({ text: text, fontStyle: this.getShallow('fontStyle'), fontWeight: this.getShallow('fontWeight'), fontSize: this.getShallow('fontSize'), fontFamily: this.getShallow('fontFamily'), verticalAlign: this.getShallow('verticalAlign') || this.getShallow('baseline'), padding: this.getShallow('padding'), lineHeight: this.getShallow('lineHeight'), rich: this.getShallow('rich') }), tmpRichText.update(), tmpRichText.getBoundingRect(); }, TextStyleMixin; }(), LINE_STYLE_KEY_MAP = [ [ 'lineWidth', 'width' ], [ 'stroke', 'color' ], [ 'opacity' ], [ 'shadowBlur' ], [ 'shadowOffsetX' ], [ 'shadowOffsetY' ], [ 'shadowColor' ], [ 'lineDash', 'type' ], [ 'lineDashOffset', 'dashOffset' ], [ 'lineCap', 'cap' ], [ 'lineJoin', 'join' ], [ 'miterLimit' ] ], getLineStyle = makeStyleMapper(LINE_STYLE_KEY_MAP), LineStyleMixin = function() { function LineStyleMixin() {} return LineStyleMixin.prototype.getLineStyle = function(excludes) { return getLineStyle(this, excludes); }, LineStyleMixin; }(), ITEM_STYLE_KEY_MAP = [ [ 'fill', 'color' ], [ 'stroke', 'borderColor' ], [ 'lineWidth', 'borderWidth' ], [ 'opacity' ], [ 'shadowBlur' ], [ 'shadowOffsetX' ], [ 'shadowOffsetY' ], [ 'shadowColor' ], [ 'lineDash', 'borderType' ], [ 'lineDashOffset', 'borderDashOffset' ], [ 'lineCap', 'borderCap' ], [ 'lineJoin', 'borderJoin' ], [ 'miterLimit', 'borderMiterLimit' ] ], getItemStyle = makeStyleMapper(ITEM_STYLE_KEY_MAP), ItemStyleMixin = function() { function ItemStyleMixin() {} return ItemStyleMixin.prototype.getItemStyle = function(excludes, includes) { return getItemStyle(this, excludes, includes); }, ItemStyleMixin; }(), Model = function() { function Model(option, parentModel, ecModel) { this.parentModel = parentModel, this.ecModel = ecModel, this.option = option; } return Model.prototype.init = function(option, parentModel, ecModel) { for(var rest = [], _i = 3; _i < arguments.length; _i++)rest[_i - 3] = arguments[_i]; }, Model.prototype.mergeOption = function(option, ecModel) { merge(this.option, option, !0); }, Model.prototype.get = function(path, ignoreParent) { return null == path ? this.option : this._doGet(this.parsePath(path), !ignoreParent && this.parentModel); }, Model.prototype.getShallow = function(key, ignoreParent) { var option = this.option, val = null == option ? option : option[key]; if (null == val && !ignoreParent) { var parentModel = this.parentModel; parentModel && (val = parentModel.getShallow(key)); } return val; }, Model.prototype.getModel = function(path, parentModel) { var hasPath = null != path, pathFinal = hasPath ? this.parsePath(path) : null, obj = hasPath ? this._doGet(pathFinal) : this.option; return parentModel = parentModel || this.parentModel && this.parentModel.getModel(this.resolveParentPath(pathFinal)), new Model(obj, parentModel, this.ecModel); }, Model.prototype.isEmpty = function() { return null == this.option; }, Model.prototype.restoreData = function() {}, Model.prototype.clone = function() { return new this.constructor(clone(this.option)); }, Model.prototype.parsePath = function(path) { return 'string' == typeof path ? path.split('.') : path; }, Model.prototype.resolveParentPath = function(path) { return path; }, Model.prototype.isAnimationEnabled = function() { if (!env1.node && this.option) { if (null != this.option.animation) return !!this.option.animation; if (this.parentModel) return this.parentModel.isAnimationEnabled(); } }, Model.prototype._doGet = function(pathArr, parentModel) { var obj = this.option; if (!pathArr) return obj; for(var i = 0; i < pathArr.length && (!pathArr[i] || null != (obj = obj && 'object' == typeof obj ? obj[pathArr[i]] : null)); i++); return null == obj && parentModel && (obj = parentModel._doGet(this.resolveParentPath(pathArr), parentModel.parentModel)), obj; }, Model; }(); enableClassExtend(Model), target = Model, classAttr = [ '__\0is_clz', classBase++ ].join('_'), target.prototype[classAttr] = !0, assert(!target.isInstance, 'The method "is" can not be defined.'), target.isInstance = function(obj) { return !!(obj && obj[classAttr]); }, mixin(Model, LineStyleMixin), mixin(Model, ItemStyleMixin), mixin(Model, AreaStyleMixin), mixin(Model, TextStyleMixin); var base = Math.round(10 * Math.random()); function getUID(type) { return [ type || '', base++ ].join('_'); } function inheritDefaultOption(superOption, subOption) { return merge(merge({}, superOption, !0), subOption, !0); } var localeStorage = {}, localeModels = {}, SYSTEM_LANG = env1.domSupported && (document.documentElement.lang || navigator.language || navigator.browserLanguage).toUpperCase().indexOf('ZH') > -1 ? 'ZH' : 'EN'; function registerLocale(locale, localeObj) { localeModels[locale = locale.toUpperCase()] = new Model(localeObj), localeStorage[locale] = localeObj; } registerLocale('EN', { time: { month: [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ], monthAbbr: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ], dayOfWeek: [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ], dayOfWeekAbbr: [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ] }, legend: { selector: { all: 'All', inverse: 'Inv' } }, toolbox: { brush: { title: { rect: 'Box Select', polygon: 'Lasso Select', lineX: 'Horizontally Select', lineY: 'Vertically Select', keep: 'Keep Selections', clear: 'Clear Selections' } }, dataView: { title: 'Data View', lang: [ 'Data View', 'Close', 'Refresh' ] }, dataZoom: { title: { zoom: 'Zoom', back: 'Zoom Reset' } }, magicType: { title: { line: 'Switch to Line Chart', bar: 'Switch to Bar Chart', stack: 'Stack', tiled: 'Tile' } }, restore: { title: 'Restore' }, saveAsImage: { title: 'Save as Image', lang: [ 'Right Click to Save Image' ] } }, series: { typeNames: { pie: 'Pie chart', bar: 'Bar chart', line: 'Line chart', scatter: 'Scatter plot', effectScatter: 'Ripple scatter plot', radar: 'Radar chart', tree: 'Tree', treemap: 'Treemap', boxplot: 'Boxplot', candlestick: 'Candlestick', k: 'K line chart', heatmap: 'Heat map', map: 'Map', parallel: 'Parallel coordinate map', lines: 'Line graph', graph: 'Relationship graph', sankey: 'Sankey diagram', funnel: 'Funnel chart', gauge: 'Guage', pictorialBar: 'Pictorial bar', themeRiver: 'Theme River Map', sunburst: 'Sunburst' } }, aria: { general: { withTitle: 'This is a chart about "{title}"', withoutTitle: 'This is a chart' }, series: { single: { prefix: '', withName: ' with type {seriesType} named {seriesName}.', withoutName: ' with type {seriesType}.' }, multiple: { prefix: '. It consists of {seriesCount} series count.', withName: ' The {seriesId} series is a {seriesType} representing {seriesName}.', withoutName: ' The {seriesId} series is a {seriesType}.', separator: { middle: '', end: '' } } }, data: { allData: 'The data is as follows: ', partialData: 'The first {displayCnt} items are: ', withName: 'the data for {name} is {value}', withoutName: '{value}', separator: { middle: ', ', end: '. ' } } } }), registerLocale('ZH', { time: { month: [ '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月' ], monthAbbr: [ '1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月' ], dayOfWeek: [ '星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六' ], dayOfWeekAbbr: [ '日', '一', '二', '三', '四', '五', '六' ] }, legend: { selector: { all: '全选', inverse: '反选' } }, toolbox: { brush: { title: { rect: '矩形选择', polygon: '圈选', lineX: '横向选择', lineY: '纵向选择', keep: '保持选择', clear: '清除选择' } }, dataView: { title: '数据视图', lang: [ '数据视图', '关闭', '刷新' ] }, dataZoom: { title: { zoom: '区域缩放', back: '区域缩放还原' } }, magicType: { title: { line: '切换为折线图', bar: '切换为柱状图', stack: '切换为堆叠', tiled: '切换为平铺' } }, restore: { title: '还原' }, saveAsImage: { title: '保存为图片', lang: [ '右键另存为图片' ] } }, series: { typeNames: { pie: '饼图', bar: '柱状图', line: '折线图', scatter: '散点图', effectScatter: '涟漪散点图', radar: '雷达图', tree: '树图', treemap: '矩形树图', boxplot: '箱型图', candlestick: 'K线图', k: 'K线图', heatmap: '热力图', map: '地图', parallel: '平行坐标图', lines: '线图', graph: '关系图', sankey: '桑基图', funnel: '漏斗图', gauge: '仪表盘图', pictorialBar: '象形柱图', themeRiver: '主题河流图', sunburst: '旭日图' } }, aria: { general: { withTitle: '这是一个关于“{title}”的图表。', withoutTitle: '这是一个图表,' }, series: { single: { prefix: '', withName: '图表类型是{seriesType},表示{seriesName}。', withoutName: '图表类型是{seriesType}。' }, multiple: { prefix: '它由{seriesCount}个图表系列组成。', withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},', withoutName: '第{seriesId}个系列是一个{seriesType},', separator: { middle: ';', end: '。' } } }, data: { allData: '其数据是——', partialData: '其中,前{displayCnt}项是——', withName: '{name}的数据是{value}', withoutName: '{value}', separator: { middle: ',', end: '' } } } }); var defaultLeveledFormatter = { year: '{yyyy}', month: '{MMM}', day: '{d}', hour: '{HH}:{mm}', minute: '{HH}:{mm}', second: '{HH}:{mm}:{ss}', millisecond: '{hh}:{mm}:{ss} {SSS}', none: '{yyyy}-{MM}-{dd} {hh}:{mm}:{ss} {SSS}' }, fullDayFormatter = '{yyyy}-{MM}-{dd}', fullLeveledFormatter = { year: '{yyyy}', month: '{yyyy}-{MM}', day: fullDayFormatter, hour: fullDayFormatter + ' ' + defaultLeveledFormatter.hour, minute: fullDayFormatter + ' ' + defaultLeveledFormatter.minute, second: fullDayFormatter + ' ' + defaultLeveledFormatter.second, millisecond: defaultLeveledFormatter.none }, primaryTimeUnits = [ 'year', 'month', 'day', 'hour', 'minute', 'second', 'millisecond' ], timeUnits = [ 'year', 'half-year', 'quarter', 'month', 'week', 'half-week', 'day', 'half-day', 'quarter-day', 'hour', 'minute', 'second', 'millisecond' ]; function pad(str, len) { return str += '', '0000'.substr(0, len - str.length) + str; } function getPrimaryTimeUnit(timeUnit) { switch(timeUnit){ case 'half-year': case 'quarter': return 'month'; case 'week': case 'half-week': return 'day'; case 'half-day': case 'quarter-day': return 'hour'; default: return timeUnit; } } function format(time, template, isUTC, lang) { var date = parseDate(time), y = date[fullYearGetterName(isUTC)](), M = date[monthGetterName(isUTC)]() + 1, d = date[dateGetterName(isUTC)](), e = date['get' + (isUTC ? 'UTC' : '') + 'Day'](), H = date[hoursGetterName(isUTC)](), h = (H - 1) % 12 + 1, m = date[minutesGetterName(isUTC)](), s = date[secondsGetterName(isUTC)](), S = date[millisecondsGetterName(isUTC)](), timeModel = (lang instanceof Model ? lang : localeModels[lang || SYSTEM_LANG] || localeModels.EN).getModel('time'), month = timeModel.get('month'), monthAbbr = timeModel.get('monthAbbr'), dayOfWeek = timeModel.get('dayOfWeek'), dayOfWeekAbbr = timeModel.get('dayOfWeekAbbr'); return (template || '').replace(/{yyyy}/g, y + '').replace(/{yy}/g, y % 100 + '').replace(/{Q}/g, Math.floor((M - 1) / 4) + 1 + '').replace(/{MMMM}/g, month[M - 1]).replace(/{MMM}/g, monthAbbr[M - 1]).replace(/{MM}/g, pad(M, 2)).replace(/{M}/g, M + '').replace(/{dd}/g, pad(d, 2)).replace(/{d}/g, d + '').replace(/{eeee}/g, dayOfWeek[e]).replace(/{ee}/g, dayOfWeekAbbr[e]).replace(/{e}/g, e + '').replace(/{HH}/g, pad(H, 2)).replace(/{H}/g, H + '').replace(/{hh}/g, pad(h + '', 2)).replace(/{h}/g, h + '').replace(/{mm}/g, pad(m, 2)).replace(/{m}/g, m + '').replace(/{ss}/g, pad(s, 2)).replace(/{s}/g, s + '').replace(/{SSS}/g, pad(S, 3)).replace(/{S}/g, S + ''); } function getUnitFromValue(value, isUTC) { var date = parseDate(value), M = date[monthGetterName(isUTC)]() + 1, d = date[dateGetterName(isUTC)](), h = date[hoursGetterName(isUTC)](), m = date[minutesGetterName(isUTC)](), s = date[secondsGetterName(isUTC)](), isSecond = 0 === date[millisecondsGetterName(isUTC)](), isMinute = isSecond && 0 === s, isHour = isMinute && 0 === m, isDay = isHour && 0 === h, isMonth = isDay && 1 === d; return isMonth && 1 === M ? 'year' : isMonth ? 'month' : isDay ? 'day' : isHour ? 'hour' : isMinute ? 'minute' : isSecond ? 'second' : 'millisecond'; } function getUnitValue(value, unit, isUTC) { var date = 'number' == typeof value ? parseDate(value) : value; switch(unit = unit || getUnitFromValue(value, isUTC)){ case 'year': return date[fullYearGetterName(isUTC)](); case 'half-year': return date[monthGetterName(isUTC)]() >= 6 ? 1 : 0; case 'quarter': return Math.floor((date[monthGetterName(isUTC)]() + 1) / 4); case 'month': return date[monthGetterName(isUTC)](); case 'day': return date[dateGetterName(isUTC)](); case 'half-day': return date[hoursGetterName(isUTC)]() / 24; case 'hour': return date[hoursGetterName(isUTC)](); case 'minute': return date[minutesGetterName(isUTC)](); case 'second': return date[secondsGetterName(isUTC)](); case 'millisecond': return date[millisecondsGetterName(isUTC)](); } } function fullYearGetterName(isUTC) { return isUTC ? 'getUTCFullYear' : 'getFullYear'; } function monthGetterName(isUTC) { return isUTC ? 'getUTCMonth' : 'getMonth'; } function dateGetterName(isUTC) { return isUTC ? 'getUTCDate' : 'getDate'; } function hoursGetterName(isUTC) { return isUTC ? 'getUTCHours' : 'getHours'; } function minutesGetterName(isUTC) { return isUTC ? 'getUTCMinutes' : 'getMinutes'; } function secondsGetterName(isUTC) { return isUTC ? 'getUTCSeconds' : 'getSeconds'; } function millisecondsGetterName(isUTC) { return isUTC ? 'getUTCSeconds' : 'getSeconds'; } function monthSetterName(isUTC) { return isUTC ? 'setUTCMonth' : 'setMonth'; } function dateSetterName(isUTC) { return isUTC ? 'setUTCDate' : 'setDate'; } function hoursSetterName(isUTC) { return isUTC ? 'setUTCHours' : 'setHours'; } function minutesSetterName(isUTC) { return isUTC ? 'setUTCMinutes' : 'setMinutes'; } function secondsSetterName(isUTC) { return isUTC ? 'setUTCSeconds' : 'setSeconds'; } function millisecondsSetterName(isUTC) { return isUTC ? 'setUTCSeconds' : 'setSeconds'; } function addCommas(x) { if (!isNumeric(x)) return isString(x) ? x : '-'; var parts = (x + '').split('.'); return parts[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,') + (parts.length > 1 ? '.' + parts[1] : ''); } function toCamelCase(str, upperCaseFirst) { return str = (str || '').toLowerCase().replace(/-(.)/g, function(match, group1) { return group1.toUpperCase(); }), upperCaseFirst && str && (str = str.charAt(0).toUpperCase() + str.slice(1)), str; } var replaceReg = /([&<>"'])/g, replaceMap = { '&': '&', '<': '<', '>': '>', '"': '"', '\'': ''' }; function encodeHTML(source) { return null == source ? '' : (source + '').replace(replaceReg, function(str, c) { return replaceMap[c]; }); } function makeValueReadable(value, valueType, useUTC) { function stringToUserReadable(str) { return str && trim(str) ? str : '-'; } function isNumberUserReadable(num) { return !!(null != num && !isNaN(num) && isFinite(num)); } var isTypeTime = 'time' === valueType, isValueDate = value instanceof Date; if (isTypeTime || isValueDate) { var date = isTypeTime ? parseDate(value) : value; if (!isNaN(+date)) return format(date, '{yyyy}-{MM}-{dd} {hh}:{mm}:{ss}', useUTC); if (isValueDate) return '-'; } if ('ordinal' === valueType) return isStringSafe(value) ? stringToUserReadable(value) : isNumber(value) && isNumberUserReadable(value) ? value + '' : '-'; var numericResult = numericToNumber(value); return isNumberUserReadable(numericResult) ? addCommas(numericResult) : isStringSafe(value) ? stringToUserReadable(value) : '-'; } var TPL_VAR_ALIAS = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g' ], wrapVar = function(varName, seriesIdx) { return '{' + varName + (null == seriesIdx ? '' : seriesIdx) + '}'; }; function formatTpl(tpl, paramsList, encode) { isArray(paramsList) || (paramsList = [ paramsList ]); var seriesLen = paramsList.length; if (!seriesLen) return ''; for(var $vars = paramsList[0].$vars || [], i = 0; i < $vars.length; i++){ var alias = TPL_VAR_ALIAS[i]; tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0)); } for(var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++)for(var k = 0; k < $vars.length; k++){ var val = paramsList[seriesIdx][$vars[k]]; tpl = tpl.replace(wrapVar(TPL_VAR_ALIAS[k], seriesIdx), encode ? encodeHTML(val) : val); } return tpl; } function getTooltipMarker(inOpt, extraCssText) { var opt = isString(inOpt) ? { color: inOpt, extraCssText: extraCssText } : inOpt || {}, color = opt.color, type = opt.type; extraCssText = opt.extraCssText; var renderMode = opt.renderMode || 'html'; return color ? 'html' === renderMode ? 'subItem' === type ? '' : '' : { renderMode: renderMode, content: '{' + (opt.markerId || 'markerX') + '|} ', style: 'subItem' === type ? { width: 4, height: 4, borderRadius: 2, backgroundColor: color } : { width: 10, height: 10, borderRadius: 5, backgroundColor: color } } : ''; } function convertToColorString(color, defaultColor) { return defaultColor = defaultColor || 'transparent', isString(color) ? color : isObject(color) && color.colorStops && (color.colorStops[0] || {}).color || defaultColor; } function windowOpen(link, target) { if ('_blank' === target || 'blank' === target) { var blank = window.open(); blank.opener = null, blank.location.href = link; } else window.open(link, target); } var LOCATION_PARAMS = [ 'left', 'right', 'top', 'bottom', 'width', 'height' ], HV_NAMES = [ [ 'width', 'left', 'right' ], [ 'height', 'top', 'bottom' ] ]; function boxLayout(orient, group, gap, maxWidth, maxHeight) { var x = 0, y = 0; null == maxWidth && (maxWidth = 1 / 0), null == maxHeight && (maxHeight = 1 / 0); var currentLineMaxSize = 0; group.eachChild(function(child, idx) { var nextX, nextY, rect = child.getBoundingRect(), nextChild = group.childAt(idx + 1), nextChildRect = nextChild && nextChild.getBoundingRect(); if ('horizontal' === orient) { var moveX = rect.width + (nextChildRect ? -nextChildRect.x + rect.x : 0); (nextX = x + moveX) > maxWidth || child.newline ? (x = 0, nextX = moveX, y += currentLineMaxSize + gap, currentLineMaxSize = rect.height) : currentLineMaxSize = Math.max(currentLineMaxSize, rect.height); } else { var moveY = rect.height + (nextChildRect ? -nextChildRect.y + rect.y : 0); (nextY = y + moveY) > maxHeight || child.newline ? (x += currentLineMaxSize + gap, y = 0, nextY = moveY, currentLineMaxSize = rect.width) : currentLineMaxSize = Math.max(currentLineMaxSize, rect.width); } child.newline || (child.x = x, child.y = y, child.markRedraw(), 'horizontal' === orient ? x = nextX + gap : y = nextY + gap); }); } function getLayoutRect(positionInfo, containerRect, margin) { margin = normalizeCssArray(margin || 0); var containerWidth = containerRect.width, containerHeight = containerRect.height, left = parsePercent$1(positionInfo.left, containerWidth), top = parsePercent$1(positionInfo.top, containerHeight), right = parsePercent$1(positionInfo.right, containerWidth), bottom = parsePercent$1(positionInfo.bottom, containerHeight), width = parsePercent$1(positionInfo.width, containerWidth), height = parsePercent$1(positionInfo.height, containerHeight), verticalMargin = margin[2] + margin[0], horizontalMargin = margin[1] + margin[3], aspect = positionInfo.aspect; switch(isNaN(width) && (width = containerWidth - right - horizontalMargin - left), isNaN(height) && (height = containerHeight - bottom - verticalMargin - top), null != aspect && (isNaN(width) && isNaN(height) && (aspect > containerWidth / containerHeight ? width = 0.8 * containerWidth : height = 0.8 * containerHeight), isNaN(width) && (width = aspect * height), isNaN(height) && (height = width / aspect)), isNaN(left) && (left = containerWidth - right - width - horizontalMargin), isNaN(top) && (top = containerHeight - bottom - height - verticalMargin), positionInfo.left || positionInfo.right){ case 'center': left = containerWidth / 2 - width / 2 - margin[3]; break; case 'right': left = containerWidth - width - horizontalMargin; } switch(positionInfo.top || positionInfo.bottom){ case 'middle': case 'center': top = containerHeight / 2 - height / 2 - margin[0]; break; case 'bottom': top = containerHeight - height - verticalMargin; } left = left || 0, top = top || 0, isNaN(width) && (width = containerWidth - horizontalMargin - left - (right || 0)), isNaN(height) && (height = containerHeight - verticalMargin - top - (bottom || 0)); var rect = new BoundingRect(left + margin[3], top + margin[0], width, height); return rect.margin = margin, rect; } function positionElement(el, positionInfo, containerRect, margin, opt) { var rect, h = !opt || !opt.hv || opt.hv[0], v = !opt || !opt.hv || opt.hv[1], boundingMode = opt && opt.boundingMode || 'all'; if (h || v) { if ('raw' === boundingMode) rect = 'group' === el.type ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0) : el.getBoundingRect(); else if (rect = el.getBoundingRect(), el.needLocalTransform()) { var transform = el.getLocalTransform(); (rect = rect.clone()).applyTransform(transform); } var layoutRect = getLayoutRect(defaults({ width: rect.width, height: rect.height }, positionInfo), containerRect, margin), dx = h ? layoutRect.x - rect.x : 0, dy = v ? layoutRect.y - rect.y : 0; 'raw' === boundingMode ? (el.x = dx, el.y = dy) : (el.x += dx, el.y += dy), el.markRedraw(); } } function fetchLayoutMode(ins) { var layoutMode = ins.layoutMode || ins.constructor.layoutMode; return isObject(layoutMode) ? layoutMode : layoutMode ? { type: layoutMode } : null; } function mergeLayoutParam(targetOption, newOption, opt) { var ignoreSize = opt && opt.ignoreSize; isArray(ignoreSize) || (ignoreSize = [ ignoreSize, ignoreSize ]); var hResult = merge(HV_NAMES[0], 0), vResult = merge(HV_NAMES[1], 1); function merge(names, hvIdx) { var newParams = {}, newValueCount = 0, merged = {}, mergedValueCount = 0; if (each(names, function(name) { merged[name] = targetOption[name]; }), each(names, function(name) { hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]), hasValue(newParams, name) && newValueCount++, hasValue(merged, name) && mergedValueCount++; }), ignoreSize[hvIdx]) return hasValue(newOption, names[1]) ? merged[names[2]] = null : hasValue(newOption, names[2]) && (merged[names[1]] = null), merged; if (2 === mergedValueCount || !newValueCount) return merged; if (newValueCount >= 2) return newParams; for(var i = 0; i < names.length; i++){ var name_1 = names[i]; if (!hasProp(newParams, name_1) && hasProp(targetOption, name_1)) { newParams[name_1] = targetOption[name_1]; break; } } return newParams; } function hasProp(obj, name) { return obj.hasOwnProperty(name); } function hasValue(obj, name) { return null != obj[name] && 'auto' !== obj[name]; } function copy(names, target, source) { each(names, function(name) { target[name] = source[name]; }); } copy(HV_NAMES[0], targetOption, hResult), copy(HV_NAMES[1], targetOption, vResult); } function getLayoutParams(source) { return copyLayoutParams({}, source); } function copyLayoutParams(target, source) { return source && target && each(LOCATION_PARAMS, function(name) { source.hasOwnProperty(name) && (target[name] = source[name]); }), target; } curry(boxLayout, 'vertical'), curry(boxLayout, 'horizontal'); var inner = makeInner(), ComponentModel = function(_super) { var proto; function ComponentModel(option, parentModel, ecModel) { var _this = _super.call(this, option, parentModel, ecModel) || this; return _this.uid = getUID('ec_cpt_model'), _this; } return __extends(ComponentModel, _super), ComponentModel.prototype.init = function(option, parentModel, ecModel) { this.mergeDefaultAndTheme(option, ecModel); }, ComponentModel.prototype.mergeDefaultAndTheme = function(option, ecModel) { var layoutMode = fetchLayoutMode(this), inputPositionParams = layoutMode ? getLayoutParams(option) : {}; merge(option, ecModel.getTheme().get(this.mainType)), merge(option, this.getDefaultOption()), layoutMode && mergeLayoutParam(option, inputPositionParams, layoutMode); }, ComponentModel.prototype.mergeOption = function(option, ecModel) { merge(this.option, option, !0); var layoutMode = fetchLayoutMode(this); layoutMode && mergeLayoutParam(this.option, option, layoutMode); }, ComponentModel.prototype.optionUpdated = function(newCptOption, isInit) {}, ComponentModel.prototype.getDefaultOption = function() { var ctor = this.constructor; if (!(ctor && ctor[IS_EXTENDED_CLASS])) return ctor.defaultOption; var fields = inner(this); if (!fields.defaultOption) { for(var optList = [], clz = ctor; clz;){ var opt = clz.prototype.defaultOption; opt && optList.push(opt), clz = clz.superClass; } for(var defaultOption = {}, i = optList.length - 1; i >= 0; i--)defaultOption = merge(defaultOption, optList[i], !0); fields.defaultOption = defaultOption; } return fields.defaultOption; }, ComponentModel.prototype.getReferringComponents = function(mainType, opt) { return queryReferringComponents(this.ecModel, mainType, { index: this.get(mainType + 'Index', !0), id: this.get(mainType + 'Id', !0) }, opt); }, ComponentModel.prototype.getBoxLayoutParams = function() { return { left: this.get('left'), top: this.get('top'), right: this.get('right'), bottom: this.get('bottom'), width: this.get('width'), height: this.get('height') }; }, ComponentModel.protoInitialize = void ((proto = ComponentModel.prototype).type = 'component', proto.id = '', proto.name = '', proto.mainType = '', proto.subType = '', proto.componentIndex = 0), ComponentModel; }(Model); mountExtend(ComponentModel, Model), enableClassManagement(ComponentModel), subTypeDefaulters = {}, (target1 = ComponentModel).registerSubTypeDefaulter = function(componentType, defaulter) { subTypeDefaulters[parseClassType(componentType).main] = defaulter; }, target1.determineSubType = function(componentType, option) { var type = option.type; if (!type) { var componentTypeMain = parseClassType(componentType).main; target1.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain] && (type = subTypeDefaulters[componentTypeMain](option)); } return type; }, function(entity, dependencyGetter) { entity.topologicalTravel = function(targetNameList, fullNameList, callback, context) { if (targetNameList.length) { var graph, noEntryList, result = (graph = {}, noEntryList = [], each(fullNameList, function(name) { var originalDeps, availableDeps, thisItem = createDependencyGraphItem(graph, name), availableDeps1 = (originalDeps = thisItem.originalDeps = dependencyGetter(name), availableDeps = [], each(originalDeps, function(dep) { indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep); }), availableDeps); thisItem.entryCount = availableDeps1.length, 0 === thisItem.entryCount && noEntryList.push(name), each(availableDeps1, function(dependentName) { 0 > indexOf(thisItem.predecessor, dependentName) && thisItem.predecessor.push(dependentName); var thatItem = createDependencyGraphItem(graph, dependentName); 0 > indexOf(thatItem.successor, dependentName) && thatItem.successor.push(name); }); }), { graph: graph, noEntryList: noEntryList }), graph1 = result.graph, noEntryList1 = result.noEntryList, targetNameSet = {}; for(each(targetNameList, function(name) { targetNameSet[name] = !0; }); noEntryList1.length;){ var currComponentType = noEntryList1.pop(), currVertex = graph1[currComponentType], isInTargetNameSet = !!targetNameSet[currComponentType]; isInTargetNameSet && (callback.call(context, currComponentType, currVertex.originalDeps.slice()), delete targetNameSet[currComponentType]), each(currVertex.successor, isInTargetNameSet ? removeEdgeAndAdd : removeEdge); } each(targetNameSet, function() { throw Error(makePrintable('Circular dependency may exists: ', targetNameSet, targetNameList, fullNameList)); }); } function removeEdge(succComponentType) { graph1[succComponentType].entryCount--, 0 === graph1[succComponentType].entryCount && noEntryList1.push(succComponentType); } function removeEdgeAndAdd(succComponentType) { targetNameSet[succComponentType] = !0, removeEdge(succComponentType); } }; function createDependencyGraphItem(graph, name) { return graph[name] || (graph[name] = { predecessor: [], successor: [] }), graph[name]; } }(ComponentModel, function(componentType) { var deps = []; return each(ComponentModel.getClassesByMainType(componentType), function(clz) { deps = deps.concat(clz.dependencies || clz.prototype.dependencies || []); }), deps = map(deps, function(type) { return parseClassType(type).main; }), 'dataset' !== componentType && 0 >= indexOf(deps, 'dataset') && deps.unshift('dataset'), deps; }); var platform = ''; 'undefined' != typeof navigator && (platform = navigator.platform || ''); var decalColor = 'rgba(0, 0, 0, 0.2)', globalDefault = { darkMode: 'auto', color: [ '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc' ], gradientColor: [ '#f6efa6', '#d88273', '#bf444c' ], aria: { decal: { decals: [ { color: decalColor, dashArrayX: [ 1, 0 ], dashArrayY: [ 2, 5 ], symbolSize: 1, rotation: Math.PI / 6 }, { color: decalColor, symbol: 'circle', dashArrayX: [ [ 8, 8 ], [ 0, 8, 8, 0 ] ], dashArrayY: [ 6, 0 ], symbolSize: 0.8 }, { color: decalColor, dashArrayX: [ 1, 0 ], dashArrayY: [ 4, 3 ], rotation: -Math.PI / 4 }, { color: decalColor, dashArrayX: [ [ 6, 6 ], [ 0, 6, 6, 0 ] ], dashArrayY: [ 6, 0 ] }, { color: decalColor, dashArrayX: [ [ 1, 0 ], [ 1, 6 ] ], dashArrayY: [ 1, 0, 6, 0 ], rotation: Math.PI / 4 }, { color: decalColor, symbol: 'triangle', dashArrayX: [ [ 9, 9 ], [ 0, 9, 9, 0 ] ], dashArrayY: [ 7, 2 ], symbolSize: 0.75 } ] } }, textStyle: { fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif', fontSize: 12, fontStyle: 'normal', fontWeight: 'normal' }, blendMode: null, stateAnimation: { duration: 300, easing: 'cubicOut' }, animation: 'auto', animationDuration: 1000, animationDurationUpdate: 500, animationEasing: 'cubicInOut', animationEasingUpdate: 'cubicInOut', animationThreshold: 2000, progressiveThreshold: 3000, progressive: 400, hoverLayerThreshold: 3000, useUTC: !1 }, VISUAL_DIMENSIONS = createHashMap([ 'tooltip', 'label', 'itemName', 'itemId', 'seriesName' ]), SOURCE_FORMAT_ORIGINAL = 'original', SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows', SOURCE_FORMAT_OBJECT_ROWS = 'objectRows', SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns', SOURCE_FORMAT_TYPED_ARRAY = 'typedArray', SOURCE_FORMAT_UNKNOWN = 'unknown', SERIES_LAYOUT_BY_COLUMN = 'column', BE_ORDINAL = { Must: 1, Might: 2, Not: 3 }, innerGlobalModel = makeInner(); function makeSeriesEncodeForAxisCoordSys(coordDimensions, seriesModel, source) { var baseCategoryDimIndex, categoryWayValueDimStart, encode = {}, datasetModel = querySeriesUpstreamDatasetModel(seriesModel); if (!datasetModel || !coordDimensions) return encode; var encodeItemName = [], encodeSeriesName = [], datasetMap = innerGlobalModel(seriesModel.ecModel).datasetMap, key = datasetModel.uid + '_' + source.seriesLayoutBy; each(coordDimensions = coordDimensions.slice(), function(coordDimInfoLoose, coordDimIdx) { var coordDimInfo = isObject(coordDimInfoLoose) ? coordDimInfoLoose : coordDimensions[coordDimIdx] = { name: coordDimInfoLoose }; 'ordinal' === coordDimInfo.type && null == baseCategoryDimIndex && (baseCategoryDimIndex = coordDimIdx, categoryWayValueDimStart = getDataDimCountOnCoordDim(coordDimInfo)), encode[coordDimInfo.name] = []; }); var datasetRecord = datasetMap.get(key) || datasetMap.set(key, { categoryWayDim: categoryWayValueDimStart, valueWayDim: 0 }); function pushDim(dimIdxArr, idxFrom, idxCount) { for(var i = 0; i < idxCount; i++)dimIdxArr.push(idxFrom + i); } function getDataDimCountOnCoordDim(coordDimInfo) { var dimsDef = coordDimInfo.dimsDef; return dimsDef ? dimsDef.length : 1; } return each(coordDimensions, function(coordDimInfo, coordDimIdx) { var coordDimName = coordDimInfo.name, count = getDataDimCountOnCoordDim(coordDimInfo); if (null == baseCategoryDimIndex) { var start = datasetRecord.valueWayDim; pushDim(encode[coordDimName], start, count), pushDim(encodeSeriesName, start, count), datasetRecord.valueWayDim += count; } else if (baseCategoryDimIndex === coordDimIdx) pushDim(encode[coordDimName], 0, count), pushDim(encodeItemName, 0, count); else { var start = datasetRecord.categoryWayDim; pushDim(encode[coordDimName], start, count), pushDim(encodeSeriesName, start, count), datasetRecord.categoryWayDim += count; } }), encodeItemName.length && (encode.itemName = encodeItemName), encodeSeriesName.length && (encode.seriesName = encodeSeriesName), encode; } function makeSeriesEncodeForNameBased(seriesModel, source, dimCount) { var potentialNameDimIndex, encode = {}; if (!querySeriesUpstreamDatasetModel(seriesModel)) return encode; var sourceFormat = source.sourceFormat, dimensionsDefine = source.dimensionsDefine; (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) && each(dimensionsDefine, function(dim, idx) { (isObject(dim) ? dim.name : dim) === 'name' && (potentialNameDimIndex = idx); }); var idxResult = function() { for(var idxRes0 = {}, idxRes1 = {}, guessRecords = [], i = 0, len = Math.min(5, dimCount); i < len; i++){ var guessResult = doGuessOrdinal(source.data, sourceFormat, source.seriesLayoutBy, dimensionsDefine, source.startIndex, i); guessRecords.push(guessResult); var isPureNumber = guessResult === BE_ORDINAL.Not; if (isPureNumber && null == idxRes0.v && i !== potentialNameDimIndex && (idxRes0.v = i), null != idxRes0.n && idxRes0.n !== idxRes0.v && (isPureNumber || guessRecords[idxRes0.n] !== BE_ORDINAL.Not) || (idxRes0.n = i), fulfilled(idxRes0) && guessRecords[idxRes0.n] !== BE_ORDINAL.Not) return idxRes0; isPureNumber || (guessResult === BE_ORDINAL.Might && null == idxRes1.v && i !== potentialNameDimIndex && (idxRes1.v = i), null != idxRes1.n && idxRes1.n !== idxRes1.v || (idxRes1.n = i)); } function fulfilled(idxResult) { return null != idxResult.v && null != idxResult.n; } return fulfilled(idxRes0) ? idxRes0 : fulfilled(idxRes1) ? idxRes1 : null; }(); if (idxResult) { encode.value = [ idxResult.v ]; var nameDimIndex = null != potentialNameDimIndex ? potentialNameDimIndex : idxResult.n; encode.itemName = [ nameDimIndex ], encode.seriesName = [ nameDimIndex ]; } return encode; } function querySeriesUpstreamDatasetModel(seriesModel) { if (!seriesModel.get('data', !0)) return queryReferringComponents(seriesModel.ecModel, 'dataset', { index: seriesModel.get('datasetIndex', !0), id: seriesModel.get('datasetId', !0) }, SINGLE_REFERRING).models[0]; } function doGuessOrdinal(data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex) { var result, dimName, dimType; if (isTypedArray(data)) return BE_ORDINAL.Not; if (dimensionsDefine) { var dimDefItem = dimensionsDefine[dimIndex]; isObject(dimDefItem) ? (dimName = dimDefItem.name, dimType = dimDefItem.type) : isString(dimDefItem) && (dimName = dimDefItem); } if (null != dimType) return 'ordinal' === dimType ? BE_ORDINAL.Must : BE_ORDINAL.Not; if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) { if ('row' === seriesLayoutBy) { for(var sample = data[dimIndex], i = 0; i < (sample || []).length && i < 5; i++)if (null != (result = detectValue(sample[startIndex + i]))) return result; } else for(var i = 0; i < data.length && i < 5; i++){ var row = data[startIndex + i]; if (row && null != (result = detectValue(row[dimIndex]))) return result; } } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) { if (!dimName) return BE_ORDINAL.Not; for(var i = 0; i < data.length && i < 5; i++){ var item = data[i]; if (item && null != (result = detectValue(item[dimName]))) return result; } } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) { if (!dimName) return BE_ORDINAL.Not; var sample = data[dimName]; if (!sample || isTypedArray(sample)) return BE_ORDINAL.Not; for(var i = 0; i < sample.length && i < 5; i++)if (null != (result = detectValue(sample[i]))) return result; } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) for(var i = 0; i < data.length && i < 5; i++){ var item = data[i], val = getDataItemValue(item); if (!isArray(val)) return BE_ORDINAL.Not; if (null != (result = detectValue(val[dimIndex]))) return result; } function detectValue(val) { var beStr = isString(val); return null != val && isFinite(val) && '' !== val ? beStr ? BE_ORDINAL.Might : BE_ORDINAL.Not : beStr && '-' !== val ? BE_ORDINAL.Must : void 0; } return BE_ORDINAL.Not; } var internalOptionCreatorMap = createHashMap(), innerColor = makeInner(), innerDecal = makeInner(), PaletteMixin = function() { function PaletteMixin() {} return PaletteMixin.prototype.getColorFromPalette = function(name, scope, requestNum) { return getFromPalette(this, innerColor, normalizeToArray(this.get('color', !0)), this.get('colorLayer', !0), name, scope, requestNum); }, PaletteMixin.prototype.clearColorPalette = function() { innerColor(this).paletteIdx = 0, innerColor(this).paletteNameMap = {}; }, PaletteMixin; }(); function getDecalFromPalette(ecModel, name, scope, requestNum) { var defaultDecals = normalizeToArray(ecModel.get([ 'aria', 'decal', 'decals' ])); return getFromPalette(ecModel, innerDecal, defaultDecals, null, name, scope, requestNum); } function getFromPalette(that, inner, defaultPalette, layeredPalette, name, scope, requestNum) { var scopeFields = inner(scope = scope || that), paletteIdx = scopeFields.paletteIdx || 0, paletteNameMap = scopeFields.paletteNameMap = scopeFields.paletteNameMap || {}; if (paletteNameMap.hasOwnProperty(name)) return paletteNameMap[name]; var palette = null != requestNum && layeredPalette ? function(palettes, requestColorNum) { for(var paletteNum = palettes.length, i = 0; i < paletteNum; i++)if (palettes[i].length > requestColorNum) return palettes[i]; return palettes[paletteNum - 1]; }(layeredPalette, requestNum) : defaultPalette; if ((palette = palette || defaultPalette) && palette.length) { var pickedPaletteItem = palette[paletteIdx]; return name && (paletteNameMap[name] = pickedPaletteItem), scopeFields.paletteIdx = (paletteIdx + 1) % palette.length, pickedPaletteItem; } } var OPTION_INNER_KEY = '\0_ec_inner', BUITIN_COMPONENTS_MAP = { grid: 'GridComponent', polar: 'PolarComponent', geo: 'GeoComponent', singleAxis: 'SingleAxisComponent', parallel: 'ParallelComponent', calendar: 'CalendarComponent', graphic: 'GraphicComponent', toolbox: 'ToolboxComponent', tooltip: 'TooltipComponent', axisPointer: 'AxisPointerComponent', brush: 'BrushComponent', title: 'TitleComponent', timeline: 'TimelineComponent', markPoint: 'MarkPointComponent', markLine: 'MarkLineComponent', markArea: 'MarkAreaComponent', legend: 'LegendComponent', dataZoom: 'DataZoomComponent', visualMap: 'VisualMapComponent', xAxis: 'GridComponent', yAxis: 'GridComponent', angleAxis: 'PolarComponent', radiusAxis: 'PolarComponent' }, BUILTIN_CHARTS_MAP = { line: 'LineChart', bar: 'BarChart', pie: 'PieChart', scatter: 'ScatterChart', radar: 'RadarChart', map: 'MapChart', tree: 'TreeChart', treemap: 'TreemapChart', graph: 'GraphChart', gauge: 'GaugeChart', funnel: 'FunnelChart', parallel: 'ParallelChart', sankey: 'SankeyChart', boxplot: 'BoxplotChart', candlestick: 'CandlestickChart', effectScatter: 'EffectScatterChart', lines: 'LinesChart', heatmap: 'HeatmapChart', pictorialBar: 'PictorialBarChart', themeRiver: 'ThemeRiverChart', sunburst: 'SunburstChart', custom: 'CustomChart' }, componetsMissingLogPrinted = {}, GlobalModel = function(_super) { function GlobalModel() { return null !== _super && _super.apply(this, arguments) || this; } return __extends(GlobalModel, _super), GlobalModel.prototype.init = function(option, parentModel, ecModel, theme, locale, optionManager) { theme = theme || {}, this.option = null, this._theme = new Model(theme), this._locale = new Model(locale), this._optionManager = optionManager; }, GlobalModel.prototype.setOption = function(option, opts, optionPreprocessorFuncs) { assert(null != option, 'option is null/undefined'), assert(1 !== option[OPTION_INNER_KEY], 'please use chart.getOption()'); var innerOpt = normalizeSetOptionInput(opts); this._optionManager.setOption(option, optionPreprocessorFuncs, innerOpt), this._resetOption(null, innerOpt); }, GlobalModel.prototype.resetOption = function(type, opt) { return this._resetOption(type, normalizeSetOptionInput(opt)); }, GlobalModel.prototype._resetOption = function(type, opt) { var optionChanged = !1, optionManager = this._optionManager; if (!type || 'recreate' === type) { var baseOption = optionManager.mountOption('recreate' === type); this.option && 'recreate' !== type ? (this.restoreData(), this._mergeOption(baseOption, opt)) : initBase(this, baseOption), optionChanged = !0; } if (('timeline' === type || 'media' === type) && this.restoreData(), !type || 'recreate' === type || 'timeline' === type) { var timelineOption = optionManager.getTimelineOption(this); timelineOption && (optionChanged = !0, this._mergeOption(timelineOption, opt)); } if (!type || 'recreate' === type || 'media' === type) { var mediaOptions = optionManager.getMediaOption(this); mediaOptions.length && each(mediaOptions, function(mediaOption) { optionChanged = !0, this._mergeOption(mediaOption, opt); }, this); } return optionChanged; }, GlobalModel.prototype.mergeOption = function(option) { this._mergeOption(option, null); }, GlobalModel.prototype._mergeOption = function(newOption, opt) { var option = this.option, componentsMap = this._componentsMap, componentsCount = this._componentsCount, newCmptTypes = [], newCmptTypeMap = createHashMap(), replaceMergeMainTypeMap = opt && opt.replaceMergeMainTypeMap; innerGlobalModel(this).datasetMap = createHashMap(), each(newOption, function(componentOption, mainType) { if (null != componentOption) { if (ComponentModel.hasClass(mainType)) mainType && (newCmptTypes.push(mainType), newCmptTypeMap.set(mainType, !0)); else { var componentImportName = BUITIN_COMPONENTS_MAP[mainType]; componentImportName && !componetsMissingLogPrinted[componentImportName] && (error("Component " + mainType + " is used but not imported.\nimport { " + componentImportName + " } from 'echarts/components';\necharts.use([" + componentImportName + "]);"), componetsMissingLogPrinted[componentImportName] = !0), option[mainType] = null == option[mainType] ? clone(componentOption) : merge(option[mainType], componentOption, !0); } } }), replaceMergeMainTypeMap && replaceMergeMainTypeMap.each(function(val, mainTypeInReplaceMerge) { ComponentModel.hasClass(mainTypeInReplaceMerge) && !newCmptTypeMap.get(mainTypeInReplaceMerge) && (newCmptTypes.push(mainTypeInReplaceMerge), newCmptTypeMap.set(mainTypeInReplaceMerge, !0)); }), ComponentModel.topologicalTravel(newCmptTypes, ComponentModel.getAllClassMainTypes(), function(mainType) { var newCmptOptionList = function(ecModel, mainType, newCmptOptionList) { var internalOptionCreator = internalOptionCreatorMap.get(mainType); if (!internalOptionCreator) return newCmptOptionList; var internalOptions = internalOptionCreator(ecModel); if (!internalOptions) return newCmptOptionList; for(var i = 0; i < internalOptions.length; i++)assert(isComponentIdInternal(internalOptions[i])); return newCmptOptionList.concat(internalOptions); }(this, mainType, normalizeToArray(newOption[mainType])), oldCmptList = componentsMap.get(mainType), mergeMode = oldCmptList ? replaceMergeMainTypeMap && replaceMergeMainTypeMap.get(mainType) ? 'replaceMerge' : 'normalMerge' : 'replaceAll', mappingResult = mappingToExists(oldCmptList, newCmptOptionList, mergeMode); each(mappingResult, function(item) { var existComponent, newOption = item.newOption; isObject(newOption) && (item.keyInfo.mainType = mainType, item.keyInfo.subType = (existComponent = item.existing, newOption.type ? newOption.type : existComponent ? existComponent.subType : ComponentModel.determineSubType(mainType, newOption))); }), option[mainType] = null, componentsMap.set(mainType, null), componentsCount.set(mainType, 0); var optionsByMainType = [], cmptsByMainType = [], cmptsCountByMainType = 0; each(mappingResult, function(resultItem, index) { var componentModel = resultItem.existing, newCmptOption = resultItem.newOption; if (newCmptOption) { var ComponentModelClass = ComponentModel.getClass(mainType, resultItem.keyInfo.subType, 'series' !== mainType); if (!ComponentModelClass) { var subType = resultItem.keyInfo.subType, seriesImportName = BUILTIN_CHARTS_MAP[subType]; componetsMissingLogPrinted[subType] || (componetsMissingLogPrinted[subType] = !0, seriesImportName ? error("Series " + subType + " is used but not imported.\nimport { " + seriesImportName + " } from 'echarts/charts';\necharts.use([" + seriesImportName + "]);") : error("Unkown series " + subType)); return; } if (componentModel && componentModel.constructor === ComponentModelClass) componentModel.name = resultItem.keyInfo.name, componentModel.mergeOption(newCmptOption, this), componentModel.optionUpdated(newCmptOption, !1); else { var extraOpt = extend({ componentIndex: index }, resultItem.keyInfo); extend(componentModel = new ComponentModelClass(newCmptOption, this, this, extraOpt), extraOpt), resultItem.brandNew && (componentModel.__requireNewView = !0), componentModel.init(newCmptOption, this, this), componentModel.optionUpdated(null, !0); } } else componentModel && (componentModel.mergeOption({}, this), componentModel.optionUpdated({}, !1)); componentModel ? (optionsByMainType.push(componentModel.option), cmptsByMainType.push(componentModel), cmptsCountByMainType++) : (optionsByMainType.push(void 0), cmptsByMainType.push(void 0)); }, this), option[mainType] = optionsByMainType, componentsMap.set(mainType, cmptsByMainType), componentsCount.set(mainType, cmptsCountByMainType), 'series' === mainType && reCreateSeriesIndices(this); }, this), this._seriesIndices || reCreateSeriesIndices(this); }, GlobalModel.prototype.getOption = function() { var option = clone(this.option); return each(option, function(optInMainType, mainType) { if (ComponentModel.hasClass(mainType)) { for(var opts = normalizeToArray(optInMainType), realLen = opts.length, metNonInner = !1, i = realLen - 1; i >= 0; i--)opts[i] && !isComponentIdInternal(opts[i]) ? metNonInner = !0 : (opts[i] = null, !metNonInner && realLen--); opts.length = realLen, option[mainType] = opts; } }), delete option[OPTION_INNER_KEY], option; }, GlobalModel.prototype.getTheme = function() { return this._theme; }, GlobalModel.prototype.getLocaleModel = function() { return this._locale; }, GlobalModel.prototype.getLocale = function(localePosition) { return this.getLocaleModel().get(localePosition); }, GlobalModel.prototype.setUpdatePayload = function(payload) { this._payload = payload; }, GlobalModel.prototype.getUpdatePayload = function() { return this._payload; }, GlobalModel.prototype.getComponent = function(mainType, idx) { var list = this._componentsMap.get(mainType); if (list) { var cmpt = list[idx || 0]; if (cmpt) return cmpt; if (null == idx) { for(var i = 0; i < list.length; i++)if (list[i]) return list[i]; } } }, GlobalModel.prototype.queryComponents = function(condition) { var result, mainType = condition.mainType; if (!mainType) return []; var index = condition.index, id = condition.id, name = condition.name, cmpts = this._componentsMap.get(mainType); return cmpts && cmpts.length ? (null != index ? (result = [], each(normalizeToArray(index), function(idx) { cmpts[idx] && result.push(cmpts[idx]); })) : result = null != id ? queryByIdOrName('id', id, cmpts) : null != name ? queryByIdOrName('name', name, cmpts) : filter(cmpts, function(cmpt) { return !!cmpt; }), filterBySubType(result, condition)) : []; }, GlobalModel.prototype.findComponents = function(condition) { var indexAttr, idAttr, nameAttr, res, query = condition.query, mainType = condition.mainType, queryCond = (indexAttr = mainType + 'Index', idAttr = mainType + 'Id', nameAttr = mainType + 'Name', query && (null != query[indexAttr] || null != query[idAttr] || null != query[nameAttr]) ? { mainType: mainType, index: query[indexAttr], id: query[idAttr], name: query[nameAttr] } : null); return res = filterBySubType(queryCond ? this.queryComponents(queryCond) : filter(this._componentsMap.get(mainType), function(cmpt) { return !!cmpt; }), condition), condition.filter ? filter(res, condition.filter) : res; }, GlobalModel.prototype.eachComponent = function(mainType, cb, context) { var componentsMap = this._componentsMap; if (isFunction(mainType)) componentsMap.each(function(cmpts, componentType) { for(var i = 0; cmpts && i < cmpts.length; i++){ var cmpt = cmpts[i]; cmpt && mainType.call(cb, componentType, cmpt, cmpt.componentIndex); } }); else for(var cmpts = isString(mainType) ? componentsMap.get(mainType) : isObject(mainType) ? this.findComponents(mainType) : null, i = 0; cmpts && i < cmpts.length; i++){ var cmpt = cmpts[i]; cmpt && cb.call(context, cmpt, cmpt.componentIndex); } }, GlobalModel.prototype.getSeriesByName = function(name) { var nameStr = convertOptionIdName(name, null); return filter(this._componentsMap.get('series'), function(oneSeries) { return !!oneSeries && null != nameStr && oneSeries.name === nameStr; }); }, GlobalModel.prototype.getSeriesByIndex = function(seriesIndex) { return this._componentsMap.get('series')[seriesIndex]; }, GlobalModel.prototype.getSeriesByType = function(subType) { return filter(this._componentsMap.get('series'), function(oneSeries) { return !!oneSeries && oneSeries.subType === subType; }); }, GlobalModel.prototype.getSeries = function() { return filter(this._componentsMap.get('series').slice(), function(oneSeries) { return !!oneSeries; }); }, GlobalModel.prototype.getSeriesCount = function() { return this._componentsCount.get('series'); }, GlobalModel.prototype.eachSeries = function(cb, context) { assertSeriesInitialized(this), each(this._seriesIndices, function(rawSeriesIndex) { var series = this._componentsMap.get('series')[rawSeriesIndex]; cb.call(context, series, rawSeriesIndex); }, this); }, GlobalModel.prototype.eachRawSeries = function(cb, context) { each(this._componentsMap.get('series'), function(series) { series && cb.call(context, series, series.componentIndex); }); }, GlobalModel.prototype.eachSeriesByType = function(subType, cb, context) { assertSeriesInitialized(this), each(this._seriesIndices, function(rawSeriesIndex) { var series = this._componentsMap.get('series')[rawSeriesIndex]; series.subType === subType && cb.call(context, series, rawSeriesIndex); }, this); }, GlobalModel.prototype.eachRawSeriesByType = function(subType, cb, context) { return each(this.getSeriesByType(subType), cb, context); }, GlobalModel.prototype.isSeriesFiltered = function(seriesModel) { return assertSeriesInitialized(this), null == this._seriesIndicesMap.get(seriesModel.componentIndex); }, GlobalModel.prototype.getCurrentSeriesIndices = function() { return (this._seriesIndices || []).slice(); }, GlobalModel.prototype.filterSeries = function(cb, context) { assertSeriesInitialized(this); var newSeriesIndices = []; each(this._seriesIndices, function(seriesRawIdx) { var series = this._componentsMap.get('series')[seriesRawIdx]; cb.call(context, series, seriesRawIdx) && newSeriesIndices.push(seriesRawIdx); }, this), this._seriesIndices = newSeriesIndices, this._seriesIndicesMap = createHashMap(newSeriesIndices); }, GlobalModel.prototype.restoreData = function(payload) { reCreateSeriesIndices(this); var componentsMap = this._componentsMap, componentTypes = []; componentsMap.each(function(components, componentType) { ComponentModel.hasClass(componentType) && componentTypes.push(componentType); }), ComponentModel.topologicalTravel(componentTypes, ComponentModel.getAllClassMainTypes(), function(componentType) { each(componentsMap.get(componentType), function(component) { component && ('series' !== componentType || !function(seriesModel, payload) { if (payload) { var index = payload.seriesIndex, id = payload.seriesId, name_1 = payload.seriesName; return null != index && seriesModel.componentIndex !== index || null != id && seriesModel.id !== id || null != name_1 && seriesModel.name !== name_1; } }(component, payload)) && component.restoreData(); }); }); }, GlobalModel.internalField = void (reCreateSeriesIndices = function(ecModel) { var seriesIndices = ecModel._seriesIndices = []; each(ecModel._componentsMap.get('series'), function(series) { series && seriesIndices.push(series.componentIndex); }), ecModel._seriesIndicesMap = createHashMap(seriesIndices); }, assertSeriesInitialized = function(ecModel) { if (!ecModel._seriesIndices) throw Error('Option should contains series.'); }, initBase = function(ecModel, baseOption) { ecModel.option = {}, ecModel.option[OPTION_INNER_KEY] = 1, ecModel._componentsMap = createHashMap({ series: [] }), ecModel._componentsCount = createHashMap(); var option, theme, notMergeColorLayer, airaOption = baseOption.aria; isObject(airaOption) && null == airaOption.enabled && (airaOption.enabled = !0), option = baseOption, theme = ecModel._theme.option, notMergeColorLayer = option.color && !option.colorLayer, each(theme, function(themeItem, name) { ('colorLayer' !== name || !notMergeColorLayer) && (ComponentModel.hasClass(name) || ('object' == typeof themeItem ? option[name] = option[name] ? merge(option[name], themeItem, !1) : clone(themeItem) : null != option[name] || (option[name] = themeItem))); }), merge(baseOption, globalDefault, !1), ecModel._mergeOption(baseOption, null); }), GlobalModel; }(Model); function queryByIdOrName(attr, idOrName, cmpts) { if (isArray(idOrName)) { var keyMap_1 = createHashMap(); return each(idOrName, function(idOrNameItem) { null != idOrNameItem && null != convertOptionIdName(idOrNameItem, null) && keyMap_1.set(idOrNameItem, !0); }), filter(cmpts, function(cmpt) { return cmpt && keyMap_1.get(cmpt[attr]); }); } var idName_1 = convertOptionIdName(idOrName, null); return filter(cmpts, function(cmpt) { return cmpt && null != idName_1 && cmpt[attr] === idName_1; }); } function filterBySubType(components, condition) { return condition.hasOwnProperty('subType') ? filter(components, function(cmpt) { return cmpt && cmpt.subType === condition.subType; }) : components; } function normalizeSetOptionInput(opts) { var replaceMergeMainTypeMap = createHashMap(); return opts && each(normalizeToArray(opts.replaceMerge), function(mainType) { assert(ComponentModel.hasClass(mainType), '"' + mainType + '" is not valid component main type in "replaceMerge"'), replaceMergeMainTypeMap.set(mainType, !0); }), { replaceMergeMainTypeMap: replaceMergeMainTypeMap }; } mixin(GlobalModel, PaletteMixin); var availableMethods = [ 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed', 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getOption', 'getId', 'updateLabelLayout' ], ExtensionAPI = function(ecInstance) { each(availableMethods, function(methodName) { this[methodName] = bind(ecInstance[methodName], ecInstance); }, this); }, coordinateSystemCreators = {}, CoordinateSystemManager = function() { function CoordinateSystemManager() { this._coordinateSystems = []; } return CoordinateSystemManager.prototype.create = function(ecModel, api) { var coordinateSystems = []; each(coordinateSystemCreators, function(creater, type) { var list = creater.create(ecModel, api); coordinateSystems = coordinateSystems.concat(list || []); }), this._coordinateSystems = coordinateSystems; }, CoordinateSystemManager.prototype.update = function(ecModel, api) { each(this._coordinateSystems, function(coordSys) { coordSys.update && coordSys.update(ecModel, api); }); }, CoordinateSystemManager.prototype.getCoordinateSystems = function() { return this._coordinateSystems.slice(); }, CoordinateSystemManager.register = function(type, creator) { coordinateSystemCreators[type] = creator; }, CoordinateSystemManager.get = function(type) { return coordinateSystemCreators[type]; }, CoordinateSystemManager; }(), QUERY_REG = /^(min|max)?(.+)$/, OptionManager = function() { function OptionManager(api) { this._timelineOptions = [], this._mediaList = [], this._currentMediaIndices = [], this._api = api; } return OptionManager.prototype.setOption = function(rawOption, optionPreprocessorFuncs, opt) { rawOption && (each(normalizeToArray(rawOption.series), function(series) { series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data); }), each(normalizeToArray(rawOption.dataset), function(dataset) { dataset && dataset.source && isTypedArray(dataset.source) && setAsPrimitive(dataset.source); })), rawOption = clone(rawOption); var optionBackup = this._optionBackup, newParsedOption = function(rawOption, optionPreprocessorFuncs, isNew) { var mediaDefault, baseOption, mediaList = [], declaredBaseOption = rawOption.baseOption, timelineOnRoot = rawOption.timeline, timelineOptionsOnRoot = rawOption.options, mediaOnRoot = rawOption.media, hasMedia = !!rawOption.media, hasTimeline = !!(timelineOptionsOnRoot || timelineOnRoot || declaredBaseOption && declaredBaseOption.timeline); function doPreprocess(option) { each(optionPreprocessorFuncs, function(preProcess) { preProcess(option, isNew); }); } return declaredBaseOption ? (baseOption = declaredBaseOption).timeline || (baseOption.timeline = timelineOnRoot) : ((hasTimeline || hasMedia) && (rawOption.options = rawOption.media = null), baseOption = rawOption), hasMedia && (isArray(mediaOnRoot) ? each(mediaOnRoot, function(singleMedia) { singleMedia && !singleMedia.option && isObject(singleMedia.query) && isObject(singleMedia.query.option) && error('Illegal media option. Must be like { media: [ { query: {}, option: {} } ] }'), singleMedia && singleMedia.option && (singleMedia.query ? mediaList.push(singleMedia) : mediaDefault || (mediaDefault = singleMedia)); }) : error('Illegal media option. Must be an array. Like { media: [ {...}, {...} ] }')), doPreprocess(baseOption), each(timelineOptionsOnRoot, function(option) { return doPreprocess(option); }), each(mediaList, function(media) { return doPreprocess(media.option); }), { baseOption: baseOption, timelineOptions: timelineOptionsOnRoot || [], mediaDefault: mediaDefault, mediaList: mediaList }; }(rawOption, optionPreprocessorFuncs, !optionBackup); this._newBaseOption = newParsedOption.baseOption, optionBackup ? (newParsedOption.timelineOptions.length && (optionBackup.timelineOptions = newParsedOption.timelineOptions), newParsedOption.mediaList.length && (optionBackup.mediaList = newParsedOption.mediaList), newParsedOption.mediaDefault && (optionBackup.mediaDefault = newParsedOption.mediaDefault)) : this._optionBackup = newParsedOption; }, OptionManager.prototype.mountOption = function(isRecreate) { var optionBackup = this._optionBackup; return this._timelineOptions = optionBackup.timelineOptions, this._mediaList = optionBackup.mediaList, this._mediaDefault = optionBackup.mediaDefault, this._currentMediaIndices = [], clone(isRecreate ? optionBackup.baseOption : this._newBaseOption); }, OptionManager.prototype.getTimelineOption = function(ecModel) { var option, timelineOptions = this._timelineOptions; if (timelineOptions.length) { var timelineModel = ecModel.getComponent('timeline'); timelineModel && (option = clone(timelineOptions[timelineModel.getCurrentIndex()])); } return option; }, OptionManager.prototype.getMediaOption = function(ecModel) { var indices1, indices2, ecWidth = this._api.getWidth(), ecHeight = this._api.getHeight(), mediaList = this._mediaList, mediaDefault = this._mediaDefault, indices = [], result = []; if (!mediaList.length && !mediaDefault) return result; for(var i = 0, len = mediaList.length; i < len; i++)(function(query, ecWidth, ecHeight) { var realMap = { width: ecWidth, height: ecHeight, aspectratio: ecWidth / ecHeight }, applicatable = !0; return each(query, function(value, attr) { var matched = attr.match(QUERY_REG); if (matched && matched[1] && matched[2]) { var real, operator = matched[1]; real = realMap[matched[2].toLowerCase()], ('min' === operator ? real >= value : 'max' === operator ? real <= value : real === value) || (applicatable = !1); } }), applicatable; })(mediaList[i].query, ecWidth, ecHeight) && indices.push(i); return !indices.length && mediaDefault && (indices = [ -1 ]), indices.length && (indices1 = indices, indices2 = this._currentMediaIndices, indices1.join(',') !== indices2.join(',')) && (result = map(indices, function(index) { return clone(-1 === index ? mediaDefault.option : mediaList[index].option); })), this._currentMediaIndices = indices, result; }, OptionManager; }(), POSSIBLE_STYLES = [ 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle', 'chordStyle', 'label', 'labelLine' ]; function compatEC2ItemStyle(opt) { var itemStyleOpt = opt && opt.itemStyle; if (itemStyleOpt) for(var i = 0, len = POSSIBLE_STYLES.length; i < len; i++){ var styleName = POSSIBLE_STYLES[i], normalItemStyleOpt = itemStyleOpt.normal, emphasisItemStyleOpt = itemStyleOpt.emphasis; normalItemStyleOpt && normalItemStyleOpt[styleName] && (deprecateReplaceLog("itemStyle.normal." + styleName, styleName), opt[styleName] = opt[styleName] || {}, opt[styleName].normal ? merge(opt[styleName].normal, normalItemStyleOpt[styleName]) : opt[styleName].normal = normalItemStyleOpt[styleName], normalItemStyleOpt[styleName] = null), emphasisItemStyleOpt && emphasisItemStyleOpt[styleName] && (deprecateReplaceLog("itemStyle.emphasis." + styleName, "emphasis." + styleName), opt[styleName] = opt[styleName] || {}, opt[styleName].emphasis ? merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]) : opt[styleName].emphasis = emphasisItemStyleOpt[styleName], emphasisItemStyleOpt[styleName] = null); } } function convertNormalEmphasis(opt, optType, useExtend) { if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) { var normalOpt = opt[optType].normal, emphasisOpt = opt[optType].emphasis; normalOpt && (deprecateLog("'normal' hierarchy in " + optType + " has been removed since 4.0. All style properties are configured in " + optType + " directly now."), useExtend ? (opt[optType].normal = opt[optType].emphasis = null, defaults(opt[optType], normalOpt)) : opt[optType] = normalOpt), emphasisOpt && (deprecateLog(optType + ".emphasis has been changed to emphasis." + optType + " since 4.0"), opt.emphasis = opt.emphasis || {}, opt.emphasis[optType] = emphasisOpt, emphasisOpt.focus && (opt.emphasis.focus = emphasisOpt.focus), emphasisOpt.blurScope && (opt.emphasis.blurScope = emphasisOpt.blurScope)); } } function removeEC3NormalStatus(opt) { convertNormalEmphasis(opt, 'itemStyle'), convertNormalEmphasis(opt, 'lineStyle'), convertNormalEmphasis(opt, 'areaStyle'), convertNormalEmphasis(opt, 'label'), convertNormalEmphasis(opt, 'labelLine'), convertNormalEmphasis(opt, 'upperLabel'), convertNormalEmphasis(opt, 'edgeLabel'); } function compatTextStyle(opt, propName) { var labelOptSingle = isObject(opt) && opt[propName], textStyle = isObject(labelOptSingle) && labelOptSingle.textStyle; if (textStyle) { deprecateLog("textStyle hierarchy in " + propName + " has been removed since 4.0. All textStyle properties are configured in " + propName + " directly now."); for(var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++){ var textPropName = TEXT_STYLE_OPTIONS[i]; textStyle.hasOwnProperty(textPropName) && (labelOptSingle[textPropName] = textStyle[textPropName]); } } } function compatEC3CommonStyles(opt) { opt && (removeEC3NormalStatus(opt), compatTextStyle(opt, 'label'), opt.emphasis && compatTextStyle(opt.emphasis, 'label')); } function toArr(o) { return isArray(o) ? o : o ? [ o ] : []; } function toObj(o) { return (isArray(o) ? o[0] : o) || {}; } function compatLayoutProperties(option) { option && each(LAYOUT_PROPERTIES, function(prop) { prop[0] in option && !(prop[1] in option) && (option[prop[1]] = option[prop[0]]); }); } var LAYOUT_PROPERTIES = [ [ 'x', 'left' ], [ 'y', 'top' ], [ 'x2', 'right' ], [ 'y2', 'bottom' ] ], COMPATITABLE_COMPONENTS = [ 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline' ], BAR_ITEM_STYLE_MAP = [ [ 'borderRadius', 'barBorderRadius' ], [ 'borderColor', 'barBorderColor' ], [ 'borderWidth', 'barBorderWidth' ] ]; function compatBarItemStyle(option) { var itemStyle = option && option.itemStyle; if (itemStyle) for(var i = 0; i < BAR_ITEM_STYLE_MAP.length; i++){ var oldName = BAR_ITEM_STYLE_MAP[i][1], newName = BAR_ITEM_STYLE_MAP[i][0]; null != itemStyle[oldName] && (itemStyle[newName] = itemStyle[oldName], deprecateReplaceLog(oldName, newName)); } } function compatPieLabel(option) { option && 'edge' === option.alignTo && null != option.margin && null == option.edgeDistance && (deprecateReplaceLog('label.margin', 'label.edgeDistance', 'pie'), option.edgeDistance = option.margin); } function compatSunburstState(option) { option && option.downplay && !option.blur && (option.blur = option.downplay, deprecateReplaceLog('downplay', 'blur', 'sunburst')); } function globalBackwardCompat(option, isTheme) { var axes; each(toArr(option.series), function(seriesOpt) { isObject(seriesOpt) && function(seriesOpt) { if (isObject(seriesOpt)) { compatEC2ItemStyle(seriesOpt), removeEC3NormalStatus(seriesOpt), compatTextStyle(seriesOpt, 'label'), compatTextStyle(seriesOpt, 'upperLabel'), compatTextStyle(seriesOpt, 'edgeLabel'), seriesOpt.emphasis && (compatTextStyle(seriesOpt.emphasis, 'label'), compatTextStyle(seriesOpt.emphasis, 'upperLabel'), compatTextStyle(seriesOpt.emphasis, 'edgeLabel')); var markPoint = seriesOpt.markPoint; markPoint && (compatEC2ItemStyle(markPoint), compatEC3CommonStyles(markPoint)); var markLine = seriesOpt.markLine; markLine && (compatEC2ItemStyle(markLine), compatEC3CommonStyles(markLine)); var markArea = seriesOpt.markArea; markArea && compatEC3CommonStyles(markArea); var data = seriesOpt.data; if ('graph' === seriesOpt.type) { data = data || seriesOpt.nodes; var edgeData = seriesOpt.links || seriesOpt.edges; if (edgeData && !isTypedArray(edgeData)) for(var i = 0; i < edgeData.length; i++)compatEC3CommonStyles(edgeData[i]); each(seriesOpt.categories, function(opt) { removeEC3NormalStatus(opt); }); } if (data && !isTypedArray(data)) for(var i = 0; i < data.length; i++)compatEC3CommonStyles(data[i]); if ((markPoint = seriesOpt.markPoint) && markPoint.data) for(var mpData = markPoint.data, i = 0; i < mpData.length; i++)compatEC3CommonStyles(mpData[i]); if ((markLine = seriesOpt.markLine) && markLine.data) for(var mlData = markLine.data, i = 0; i < mlData.length; i++)isArray(mlData[i]) ? (compatEC3CommonStyles(mlData[i][0]), compatEC3CommonStyles(mlData[i][1])) : compatEC3CommonStyles(mlData[i]); 'gauge' === seriesOpt.type ? (compatTextStyle(seriesOpt, 'axisLabel'), compatTextStyle(seriesOpt, 'title'), compatTextStyle(seriesOpt, 'detail')) : 'treemap' === seriesOpt.type ? (convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle'), each(seriesOpt.levels, function(opt) { removeEC3NormalStatus(opt); })) : 'tree' === seriesOpt.type && removeEC3NormalStatus(seriesOpt.leaves); } }(seriesOpt); }), axes = [ 'xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar' ], isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis'), each(axes, function(axisName) { each(toArr(option[axisName]), function(axisOpt) { axisOpt && (compatTextStyle(axisOpt, 'axisLabel'), compatTextStyle(axisOpt.axisPointer, 'label')); }); }), each(toArr(option.parallel), function(parallelOpt) { var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault; compatTextStyle(parallelAxisDefault, 'axisLabel'), compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label'); }), each(toArr(option.calendar), function(calendarOpt) { convertNormalEmphasis(calendarOpt, 'itemStyle'), compatTextStyle(calendarOpt, 'dayLabel'), compatTextStyle(calendarOpt, 'monthLabel'), compatTextStyle(calendarOpt, 'yearLabel'); }), each(toArr(option.radar), function(radarOpt) { compatTextStyle(radarOpt, 'name'), radarOpt.name && null == radarOpt.axisName && (radarOpt.axisName = radarOpt.name, delete radarOpt.name, deprecateLog('name property in radar component has been changed to axisName')), null != radarOpt.nameGap && null == radarOpt.axisNameGap && (radarOpt.axisNameGap = radarOpt.nameGap, delete radarOpt.nameGap, deprecateLog('nameGap property in radar component has been changed to axisNameGap')); }), each(toArr(option.geo), function(geoOpt) { isObject(geoOpt) && (compatEC3CommonStyles(geoOpt), each(toArr(geoOpt.regions), function(regionObj) { compatEC3CommonStyles(regionObj); })); }), each(toArr(option.timeline), function(timelineOpt) { compatEC3CommonStyles(timelineOpt), convertNormalEmphasis(timelineOpt, 'label'), convertNormalEmphasis(timelineOpt, 'itemStyle'), convertNormalEmphasis(timelineOpt, 'controlStyle', !0); var data = timelineOpt.data; isArray(data) && each(data, function(item) { isObject(item) && (convertNormalEmphasis(item, 'label'), convertNormalEmphasis(item, 'itemStyle')); }); }), each(toArr(option.toolbox), function(toolboxOpt) { convertNormalEmphasis(toolboxOpt, 'iconStyle'), each(toolboxOpt.feature, function(featureOpt) { convertNormalEmphasis(featureOpt, 'iconStyle'); }); }), compatTextStyle(toObj(option.axisPointer), 'label'), compatTextStyle(toObj(option.tooltip).axisPointer, 'label'), option.series = normalizeToArray(option.series), each(option.series, function(seriesOpt) { if (isObject(seriesOpt)) { var option, seriesType = seriesOpt.type; if ('line' === seriesType) null != seriesOpt.clipOverflow && (seriesOpt.clip = seriesOpt.clipOverflow, deprecateReplaceLog('clipOverflow', 'clip', 'line')); else if ('pie' === seriesType || 'gauge' === seriesType) { null != seriesOpt.clockWise && (seriesOpt.clockwise = seriesOpt.clockWise, deprecateReplaceLog('clockWise', 'clockwise')), compatPieLabel(seriesOpt.label); var data = seriesOpt.data; if (data && !isTypedArray(data)) for(var i = 0; i < data.length; i++)compatPieLabel(data[i]); null != seriesOpt.hoverOffset && (seriesOpt.emphasis = seriesOpt.emphasis || {}, seriesOpt.emphasis.scaleSize = null); } else if ('gauge' === seriesType) { var pointerColor = function(opt, path) { for(var pathArr = path.split(','), obj = opt, i = 0; i < pathArr.length && null != (obj = obj && obj[pathArr[i]]); i++); return obj; }(seriesOpt, 'pointer.color'); null != pointerColor && function(opt, path, val, overwrite) { for(var key, pathArr = path.split(','), obj = opt, i = 0; i < pathArr.length - 1; i++)null == obj[key = pathArr[i]] && (obj[key] = {}), obj = obj[key]; null == obj[pathArr[i]] && (obj[pathArr[i]] = val); }(seriesOpt, 'itemStyle.color', pointerColor); } else if ('bar' === seriesType) { compatBarItemStyle(seriesOpt), compatBarItemStyle(seriesOpt.backgroundStyle), compatBarItemStyle(seriesOpt.emphasis); var data = seriesOpt.data; if (data && !isTypedArray(data)) for(var i = 0; i < data.length; i++)'object' == typeof data[i] && (compatBarItemStyle(data[i]), compatBarItemStyle(data[i] && data[i].emphasis)); } else if ('sunburst' === seriesType) { var highlightPolicy = seriesOpt.highlightPolicy; highlightPolicy && (seriesOpt.emphasis = seriesOpt.emphasis || {}, !seriesOpt.emphasis.focus) && (seriesOpt.emphasis.focus = highlightPolicy, deprecateReplaceLog('highlightPolicy', 'emphasis.focus', 'sunburst')), compatSunburstState(seriesOpt), function traverseTree(data, cb) { if (data) for(var i = 0; i < data.length; i++)cb(data[i]), data[i] && traverseTree(data[i].children, cb); }(seriesOpt.data, compatSunburstState); } else 'graph' === seriesType || 'sankey' === seriesType ? (option = seriesOpt) && null != option.focusNodeAdjacency && (option.emphasis = option.emphasis || {}, null == option.emphasis.focus && (deprecateReplaceLog('focusNodeAdjacency', 'emphasis: { focus: \'adjacency\'}', 'graph/sankey'), option.emphasis.focus = 'adjacency')) : 'map' === seriesType && (seriesOpt.mapType && !seriesOpt.map && (deprecateReplaceLog('mapType', 'map', 'map'), seriesOpt.map = seriesOpt.mapType), seriesOpt.mapLocation && (deprecateLog('`mapLocation` is not used anymore.'), defaults(seriesOpt, seriesOpt.mapLocation))); null != seriesOpt.hoverAnimation && (seriesOpt.emphasis = seriesOpt.emphasis || {}, seriesOpt.emphasis && null == seriesOpt.emphasis.scale && (deprecateReplaceLog('hoverAnimation', 'emphasis.scale'), seriesOpt.emphasis.scale = seriesOpt.hoverAnimation)), compatLayoutProperties(seriesOpt); } }), option.dataRange && (option.visualMap = option.dataRange), each(COMPATITABLE_COMPONENTS, function(componentName) { var options = option[componentName]; options && (isArray(options) || (options = [ options ]), each(options, function(option) { compatLayoutProperties(option); })); }); } function calculateStack(stackInfoList) { each(stackInfoList, function(targetStackInfo, idxInStack) { var resultVal = [], resultNaN = [ NaN, NaN ], dims = [ targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension ], targetData = targetStackInfo.data, isStackedByIndex = targetStackInfo.isStackedByIndex, newData = targetData.map(dims, function(v0, v1, dataIndex) { var byValue, stackedDataRawIndex, sum = targetData.get(targetStackInfo.stackedDimension, dataIndex); if (isNaN(sum)) return resultNaN; isStackedByIndex ? stackedDataRawIndex = targetData.getRawIndex(dataIndex) : byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex); for(var stackedOver = NaN, j = idxInStack - 1; j >= 0; j--){ var stackInfo = stackInfoList[j]; if (isStackedByIndex || (stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue)), stackedDataRawIndex >= 0) { var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex); if (sum >= 0 && val > 0 || sum <= 0 && val < 0) { sum += val, stackedOver = val; break; } } } return resultVal[0] = sum, resultVal[1] = stackedOver, resultVal; }); targetData.hostModel.setData(newData), targetStackInfo.data = newData; }); } var SourceImpl = function(fields) { this.data = fields.data || (fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []), this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN, this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN, this.startIndex = fields.startIndex || 0, this.dimensionsDefine = fields.dimensionsDefine, this.dimensionsDetectedCount = fields.dimensionsDetectedCount, this.encodeDefine = fields.encodeDefine, this.metaRawOption = fields.metaRawOption; }; function isSourceInstance(val) { return val instanceof SourceImpl; } function createSource(sourceData, thisMetaRawOption, sourceFormat, encodeDefine) { sourceFormat = sourceFormat || detectSourceFormat(sourceData); var seriesLayoutBy = thisMetaRawOption.seriesLayoutBy, determined = function(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine) { if (!data) return { dimensionsDefine: normalizeDimensionsOption(dimensionsDefine), startIndex: startIndex, dimensionsDetectedCount: dimensionsDetectedCount }; if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) { var dimensionsDetectedCount, startIndex; 'auto' === sourceHeader || null == sourceHeader ? arrayRowsTravelFirst(function(val) { null != val && '-' !== val && (isString(val) ? null == startIndex && (startIndex = 1) : startIndex = 0); }, seriesLayoutBy, data, 10) : startIndex = isNumber(sourceHeader) ? sourceHeader : sourceHeader ? 1 : 0, dimensionsDefine || 1 !== startIndex || (dimensionsDefine = [], arrayRowsTravelFirst(function(val, index) { dimensionsDefine[index] = null != val ? val + '' : ''; }, seriesLayoutBy, data, 1 / 0)), dimensionsDetectedCount = dimensionsDefine ? dimensionsDefine.length : 'row' === seriesLayoutBy ? data.length : data[0] ? data[0].length : null; } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) dimensionsDefine || (dimensionsDefine = function(data) { for(var obj, firstIndex = 0; firstIndex < data.length && !(obj = data[firstIndex++]);); if (obj) { var dimensions_1 = []; return each(obj, function(value, key) { dimensions_1.push(key); }), dimensions_1; } }(data)); else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) dimensionsDefine || (dimensionsDefine = [], each(data, function(colArr, key) { dimensionsDefine.push(key); })); else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) { var value0 = getDataItemValue(data[0]); dimensionsDetectedCount = isArray(value0) && value0.length || 1; } else sourceFormat === SOURCE_FORMAT_TYPED_ARRAY && assert(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.'); return { startIndex: startIndex, dimensionsDefine: normalizeDimensionsOption(dimensionsDefine), dimensionsDetectedCount: dimensionsDetectedCount }; }(sourceData, sourceFormat, seriesLayoutBy, thisMetaRawOption.sourceHeader, thisMetaRawOption.dimensions); return new SourceImpl({ data: sourceData, sourceFormat: sourceFormat, seriesLayoutBy: seriesLayoutBy, dimensionsDefine: determined.dimensionsDefine, startIndex: determined.startIndex, dimensionsDetectedCount: determined.dimensionsDetectedCount, encodeDefine: encodeDefine ? createHashMap(encodeDefine) : null, metaRawOption: clone(thisMetaRawOption) }); } function createSourceFromSeriesDataOption(data) { return new SourceImpl({ data: data, sourceFormat: isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL }); } function detectSourceFormat(data) { var sourceFormat = SOURCE_FORMAT_UNKNOWN; if (isTypedArray(data)) sourceFormat = SOURCE_FORMAT_TYPED_ARRAY; else if (isArray(data)) { 0 === data.length && (sourceFormat = SOURCE_FORMAT_ARRAY_ROWS); for(var i = 0, len = data.length; i < len; i++){ var item = data[i]; if (null != item) { if (isArray(item)) { sourceFormat = SOURCE_FORMAT_ARRAY_ROWS; break; } if (isObject(item)) { sourceFormat = SOURCE_FORMAT_OBJECT_ROWS; break; } } } } else if (isObject(data)) { for(var key in data)if (hasOwn(data, key) && isArrayLike(data[key])) { sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS; break; } } return sourceFormat; } function normalizeDimensionsOption(dimensionsDefine) { if (dimensionsDefine) { var nameMap = createHashMap(); return map(dimensionsDefine, function(rawItem, index) { var item = { name: (rawItem = isObject(rawItem) ? rawItem : { name: rawItem }).name, displayName: rawItem.displayName, type: rawItem.type }; if (null == item.name) return item; item.name += '', null == item.displayName && (item.displayName = item.name); var exist = nameMap.get(item.name); return exist ? item.name += '-' + exist.count++ : nameMap.set(item.name, { count: 1 }), item; }); } } function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) { if ('row' === seriesLayoutBy) for(var i = 0; i < data.length && i < maxLoop; i++)cb(data[i] ? data[i][0] : null, i); else for(var value0 = data[0] || [], i = 0; i < value0.length && i < maxLoop; i++)cb(value0[i], i); } var DefaultDataProvider = function() { var proto; function DefaultDataProvider(sourceParam, dimSize) { var source = isSourceInstance(sourceParam) ? sourceParam : createSourceFromSeriesDataOption(sourceParam); this._source = source; var data = this._data = source.data; if (source.sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) { if (null == dimSize) throw Error('Typed array data must specify dimension size'); this._offset = 0, this._dimSize = dimSize, this._data = data; } mountMethods(this, data, source); } return DefaultDataProvider.prototype.getSource = function() { return this._source; }, DefaultDataProvider.prototype.count = function() { return 0; }, DefaultDataProvider.prototype.getItem = function(idx, out) {}, DefaultDataProvider.prototype.appendData = function(newData) {}, DefaultDataProvider.prototype.clean = function() {}, DefaultDataProvider.protoInitialize = void ((proto = DefaultDataProvider.prototype).pure = !1, proto.persistent = !0), DefaultDataProvider.internalField = function() { mountMethods = function(provider, data, source) { var sourceFormat = source.sourceFormat, seriesLayoutBy = source.seriesLayoutBy, startIndex = source.startIndex, dimsDef = source.dimensionsDefine, methods = providerMethods[getMethodMapKey(sourceFormat, seriesLayoutBy)]; if (assert(methods, 'Invalide sourceFormat: ' + sourceFormat), extend(provider, methods), sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) provider.getItem = getItemForTypedArray, provider.count = countForTypedArray, provider.fillStorage = fillStorageForTypedArray; else { var rawItemGetter = getRawSourceItemGetter(sourceFormat, seriesLayoutBy); provider.getItem = bind(rawItemGetter, null, data, startIndex, dimsDef); var rawCounter = getRawSourceDataCounter(sourceFormat, seriesLayoutBy); provider.count = bind(rawCounter, null, data, startIndex, dimsDef); } }; var _a, getItemForTypedArray = function(idx, out) { idx -= this._offset, out = out || []; for(var data = this._data, dimSize = this._dimSize, offset = dimSize * idx, i = 0; i < dimSize; i++)out[i] = data[offset + i]; return out; }, fillStorageForTypedArray = function(start, end, storage, extent) { for(var data = this._data, dimSize = this._dimSize, dim = 0; dim < dimSize; dim++){ for(var dimExtent = extent[dim], min = null == dimExtent[0] ? 1 / 0 : dimExtent[0], max = null == dimExtent[1] ? -1 / 0 : dimExtent[1], count = end - start, arr = storage[dim], i = 0; i < count; i++){ var val = data[i * dimSize + dim]; arr[start + i] = val, val < min && (min = val), val > max && (max = val); } dimExtent[0] = min, dimExtent[1] = max; } }, countForTypedArray = function() { return this._data ? this._data.length / this._dimSize : 0; }; function appendDataSimply(newData) { for(var i = 0; i < newData.length; i++)this._data.push(newData[i]); } (_a = {})[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = { pure: !0, appendData: appendDataSimply }, _a[SOURCE_FORMAT_ARRAY_ROWS + "_row"] = { pure: !0, appendData: function() { throw Error('Do not support appendData when set seriesLayoutBy: "row".'); } }, _a[SOURCE_FORMAT_OBJECT_ROWS] = { pure: !0, appendData: appendDataSimply }, _a[SOURCE_FORMAT_KEYED_COLUMNS] = { pure: !0, appendData: function(newData) { var data = this._data; each(newData, function(newCol, key) { for(var oldCol = data[key] || (data[key] = []), i = 0; i < (newCol || []).length; i++)oldCol.push(newCol[i]); }); } }, _a[SOURCE_FORMAT_ORIGINAL] = { appendData: appendDataSimply }, _a[SOURCE_FORMAT_TYPED_ARRAY] = { persistent: !1, pure: !0, appendData: function(newData) { assert(isTypedArray(newData), 'Added data must be TypedArray if data in initialization is TypedArray'), this._data = newData; }, clean: function() { this._offset += this.count(), this._data = null; } }, providerMethods = _a; }(), DefaultDataProvider; }(), getItemSimply = function(rawData, startIndex, dimsDef, idx) { return rawData[idx]; }, rawSourceItemGetterMap = ((_a = {})[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function(rawData, startIndex, dimsDef, idx) { return rawData[idx + startIndex]; }, _a[SOURCE_FORMAT_ARRAY_ROWS + "_row"] = function(rawData, startIndex, dimsDef, idx) { idx += startIndex; for(var item = [], i = 0; i < rawData.length; i++){ var row = rawData[i]; item.push(row ? row[idx] : null); } return item; }, _a[SOURCE_FORMAT_OBJECT_ROWS] = getItemSimply, _a[SOURCE_FORMAT_KEYED_COLUMNS] = function(rawData, startIndex, dimsDef, idx) { for(var item = [], i = 0; i < dimsDef.length; i++){ var dimName = dimsDef[i].name; if (null == dimName) throw Error(); var col = rawData[dimName]; item.push(col ? col[idx] : null); } return item; }, _a[SOURCE_FORMAT_ORIGINAL] = getItemSimply, _a); function getRawSourceItemGetter(sourceFormat, seriesLayoutBy) { var method = rawSourceItemGetterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)]; return assert(method, 'Do not suppport get item on "' + sourceFormat + '", "' + seriesLayoutBy + '".'), method; } var countSimply = function(rawData, startIndex, dimsDef) { return rawData.length; }, rawSourceDataCounterMap = ((_b = {})[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function(rawData, startIndex, dimsDef) { return Math.max(0, rawData.length - startIndex); }, _b[SOURCE_FORMAT_ARRAY_ROWS + "_row"] = function(rawData, startIndex, dimsDef) { var row = rawData[0]; return row ? Math.max(0, row.length - startIndex) : 0; }, _b[SOURCE_FORMAT_OBJECT_ROWS] = countSimply, _b[SOURCE_FORMAT_KEYED_COLUMNS] = function(rawData, startIndex, dimsDef) { var dimName = dimsDef[0].name; if (null == dimName) throw Error(); var col = rawData[dimName]; return col ? col.length : 0; }, _b[SOURCE_FORMAT_ORIGINAL] = countSimply, _b); function getRawSourceDataCounter(sourceFormat, seriesLayoutBy) { var method = rawSourceDataCounterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)]; return assert(method, 'Do not suppport count on "' + sourceFormat + '", "' + seriesLayoutBy + '".'), method; } var getRawValueSimply = function(dataItem, dimIndex, dimName) { return null != dimIndex ? dataItem[dimIndex] : dataItem; }, rawSourceValueGetterMap = ((_c = {})[SOURCE_FORMAT_ARRAY_ROWS] = getRawValueSimply, _c[SOURCE_FORMAT_OBJECT_ROWS] = function(dataItem, dimIndex, dimName) { return null != dimIndex ? dataItem[dimName] : dataItem; }, _c[SOURCE_FORMAT_KEYED_COLUMNS] = getRawValueSimply, _c[SOURCE_FORMAT_ORIGINAL] = function(dataItem, dimIndex, dimName) { var value = getDataItemValue(dataItem); return null != dimIndex && value instanceof Array ? value[dimIndex] : value; }, _c[SOURCE_FORMAT_TYPED_ARRAY] = getRawValueSimply, _c); function getRawSourceValueGetter(sourceFormat) { var method = rawSourceValueGetterMap[sourceFormat]; return assert(method, 'Do not suppport get value on "' + sourceFormat + '".'), method; } function getMethodMapKey(sourceFormat, seriesLayoutBy) { return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS ? sourceFormat + '_' + seriesLayoutBy : sourceFormat; } function retrieveRawValue(data, dataIndex, dim) { if (data) { var dimName, dimIndex, dataItem = data.getRawDataItem(dataIndex); if (null != dataItem) { var sourceFormat = data.getProvider().getSource().sourceFormat, dimInfo = data.getDimensionInfo(dim); return dimInfo && (dimName = dimInfo.name, dimIndex = dimInfo.index), getRawSourceValueGetter(sourceFormat)(dataItem, dimIndex, dimName); } } } var DIMENSION_LABEL_REG = /\{@(.+?)\}/g, DataFormatMixin = function() { function DataFormatMixin() {} return DataFormatMixin.prototype.getDataParams = function(dataIndex, dataType) { var data = this.getData(dataType), rawValue = this.getRawValue(dataIndex, dataType), rawDataIndex = data.getRawIndex(dataIndex), name = data.getName(dataIndex), itemOpt = data.getRawDataItem(dataIndex), style = data.getItemVisual(dataIndex, 'style'), color = style && style[data.getItemVisual(dataIndex, 'drawType') || 'fill'], borderColor = style && style.stroke, mainType = this.mainType, isSeries = 'series' === mainType, userOutput = data.userOutput; return { componentType: mainType, componentSubType: this.subType, componentIndex: this.componentIndex, seriesType: isSeries ? this.subType : null, seriesIndex: this.seriesIndex, seriesId: isSeries ? this.id : null, seriesName: isSeries ? this.name : null, name: name, dataIndex: rawDataIndex, data: itemOpt, dataType: dataType, value: rawValue, color: color, borderColor: borderColor, dimensionNames: userOutput ? userOutput.dimensionNames : null, encode: userOutput ? userOutput.encode : null, $vars: [ 'seriesName', 'name', 'value' ] }; }, DataFormatMixin.prototype.getFormattedLabel = function(dataIndex, status, dataType, labelDimIndex, formatter, extendParams) { status = status || 'normal'; var data = this.getData(dataType), params = this.getDataParams(dataIndex, dataType); return (extendParams && (params.value = extendParams.interpolatedValue), null != labelDimIndex && isArray(params.value) && (params.value = params.value[labelDimIndex]), formatter || (formatter = data.getItemModel(dataIndex).get('normal' === status ? [ 'label', 'formatter' ] : [ status, 'label', 'formatter' ])), 'function' == typeof formatter) ? (params.status = status, params.dimensionIndex = labelDimIndex, formatter(params)) : 'string' == typeof formatter ? formatTpl(formatter, params).replace(DIMENSION_LABEL_REG, function(origin, dimStr) { var len = dimStr.length, dimLoose = '[' === dimStr.charAt(0) && ']' === dimStr.charAt(len - 1) ? +dimStr.slice(1, len - 1) : dimStr, val = retrieveRawValue(data, dataIndex, dimLoose); if (extendParams && isArray(extendParams.interpolatedValue)) { var dimInfo = data.getDimensionInfo(dimLoose); dimInfo && (val = extendParams.interpolatedValue[dimInfo.index]); } return null != val ? val + '' : ''; }) : void 0; }, DataFormatMixin.prototype.getRawValue = function(idx, dataType) { return retrieveRawValue(this.getData(dataType), idx); }, DataFormatMixin.prototype.formatTooltip = function(dataIndex, multipleSeries, dataType) {}, DataFormatMixin; }(); function normalizeTooltipFormatResult(result) { var markupText, markupFragment; return isObject(result) ? result.type ? markupFragment = result : console.warn('The return type of `formatTooltip` is not supported: ' + makePrintable(result)) : markupText = result, { markupText: markupText, markupFragment: markupFragment }; } function createTask(define1) { return new Task(define1); } var Task = function() { function Task(define1) { define1 = define1 || {}, this._reset = define1.reset, this._plan = define1.plan, this._count = define1.count, this._onDirty = define1.onDirty, this._dirty = !0; } return Task.prototype.perform = function(performArgs) { var val, val1, planResult, forceFirstProgress, upTask = this._upstream, skip = performArgs && performArgs.skip; if (this._dirty && upTask) { var context = this.context; context.data = context.outputData = upTask.context.outputData; } this.__pipeline && (this.__pipeline.currentTask = this), this._plan && !skip && (planResult = this._plan(this.context)); var lastModBy = ((val = this._modBy) >= 1 || (val = 1), val), lastModDataCount = this._modDataCount || 0, modBy = ((val1 = performArgs && performArgs.modBy) >= 1 || (val1 = 1), val1), modDataCount = performArgs && performArgs.modDataCount || 0; (lastModBy !== modBy || lastModDataCount !== modDataCount) && (planResult = 'reset'), (this._dirty || 'reset' === planResult) && (this._dirty = !1, forceFirstProgress = this._doReset(skip)), this._modBy = modBy, this._modDataCount = modDataCount; var step = performArgs && performArgs.step; if (upTask ? (assert(null != upTask._outputDueEnd), this._dueEnd = upTask._outputDueEnd) : (assert(!this._progress || this._count), this._dueEnd = this._count ? this._count(this.context) : 1 / 0), this._progress) { var start = this._dueIndex, end = Math.min(null != step ? this._dueIndex + step : 1 / 0, this._dueEnd); if (!skip && (forceFirstProgress || start < end)) { var progress = this._progress; if (isArray(progress)) for(var i = 0; i < progress.length; i++)this._doProgress(progress[i], start, end, modBy, modDataCount); else this._doProgress(progress, start, end, modBy, modDataCount); } this._dueIndex = end; var outputDueEnd = null != this._settedOutputEnd ? this._settedOutputEnd : end; assert(outputDueEnd >= this._outputDueEnd), this._outputDueEnd = outputDueEnd; } else this._dueIndex = this._outputDueEnd = null != this._settedOutputEnd ? this._settedOutputEnd : this._dueEnd; return this.unfinished(); }, Task.prototype.dirty = function() { this._dirty = !0, this._onDirty && this._onDirty(this.context); }, Task.prototype._doProgress = function(progress, start, end, modBy, modDataCount) { iterator.reset(start, end, modBy, modDataCount), this._callingProgress = progress, this._callingProgress({ start: start, end: end, count: end - start, next: iterator.next }, this.context); }, Task.prototype._doReset = function(skip) { this._dueIndex = this._outputDueEnd = this._dueEnd = 0, this._settedOutputEnd = null, !skip && this._reset && ((progress = this._reset(this.context)) && progress.progress && (forceFirstProgress = progress.forceFirstProgress, progress = progress.progress), isArray(progress) && !progress.length && (progress = null)), this._progress = progress, this._modBy = this._modDataCount = null; var progress, forceFirstProgress, downstream = this._downstream; return downstream && downstream.dirty(), forceFirstProgress; }, Task.prototype.unfinished = function() { return this._progress && this._dueIndex < this._dueEnd; }, Task.prototype.pipe = function(downTask) { assert(downTask && !downTask._disposed && downTask !== this), (this._downstream !== downTask || this._dirty) && (this._downstream = downTask, downTask._upstream = this, downTask.dirty()); }, Task.prototype.dispose = function() { this._disposed || (this._upstream && (this._upstream._downstream = null), this._downstream && (this._downstream._upstream = null), this._dirty = !1, this._disposed = !0); }, Task.prototype.getUpstream = function() { return this._upstream; }, Task.prototype.getDownstream = function() { return this._downstream; }, Task.prototype.setOutputEnd = function(end) { this._outputDueEnd = this._settedOutputEnd = end; }, Task; }(), iterator = function() { var end, current, modBy, modDataCount, winCount, it = { reset: function(s, e, sStep, sCount) { current = s, end = e, modBy = sStep, winCount = Math.ceil((modDataCount = sCount) / modBy), it.next = modBy > 1 && modDataCount > 0 ? modNext : sequentialNext; } }; return it; function sequentialNext() { return current < end ? current++ : null; } function modNext() { var dataIndex = current % winCount * modBy + Math.ceil(current / winCount), result = current >= end ? null : dataIndex < modDataCount ? dataIndex : current; return current++, result; } }(); function parseDataValue(value, opt) { var dimType = opt && opt.type; if ('ordinal' === dimType) { var ordinalMeta = opt && opt.ordinalMeta; return ordinalMeta ? ordinalMeta.parseAndCollect(value) : value; } return 'time' === dimType && 'number' != typeof value && null != value && '-' !== value && (value = +parseDate(value)), null == value || '' === value ? NaN : +value; } var valueParserMap = createHashMap({ number: function(val) { return parseFloat(val); }, time: function(val) { return +parseDate(val); }, trim: function(val) { return 'string' == typeof val ? trim(val) : val; } }), ORDER_COMPARISON_OP_MAP = { lt: function(lval, rval) { return lval < rval; }, lte: function(lval, rval) { return lval <= rval; }, gt: function(lval, rval) { return lval > rval; }, gte: function(lval, rval) { return lval >= rval; } }, FilterOrderComparator = function() { function FilterOrderComparator(op, rval) { 'number' != typeof rval && throwError('rvalue of "<", ">", "<=", ">=" can only be number in filter.'), this._opFn = ORDER_COMPARISON_OP_MAP[op], this._rvalFloat = numericToNumber(rval); } return FilterOrderComparator.prototype.evaluate = function(lval) { return 'number' == typeof lval ? this._opFn(lval, this._rvalFloat) : this._opFn(numericToNumber(lval), this._rvalFloat); }, FilterOrderComparator; }(), SortOrderComparator = function() { function SortOrderComparator(order, incomparable) { var isDesc = 'desc' === order; this._resultLT = isDesc ? 1 : -1, null == incomparable && (incomparable = isDesc ? 'min' : 'max'), this._incomparable = 'min' === incomparable ? -1 / 0 : 1 / 0; } return SortOrderComparator.prototype.evaluate = function(lval, rval) { var lvalTypeof = typeof lval, rvalTypeof = typeof rval, lvalFloat = 'number' === lvalTypeof ? lval : numericToNumber(lval), rvalFloat = 'number' === rvalTypeof ? rval : numericToNumber(rval), lvalNotNumeric = isNaN(lvalFloat), rvalNotNumeric = isNaN(rvalFloat); if (lvalNotNumeric && (lvalFloat = this._incomparable), rvalNotNumeric && (rvalFloat = this._incomparable), lvalNotNumeric && rvalNotNumeric) { var lvalIsStr = 'string' === lvalTypeof, rvalIsStr = 'string' === rvalTypeof; lvalIsStr && (lvalFloat = rvalIsStr ? lval : 0), rvalIsStr && (rvalFloat = lvalIsStr ? rval : 0); } return lvalFloat < rvalFloat ? this._resultLT : lvalFloat > rvalFloat ? -this._resultLT : 0; }, SortOrderComparator; }(), FilterEqualityComparator = function() { function FilterEqualityComparator(isEq, rval) { this._rval = rval, this._isEQ = isEq, this._rvalTypeof = typeof rval, this._rvalFloat = numericToNumber(rval); } return FilterEqualityComparator.prototype.evaluate = function(lval) { var eqResult = lval === this._rval; if (!eqResult) { var lvalTypeof = typeof lval; lvalTypeof !== this._rvalTypeof && ('number' === lvalTypeof || 'number' === this._rvalTypeof) && (eqResult = numericToNumber(lval) === this._rvalFloat); } return this._isEQ ? eqResult : !eqResult; }, FilterEqualityComparator; }(), ExternalSource = function() { function ExternalSource() {} return ExternalSource.prototype.getRawData = function() { throw Error('not supported'); }, ExternalSource.prototype.getRawDataItem = function(dataIndex) { throw Error('not supported'); }, ExternalSource.prototype.cloneRawData = function() {}, ExternalSource.prototype.getDimensionInfo = function(dim) {}, ExternalSource.prototype.cloneAllDimensionInfo = function() {}, ExternalSource.prototype.count = function() {}, ExternalSource.prototype.retrieveValue = function(dataIndex, dimIndex) {}, ExternalSource.prototype.retrieveValueFromItem = function(dataItem, dimIndex) {}, ExternalSource.prototype.convertValue = function(rawVal, dimInfo) { return parseDataValue(rawVal, dimInfo); }, ExternalSource; }(); function getRawData(upstream) { var sourceFormat = upstream.sourceFormat; return !isSupportedSourceFormat(sourceFormat) && throwError('`getRawData` is not supported in source format ' + sourceFormat), upstream.data; } function cloneRawData(upstream) { var sourceFormat = upstream.sourceFormat, data = upstream.data; if (!isSupportedSourceFormat(sourceFormat) && throwError('`cloneRawData` is not supported in source format ' + sourceFormat), sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) { for(var result = [], i = 0, len = data.length; i < len; i++)result.push(data[i].slice()); return result; } if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) { for(var result = [], i = 0, len = data.length; i < len; i++)result.push(extend({}, data[i])); return result; } } function getDimensionInfo(dimensions, dimsByName, dim) { return null == dim ? void 0 : 'number' != typeof dim && (isNaN(dim) || hasOwn(dimsByName, dim)) ? hasOwn(dimsByName, dim) ? dimsByName[dim] : void 0 : dimensions[dim]; } function cloneAllDimensionInfo(dimensions) { return clone(dimensions); } var externalTransformMap = createHashMap(); function isSupportedSourceFormat(sourceFormat) { return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS || sourceFormat === SOURCE_FORMAT_OBJECT_ROWS; } var SourceManager = function() { function SourceManager(sourceHost) { this._sourceList = [], this._upstreamSignList = [], this._versionSignBase = 0, this._sourceHost = sourceHost; } return SourceManager.prototype.dirty = function() { this._setLocalSource([], []); }, SourceManager.prototype._setLocalSource = function(sourceList, upstreamSignList) { this._sourceList = sourceList, this._upstreamSignList = upstreamSignList, this._versionSignBase++, this._versionSignBase > 9e10 && (this._versionSignBase = 0); }, SourceManager.prototype._getVersionSign = function() { return this._sourceHost.uid + '_' + this._versionSignBase; }, SourceManager.prototype.prepareSource = function() { this._isDirty() && this._createSource(); }, SourceManager.prototype._createSource = function() { this._setLocalSource([], []); var resultSourceList, upstreamSignList, sourceHost = this._sourceHost, upSourceMgrList = this._getUpstreamSourceManagers(), hasUpstream = !!upSourceMgrList.length; if (isSeries(sourceHost)) { var data = void 0, sourceFormat = void 0, upSource = void 0; if (hasUpstream) { var upSourceMgr = upSourceMgrList[0]; upSourceMgr.prepareSource(), data = (upSource = upSourceMgr.getSource()).data, sourceFormat = upSource.sourceFormat, upstreamSignList = [ upSourceMgr._getVersionSign() ]; } else sourceFormat = isTypedArray(data = sourceHost.get('data', !0)) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL, upstreamSignList = []; var newMetaRawOption = this._getSourceMetaRawOption(), upMetaRawOption = upSource ? upSource.metaRawOption : null; resultSourceList = [ createSource(data, { seriesLayoutBy: retrieve2(newMetaRawOption.seriesLayoutBy, upMetaRawOption ? upMetaRawOption.seriesLayoutBy : null), sourceHeader: retrieve2(newMetaRawOption.sourceHeader, upMetaRawOption ? upMetaRawOption.sourceHeader : null), dimensions: retrieve2(newMetaRawOption.dimensions, upMetaRawOption ? upMetaRawOption.dimensions : null) }, sourceFormat, sourceHost.get('encode', !0)) ]; } else if (hasUpstream) { var result = this._applyTransform(upSourceMgrList); resultSourceList = result.sourceList, upstreamSignList = result.upstreamSignList; } else resultSourceList = [ createSource(sourceHost.get('source', !0), this._getSourceMetaRawOption(), null, null) ], upstreamSignList = []; assert(resultSourceList && upstreamSignList), this._setLocalSource(resultSourceList, upstreamSignList); }, SourceManager.prototype._applyTransform = function(upMgrList) { var encodeDefine, source, sourceList, datasetModel = this._sourceHost, transformOption = datasetModel.get('transform', !0), fromTransformResult = datasetModel.get('fromTransformResult', !0); assert(null != fromTransformResult || null != transformOption), null != fromTransformResult && 1 !== upMgrList.length && doThrow('When using `fromTransformResult`, there should be only one upstream dataset'); var upSourceList = [], upstreamSignList = []; return (each(upMgrList, function(upMgr) { upMgr.prepareSource(); var upSource = upMgr.getSource(fromTransformResult || 0); null == fromTransformResult || upSource || doThrow('Can not retrieve result by `fromTransformResult`: ' + fromTransformResult), upSourceList.push(upSource), upstreamSignList.push(upMgr._getVersionSign()); }), transformOption) ? sourceList = function(rawTransOption, sourceList, infoForPrint) { var pipedTransOption = normalizeToArray(rawTransOption), pipeLen = pipedTransOption.length; pipeLen || throwError('If `transform` declared, it should at least contain one transform.'); for(var i = 0; i < pipeLen; i++)sourceList = function(transOption, upSourceList, infoForPrint, pipeIndex) { upSourceList.length || throwError('Must have at least one upstream dataset.'), isObject(transOption) || throwError('transform declaration must be an object rather than ' + typeof transOption + '.'); var transType = transOption.type, externalTransform = externalTransformMap.get(transType); externalTransform || throwError('Can not find transform on type "' + transType + '".'); var extUpSourceList = map(upSourceList, function(upSource) { return function(internalSource, externalTransform) { var extSource = new ExternalSource(), data = internalSource.data, sourceFormat = extSource.sourceFormat = internalSource.sourceFormat, sourceHeaderCount = internalSource.startIndex; internalSource.seriesLayoutBy !== SERIES_LAYOUT_BY_COLUMN && throwError('`seriesLayoutBy` of upstream dataset can only be "column" in data transform.'); var dimensions = [], dimsByName = {}, dimsDef = internalSource.dimensionsDefine; if (dimsDef) each(dimsDef, function(dimDef, idx) { var name = dimDef.name, dimDefExt = { index: idx, name: name, displayName: dimDef.displayName }; dimensions.push(dimDefExt), null != name && (hasOwn(dimsByName, name) && throwError('dimension name "' + name + '" duplicated.'), dimsByName[name] = dimDefExt); }); else for(var i = 0; i < internalSource.dimensionsDetectedCount; i++)dimensions.push({ index: i }); var rawItemGetter = getRawSourceItemGetter(sourceFormat, SERIES_LAYOUT_BY_COLUMN); externalTransform.__isBuiltIn && (extSource.getRawDataItem = function(dataIndex) { return rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex); }, extSource.getRawData = bind(getRawData, null, internalSource)), extSource.cloneRawData = bind(cloneRawData, null, internalSource); var rawCounter = getRawSourceDataCounter(sourceFormat, SERIES_LAYOUT_BY_COLUMN); extSource.count = bind(rawCounter, null, data, sourceHeaderCount, dimensions); var rawValueGetter = getRawSourceValueGetter(sourceFormat); extSource.retrieveValue = function(dataIndex, dimIndex) { return retrieveValueFromItem(rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex), dimIndex); }; var retrieveValueFromItem = extSource.retrieveValueFromItem = function(dataItem, dimIndex) { if (null != dataItem) { var dimDef = dimensions[dimIndex]; if (dimDef) return rawValueGetter(dataItem, dimIndex, dimDef.name); } }; return extSource.getDimensionInfo = bind(getDimensionInfo, null, dimensions, dimsByName), extSource.cloneAllDimensionInfo = bind(cloneAllDimensionInfo, null, dimensions), extSource; }(upSource, externalTransform); }), resultList = normalizeToArray(externalTransform.transform({ upstream: extUpSourceList[0], upstreamList: extUpSourceList, config: clone(transOption.config) })); return transOption.print && function() { for(var args = [], _i = 0; _i < arguments.length; _i++)args[_i] = arguments[_i]; 'undefined' != typeof console && console.log && console.log.apply(console, args); }(map(resultList, function(extSource) { return [ '=== dataset index: ' + infoForPrint.datasetIndex + (null != pipeIndex ? ' === pipe index: ' + pipeIndex : '') + ' ===', '- transform result data:', makePrintable(extSource.data), '- transform result dimensions:', makePrintable(extSource.dimensions) ].join('\n'); }).join('\n')), map(resultList, function(result, resultIndex) { isObject(result) || throwError('A transform should not return some empty results.'), result.data || throwError('Transform result data should be not be null or undefined'), isSupportedSourceFormat(detectSourceFormat(result.data)) || throwError('Transform result data should be array rows or object rows.'); var resultMetaRawOption, firstUpSource = upSourceList[0]; if (firstUpSource && 0 === resultIndex && !result.dimensions) { var startIndex = firstUpSource.startIndex; startIndex && (result.data = firstUpSource.data.slice(0, startIndex).concat(result.data)), resultMetaRawOption = { seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN, sourceHeader: startIndex, dimensions: firstUpSource.metaRawOption.dimensions }; } else resultMetaRawOption = { seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN, sourceHeader: 0, dimensions: result.dimensions }; return createSource(result.data, resultMetaRawOption, null, null); }); }(pipedTransOption[i], sourceList, infoForPrint, 1 === pipeLen ? null : i), i !== pipeLen - 1 && (sourceList.length = Math.max(sourceList.length, 1)); return sourceList; }(transformOption, upSourceList, { datasetIndex: datasetModel.componentIndex }) : null != fromTransformResult && (sourceList = [ (source = upSourceList[0], new SourceImpl({ data: source.data, sourceFormat: source.sourceFormat, seriesLayoutBy: source.seriesLayoutBy, dimensionsDefine: clone(source.dimensionsDefine), startIndex: source.startIndex, dimensionsDetectedCount: source.dimensionsDetectedCount, encodeDefine: (encodeDefine = source.encodeDefine) ? createHashMap(encodeDefine) : null })) ]), { sourceList: sourceList, upstreamSignList: upstreamSignList }; }, SourceManager.prototype._isDirty = function() { if (!this._sourceList.length) return !0; for(var upSourceMgrList = this._getUpstreamSourceManagers(), i = 0; i < upSourceMgrList.length; i++){ var upSrcMgr = upSourceMgrList[i]; if (upSrcMgr._isDirty() || this._upstreamSignList[i] !== upSrcMgr._getVersionSign()) return !0; } }, SourceManager.prototype.getSource = function(sourceIndex) { return this._sourceList[sourceIndex || 0]; }, SourceManager.prototype._getUpstreamSourceManagers = function() { var sourceHost = this._sourceHost; if (isSeries(sourceHost)) { var datasetModel = querySeriesUpstreamDatasetModel(sourceHost); return datasetModel ? [ datasetModel.getSourceManager() ] : []; } return map(sourceHost.get('transform', !0) || sourceHost.get('fromTransformResult', !0) ? queryReferringComponents(sourceHost.ecModel, 'dataset', { index: sourceHost.get('fromDatasetIndex', !0), id: sourceHost.get('fromDatasetId', !0) }, SINGLE_REFERRING).models : [], function(datasetModel) { return datasetModel.getSourceManager(); }); }, SourceManager.prototype._getSourceMetaRawOption = function() { var seriesLayoutBy, sourceHeader, dimensions, sourceHost = this._sourceHost; return isSeries(sourceHost) ? (seriesLayoutBy = sourceHost.get('seriesLayoutBy', !0), sourceHeader = sourceHost.get('sourceHeader', !0), dimensions = sourceHost.get('dimensions', !0)) : this._getUpstreamSourceManagers().length || (seriesLayoutBy = sourceHost.get('seriesLayoutBy', !0), sourceHeader = sourceHost.get('sourceHeader', !0), dimensions = sourceHost.get('dimensions', !0)), { seriesLayoutBy: seriesLayoutBy, sourceHeader: sourceHeader, dimensions: dimensions }; }, SourceManager; }(); function disableTransformOptionMerge(datasetModel) { datasetModel.option.transform && setAsPrimitive(datasetModel.option.transform); } function isSeries(sourceHost) { return 'series' === sourceHost.mainType; } function doThrow(errMsg) { throw Error(errMsg); } var TOOLTIP_LINE_HEIGHT_CSS = 'line-height:1'; function getTooltipTextStyle(textStyle, renderMode) { var nameFontColor = textStyle.color || '#6e7079', nameFontSize = textStyle.fontSize || 12, nameFontWeight = textStyle.fontWeight || '400', valueFontColor = textStyle.color || '#464646', valueFontSize = textStyle.fontSize || 14, valueFontWeight = textStyle.fontWeight || '900'; return 'html' === renderMode ? { nameStyle: "font-size:" + encodeHTML(nameFontSize + '') + "px;color:" + encodeHTML(nameFontColor) + ";font-weight:" + encodeHTML(nameFontWeight + ''), valueStyle: "font-size:" + encodeHTML(valueFontSize + '') + "px;color:" + encodeHTML(valueFontColor) + ";font-weight:" + encodeHTML(valueFontWeight + '') } : { nameStyle: { fontSize: nameFontSize, fill: nameFontColor, fontWeight: nameFontWeight }, valueStyle: { fontSize: valueFontSize, fill: valueFontColor, fontWeight: valueFontWeight } }; } var HTML_GAPS = [ 0, 10, 20, 30 ], RICH_TEXT_GAPS = [ '', '\n', '\n\n', '\n\n\n' ]; function createTooltipMarkup(type, option) { return option.type = type, option; } function getBuilder(fragment) { return hasOwn(builderMap, fragment.type) && builderMap[fragment.type]; } var builderMap = { section: { planLayout: function(fragment) { var subBlockLen = fragment.blocks.length, thisBlockHasInnerGap = subBlockLen > 1 || subBlockLen > 0 && !fragment.noHeader, thisGapLevelBetweenSubBlocks = 0; each(fragment.blocks, function(subBlock) { getBuilder(subBlock).planLayout(subBlock); var subGapLevel = subBlock.__gapLevelBetweenSubBlocks; subGapLevel >= thisGapLevelBetweenSubBlocks && (thisGapLevelBetweenSubBlocks = subGapLevel + (!thisBlockHasInnerGap || subGapLevel && ('section' !== subBlock.type || subBlock.noHeader) ? 0 : 1)); }), fragment.__gapLevelBetweenSubBlocks = thisGapLevelBetweenSubBlocks; }, build: function(ctx, fragment, topMarginForOuterGap, toolTipTextStyle) { var noHeader = fragment.noHeader, gaps = getGap(fragment), subMarkupText = function(ctx, fragment, topMarginForOuterGap, tooltipTextStyle) { var subMarkupTextList = [], subBlocks = fragment.blocks || []; assert(!subBlocks || isArray(subBlocks)), subBlocks = subBlocks || []; var orderMode = ctx.orderMode; if (fragment.sortBlocks && orderMode) { subBlocks = subBlocks.slice(); var orderMap = { valueAsc: 'asc', valueDesc: 'desc' }; if (hasOwn(orderMap, orderMode)) { var comparator_1 = new SortOrderComparator(orderMap[orderMode], null); subBlocks.sort(function(a, b) { return comparator_1.evaluate(a.sortParam, b.sortParam); }); } else 'seriesDesc' === orderMode && subBlocks.reverse(); } var gaps = getGap(fragment); if (each(subBlocks, function(subBlock, idx) { var subMarkupText = getBuilder(subBlock).build(ctx, subBlock, idx > 0 ? gaps.html : 0, tooltipTextStyle); null != subMarkupText && subMarkupTextList.push(subMarkupText); }), subMarkupTextList.length) return 'richText' === ctx.renderMode ? subMarkupTextList.join(gaps.richText) : wrapBlockHTML(subMarkupTextList.join(''), topMarginForOuterGap); }(ctx, fragment, noHeader ? topMarginForOuterGap : gaps.html, toolTipTextStyle); if (noHeader) return subMarkupText; var displayableHeader = makeValueReadable(fragment.header, 'ordinal', ctx.useUTC), nameStyle = getTooltipTextStyle(toolTipTextStyle, ctx.renderMode).nameStyle; return 'richText' === ctx.renderMode ? wrapInlineNameRichText(ctx, displayableHeader, nameStyle) + gaps.richText + subMarkupText : wrapBlockHTML("
" + encodeHTML(displayableHeader) + '
' + subMarkupText, topMarginForOuterGap); } }, nameValue: { planLayout: function(fragment) { fragment.__gapLevelBetweenSubBlocks = 0; }, build: function(ctx, fragment, topMarginForOuterGap, toolTipTextStyle) { var renderMode = ctx.renderMode, noName = fragment.noName, noValue = fragment.noValue, noMarker = !fragment.markerType, name = fragment.name, value = fragment.value, useUTC = ctx.useUTC; if (!noName || !noValue) { var styles, markerStr = noMarker ? '' : ctx.markupStyleCreator.makeTooltipMarker(fragment.markerType, fragment.markerColor || '#333', renderMode), readableName = noName ? '' : makeValueReadable(name, 'ordinal', useUTC), valueTypeOption = fragment.valueType, readableValueList = noValue ? [] : isArray(value) ? map(value, function(val, idx) { return makeValueReadable(val, isArray(valueTypeOption) ? valueTypeOption[idx] : valueTypeOption, useUTC); }) : [ makeValueReadable(value, isArray(valueTypeOption) ? valueTypeOption[0] : valueTypeOption, useUTC) ], valueAlignRight = !noMarker || !noName, valueCloseToMarker = !noMarker && noName, _a = getTooltipTextStyle(toolTipTextStyle, renderMode), nameStyle = _a.nameStyle, valueStyle = _a.valueStyle; return 'richText' === renderMode ? (noMarker ? '' : markerStr) + (noName ? '' : wrapInlineNameRichText(ctx, readableName, nameStyle)) + (noValue ? '' : (styles = [ valueStyle ], valueAlignRight && styles.push({ padding: [ 0, 0, 0, valueCloseToMarker ? 10 : 20 ], align: 'right' }), ctx.markupStyleCreator.wrapRichTextStyle(readableValueList.join(' '), styles))) : wrapBlockHTML((noMarker ? '' : markerStr) + (noName ? '' : "" + encodeHTML(readableName) + '') + (noValue ? '' : "" + map(readableValueList, function(value) { return encodeHTML(value); }).join('  ') + ''), topMarginForOuterGap); } } } }; function buildTooltipMarkup(fragment, markupStyleCreator, renderMode, orderMode, useUTC, toolTipTextStyle) { if (fragment) { var builder = getBuilder(fragment); return builder.planLayout(fragment), builder.build({ useUTC: useUTC, renderMode: renderMode, orderMode: orderMode, markupStyleCreator: markupStyleCreator }, fragment, 0, toolTipTextStyle); } } function getGap(fragment) { var gapLevelBetweenSubBlocks = fragment.__gapLevelBetweenSubBlocks; return { html: HTML_GAPS[gapLevelBetweenSubBlocks], richText: RICH_TEXT_GAPS[gapLevelBetweenSubBlocks] }; } function wrapBlockHTML(encodedContent, topGap) { return '
" + encodedContent + '
'; } function wrapInlineNameRichText(ctx, name, style) { return ctx.markupStyleCreator.wrapRichTextStyle(name, style); } function retrieveVisualColorForTooltipMarker(series, dataIndex) { return convertToColorString(series.getData().getItemVisual(dataIndex, 'style')[series.visualDrawType]); } function getPaddingFromTooltipModel(model, renderMode) { var padding = model.get('padding'); return null != padding ? padding : 'richText' === renderMode ? [ 8, 10 ] : 10; } var TooltipMarkupStyleCreator = function() { function TooltipMarkupStyleCreator() { this.richTextStyles = {}, this._nextStyleNameId = getRandomIdBase(); } return TooltipMarkupStyleCreator.prototype._generateStyleName = function() { return '__EC_aUTo_' + this._nextStyleNameId++; }, TooltipMarkupStyleCreator.prototype.makeTooltipMarker = function(markerType, colorStr, renderMode) { var markerId = 'richText' === renderMode ? this._generateStyleName() : null, marker = getTooltipMarker({ color: colorStr, type: markerType, renderMode: renderMode, markerId: markerId }); return isString(marker) ? marker : (assert(markerId), this.richTextStyles[markerId] = marker.style, marker.content); }, TooltipMarkupStyleCreator.prototype.wrapRichTextStyle = function(text, styles) { var finalStl = {}; isArray(styles) ? each(styles, function(stl) { return extend(finalStl, stl); }) : extend(finalStl, styles); var styleName = this._generateStyleName(); return this.richTextStyles[styleName] = finalStl, "{" + styleName + "|" + text + "}"; }, TooltipMarkupStyleCreator; }(); function defaultSeriesFormatTooltip(opt) { var inlineValue, inlineValueType, subBlocks, sortParam, series = opt.series, dataIndex = opt.dataIndex, multipleSeries = opt.multipleSeries, data = series.getData(), tooltipDims = data.mapDimensionsAll('defaultedTooltip'), tooltipDimLen = tooltipDims.length, value = series.getRawValue(dataIndex), isValueArr = isArray(value), markerColor = retrieveVisualColorForTooltipMarker(series, dataIndex); if (tooltipDimLen > 1 || isValueArr && !tooltipDimLen) { var formatArrResult = function(value, series, dataIndex, tooltipDims, colorStr) { var data = series.getData(), isValueMultipleLine = reduce(value, function(isValueMultipleLine, val, idx) { var dimItem = data.getDimensionInfo(idx); return isValueMultipleLine = isValueMultipleLine || dimItem && !1 !== dimItem.tooltip && null != dimItem.displayName; }, !1), inlineValues = [], inlineValueTypes = [], blocks = []; function setEachItem(val, dim) { var dimInfo = data.getDimensionInfo(dim); dimInfo && !1 !== dimInfo.otherDims.tooltip && (isValueMultipleLine ? blocks.push(createTooltipMarkup('nameValue', { markerType: 'subItem', markerColor: colorStr, name: dimInfo.displayName, value: val, valueType: dimInfo.type })) : (inlineValues.push(val), inlineValueTypes.push(dimInfo.type))); } return tooltipDims.length ? each(tooltipDims, function(dim) { setEachItem(retrieveRawValue(data, dataIndex, dim), dim); }) : each(value, setEachItem), { inlineValues: inlineValues, inlineValueTypes: inlineValueTypes, blocks: blocks }; }(value, series, dataIndex, tooltipDims, markerColor); inlineValue = formatArrResult.inlineValues, inlineValueType = formatArrResult.inlineValueTypes, subBlocks = formatArrResult.blocks, sortParam = formatArrResult.inlineValues[0]; } else if (tooltipDimLen) { var dimInfo = data.getDimensionInfo(tooltipDims[0]); sortParam = inlineValue = retrieveRawValue(data, dataIndex, tooltipDims[0]), inlineValueType = dimInfo.type; } else sortParam = inlineValue = isValueArr ? value[0] : value; var seriesNameSpecified = isNameSpecified(series), seriesName = seriesNameSpecified && series.name || '', itemName = data.getName(dataIndex), inlineName = multipleSeries ? seriesName : itemName; return createTooltipMarkup('section', { header: seriesName, noHeader: multipleSeries || !seriesNameSpecified, sortParam: sortParam, blocks: [ createTooltipMarkup('nameValue', { markerType: 'item', markerColor: markerColor, name: inlineName, noName: !trim(inlineName), value: inlineValue, valueType: inlineValueType }) ].concat(subBlocks || []) }); } var inner$1 = makeInner(); function getSelectionKey(data, dataIndex) { return data.getName(dataIndex) || data.getId(dataIndex); } var SeriesModel = function(_super) { var proto; function SeriesModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this._selectedDataIndicesMap = {}, _this; } return __extends(SeriesModel, _super), SeriesModel.prototype.init = function(option, parentModel, ecModel) { this.seriesIndex = this.componentIndex, this.dataTask = createTask({ count: dataTaskCount, reset: dataTaskReset }), this.dataTask.context = { model: this }, this.mergeDefaultAndTheme(option, ecModel), (inner$1(this).sourceManager = new SourceManager(this)).prepareSource(); var data = this.getInitialData(option, ecModel); wrapData(data, this), this.dataTask.context.data = data, assert(data, 'getInitialData returned invalid data.'), inner$1(this).dataBeforeProcessed = data, autoSeriesName(this), this._initSelectedMapFromData(data); }, SeriesModel.prototype.mergeDefaultAndTheme = function(option, ecModel) { var layoutMode = fetchLayoutMode(this), inputPositionParams = layoutMode ? getLayoutParams(option) : {}, themeSubType = this.subType; ComponentModel.hasClass(themeSubType) && (themeSubType += 'Series'), merge(option, ecModel.getTheme().get(this.subType)), merge(option, this.getDefaultOption()), defaultEmphasis(option, 'label', [ 'show' ]), this.fillDataTextStyle(option.data), layoutMode && mergeLayoutParam(option, inputPositionParams, layoutMode); }, SeriesModel.prototype.mergeOption = function(newSeriesOption, ecModel) { newSeriesOption = merge(this.option, newSeriesOption, !0), this.fillDataTextStyle(newSeriesOption.data); var layoutMode = fetchLayoutMode(this); layoutMode && mergeLayoutParam(this.option, newSeriesOption, layoutMode); var sourceManager = inner$1(this).sourceManager; sourceManager.dirty(), sourceManager.prepareSource(); var data = this.getInitialData(newSeriesOption, ecModel); wrapData(data, this), this.dataTask.dirty(), this.dataTask.context.data = data, inner$1(this).dataBeforeProcessed = data, autoSeriesName(this), this._initSelectedMapFromData(data); }, SeriesModel.prototype.fillDataTextStyle = function(data) { if (data && !isTypedArray(data)) for(var props = [ 'show' ], i = 0; i < data.length; i++)data[i] && data[i].label && defaultEmphasis(data[i], 'label', props); }, SeriesModel.prototype.getInitialData = function(option, ecModel) {}, SeriesModel.prototype.appendData = function(params) { this.getRawData().appendData(params.data); }, SeriesModel.prototype.getData = function(dataType) { var task = getCurrentTask(this); if (!task) return inner$1(this).data; var data = task.context.data; return null == dataType ? data : data.getLinkedData(dataType); }, SeriesModel.prototype.getAllData = function() { var mainData = this.getData(); return mainData && mainData.getLinkedDataAll ? mainData.getLinkedDataAll() : [ { data: mainData } ]; }, SeriesModel.prototype.setData = function(data) { var task = getCurrentTask(this); if (task) { var context = task.context; context.outputData = data, task !== this.dataTask && (context.data = data); } inner$1(this).data = data; }, SeriesModel.prototype.getSource = function() { return inner$1(this).sourceManager.getSource(); }, SeriesModel.prototype.getRawData = function() { return inner$1(this).dataBeforeProcessed; }, SeriesModel.prototype.getBaseAxis = function() { var coordSys = this.coordinateSystem; return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis(); }, SeriesModel.prototype.formatTooltip = function(dataIndex, multipleSeries, dataType) { return defaultSeriesFormatTooltip({ series: this, dataIndex: dataIndex, multipleSeries: multipleSeries }); }, SeriesModel.prototype.isAnimationEnabled = function() { if (env1.node) return !1; var animationEnabled = this.getShallow('animation'); return animationEnabled && this.getData().count() > this.getShallow('animationThreshold') && (animationEnabled = !1), !!animationEnabled; }, SeriesModel.prototype.restoreData = function() { this.dataTask.dirty(); }, SeriesModel.prototype.getColorFromPalette = function(name, scope, requestColorNum) { var ecModel = this.ecModel, color = PaletteMixin.prototype.getColorFromPalette.call(this, name, scope, requestColorNum); return color || (color = ecModel.getColorFromPalette(name, scope, requestColorNum)), color; }, SeriesModel.prototype.coordDimToDataDim = function(coordDim) { return this.getRawData().mapDimensionsAll(coordDim); }, SeriesModel.prototype.getProgressive = function() { return this.get('progressive'); }, SeriesModel.prototype.getProgressiveThreshold = function() { return this.get('progressiveThreshold'); }, SeriesModel.prototype.select = function(innerDataIndices, dataType) { this._innerSelect(this.getData(dataType), innerDataIndices); }, SeriesModel.prototype.unselect = function(innerDataIndices, dataType) { var selectedMap = this.option.selectedMap; if (selectedMap) for(var data = this.getData(dataType), i = 0; i < innerDataIndices.length; i++){ var nameOrId = getSelectionKey(data, innerDataIndices[i]); selectedMap[nameOrId] = !1, this._selectedDataIndicesMap[nameOrId] = -1; } }, SeriesModel.prototype.toggleSelect = function(innerDataIndices, dataType) { for(var tmpArr = [], i = 0; i < innerDataIndices.length; i++)tmpArr[0] = innerDataIndices[i], this.isSelected(innerDataIndices[i], dataType) ? this.unselect(tmpArr, dataType) : this.select(tmpArr, dataType); }, SeriesModel.prototype.getSelectedDataIndices = function() { for(var selectedDataIndicesMap = this._selectedDataIndicesMap, nameOrIds = keys(selectedDataIndicesMap), dataIndices = [], i = 0; i < nameOrIds.length; i++){ var dataIndex = selectedDataIndicesMap[nameOrIds[i]]; dataIndex >= 0 && dataIndices.push(dataIndex); } return dataIndices; }, SeriesModel.prototype.isSelected = function(dataIndex, dataType) { var selectedMap = this.option.selectedMap; return !!selectedMap && !!selectedMap[getSelectionKey(this.getData(dataType), dataIndex)]; }, SeriesModel.prototype._innerSelect = function(data, innerDataIndices) { var _a, _b, selectedMode = this.option.selectedMode, len = innerDataIndices.length; if (selectedMode && len) { if ('multiple' === selectedMode) for(var selectedMap = this.option.selectedMap || (this.option.selectedMap = {}), i = 0; i < len; i++){ var dataIndex = innerDataIndices[i], nameOrId = getSelectionKey(data, dataIndex); selectedMap[nameOrId] = !0, this._selectedDataIndicesMap[nameOrId] = data.getRawIndex(dataIndex); } else if ('single' === selectedMode || !0 === selectedMode) { var lastDataIndex = innerDataIndices[len - 1], nameOrId = getSelectionKey(data, lastDataIndex); this.option.selectedMap = ((_a = {})[nameOrId] = !0, _a), this._selectedDataIndicesMap = ((_b = {})[nameOrId] = data.getRawIndex(lastDataIndex), _b); } } }, SeriesModel.prototype._initSelectedMapFromData = function(data) { if (!this.option.selectedMap) { var dataIndices = []; data.hasItemOption && data.each(function(idx) { var rawItem = data.getRawDataItem(idx); rawItem && rawItem.selected && dataIndices.push(idx); }), dataIndices.length > 0 && this._innerSelect(data, dataIndices); } }, SeriesModel.registerClass = function(clz) { return ComponentModel.registerClass(clz); }, SeriesModel.protoInitialize = void ((proto = SeriesModel.prototype).type = 'series.__base__', proto.seriesIndex = 0, proto.useColorPaletteOnData = !1, proto.ignoreStyleOnData = !1, proto.hasSymbolVisual = !1, proto.defaultSymbol = 'circle', proto.visualStyleAccessPath = 'itemStyle', proto.visualDrawType = 'fill'), SeriesModel; }(ComponentModel); function autoSeriesName(seriesModel) { var data, dataDims, nameArr, name = seriesModel.name; isNameSpecified(seriesModel) || (seriesModel.name = (dataDims = (data = seriesModel.getRawData()).mapDimensionsAll('seriesName'), nameArr = [], each(dataDims, function(dataDim) { var dimInfo = data.getDimensionInfo(dataDim); dimInfo.displayName && nameArr.push(dimInfo.displayName); }), nameArr.join(' ') || name)); } function dataTaskCount(context) { return context.model.getRawData().count(); } function dataTaskReset(context) { var seriesModel = context.model; return seriesModel.setData(seriesModel.getRawData().cloneShallow()), dataTaskProgress; } function dataTaskProgress(param, context) { context.outputData && param.end > context.outputData.count() && context.model.getRawData().cloneShallow(context.outputData); } function wrapData(data, seriesModel) { each(__spreadArrays(data.CHANGABLE_METHODS, data.DOWNSAMPLE_METHODS), function(methodName) { data.wrapMethod(methodName, curry(onDataChange, seriesModel)); }); } function onDataChange(seriesModel, newList) { var task = getCurrentTask(seriesModel); return task && task.setOutputEnd((newList || this).count()), newList; } function getCurrentTask(seriesModel) { var scheduler = (seriesModel.ecModel || {}).scheduler, pipeline = scheduler && scheduler.getPipeline(seriesModel.uid); if (pipeline) { var task = pipeline.currentTask; if (task) { var agentStubMap = task.agentStubMap; agentStubMap && (task = agentStubMap.get(seriesModel.uid)); } return task; } } mixin(SeriesModel, DataFormatMixin), mixin(SeriesModel, PaletteMixin), mountExtend(SeriesModel, ComponentModel); var ComponentView = function() { function ComponentView() { this.group = new Group(), this.uid = getUID('viewComponent'); } return ComponentView.prototype.init = function(ecModel, api) {}, ComponentView.prototype.render = function(model, ecModel, api, payload) {}, ComponentView.prototype.dispose = function(ecModel, api) {}, ComponentView.prototype.updateView = function(model, ecModel, api, payload) {}, ComponentView.prototype.updateLayout = function(model, ecModel, api, payload) {}, ComponentView.prototype.updateVisual = function(model, ecModel, api, payload) {}, ComponentView.prototype.blurSeries = function(seriesModels, ecModel) {}, ComponentView; }(); function createRenderPlanner() { var inner = makeInner(); return function(seriesModel) { var fields = inner(seriesModel), pipelineContext = seriesModel.pipelineContext, originalLarge = !!fields.large, originalProgressive = !!fields.progressiveRender, large = fields.large = !!(pipelineContext && pipelineContext.large), progressive = fields.progressiveRender = !!(pipelineContext && pipelineContext.progressiveRender); return !!(originalLarge !== large || originalProgressive !== progressive) && 'reset'; }; } enableClassExtend(ComponentView), enableClassManagement(ComponentView); var inner$2 = makeInner(), renderPlanner = createRenderPlanner(), ChartView = function() { function ChartView() { this.group = new Group(), this.uid = getUID('viewChart'), this.renderTask = createTask({ plan: renderTaskPlan, reset: renderTaskReset }), this.renderTask.context = { view: this }; } return ChartView.prototype.init = function(ecModel, api) {}, ChartView.prototype.render = function(seriesModel, ecModel, api, payload) {}, ChartView.prototype.highlight = function(seriesModel, ecModel, api, payload) { toggleHighlight(seriesModel.getData(), payload, 'emphasis'); }, ChartView.prototype.downplay = function(seriesModel, ecModel, api, payload) { toggleHighlight(seriesModel.getData(), payload, 'normal'); }, ChartView.prototype.remove = function(ecModel, api) { this.group.removeAll(); }, ChartView.prototype.dispose = function(ecModel, api) {}, ChartView.prototype.updateView = function(seriesModel, ecModel, api, payload) { this.render(seriesModel, ecModel, api, payload); }, ChartView.prototype.updateLayout = function(seriesModel, ecModel, api, payload) { this.render(seriesModel, ecModel, api, payload); }, ChartView.prototype.updateVisual = function(seriesModel, ecModel, api, payload) { this.render(seriesModel, ecModel, api, payload); }, ChartView.markUpdateMethod = function(payload, methodName) { inner$2(payload).updateMethod = methodName; }, ChartView.protoInitialize = void (ChartView.prototype.type = 'chart'), ChartView; }(); function elSetState(el, state, highlightDigit) { el && ('emphasis' === state ? enterEmphasis : leaveEmphasis)(el, highlightDigit); } function toggleHighlight(data, payload, state) { var highlightKey, highlightDigit, dataIndex = queryDataIndex(data, payload), highlightDigit1 = payload && null != payload.highlightKey ? (null == (highlightDigit = _highlightKeyMap[highlightKey = payload.highlightKey]) && _highlightNextDigit <= 32 && (highlightDigit = _highlightKeyMap[highlightKey] = _highlightNextDigit++), highlightDigit) : null; null != dataIndex ? each(normalizeToArray(dataIndex), function(dataIdx) { elSetState(data.getItemGraphicEl(dataIdx), state, highlightDigit1); }) : data.eachItemGraphicEl(function(el) { elSetState(el, state, highlightDigit1); }); } function renderTaskPlan(context) { return renderPlanner(context.model); } function renderTaskReset(context) { var seriesModel = context.model, ecModel = context.ecModel, api = context.api, payload = context.payload, progressiveRender = seriesModel.pipelineContext.progressiveRender, view = context.view, updateMethod = payload && inner$2(payload).updateMethod, methodName = progressiveRender ? 'incrementalPrepareRender' : updateMethod && view[updateMethod] ? updateMethod : 'render'; return 'render' !== methodName && view[methodName](seriesModel, ecModel, api, payload), progressMethodMap[methodName]; } enableClassExtend(ChartView, [ 'dispose' ]), enableClassManagement(ChartView); var progressMethodMap = { incrementalPrepareRender: { progress: function(params, context) { context.view.incrementalRender(params, context.model, context.ecModel, context.api, context.payload); } }, render: { forceFirstProgress: !0, progress: function(params, context) { context.view.render(context.model, context.ecModel, context.api, context.payload); } } }, ORIGIN_METHOD = '\0__throttleOriginMethod', RATE = '\0__throttleRate', THROTTLE_TYPE = '\0__throttleType'; function throttle(fn, delay, debounce) { var currCall, diff, scope, args, debounceNextCall, lastCall = 0, lastExec = 0, timer = null; function exec() { lastExec = new Date().getTime(), timer = null, fn.apply(scope, args || []); } delay = delay || 0; var cb = function() { for(var cbArgs = [], _i = 0; _i < arguments.length; _i++)cbArgs[_i] = arguments[_i]; currCall = new Date().getTime(), scope = this, args = cbArgs; var thisDelay = debounceNextCall || delay, thisDebounce = debounceNextCall || debounce; debounceNextCall = null, diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay, clearTimeout(timer), thisDebounce ? timer = setTimeout(exec, thisDelay) : diff >= 0 ? exec() : timer = setTimeout(exec, -diff), lastCall = currCall; }; return cb.clear = function() { timer && (clearTimeout(timer), timer = null); }, cb.debounceNextCall = function(debounceDelay) { debounceNextCall = debounceDelay; }, cb; } function createOrUpdate(obj, fnAttr, rate, throttleType) { var fn = obj[fnAttr]; if (fn) { var originFn = fn[ORIGIN_METHOD] || fn, lastThrottleType = fn[THROTTLE_TYPE]; if (fn[RATE] !== rate || lastThrottleType !== throttleType) { if (null == rate || !throttleType) return obj[fnAttr] = originFn; (fn = obj[fnAttr] = throttle(originFn, rate, 'debounce' === throttleType))[ORIGIN_METHOD] = originFn, fn[THROTTLE_TYPE] = throttleType, fn[RATE] = rate; } return fn; } } var inner$3 = makeInner(), defaultStyleMappers = { itemStyle: makeStyleMapper(ITEM_STYLE_KEY_MAP, !0), lineStyle: makeStyleMapper(LINE_STYLE_KEY_MAP, !0) }, defaultColorKey = { lineStyle: 'stroke', itemStyle: 'fill' }; function getStyleMapper(seriesModel, stylePath) { return seriesModel.visualStyleMapper || defaultStyleMappers[stylePath] || (console.warn("Unkown style type '" + stylePath + "'."), defaultStyleMappers.itemStyle); } function getDefaultColorKey(seriesModel, stylePath) { return seriesModel.visualDrawType || defaultColorKey[stylePath] || (console.warn("Unkown style type '" + stylePath + "'."), 'fill'); } var sharedModel = new Model(), PI$3 = Math.PI, Scheduler = function() { function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) { this._stageTaskMap = createHashMap(), this.ecInstance = ecInstance, this.api = api, dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice(), visualHandlers = this._visualHandlers = visualHandlers.slice(), this._allHandlers = dataProcessorHandlers.concat(visualHandlers); } return Scheduler.prototype.restoreData = function(ecModel, payload) { ecModel.restoreData(payload), this._stageTaskMap.each(function(taskRecord) { var overallTask = taskRecord.overallTask; overallTask && overallTask.dirty(); }); }, Scheduler.prototype.getPerformArgs = function(task, isBlock) { if (task.__pipeline) { var pipeline = this._pipelineMap.get(task.__pipeline.id), pCtx = pipeline.context, step = !isBlock && pipeline.progressiveEnabled && (!pCtx || pCtx.progressiveRender) && task.__idxInPipeline > pipeline.blockIndex ? pipeline.step : null, modDataCount = pCtx && pCtx.modDataCount; return { step: step, modBy: null != modDataCount ? Math.ceil(modDataCount / step) : null, modDataCount: modDataCount }; } }, Scheduler.prototype.getPipeline = function(pipelineId) { return this._pipelineMap.get(pipelineId); }, Scheduler.prototype.updateStreamModes = function(seriesModel, view) { var pipeline = this._pipelineMap.get(seriesModel.uid), dataLen = seriesModel.getData().count(), progressiveRender = pipeline.progressiveEnabled && view.incrementalPrepareRender && dataLen >= pipeline.threshold, large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold'), modDataCount = 'mod' === seriesModel.get('progressiveChunkMode') ? dataLen : null; seriesModel.pipelineContext = pipeline.context = { progressiveRender: progressiveRender, modDataCount: modDataCount, large: large }; }, Scheduler.prototype.restorePipelines = function(ecModel) { var scheduler = this, pipelineMap = scheduler._pipelineMap = createHashMap(); ecModel.eachSeries(function(seriesModel) { var progressive = seriesModel.getProgressive(), pipelineId = seriesModel.uid; pipelineMap.set(pipelineId, { id: pipelineId, head: null, tail: null, threshold: seriesModel.getProgressiveThreshold(), progressiveEnabled: progressive && !(seriesModel.preventIncremental && seriesModel.preventIncremental()), blockIndex: -1, step: Math.round(progressive || 700), count: 0 }), scheduler._pipe(seriesModel, seriesModel.dataTask); }); }, Scheduler.prototype.prepareStageTasks = function() { var stageTaskMap = this._stageTaskMap, ecModel = this.api.getModel(), api = this.api; each(this._allHandlers, function(handler) { var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, {}), errMsg = ''; errMsg = '"reset" and "overallReset" must not be both specified.', assert(!(handler.reset && handler.overallReset), errMsg), handler.reset && this._createSeriesStageTask(handler, record, ecModel, api), handler.overallReset && this._createOverallStageTask(handler, record, ecModel, api); }, this); }, Scheduler.prototype.prepareView = function(view, model, ecModel, api) { var renderTask = view.renderTask, context = renderTask.context; context.model = model, context.ecModel = ecModel, context.api = api, renderTask.__block = !view.incrementalPrepareRender, this._pipe(model, renderTask); }, Scheduler.prototype.performDataProcessorTasks = function(ecModel, payload) { this._performStageTasks(this._dataProcessorHandlers, ecModel, payload, { block: !0 }); }, Scheduler.prototype.performVisualTasks = function(ecModel, payload, opt) { this._performStageTasks(this._visualHandlers, ecModel, payload, opt); }, Scheduler.prototype._performStageTasks = function(stageHandlers, ecModel, payload, opt) { opt = opt || {}; var unfinished = !1, scheduler = this; function needSetDirty(opt, task) { return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id)); } each(stageHandlers, function(stageHandler, idx) { if (!opt.visualType || opt.visualType === stageHandler.visualType) { var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid), seriesTaskMap = stageHandlerRecord.seriesTaskMap, overallTask = stageHandlerRecord.overallTask; if (overallTask) { var overallNeedDirty_1, agentStubMap = overallTask.agentStubMap; agentStubMap.each(function(stub) { needSetDirty(opt, stub) && (stub.dirty(), overallNeedDirty_1 = !0); }), overallNeedDirty_1 && overallTask.dirty(), scheduler.updatePayload(overallTask, payload); var performArgs_1 = scheduler.getPerformArgs(overallTask, opt.block); agentStubMap.each(function(stub) { stub.perform(performArgs_1); }), overallTask.perform(performArgs_1) && (unfinished = !0); } else seriesTaskMap && seriesTaskMap.each(function(task, pipelineId) { needSetDirty(opt, task) && task.dirty(); var performArgs = scheduler.getPerformArgs(task, opt.block); performArgs.skip = !stageHandler.performRawSeries && ecModel.isSeriesFiltered(task.context.model), scheduler.updatePayload(task, payload), task.perform(performArgs) && (unfinished = !0); }); } }), this.unfinished = unfinished || this.unfinished; }, Scheduler.prototype.performSeriesTasks = function(ecModel) { var unfinished; ecModel.eachSeries(function(seriesModel) { unfinished = seriesModel.dataTask.perform() || unfinished; }), this.unfinished = unfinished || this.unfinished; }, Scheduler.prototype.plan = function() { this._pipelineMap.each(function(pipeline) { var task = pipeline.tail; do { if (task.__block) { pipeline.blockIndex = task.__idxInPipeline; break; } task = task.getUpstream(); }while (task) }); }, Scheduler.prototype.updatePayload = function(task, payload) { 'remain' !== payload && (task.context.payload = payload); }, Scheduler.prototype._createSeriesStageTask = function(stageHandler, stageHandlerRecord, ecModel, api) { var scheduler = this, oldSeriesTaskMap = stageHandlerRecord.seriesTaskMap, newSeriesTaskMap = stageHandlerRecord.seriesTaskMap = createHashMap(), seriesType = stageHandler.seriesType, getTargetSeries = stageHandler.getTargetSeries; function create(seriesModel) { var pipelineId = seriesModel.uid, task = newSeriesTaskMap.set(pipelineId, oldSeriesTaskMap && oldSeriesTaskMap.get(pipelineId) || createTask({ plan: seriesTaskPlan, reset: seriesTaskReset, count: seriesTaskCount })); task.context = { model: seriesModel, ecModel: ecModel, api: api, useClearVisual: stageHandler.isVisual && !stageHandler.isLayout, plan: stageHandler.plan, reset: stageHandler.reset, scheduler: scheduler }, scheduler._pipe(seriesModel, task); } stageHandler.createOnAllSeries ? ecModel.eachRawSeries(create) : seriesType ? ecModel.eachRawSeriesByType(seriesType, create) : getTargetSeries && getTargetSeries(ecModel, api).each(create); }, Scheduler.prototype._createOverallStageTask = function(stageHandler, stageHandlerRecord, ecModel, api) { var scheduler = this, overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask || createTask({ reset: overallTaskReset }); overallTask.context = { ecModel: ecModel, api: api, overallReset: stageHandler.overallReset, scheduler: scheduler }; var oldAgentStubMap = overallTask.agentStubMap, newAgentStubMap = overallTask.agentStubMap = createHashMap(), seriesType = stageHandler.seriesType, getTargetSeries = stageHandler.getTargetSeries, overallProgress = !0, shouldOverallTaskDirty = !1, errMsg = ''; function createStub(seriesModel) { var pipelineId = seriesModel.uid, stub = newAgentStubMap.set(pipelineId, oldAgentStubMap && oldAgentStubMap.get(pipelineId) || (shouldOverallTaskDirty = !0, createTask({ reset: stubReset, onDirty: stubOnDirty }))); stub.context = { model: seriesModel, overallProgress: overallProgress }, stub.agent = overallTask, stub.__block = overallProgress, scheduler._pipe(seriesModel, stub); } errMsg = '"createOnAllSeries" do not supported for "overallReset", becuase it will block all streams.', assert(!stageHandler.createOnAllSeries, errMsg), seriesType ? ecModel.eachRawSeriesByType(seriesType, createStub) : getTargetSeries ? getTargetSeries(ecModel, api).each(createStub) : (overallProgress = !1, each(ecModel.getSeries(), createStub)), shouldOverallTaskDirty && overallTask.dirty(); }, Scheduler.prototype._pipe = function(seriesModel, task) { var pipelineId = seriesModel.uid, pipeline = this._pipelineMap.get(pipelineId); pipeline.head || (pipeline.head = task), pipeline.tail && pipeline.tail.pipe(task), pipeline.tail = task, task.__idxInPipeline = pipeline.count++, task.__pipeline = pipeline; }, Scheduler.wrapStageHandler = function(stageHandler, visualType) { return isFunction(stageHandler) && (stageHandler = { overallReset: stageHandler, seriesType: function(legacyFunc) { seriesType = null; try { legacyFunc(ecModelMock, apiMock); } catch (e) {} return seriesType; }(stageHandler) }), stageHandler.uid = getUID('stageHandler'), visualType && (stageHandler.visualType = visualType), stageHandler; }, Scheduler; }(); function overallTaskReset(context) { context.overallReset(context.ecModel, context.api, context.payload); } function stubReset(context) { return context.overallProgress && stubProgress; } function stubProgress() { this.agent.dirty(), this.getDownstream().dirty(); } function stubOnDirty() { this.agent && this.agent.dirty(); } function seriesTaskPlan(context) { return context.plan ? context.plan(context.model, context.ecModel, context.api, context.payload) : null; } function seriesTaskReset(context) { context.useClearVisual && context.data.clearAllVisual(); var resetDefines = context.resetDefines = normalizeToArray(context.reset(context.model, context.ecModel, context.api, context.payload)); return resetDefines.length > 1 ? map(resetDefines, function(v, idx) { return makeSeriesTaskProgress(idx); }) : singleSeriesTaskProgress; } var singleSeriesTaskProgress = makeSeriesTaskProgress(0); function makeSeriesTaskProgress(resetDefineIdx) { return function(params, context) { var data = context.data, resetDefine = context.resetDefines[resetDefineIdx]; if (resetDefine && resetDefine.dataEach) for(var i = params.start; i < params.end; i++)resetDefine.dataEach(data, i); else resetDefine && resetDefine.progress && resetDefine.progress(params, data); }; } function seriesTaskCount(context) { return context.data.count(); } var ecModelMock = {}, apiMock = {}; function mockMethods(target, Clz) { for(var name_1 in Clz.prototype)target[name_1] = noop; } mockMethods(ecModelMock, GlobalModel), mockMethods(apiMock, ExtensionAPI), ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function(type) { seriesType = type; }, ecModelMock.eachComponent = function(cond) { 'series' === cond.mainType && cond.subType && (seriesType = cond.subType); }; var colorAll = [ '#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF' ], contrastColor = '#B9B8CE', backgroundColor = '#100C2A', axisCommon = function() { return { axisLine: { lineStyle: { color: contrastColor } }, splitLine: { lineStyle: { color: '#484753' } }, splitArea: { areaStyle: { color: [ 'rgba(255,255,255,0.02)', 'rgba(255,255,255,0.05)' ] } }, minorSplitLine: { lineStyle: { color: '#20203B' } } }; }, colorPalette = [ '#4992ff', '#7cffb2', '#fddd60', '#ff6e76', '#58d9f9', '#05c091', '#ff8a45', '#8d48e3', '#dd79ff' ], theme1 = { darkMode: !0, color: colorPalette, backgroundColor: backgroundColor, axisPointer: { lineStyle: { color: '#817f91' }, crossStyle: { color: '#817f91' }, label: { color: '#fff' } }, legend: { textStyle: { color: contrastColor } }, textStyle: { color: contrastColor }, title: { textStyle: { color: '#EEF1FA' }, subtextStyle: { color: '#B9B8CE' } }, toolbox: { iconStyle: { borderColor: contrastColor } }, dataZoom: { borderColor: '#71708A', textStyle: { color: contrastColor }, brushStyle: { color: 'rgba(135,163,206,0.3)' }, handleStyle: { color: '#353450', borderColor: '#C5CBE3' }, moveHandleStyle: { color: '#B0B6C3', opacity: 0.3 }, fillerColor: 'rgba(135,163,206,0.2)', emphasis: { handleStyle: { borderColor: '#91B7F2', color: '#4D587D' }, moveHandleStyle: { color: '#636D9A', opacity: 0.7 } }, dataBackground: { lineStyle: { color: '#71708A', width: 1 }, areaStyle: { color: '#71708A' } }, selectedDataBackground: { lineStyle: { color: '#87A3CE' }, areaStyle: { color: '#87A3CE' } } }, visualMap: { textStyle: { color: contrastColor } }, timeline: { lineStyle: { color: contrastColor }, label: { color: contrastColor }, controlStyle: { color: contrastColor, borderColor: contrastColor } }, calendar: { itemStyle: { color: backgroundColor }, dayLabel: { color: contrastColor }, monthLabel: { color: contrastColor }, yearLabel: { color: contrastColor } }, timeAxis: axisCommon(), logAxis: axisCommon(), valueAxis: axisCommon(), categoryAxis: axisCommon(), line: { symbol: 'circle' }, graph: { color: colorPalette }, gauge: { title: { color: contrastColor }, axisLine: { lineStyle: { color: [ [ 1, 'rgba(207,212,219,0.2)' ] ] } }, axisLabel: { color: contrastColor }, detail: { color: '#EEF1FA' } }, candlestick: { itemStyle: { color: '#f64e56', color0: '#54ea92', borderColor: '#f64e56', borderColor0: '#54ea92' } } }; theme1.categoryAxis.splitLine.show = !1; var ECEventProcessor = function() { function ECEventProcessor() {} return ECEventProcessor.prototype.normalizeQuery = function(query) { var cptQuery = {}, dataQuery = {}, otherQuery = {}; if (isString(query)) { var condCptType = parseClassType(query); cptQuery.mainType = condCptType.main || null, cptQuery.subType = condCptType.sub || null; } else { var suffixes_1 = [ 'Index', 'Name', 'Id' ], dataKeys_1 = { name: 1, dataIndex: 1, dataType: 1 }; each(query, function(val, key) { for(var reserved = !1, i = 0; i < suffixes_1.length; i++){ var propSuffix = suffixes_1[i], suffixPos = key.lastIndexOf(propSuffix); if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) { var mainType = key.slice(0, suffixPos); 'data' !== mainType && (cptQuery.mainType = mainType, cptQuery[propSuffix.toLowerCase()] = val, reserved = !0); } } dataKeys_1.hasOwnProperty(key) && (dataQuery[key] = val, reserved = !0), reserved || (otherQuery[key] = val); }); } return { cptQuery: cptQuery, dataQuery: dataQuery, otherQuery: otherQuery }; }, ECEventProcessor.prototype.filter = function(eventType, query) { var eventInfo = this.eventInfo; if (!eventInfo) return !0; var targetEl = eventInfo.targetEl, packedEvent = eventInfo.packedEvent, model = eventInfo.model, view = eventInfo.view; if (!model || !view) return !0; var cptQuery = query.cptQuery, dataQuery = query.dataQuery; return check(cptQuery, model, 'mainType') && check(cptQuery, model, 'subType') && check(cptQuery, model, 'index', 'componentIndex') && check(cptQuery, model, 'name') && check(cptQuery, model, 'id') && check(dataQuery, packedEvent, 'name') && check(dataQuery, packedEvent, 'dataIndex') && check(dataQuery, packedEvent, 'dataType') && (!view.filterForExposedEvent || view.filterForExposedEvent(eventType, query.otherQuery, targetEl, packedEvent)); function check(query, host, prop, propOnHost) { return null == query[prop] || host[propOnHost || prop] === query[prop]; } }, ECEventProcessor.prototype.afterTrigger = function() { this.eventInfo = null; }, ECEventProcessor; }(); function getItemVisualFromData(data, dataIndex, key) { switch(key){ case 'color': return data.getItemVisual(dataIndex, 'style')[data.getVisual('drawType')]; case 'opacity': return data.getItemVisual(dataIndex, 'style').opacity; case 'symbol': case 'symbolSize': case 'liftZ': return data.getItemVisual(dataIndex, key); default: console.warn("Unknown visual type " + key); } } function getVisualFromData(data, key) { switch(key){ case 'color': return data.getVisual('style')[data.getVisual('drawType')]; case 'opacity': return data.getVisual('style').opacity; case 'symbol': case 'symbolSize': case 'liftZ': return data.getVisual(key); default: console.warn("Unknown visual type " + key); } } function setItemVisualFromData(data, dataIndex, key, value) { switch(key){ case 'color': data.ensureUniqueItemVisual(dataIndex, 'style')[data.getVisual('drawType')] = value, data.setItemVisual(dataIndex, 'colorFromPalette', !1); break; case 'opacity': data.ensureUniqueItemVisual(dataIndex, 'style').opacity = value; break; case 'symbol': case 'symbolSize': case 'liftZ': data.setItemVisual(dataIndex, key, value); break; default: console.warn("Unknown visual type " + key); } } var PI2$6 = 2 * Math.PI, CMD$3 = PathProxy.CMD, DEFAULT_SEARCH_SPACE = [ 'top', 'right', 'bottom', 'left' ]; function projectPointToLine(x1, y1, x2, y2, x, y, out, limitToEnds) { var dx1 = x2 - x1, dy1 = y2 - y1, lineLen = Math.sqrt(dx1 * dx1 + dy1 * dy1), t = ((x - x1) * (dx1 /= lineLen) + (y - y1) * (dy1 /= lineLen)) / lineLen; limitToEnds && (t = Math.min(Math.max(t, 0), 1)), t *= lineLen; var ox = out[0] = x1 + t * dx1, oy = out[1] = y1 + t * dy1; return Math.sqrt((ox - x) * (ox - x) + (oy - y) * (oy - y)); } function projectPointToRect(x1, y1, width, height, x, y, out) { width < 0 && (x1 += width, width = -width), height < 0 && (y1 += height, height = -height); var x2 = x1 + width, y2 = y1 + height, ox = out[0] = Math.min(Math.max(x, x1), x2), oy = out[1] = Math.min(Math.max(y, y1), y2); return Math.sqrt((ox - x) * (ox - x) + (oy - y) * (oy - y)); } var tmpPt = [], pt0 = new Point(), pt1 = new Point(), pt2 = new Point(), dir = new Point(), dir2 = new Point(); function updateLabelLinePoints(target, labelLineModel) { if (target) { var labelLine = target.getTextGuideLine(), label = target.getTextContent(); if (label && labelLine) { var labelGuideConfig = target.textGuideLineConfig || {}, points = [ [ 0, 0 ], [ 0, 0 ], [ 0, 0 ] ], searchSpace = labelGuideConfig.candidates || DEFAULT_SEARCH_SPACE, labelRect = label.getBoundingRect().clone(); labelRect.applyTransform(label.getComputedTransform()); var minDist = 1 / 0, anchorPoint = labelGuideConfig.anchor, targetTransform = target.getComputedTransform(), targetInversedTransform = targetTransform && invert([], targetTransform), len = labelLineModel.get('length2') || 0; anchorPoint && pt2.copy(anchorPoint); for(var i = 0; i < searchSpace.length; i++){ !function(pos, distance, rect, outPt, outDir) { var width = rect.width, height = rect.height; switch(pos){ case 'top': outPt.set(rect.x + width / 2, rect.y - distance), outDir.set(0, -1); break; case 'bottom': outPt.set(rect.x + width / 2, rect.y + height + distance), outDir.set(0, 1); break; case 'left': outPt.set(rect.x - distance, rect.y + height / 2), outDir.set(-1, 0); break; case 'right': outPt.set(rect.x + width + distance, rect.y + height / 2), outDir.set(1, 0); } }(searchSpace[i], 0, labelRect, pt0, dir), Point.scaleAndAdd(pt1, pt0, dir, len), pt1.transform(targetInversedTransform); var boundingRect = target.getBoundingRect(), dist = anchorPoint ? anchorPoint.distance(pt1) : target instanceof Path ? function(pt, path, out) { for(var x1, y1, xi = 0, yi = 0, x0 = 0, y0 = 0, minDist = 1 / 0, data = path.data, x = pt.x, y = pt.y, i = 0; i < data.length;){ var cmd = data[i++]; 1 === i && (xi = data[i], yi = data[i + 1], x0 = xi, y0 = yi); var d = minDist; switch(cmd){ case CMD$3.M: x0 = data[i++], y0 = data[i++], xi = x0, yi = y0; break; case CMD$3.L: d = projectPointToLine(xi, yi, data[i], data[i + 1], x, y, tmpPt, !0), xi = data[i++], yi = data[i++]; break; case CMD$3.C: d = cubicProjectPoint(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], x, y, tmpPt), xi = data[i++], yi = data[i++]; break; case CMD$3.Q: d = quadraticProjectPoint(xi, yi, data[i++], data[i++], data[i], data[i + 1], x, y, tmpPt), xi = data[i++], yi = data[i++]; break; case CMD$3.A: var cx = data[i++], cy = data[i++], rx = data[i++], ry = data[i++], theta = data[i++], dTheta = data[i++]; i += 1; var anticlockwise = !!(1 - data[i++]); x1 = Math.cos(theta) * rx + cx, y1 = Math.sin(theta) * ry + cy, i <= 1 && (x0 = x1, y0 = y1); var _x = (x - cx) * ry / rx + cx; d = function(cx, cy, r, startAngle, endAngle, anticlockwise, x, y, out) { var d = Math.sqrt((x -= cx) * x + (y -= cy) * y), ox = (x /= d) * r + cx, oy = (y /= d) * r + cy; if (Math.abs(startAngle - endAngle) % PI2$6 < 1e-4) return out[0] = ox, out[1] = oy, d - r; if (anticlockwise) { var tmp = startAngle; startAngle = normalizeRadian(endAngle), endAngle = normalizeRadian(tmp); } else startAngle = normalizeRadian(startAngle), endAngle = normalizeRadian(endAngle); startAngle > endAngle && (endAngle += PI2$6); var angle = Math.atan2(y, x); if (angle < 0 && (angle += PI2$6), angle >= startAngle && angle <= endAngle || angle + PI2$6 >= startAngle && angle + PI2$6 <= endAngle) return out[0] = ox, out[1] = oy, d - r; var x1 = r * Math.cos(startAngle) + cx, y1 = r * Math.sin(startAngle) + cy, x2 = r * Math.cos(endAngle) + cx, y2 = r * Math.sin(endAngle) + cy, d1 = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y), d2 = (x2 - x) * (x2 - x) + (y2 - y) * (y2 - y); return d1 < d2 ? (out[0] = x1, out[1] = y1, Math.sqrt(d1)) : (out[0] = x2, out[1] = y2, Math.sqrt(d2)); }(cx, cy, ry, theta, theta + dTheta, anticlockwise, _x, y, tmpPt), xi = Math.cos(theta + dTheta) * rx + cx, yi = Math.sin(theta + dTheta) * ry + cy; break; case CMD$3.R: d = projectPointToRect(x0 = xi = data[i++], y0 = yi = data[i++], data[i++], data[i++], x, y, tmpPt); break; case CMD$3.Z: d = projectPointToLine(xi, yi, x0, y0, x, y, tmpPt, !0), xi = x0, yi = y0; } d < minDist && (minDist = d, out.set(tmpPt[0], tmpPt[1])); } return minDist; }(pt1, target.path, pt2) : function(pt, rect, out) { var dist = projectPointToRect(rect.x, rect.y, rect.width, rect.height, pt.x, pt.y, tmpPt); return out.set(tmpPt[0], tmpPt[1]), dist; }(pt1, boundingRect, pt2); dist < minDist && (minDist = dist, pt1.transform(targetTransform), pt2.transform(targetTransform), pt2.toArray(points[0]), pt1.toArray(points[1]), pt0.toArray(points[2])); } limitTurnAngle(points, labelLineModel.get('minTurnAngle')), labelLine.setShape({ points: points }); } } } var tmpArr = [], tmpProjPoint = new Point(); function limitTurnAngle(linePoints, minTurnAngle) { if (minTurnAngle <= 180 && minTurnAngle > 0) { minTurnAngle = minTurnAngle / 180 * Math.PI, pt0.fromArray(linePoints[0]), pt1.fromArray(linePoints[1]), pt2.fromArray(linePoints[2]), Point.sub(dir, pt0, pt1), Point.sub(dir2, pt2, pt1); var len1 = dir.len(), len2 = dir2.len(); if (!(len1 < 1e-3) && !(len2 < 1e-3) && (dir.scale(1 / len1), dir2.scale(1 / len2), Math.cos(minTurnAngle) < dir.dot(dir2))) { var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, !1); tmpProjPoint.fromArray(tmpArr), tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI - minTurnAngle)); var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y); if (isNaN(t)) return; t < 0 ? Point.copy(tmpProjPoint, pt1) : t > 1 && Point.copy(tmpProjPoint, pt2), tmpProjPoint.toArray(linePoints[1]); } } } function setLabelLineState(labelLine, ignore, stateName, stateModel) { var isNormal = 'normal' === stateName, stateObj = isNormal ? labelLine : labelLine.ensureState(stateName); stateObj.ignore = ignore; var smooth = stateModel.get('smooth'); smooth && !0 === smooth && (smooth = 0.3), stateObj.shape = stateObj.shape || {}, smooth > 0 && (stateObj.shape.smooth = smooth); var styleObj = stateModel.getModel('lineStyle').getLineStyle(); isNormal ? labelLine.useStyle(styleObj) : stateObj.style = styleObj; } function buildLabelLinePath(path, shape) { var smooth = shape.smooth, points = shape.points; if (points) { if (path.moveTo(points[0][0], points[0][1]), smooth > 0 && points.length >= 3) { var len1 = distance(points[0], points[1]), len2 = distance(points[1], points[2]); if (!len1 || !len2) { path.lineTo(points[1][0], points[1][1]), path.lineTo(points[2][0], points[2][1]); return; } var moveLen = Math.min(len1, len2) * smooth, midPoint0 = lerp([], points[1], points[0], moveLen / len1), midPoint2 = lerp([], points[1], points[2], moveLen / len2), midPoint1 = lerp([], midPoint0, midPoint2, 0.5); path.bezierCurveTo(midPoint0[0], midPoint0[1], midPoint0[0], midPoint0[1], midPoint1[0], midPoint1[1]), path.bezierCurveTo(midPoint2[0], midPoint2[1], midPoint2[0], midPoint2[1], points[2][0], points[2][1]); } else for(var i = 1; i < points.length; i++)path.lineTo(points[i][0], points[i][1]); } } function setLabelLineStyle(targetEl, statesModels, defaultStyle) { var labelLine = targetEl.getTextGuideLine(), label = targetEl.getTextContent(); if (!label) { labelLine && targetEl.removeTextGuideLine(); return; } for(var normalModel = statesModels.normal, showNormal = normalModel.get('show'), labelIgnoreNormal = label.ignore, i = 0; i < DISPLAY_STATES.length; i++){ var stateName = DISPLAY_STATES[i], stateModel = statesModels[stateName], isNormal = 'normal' === stateName; if (stateModel) { var stateShow = stateModel.get('show'); if ((isNormal ? labelIgnoreNormal : retrieve2(label.states[stateName] && label.states[stateName].ignore, labelIgnoreNormal)) || !retrieve2(stateShow, showNormal)) { var stateObj = isNormal ? labelLine : labelLine && labelLine.states.normal; stateObj && (stateObj.ignore = !0); continue; } !labelLine && (labelLine = new Polyline(), targetEl.setTextGuideLine(labelLine), isNormal || !labelIgnoreNormal && showNormal || setLabelLineState(labelLine, !0, 'normal', statesModels.normal), targetEl.stateProxy && (labelLine.stateProxy = targetEl.stateProxy)), setLabelLineState(labelLine, !1, stateName, stateModel); } } if (labelLine) { defaults(labelLine.style, defaultStyle), labelLine.style.fill = null; var showAbove = normalModel.get('showAbove'); (targetEl.textGuideLineConfig = targetEl.textGuideLineConfig || {}).showAbove = showAbove || !1, labelLine.buildPath = buildLabelLinePath; } } function getLabelLineStatesModels(itemModel, labelLineName) { labelLineName = labelLineName || 'labelLine'; for(var statesModels = { normal: itemModel.getModel(labelLineName) }, i = 0; i < SPECIAL_STATES.length; i++){ var stateName = SPECIAL_STATES[i]; statesModels[stateName] = itemModel.getModel([ stateName, labelLineName ]); } return statesModels; } function shiftLayout(list, xyDim, sizeDim, minBound, maxBound, balanceShift) { var delta, minGap, maxGap, len = list.length; if (!(len < 2)) { list.sort(function(a, b) { return a.rect[xyDim] - b.rect[xyDim]; }); for(var lastPos = 0, adjusted = !1, totalShifts = 0, i = 0; i < len; i++){ var item = list[i], rect = item.rect; (delta = rect[xyDim] - lastPos) < 0 && (rect[xyDim] -= delta, item.label[xyDim] -= delta, adjusted = !0), totalShifts += Math.max(-delta, 0), lastPos = rect[xyDim] + rect[sizeDim]; } totalShifts > 0 && balanceShift && shiftList(-totalShifts / len, 0, len); var first = list[0], last = list[len - 1]; return updateMinMaxGap(), minGap < 0 && squeezeGaps(-minGap, 0.8), maxGap < 0 && squeezeGaps(maxGap, 0.8), updateMinMaxGap(), takeBoundsGap(minGap, maxGap, 1), takeBoundsGap(maxGap, minGap, -1), updateMinMaxGap(), minGap < 0 && squeezeWhenBailout(-minGap), maxGap < 0 && squeezeWhenBailout(maxGap), adjusted; } function updateMinMaxGap() { minGap = first.rect[xyDim] - minBound, maxGap = maxBound - last.rect[xyDim] - last.rect[sizeDim]; } function takeBoundsGap(gapThisBound, gapOtherBound, moveDir) { if (gapThisBound < 0) { var moveFromMaxGap = Math.min(gapOtherBound, -gapThisBound); if (moveFromMaxGap > 0) { shiftList(moveFromMaxGap * moveDir, 0, len); var remained = moveFromMaxGap + gapThisBound; remained < 0 && squeezeGaps(-remained * moveDir, 1); } else squeezeGaps(-gapThisBound * moveDir, 1); } } function shiftList(delta, start, end) { 0 !== delta && (adjusted = !0); for(var i = start; i < end; i++){ var item = list[i], rect = item.rect; rect[xyDim] += delta, item.label[xyDim] += delta; } } function squeezeGaps(delta, maxSqeezePercent) { for(var gaps = [], totalGaps = 0, i = 1; i < len; i++){ var prevItemRect = list[i - 1].rect, gap = Math.max(list[i].rect[xyDim] - prevItemRect[xyDim] - prevItemRect[sizeDim], 0); gaps.push(gap), totalGaps += gap; } if (totalGaps) { var squeezePercent = Math.min(Math.abs(delta) / totalGaps, maxSqeezePercent); if (delta > 0) for(var i = 0; i < len - 1; i++){ var movement = gaps[i] * squeezePercent; shiftList(movement, 0, i + 1); } else for(var i = len - 1; i > 0; i--){ var movement = gaps[i - 1] * squeezePercent; shiftList(-movement, i, len); } } } function squeezeWhenBailout(delta) { for(var dir = delta < 0 ? -1 : 1, moveForEachLabel = Math.ceil((delta = Math.abs(delta)) / (len - 1)), i = 0; i < len - 1; i++)if (dir > 0 ? shiftList(moveForEachLabel, 0, i + 1) : shiftList(-moveForEachLabel, len - i - 1, len), (delta -= moveForEachLabel) <= 0) return; } } function shiftLayoutOnY(list, topBound, bottomBound, balanceShift) { return shiftLayout(list, 'y', 'height', topBound, bottomBound, balanceShift); } var LABEL_OPTION_TO_STYLE_KEYS = [ 'align', 'verticalAlign', 'width', 'height', 'fontSize' ], dummyTransformable = new Transformable(), labelLayoutInnerStore = makeInner(), labelLineAnimationStore = makeInner(); function extendWithKeys(target, source, keys) { for(var i = 0; i < keys.length; i++){ var key = keys[i]; null != source[key] && (target[key] = source[key]); } } var LABEL_LAYOUT_PROPS = [ 'x', 'y', 'rotation' ], LabelManager = function() { function LabelManager() { this._labelList = [], this._chartViewList = []; } return LabelManager.prototype.clearLabels = function() { this._labelList = [], this._chartViewList = []; }, LabelManager.prototype._addLabel = function(dataIndex, dataType, seriesModel, label, layoutOption) { var hostRect, labelStyle = label.style, textConfig = label.__hostTarget.textConfig || {}, labelTransform = label.getComputedTransform(), labelRect = label.getBoundingRect().plain(); BoundingRect.applyTransform(labelRect, labelRect, labelTransform), labelTransform ? dummyTransformable.setLocalTransform(labelTransform) : (dummyTransformable.x = dummyTransformable.y = dummyTransformable.rotation = dummyTransformable.originX = dummyTransformable.originY = 0, dummyTransformable.scaleX = dummyTransformable.scaleY = 1); var host = label.__hostTarget; if (host) { hostRect = host.getBoundingRect().plain(); var transform = host.getComputedTransform(); BoundingRect.applyTransform(hostRect, hostRect, transform); } var labelGuide = hostRect && host.getTextGuideLine(); this._labelList.push({ label: label, labelLine: labelGuide, seriesModel: seriesModel, dataIndex: dataIndex, dataType: dataType, layoutOption: layoutOption, computedLayoutOption: null, rect: labelRect, hostRect: hostRect, priority: hostRect ? hostRect.width * hostRect.height : 0, defaultAttr: { ignore: label.ignore, labelGuideIgnore: labelGuide && labelGuide.ignore, x: dummyTransformable.x, y: dummyTransformable.y, scaleX: dummyTransformable.scaleX, scaleY: dummyTransformable.scaleY, rotation: dummyTransformable.rotation, style: { x: labelStyle.x, y: labelStyle.y, align: labelStyle.align, verticalAlign: labelStyle.verticalAlign, width: labelStyle.width, height: labelStyle.height, fontSize: labelStyle.fontSize }, cursor: label.cursor, attachedPos: textConfig.position, attachedRot: textConfig.rotation } }); }, LabelManager.prototype.addLabelsOfSeries = function(chartView) { var _this = this; this._chartViewList.push(chartView); var seriesModel = chartView.__model, layoutOption = seriesModel.get('labelLayout'); (isFunction(layoutOption) || keys(layoutOption).length) && chartView.group.traverse(function(child) { if (child.ignore) return !0; var textEl = child.getTextContent(), ecData = getECData(child); textEl && !textEl.disableLabelLayout && _this._addLabel(ecData.dataIndex, ecData.dataType, seriesModel, textEl, layoutOption); }); }, LabelManager.prototype.updateLayoutConfig = function(api) { for(var width = api.getWidth(), height = api.getHeight(), i = 0; i < this._labelList.length; i++){ var labelItem = this._labelList[i], label = labelItem.label, hostEl = label.__hostTarget, defaultLabelAttr = labelItem.defaultAttr, layoutOption = void 0; layoutOption = (layoutOption = 'function' == typeof labelItem.layoutOption ? labelItem.layoutOption(function(labelItem, hostEl) { var label = labelItem.label, labelLine = hostEl && hostEl.getTextGuideLine(); return { dataIndex: labelItem.dataIndex, dataType: labelItem.dataType, seriesIndex: labelItem.seriesModel.seriesIndex, text: labelItem.label.style.text, rect: labelItem.hostRect, labelRect: labelItem.rect, align: label.style.align, verticalAlign: label.style.verticalAlign, labelLinePoints: function(points) { if (points) { for(var newPoints = [], i = 0; i < points.length; i++)newPoints.push(points[i].slice()); return newPoints; } }(labelLine && labelLine.shape.points) }; }(labelItem, hostEl)) : labelItem.layoutOption) || {}, labelItem.computedLayoutOption = layoutOption; var degreeToRadian = Math.PI / 180; hostEl && hostEl.setTextConfig({ local: !1, position: null != layoutOption.x || null != layoutOption.y ? null : defaultLabelAttr.attachedPos, rotation: null != layoutOption.rotate ? layoutOption.rotate * degreeToRadian : defaultLabelAttr.attachedRot, offset: [ layoutOption.dx || 0, layoutOption.dy || 0 ] }); var needsUpdateLabelLine = !1; if (null != layoutOption.x ? (label.x = parsePercent$1(layoutOption.x, width), label.setStyle('x', 0), needsUpdateLabelLine = !0) : (label.x = defaultLabelAttr.x, label.setStyle('x', defaultLabelAttr.style.x)), null != layoutOption.y ? (label.y = parsePercent$1(layoutOption.y, height), label.setStyle('y', 0), needsUpdateLabelLine = !0) : (label.y = defaultLabelAttr.y, label.setStyle('y', defaultLabelAttr.style.y)), layoutOption.labelLinePoints) { var guideLine = hostEl.getTextGuideLine(); guideLine && (guideLine.setShape({ points: layoutOption.labelLinePoints }), needsUpdateLabelLine = !1); } labelLayoutInnerStore(label).needsUpdateLabelLine = needsUpdateLabelLine, label.rotation = null != layoutOption.rotate ? layoutOption.rotate * degreeToRadian : defaultLabelAttr.rotation, label.scaleX = defaultLabelAttr.scaleX, label.scaleY = defaultLabelAttr.scaleY; for(var k = 0; k < LABEL_OPTION_TO_STYLE_KEYS.length; k++){ var key = LABEL_OPTION_TO_STYLE_KEYS[k]; label.setStyle(key, null != layoutOption[key] ? layoutOption[key] : defaultLabelAttr.style[key]); } if (layoutOption.draggable) { if (label.draggable = !0, label.cursor = 'move', hostEl) { var hostModel = labelItem.seriesModel; null != labelItem.dataIndex && (hostModel = labelItem.seriesModel.getData(labelItem.dataType).getItemModel(labelItem.dataIndex)), label.on('drag', function(el, labelLineModel) { return function() { updateLabelLinePoints(el, labelLineModel); }; }(hostEl, hostModel.getModel('labelLine'))); } } else label.off('drag'), label.cursor = defaultLabelAttr.cursor; } }, LabelManager.prototype.layout = function(api) { var width = api.getWidth(), height = api.getHeight(), labelList = function(input) { for(var list = [], i = 0; i < input.length; i++){ var rawItem = input[i]; if (!rawItem.defaultAttr.ignore) { var label = rawItem.label, transform = label.getComputedTransform(), localRect = label.getBoundingRect(), isAxisAligned = !transform || transform[1] < 1e-5 && transform[2] < 1e-5, minMargin = label.style.margin || 0, globalRect = localRect.clone(); globalRect.applyTransform(transform), globalRect.x -= minMargin / 2, globalRect.y -= minMargin / 2, globalRect.width += minMargin, globalRect.height += minMargin; var obb = isAxisAligned ? new OrientedBoundingRect(localRect, transform) : null; list.push({ label: label, labelLine: rawItem.labelLine, rect: globalRect, localRect: localRect, obb: obb, priority: rawItem.priority, defaultAttr: rawItem.defaultAttr, layoutOption: rawItem.computedLayoutOption, axisAligned: isAxisAligned, transform: transform }); } } return list; }(this._labelList), labelsNeedsAdjustOnX = filter(labelList, function(item) { return 'shiftX' === item.layoutOption.moveOverlap; }), labelsNeedsAdjustOnY = filter(labelList, function(item) { return 'shiftY' === item.layoutOption.moveOverlap; }); shiftLayout(labelsNeedsAdjustOnX, 'x', 'width', 0, width, void 0), shiftLayoutOnY(labelsNeedsAdjustOnY, 0, height), function(labelList) { var displayedLabels = []; labelList.sort(function(a, b) { return b.priority - a.priority; }); var globalRect = new BoundingRect(0, 0, 0, 0); function hideEl(el) { if (!el.ignore) { var emphasisState = el.ensureState('emphasis'); null == emphasisState.ignore && (emphasisState.ignore = !1); } el.ignore = !0; } for(var i = 0; i < labelList.length; i++){ var labelItem = labelList[i], isAxisAligned = labelItem.axisAligned, localRect = labelItem.localRect, transform = labelItem.transform, label = labelItem.label, labelLine = labelItem.labelLine; globalRect.copy(labelItem.rect), globalRect.width -= 0.1, globalRect.height -= 0.1, globalRect.x += 0.05, globalRect.y += 0.05; for(var obb = labelItem.obb, overlapped = !1, j = 0; j < displayedLabels.length; j++){ var existsTextCfg = displayedLabels[j]; if (globalRect.intersect(existsTextCfg.rect) && (isAxisAligned && existsTextCfg.axisAligned || (existsTextCfg.obb || (existsTextCfg.obb = new OrientedBoundingRect(existsTextCfg.localRect, existsTextCfg.transform)), obb || (obb = new OrientedBoundingRect(localRect, transform)), obb.intersect(existsTextCfg.obb)))) { overlapped = !0; break; } } overlapped ? (hideEl(label), labelLine && hideEl(labelLine)) : (label.attr('ignore', labelItem.defaultAttr.ignore), labelLine && labelLine.attr('ignore', labelItem.defaultAttr.labelGuideIgnore), displayedLabels.push(labelItem)); } }(filter(labelList, function(item) { return item.layoutOption.hideOverlap; })); }, LabelManager.prototype.processLabelsOverall = function() { var _this = this; each(this._chartViewList, function(chartView) { var seriesModel = chartView.__model, ignoreLabelLineUpdate = chartView.ignoreLabelLineUpdate, animationEnabled = seriesModel.isAnimationEnabled(); chartView.group.traverse(function(child) { if (child.ignore) return !0; var needsUpdateLabelLine = !ignoreLabelLineUpdate, label = child.getTextContent(); !needsUpdateLabelLine && label && (needsUpdateLabelLine = labelLayoutInnerStore(label).needsUpdateLabelLine), needsUpdateLabelLine && _this._updateLabelLine(child, seriesModel), animationEnabled && _this._animateLabels(child, seriesModel); }); }); }, LabelManager.prototype._updateLabelLine = function(el, seriesModel) { var textEl = el.getTextContent(), ecData = getECData(el), dataIndex = ecData.dataIndex; if (textEl && null != dataIndex) { var data = seriesModel.getData(ecData.dataType), itemModel = data.getItemModel(dataIndex), defaultStyle = {}, visualStyle = data.getItemVisual(dataIndex, 'style'), visualType = data.getVisual('drawType'); defaultStyle.stroke = visualStyle[visualType]; var labelLineModel = itemModel.getModel('labelLine'); setLabelLineStyle(el, getLabelLineStatesModels(itemModel), defaultStyle), updateLabelLinePoints(el, labelLineModel); } }, LabelManager.prototype._animateLabels = function(el, seriesModel) { var textEl = el.getTextContent(), guideLine = el.getTextGuideLine(); if (textEl && !textEl.ignore && !textEl.invisible && !el.disableLabelAnimation && !isElementRemoved(el)) { var layoutStore = labelLayoutInnerStore(textEl), oldLayout = layoutStore.oldLayout, ecData = getECData(el), dataIndex = ecData.dataIndex, newProps = { x: textEl.x, y: textEl.y, rotation: textEl.rotation }, data = seriesModel.getData(ecData.dataType); if (oldLayout) { textEl.attr(oldLayout); var prevStates = el.prevStates; prevStates && (indexOf(prevStates, 'select') >= 0 && textEl.attr(layoutStore.oldLayoutSelect), indexOf(prevStates, 'emphasis') >= 0 && textEl.attr(layoutStore.oldLayoutEmphasis)), updateProps(textEl, newProps, seriesModel, dataIndex); } else if (textEl.attr(newProps), !labelInner(textEl).valueAnimation) { var oldOpacity = retrieve2(textEl.style.opacity, 1); textEl.style.opacity = 0, initProps(textEl, { style: { opacity: oldOpacity } }, seriesModel, dataIndex); } if (layoutStore.oldLayout = newProps, textEl.states.select) { var layoutSelect = layoutStore.oldLayoutSelect = {}; extendWithKeys(layoutSelect, newProps, LABEL_LAYOUT_PROPS), extendWithKeys(layoutSelect, textEl.states.select, LABEL_LAYOUT_PROPS); } if (textEl.states.emphasis) { var layoutEmphasis = layoutStore.oldLayoutEmphasis = {}; extendWithKeys(layoutEmphasis, newProps, LABEL_LAYOUT_PROPS), extendWithKeys(layoutEmphasis, textEl.states.emphasis, LABEL_LAYOUT_PROPS); } animateLabelValue(textEl, dataIndex, data, seriesModel, seriesModel); } if (guideLine && !guideLine.ignore && !guideLine.invisible) { var layoutStore = labelLineAnimationStore(guideLine), oldLayout = layoutStore.oldLayout, newLayout = { points: guideLine.shape.points }; oldLayout ? (guideLine.attr({ shape: oldLayout }), updateProps(guideLine, { shape: newLayout }, seriesModel)) : (guideLine.setShape(newLayout), guideLine.style.strokePercent = 0, initProps(guideLine, { style: { strokePercent: 1 } }, seriesModel)), layoutStore.oldLayout = newLayout; } }, LabelManager; }(); function createLegacyDataSelectAction(seriesType, ecRegisterAction) { each([ [ seriesType + 'ToggleSelect', 'toggleSelect' ], [ seriesType + 'Select', 'select' ], [ seriesType + 'UnSelect', 'unselect' ] ], function(eventsMap) { ecRegisterAction(eventsMap[0], function(payload, ecModel, api) { var payload1, seriesIndices; deprecateReplaceLog((payload = extend({}, payload)).type, eventsMap[1]), api.dispatchAction(extend(payload, { type: eventsMap[1], seriesIndex: (payload1 = payload, seriesIndices = [], ecModel.eachComponent({ mainType: 'series', subType: seriesType, query: payload1 }, function(seriesModel) { seriesIndices.push(seriesModel.seriesIndex); }), seriesIndices) })); }); }); } function handleSeriesLegacySelectEvents(type, eventPostfix, ecIns, ecModel, payload) { var legacyEventName = type + eventPostfix; ecIns.isSilent(legacyEventName) || (deprecateLog("event " + legacyEventName + " is deprecated."), ecModel.eachComponent({ mainType: 'series', subType: 'pie' }, function(seriesModel) { for(var seriesIndex = seriesModel.seriesIndex, selected = payload.selected, i = 0; i < selected.length; i++)if (selected[i].seriesIndex === seriesIndex) { var data = seriesModel.getData(), dataIndex = queryDataIndex(data, payload.fromActionPayload); ecIns.trigger(legacyEventName, { type: legacyEventName, seriesId: seriesModel.id, name: isArray(dataIndex) ? data.getName(dataIndex[0]) : data.getName(dataIndex), selected: extend({}, seriesModel.option.selectedMap) }); } })); } function findEventDispatcher(target, det, returnFirstMatch) { for(var found; target && (!det(target) || (found = target, !returnFirstMatch));)target = target.__hostTarget || target.parent; return found; } var wmUniqueIndex = Math.round(9 * Math.random()), WeakMap = function() { function WeakMap() { this._id = '__ec_inner_' + wmUniqueIndex++; } return WeakMap.prototype.get = function(key) { return this._guard(key)[this._id]; }, WeakMap.prototype.set = function(key, value) { var target = this._guard(key); return 'function' == typeof Object.defineProperty ? Object.defineProperty(target, this._id, { value: value, enumerable: !1, configurable: !0 }) : target[this._id] = value, this; }, WeakMap.prototype.delete = function(key) { return !!this.has(key) && (delete this._guard(key)[this._id], !0); }, WeakMap.prototype.has = function(key) { return !!this._guard(key)[this._id]; }, WeakMap.prototype._guard = function(key) { if (key !== Object(key)) throw TypeError('Value of WeakMap is not a non-null object.'); return key; }, WeakMap; }(), Triangle = Path.extend({ type: 'triangle', shape: { cx: 0, cy: 0, width: 0, height: 0 }, buildPath: function(path, shape) { var cx = shape.cx, cy = shape.cy, width = shape.width / 2, height = shape.height / 2; path.moveTo(cx, cy - height), path.lineTo(cx + width, cy + height), path.lineTo(cx - width, cy + height), path.closePath(); } }), Diamond = Path.extend({ type: 'diamond', shape: { cx: 0, cy: 0, width: 0, height: 0 }, buildPath: function(path, shape) { var cx = shape.cx, cy = shape.cy, width = shape.width / 2, height = shape.height / 2; path.moveTo(cx, cy - height), path.lineTo(cx + width, cy), path.lineTo(cx, cy + height), path.lineTo(cx - width, cy), path.closePath(); } }), Pin = Path.extend({ type: 'pin', shape: { x: 0, y: 0, width: 0, height: 0 }, buildPath: function(path, shape) { var x = shape.x, y = shape.y, w = shape.width / 5 * 3, h = Math.max(w, shape.height), r = w / 2, dy = r * r / (h - r), cy = y - h + r + dy, angle = Math.asin(dy / r), dx = Math.cos(angle) * r, tanX = Math.sin(angle), tanY = Math.cos(angle), cpLen = 0.6 * r, cpLen2 = 0.7 * r; path.moveTo(x - dx, cy + dy), path.arc(x, cy, r, Math.PI - angle, 2 * Math.PI + angle), path.bezierCurveTo(x + dx - tanX * cpLen, cy + dy + tanY * cpLen, x, y - cpLen2, x, y), path.bezierCurveTo(x, y - cpLen2, x - dx + tanX * cpLen, cy + dy + tanY * cpLen, x - dx, cy + dy), path.closePath(); } }), Arrow = Path.extend({ type: 'arrow', shape: { x: 0, y: 0, width: 0, height: 0 }, buildPath: function(ctx, shape) { var height = shape.height, width = shape.width, x = shape.x, y = shape.y, dx = width / 3 * 2; ctx.moveTo(x, y), ctx.lineTo(x + dx, y + height), ctx.lineTo(x, y + height / 4 * 3), ctx.lineTo(x - dx, y + height), ctx.lineTo(x, y), ctx.closePath(); } }), symbolShapeMakers = { line: function(x, y, w, h, shape) { shape.x1 = x, shape.y1 = y + h / 2, shape.x2 = x + w, shape.y2 = y + h / 2; }, rect: function(x, y, w, h, shape) { shape.x = x, shape.y = y, shape.width = w, shape.height = h; }, roundRect: function(x, y, w, h, shape) { shape.x = x, shape.y = y, shape.width = w, shape.height = h, shape.r = Math.min(w, h) / 4; }, square: function(x, y, w, h, shape) { var size = Math.min(w, h); shape.x = x, shape.y = y, shape.width = size, shape.height = size; }, circle: function(x, y, w, h, shape) { shape.cx = x + w / 2, shape.cy = y + h / 2, shape.r = Math.min(w, h) / 2; }, diamond: function(x, y, w, h, shape) { shape.cx = x + w / 2, shape.cy = y + h / 2, shape.width = w, shape.height = h; }, pin: function(x, y, w, h, shape) { shape.x = x + w / 2, shape.y = y + h / 2, shape.width = w, shape.height = h; }, arrow: function(x, y, w, h, shape) { shape.x = x + w / 2, shape.y = y + h / 2, shape.width = w, shape.height = h; }, triangle: function(x, y, w, h, shape) { shape.cx = x + w / 2, shape.cy = y + h / 2, shape.width = w, shape.height = h; } }, symbolBuildProxies = {}; each({ line: Line, rect: Rect, roundRect: Rect, square: Rect, circle: Circle, diamond: Diamond, pin: Pin, arrow: Arrow, triangle: Triangle }, function(Ctor, name) { symbolBuildProxies[name] = new Ctor(); }); var SymbolClz = Path.extend({ type: 'symbol', shape: { symbolType: '', x: 0, y: 0, width: 0, height: 0 }, calculateTextPosition: function(out, config, rect) { var res = calculateTextPosition(out, config, rect), shape = this.shape; return shape && 'pin' === shape.symbolType && 'inside' === config.position && (res.y = rect.y + 0.4 * rect.height), res; }, buildPath: function(ctx, shape, inBundle) { var symbolType = shape.symbolType; if ('none' !== symbolType) { var proxySymbol = symbolBuildProxies[symbolType]; proxySymbol || (proxySymbol = symbolBuildProxies[symbolType = 'rect']), symbolShapeMakers[symbolType](shape.x, shape.y, shape.width, shape.height, proxySymbol.shape), proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle); } } }); function symbolPathSetColor(color, innerColor) { if ('image' !== this.type) { var symbolStyle = this.style; this.__isEmptyBrush ? (symbolStyle.stroke = color, symbolStyle.fill = innerColor || '#fff', symbolStyle.lineWidth = 2) : 'line' === this.shape.symbolType ? symbolStyle.stroke = color : symbolStyle.fill = color, this.markRedraw(); } } function createSymbol(symbolType, x, y, w, h, color, keepAspect) { var symbolPath, isEmpty = 0 === symbolType.indexOf('empty'); return isEmpty && (symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6)), (symbolPath = 0 === symbolType.indexOf('image://') ? makeImage(symbolType.slice(8), new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover') : 0 === symbolType.indexOf('path://') ? makePath(symbolType.slice(7), {}, new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover') : new SymbolClz({ shape: { symbolType: symbolType, x: x, y: y, width: w, height: h } })).__isEmptyBrush = isEmpty, symbolPath.setColor = symbolPathSetColor, color && symbolPath.setColor(color), symbolPath; } function getCanvasGradient(ctx, obj, rect) { for(var width, height, x, y, r, x1, x2, y1, y2, canvasGradient = 'radial' === obj.type ? (width = rect.width, height = rect.height, x = null == obj.x ? 0.5 : obj.x, y = null == obj.y ? 0.5 : obj.y, r = null == obj.r ? 0.5 : obj.r, obj.global || (x = x * width + rect.x, y = y * height + rect.y, r *= Math.min(width, height)), ctx.createRadialGradient(x, y, 0, x, y, r)) : (x1 = null == obj.x ? 0 : obj.x, x2 = null == obj.x2 ? 1 : obj.x2, y1 = null == obj.y ? 0 : obj.y, y2 = null == obj.y2 ? 0 : obj.y2, obj.global || (x1 = x1 * rect.width + rect.x, x2 = x2 * rect.width + rect.x, y1 = y1 * rect.height + rect.y, y2 = y2 * rect.height + rect.y), x1 = isNaN(x1) ? 0 : x1, x2 = isNaN(x2) ? 1 : x2, y1 = isNaN(y1) ? 0 : y1, y2 = isNaN(y2) ? 0 : y2, ctx.createLinearGradient(x1, y1, x2, y2)), colorStops = obj.colorStops, i = 0; i < colorStops.length; i++)canvasGradient.addColorStop(colorStops[i].offset, colorStops[i].color); return canvasGradient; } function isClipPathChanged(clipPaths, prevClipPaths) { if (clipPaths === prevClipPaths || !clipPaths && !prevClipPaths) return !1; if (!clipPaths || !prevClipPaths || clipPaths.length !== prevClipPaths.length) return !0; for(var i = 0; i < clipPaths.length; i++)if (clipPaths[i] !== prevClipPaths[i]) return !0; return !1; } function normalizeLineDash(lineType, lineWidth) { return lineType && 'solid' !== lineType && lineWidth > 0 ? (lineWidth = lineWidth || 1, 'dashed' === lineType ? [ 4 * lineWidth, 2 * lineWidth ] : 'dotted' === lineType ? [ lineWidth ] : isNumber(lineType) ? [ lineType ] : isArray(lineType) ? lineType : null) : null; } var pathProxyForDraw = new PathProxy(!0); function styleHasStroke(style) { var stroke = style.stroke; return !(null == stroke || 'none' === stroke || !(style.lineWidth > 0)); } function styleHasFill(style) { var fill = style.fill; return null != fill && 'none' !== fill; } function doFillPath(ctx, style) { if (null != style.fillOpacity && 1 !== style.fillOpacity) { var originalGlobalAlpha = ctx.globalAlpha; ctx.globalAlpha = style.fillOpacity * style.opacity, ctx.fill(), ctx.globalAlpha = originalGlobalAlpha; } else ctx.fill(); } function doStrokePath(ctx, style) { if (null != style.strokeOpacity && 1 !== style.strokeOpacity) { var originalGlobalAlpha = ctx.globalAlpha; ctx.globalAlpha = style.strokeOpacity * style.opacity, ctx.stroke(), ctx.globalAlpha = originalGlobalAlpha; } else ctx.stroke(); } function createCanvasPattern(ctx, pattern, el) { var image = createOrUpdateImage(pattern.image, pattern.__image, el); if (isImageReady(image)) { var canvasPattern = ctx.createPattern(image, pattern.repeat || 'repeat'); if ('function' == typeof DOMMatrix && canvasPattern.setTransform) { var matrix = new DOMMatrix(); matrix.rotateSelf(0, 0, (pattern.rotation || 0) / Math.PI * 180), matrix.scaleSelf(pattern.scaleX || 1, pattern.scaleY || 1), matrix.translateSelf(pattern.x || 0, pattern.y || 0), canvasPattern.setTransform(matrix); } return canvasPattern; } } var SHADOW_NUMBER_PROPS = [ 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY' ], STROKE_PROPS = [ [ 'lineCap', 'butt' ], [ 'lineJoin', 'miter' ], [ 'miterLimit', 10 ] ]; function bindCommonProps(ctx, style, prevStyle, forceSetAll, scope) { var styleChanged = !1; if (!forceSetAll && style === (prevStyle = prevStyle || {})) return !1; if (forceSetAll || style.opacity !== prevStyle.opacity) { styleChanged || (flushPathDrawn(ctx, scope), styleChanged = !0); var opacity = Math.max(Math.min(style.opacity, 1), 0); ctx.globalAlpha = isNaN(opacity) ? DEFAULT_COMMON_STYLE.opacity : opacity; } (forceSetAll || style.blend !== prevStyle.blend) && (styleChanged || (flushPathDrawn(ctx, scope), styleChanged = !0), ctx.globalCompositeOperation = style.blend || DEFAULT_COMMON_STYLE.blend); for(var i = 0; i < SHADOW_NUMBER_PROPS.length; i++){ var propName = SHADOW_NUMBER_PROPS[i]; (forceSetAll || style[propName] !== prevStyle[propName]) && (styleChanged || (flushPathDrawn(ctx, scope), styleChanged = !0), ctx[propName] = ctx.dpr * (style[propName] || 0)); } return (forceSetAll || style.shadowColor !== prevStyle.shadowColor) && (styleChanged || (flushPathDrawn(ctx, scope), styleChanged = !0), ctx.shadowColor = style.shadowColor || DEFAULT_COMMON_STYLE.shadowColor), styleChanged; } function bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetAll, scope) { var style = getStyle(el, scope.inHover), prevStyle = forceSetAll ? null : prevEl && getStyle(prevEl, scope.inHover) || {}; if (style === prevStyle) return !1; var styleChanged = bindCommonProps(ctx, style, prevStyle, forceSetAll, scope); if ((forceSetAll || style.fill !== prevStyle.fill) && (styleChanged || (flushPathDrawn(ctx, scope), styleChanged = !0), ctx.fillStyle = style.fill), (forceSetAll || style.stroke !== prevStyle.stroke) && (styleChanged || (flushPathDrawn(ctx, scope), styleChanged = !0), ctx.strokeStyle = style.stroke), (forceSetAll || style.opacity !== prevStyle.opacity) && (styleChanged || (flushPathDrawn(ctx, scope), styleChanged = !0), ctx.globalAlpha = null == style.opacity ? 1 : style.opacity), el.hasStroke()) { var newLineWidth = style.lineWidth / (style.strokeNoScale && el && el.getLineScale ? el.getLineScale() : 1); ctx.lineWidth !== newLineWidth && (styleChanged || (flushPathDrawn(ctx, scope), styleChanged = !0), ctx.lineWidth = newLineWidth); } for(var i = 0; i < STROKE_PROPS.length; i++){ var prop = STROKE_PROPS[i], propName = prop[0]; (forceSetAll || style[propName] !== prevStyle[propName]) && (styleChanged || (flushPathDrawn(ctx, scope), styleChanged = !0), ctx[propName] = style[propName] || prop[1]); } return styleChanged; } function setContextTransform(ctx, el) { var m = el.transform, dpr = ctx.dpr || 1; m ? ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]) : ctx.setTransform(dpr, 0, 0, dpr, 0, 0); } function flushPathDrawn(ctx, scope) { scope.batchFill && ctx.fill(), scope.batchStroke && ctx.stroke(), scope.batchFill = '', scope.batchStroke = ''; } function getStyle(el, inHover) { return inHover && el.__hoverStyle || el.style; } function brushSingle(ctx, el) { brush(ctx, el, { inHover: !1, viewWidth: 0, viewHeight: 0 }, !0); } function brush(ctx, el, scope, isLast) { var style, hasFill, hasStroke, m1, forceSetAll, m = el.transform; if (!el.shouldBePainted(scope.viewWidth, scope.viewHeight, !1, !1)) { el.__dirty &= ~Element.REDARAW_BIT, el.__isRendered = !1; return; } var clipPaths = el.__clipPaths, prevElClipPaths = scope.prevElClipPaths, forceSetTransform = !1, forceSetStyle = !1; if ((!prevElClipPaths || isClipPathChanged(clipPaths, prevElClipPaths)) && (prevElClipPaths && prevElClipPaths.length && (flushPathDrawn(ctx, scope), ctx.restore(), forceSetStyle = forceSetTransform = !0, scope.prevElClipPaths = null, scope.allClipped = !1, scope.prevEl = null), clipPaths && clipPaths.length && (flushPathDrawn(ctx, scope), ctx.save(), function(clipPaths, ctx, scope) { for(var allClipped = !1, i = 0; i < clipPaths.length; i++){ var clipPath = clipPaths[i]; allClipped = allClipped || clipPath.isZeroArea(), setContextTransform(ctx, clipPath), ctx.beginPath(), clipPath.buildPath(ctx, clipPath.shape), ctx.clip(); } scope.allClipped = allClipped; }(clipPaths, ctx, scope), forceSetTransform = !0), scope.prevElClipPaths = clipPaths), scope.allClipped) { el.__isRendered = !1; return; } el.beforeBrush && el.beforeBrush(), el.innerBeforeBrush(); var prevEl = scope.prevEl; prevEl || (forceSetStyle = forceSetTransform = !0); var canBatchPath = el instanceof Path && el.autoBatch && (hasFill = styleHasFill(style = el.style), hasStroke = styleHasStroke(style), !(style.lineDash || !(+hasFill ^ +hasStroke) || hasFill && 'string' != typeof style.fill || hasStroke && 'string' != typeof style.stroke || style.strokePercent < 1 || style.strokeOpacity < 1 || style.fillOpacity < 1)); !forceSetTransform && (m1 = prevEl.transform, m && m1 ? m[0] === m1[0] && m[1] === m1[1] && m[2] === m1[2] && m[3] === m1[3] && m[4] === m1[4] && m[5] === m1[5] : m || m1 ? 0 : 1) ? canBatchPath || flushPathDrawn(ctx, scope) : (flushPathDrawn(ctx, scope), setContextTransform(ctx, el)); var style1 = getStyle(el, scope.inHover); el instanceof Path ? (1 !== scope.lastDrawType && (forceSetStyle = !0, scope.lastDrawType = 1), bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope), canBatchPath && (scope.batchFill || scope.batchStroke) || ctx.beginPath(), function(ctx, el, style, inBatch) { var hasStroke = styleHasStroke(style), hasFill = styleHasFill(style), strokePercent = style.strokePercent, strokePart = strokePercent < 1, firstDraw = !el.path; (!el.silent || strokePart) && firstDraw && el.createPathProxy(); var path = el.path || pathProxyForDraw; if (!inBatch) { var fill = style.fill, stroke = style.stroke, hasFillGradient = hasFill && !!fill.colorStops, hasStrokeGradient = hasStroke && !!stroke.colorStops, hasFillPattern = hasFill && !!fill.image, hasStrokePattern = hasStroke && !!stroke.image, fillGradient = void 0, strokeGradient = void 0, fillPattern = void 0, strokePattern = void 0, rect = void 0; (hasFillGradient || hasStrokeGradient) && (rect = el.getBoundingRect()), hasFillGradient && (fillGradient = el.__dirty ? getCanvasGradient(ctx, fill, rect) : el.__canvasFillGradient, el.__canvasFillGradient = fillGradient), hasStrokeGradient && (strokeGradient = el.__dirty ? getCanvasGradient(ctx, stroke, rect) : el.__canvasStrokeGradient, el.__canvasStrokeGradient = strokeGradient), hasFillPattern && (fillPattern = el.__dirty || !el.__canvasFillPattern ? createCanvasPattern(ctx, fill, el) : el.__canvasFillPattern, el.__canvasFillPattern = fillPattern), hasStrokePattern && (strokePattern = el.__dirty || !el.__canvasStrokePattern ? createCanvasPattern(ctx, stroke, el) : el.__canvasStrokePattern, el.__canvasStrokePattern = fillPattern), hasFillGradient ? ctx.fillStyle = fillGradient : hasFillPattern && (fillPattern ? ctx.fillStyle = fillPattern : hasFill = !1), hasStrokeGradient ? ctx.strokeStyle = strokeGradient : hasStrokePattern && (strokePattern ? ctx.strokeStyle = strokePattern : hasStroke = !1); } var lineDash = style.lineDash && style.lineWidth > 0 && normalizeLineDash(style.lineDash, style.lineWidth), lineDashOffset = style.lineDashOffset, ctxLineDash = !!ctx.setLineDash, scale = el.getGlobalScale(); if (path.setScale(scale[0], scale[1], el.segmentIgnoreThreshold), lineDash) { var lineScale_1 = style.strokeNoScale && el.getLineScale ? el.getLineScale() : 1; lineScale_1 && 1 !== lineScale_1 && (lineDash = map(lineDash, function(rawVal) { return rawVal / lineScale_1; }), lineDashOffset /= lineScale_1); } var needsRebuild = !0; (firstDraw || el.__dirty & Path.SHAPE_CHANGED_BIT || lineDash && !ctxLineDash && hasStroke) && (path.setDPR(ctx.dpr), strokePart ? path.setContext(null) : (path.setContext(ctx), needsRebuild = !1), path.reset(), lineDash && !ctxLineDash && (path.setLineDash(lineDash), path.setLineDashOffset(lineDashOffset)), el.buildPath(path, el.shape, inBatch), path.toStatic(), el.pathUpdated()), needsRebuild && path.rebuildPath(ctx, strokePart ? strokePercent : 1), lineDash && ctxLineDash && (ctx.setLineDash(lineDash), ctx.lineDashOffset = lineDashOffset), !inBatch && (style.strokeFirst ? (hasStroke && doStrokePath(ctx, style), hasFill && doFillPath(ctx, style)) : (hasFill && doFillPath(ctx, style), hasStroke && doStrokePath(ctx, style))), lineDash && ctxLineDash && ctx.setLineDash([]); }(ctx, el, style1, canBatchPath), canBatchPath && (scope.batchFill = style1.fill || '', scope.batchStroke = style1.stroke || '')) : el instanceof TSpan ? (3 !== scope.lastDrawType && (forceSetStyle = !0, scope.lastDrawType = 3), bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope), function(ctx, el, style) { var text = style.text; if (null != text && (text += ''), text) { ctx.font = style.font || DEFAULT_FONT, ctx.textAlign = style.textAlign, ctx.textBaseline = style.textBaseline; var hasLineDash = void 0; if (ctx.setLineDash) { var lineDash = style.lineDash && style.lineWidth > 0 && normalizeLineDash(style.lineDash, style.lineWidth), lineDashOffset = style.lineDashOffset; if (lineDash) { var lineScale_2 = style.strokeNoScale && el.getLineScale ? el.getLineScale() : 1; lineScale_2 && 1 !== lineScale_2 && (lineDash = map(lineDash, function(rawVal) { return rawVal / lineScale_2; }), lineDashOffset /= lineScale_2), ctx.setLineDash(lineDash), ctx.lineDashOffset = lineDashOffset, hasLineDash = !0; } } style.strokeFirst ? (styleHasStroke(style) && ctx.strokeText(text, style.x, style.y), styleHasFill(style) && ctx.fillText(text, style.x, style.y)) : (styleHasFill(style) && ctx.fillText(text, style.x, style.y), styleHasStroke(style) && ctx.strokeText(text, style.x, style.y)), hasLineDash && ctx.setLineDash([]); } }(ctx, el, style1)) : el instanceof ZRImage ? (2 !== scope.lastDrawType && (forceSetStyle = !0, scope.lastDrawType = 2), forceSetAll = forceSetStyle, bindCommonProps(ctx, getStyle(el, scope.inHover), prevEl && getStyle(prevEl, scope.inHover), forceSetAll, scope), function(ctx, el, style) { var image = el.__image = createOrUpdateImage(style.image, el.__image, el, el.onload); if (image && isImageReady(image)) { var x = style.x || 0, y = style.y || 0, width = el.getWidth(), height = el.getHeight(), aspect = image.width / image.height; if (null == width && null != height ? width = height * aspect : null == height && null != width ? height = width / aspect : null == width && null == height && (width = image.width, height = image.height), style.sWidth && style.sHeight) { var sx = style.sx || 0, sy = style.sy || 0; ctx.drawImage(image, sx, sy, style.sWidth, style.sHeight, x, y, width, height); } else if (style.sx && style.sy) { var sx = style.sx, sy = style.sy, sWidth = width - sx, sHeight = height - sy; ctx.drawImage(image, sx, sy, sWidth, sHeight, x, y, width, height); } else ctx.drawImage(image, x, y, width, height); } }(ctx, el, style1)) : el instanceof IncrementalDisplayable && (4 !== scope.lastDrawType && (forceSetStyle = !0, scope.lastDrawType = 4), function(ctx, el, scope) { var i, len, displayables = el.getDisplayables(), temporalDisplayables = el.getTemporalDisplayables(); ctx.save(); var innerScope = { prevElClipPaths: null, prevEl: null, allClipped: !1, viewWidth: scope.viewWidth, viewHeight: scope.viewHeight, inHover: scope.inHover }; for(i = el.getCursor(), len = displayables.length; i < len; i++){ var displayable = displayables[i]; displayable.beforeBrush && displayable.beforeBrush(), displayable.innerBeforeBrush(), brush(ctx, displayable, innerScope, i === len - 1), displayable.innerAfterBrush(), displayable.afterBrush && displayable.afterBrush(), innerScope.prevEl = displayable; } for(var i_1 = 0, len_1 = temporalDisplayables.length; i_1 < len_1; i_1++){ var displayable = temporalDisplayables[i_1]; displayable.beforeBrush && displayable.beforeBrush(), displayable.innerBeforeBrush(), brush(ctx, displayable, innerScope, i_1 === len_1 - 1), displayable.innerAfterBrush(), displayable.afterBrush && displayable.afterBrush(), innerScope.prevEl = displayable; } el.clearTemporalDisplayables(), el.notClear = !0, ctx.restore(); }(ctx, el, scope)), canBatchPath && isLast && flushPathDrawn(ctx, scope), el.innerAfterBrush(), el.afterBrush && el.afterBrush(), scope.prevEl = el, el.__dirty = 0, el.__isRendered = !0; } var decalMap = new WeakMap(), decalCache = new LRU(100), decalKeys = [ 'symbol', 'symbolSize', 'symbolKeepAspect', 'color', 'backgroundColor', 'dashArrayX', 'dashArrayY', 'maxTileWidth', 'maxTileHeight' ]; function createOrUpdatePatternFromDecal(decalObject, api) { if ('none' === decalObject) return null; var dpr = api.getDevicePixelRatio(), zr = api.getZr(), isSVG = 'svg' === zr.painter.type; decalObject.dirty && decalMap.delete(decalObject); var oldPattern = decalMap.get(decalObject); if (oldPattern) return oldPattern; var decalOpt = defaults(decalObject, { symbol: 'rect', symbolSize: 1, symbolKeepAspect: !0, color: 'rgba(0, 0, 0, 0.2)', backgroundColor: null, dashArrayX: 5, dashArrayY: 5, rotation: 0, maxTileWidth: 512, maxTileHeight: 512 }); 'none' === decalOpt.backgroundColor && (decalOpt.backgroundColor = null); var pattern = { repeat: 'repeat' }; return function(pattern) { for(var cacheKey, ctx, keys = [ dpr ], isValidKey = !0, i = 0; i < decalKeys.length; ++i){ var value = decalOpt[decalKeys[i]], valueType = typeof value; if (null != value && !isArray(value) && 'string' !== valueType && 'number' !== valueType && 'boolean' !== valueType) { isValidKey = !1; break; } keys.push(value); } if (isValidKey) { cacheKey = keys.join(',') + (isSVG ? '-svg' : ''); var cache = decalCache.get(cacheKey); cache && (isSVG ? pattern.svgElement = cache : pattern.image = cache); } var dashArrayX = function normalizeDashArrayX(dash) { if (!dash || 0 === dash.length) return [ [ 0, 0 ] ]; if ('number' == typeof dash) { var dashValue = Math.ceil(dash); return [ [ dashValue, dashValue ] ]; } for(var isAllNumber = !0, i = 0; i < dash.length; ++i)if ('number' != typeof dash[i]) { isAllNumber = !1; break; } if (isAllNumber) return normalizeDashArrayX([ dash ]); for(var result = [], i = 0; i < dash.length; ++i)if ('number' == typeof dash[i]) { var dashValue = Math.ceil(dash[i]); result.push([ dashValue, dashValue ]); } else { var dashValue = map(dash[i], function(n) { return Math.ceil(n); }); dashValue.length % 2 == 1 ? result.push(dashValue.concat(dashValue)) : result.push(dashValue); } return result; }(decalOpt.dashArrayX), dashArrayY = function(dash) { if (!dash || 'object' == typeof dash && 0 === dash.length) return [ 0, 0 ]; if ('number' == typeof dash) { var dashValue_1 = Math.ceil(dash); return [ dashValue_1, dashValue_1 ]; } var dashValue = map(dash, function(n) { return Math.ceil(n); }); return dash.length % 2 ? dashValue.concat(dashValue) : dashValue; }(decalOpt.dashArrayY), symbolArray = function normalizeSymbolArray(symbol) { if (!symbol || 0 === symbol.length) return [ [ 'rect' ] ]; if ('string' == typeof symbol) return [ [ symbol ] ]; for(var isAllString = !0, i = 0; i < symbol.length; ++i)if ('string' != typeof symbol[i]) { isAllString = !1; break; } if (isAllString) return normalizeSymbolArray([ symbol ]); for(var result = [], i = 0; i < symbol.length; ++i)'string' == typeof symbol[i] ? result.push([ symbol[i] ]) : result.push(symbol[i]); return result; }(decalOpt.symbol), lineBlockLengthsX = map(dashArrayX, function(line) { return getLineBlockLengthY(line); }), lineBlockLengthY = getLineBlockLengthY(dashArrayY), canvas = !isSVG && createCanvas(), svgRoot = isSVG && zr.painter.createSVGElement('g'), pSize = function() { for(var width = 1, i = 0, xlen = lineBlockLengthsX.length; i < xlen; ++i)width = getLeastCommonMultiple(width, lineBlockLengthsX[i]); for(var symbolRepeats = 1, i = 0, xlen = symbolArray.length; i < xlen; ++i)symbolRepeats = getLeastCommonMultiple(symbolRepeats, symbolArray[i].length); width *= symbolRepeats; var height = lineBlockLengthY * lineBlockLengthsX.length * symbolArray.length, warn = function(attrName) { console.warn("Calculated decal size is greater than " + attrName + " due to decal option settings so " + attrName + " is used for the decal size. Please consider changing the decal option to make a smaller decal or set " + attrName + " to be larger to avoid incontinuity."); }; return width > decalOpt.maxTileWidth && warn('maxTileWidth'), height > decalOpt.maxTileHeight && warn('maxTileHeight'), { width: Math.max(1, Math.min(width, decalOpt.maxTileWidth)), height: Math.max(1, Math.min(height, decalOpt.maxTileHeight)) }; }(); canvas && (canvas.width = pSize.width * dpr, canvas.height = pSize.height * dpr, ctx = canvas.getContext('2d')), function() { ctx && (ctx.clearRect(0, 0, canvas.width, canvas.height), decalOpt.backgroundColor && (ctx.fillStyle = decalOpt.backgroundColor, ctx.fillRect(0, 0, canvas.width, canvas.height))); for(var ySum = 0, i = 0; i < dashArrayY.length; ++i)ySum += dashArrayY[i]; if (!(ySum <= 0)) for(var y = -lineBlockLengthY, yId = 0, yIdTotal = 0, xId0 = 0; y < pSize.height;){ if (yId % 2 == 0) { for(var symbolYId = yIdTotal / 2 % symbolArray.length, x = 0, xId1 = 0, xId1Total = 0; x < 2 * pSize.width;){ for(var xSum = 0, i = 0; i < dashArrayX[xId0].length; ++i)xSum += dashArrayX[xId0][i]; if (xSum <= 0) break; if (xId1 % 2 == 0) { var size = (1 - decalOpt.symbolSize) * 0.5, left = x + dashArrayX[xId0][xId1] * size, top_1 = y + dashArrayY[yId] * size, width = dashArrayX[xId0][xId1] * decalOpt.symbolSize, height = dashArrayY[yId] * decalOpt.symbolSize, symbolXId = xId1Total / 2 % symbolArray[symbolYId].length; (function(x, y, width, height, symbolType) { var scale = isSVG ? 1 : dpr, symbol = createSymbol(symbolType, x * scale, y * scale, width * scale, height * scale, decalOpt.color, decalOpt.symbolKeepAspect); isSVG ? svgRoot.appendChild(zr.painter.paintOne(symbol)) : brushSingle(ctx, symbol); })(left, top_1, width, height, symbolArray[symbolYId][symbolXId]); } x += dashArrayX[xId0][xId1], ++xId1Total, ++xId1 === dashArrayX[xId0].length && (xId1 = 0); } ++xId0 === dashArrayX.length && (xId0 = 0); } y += dashArrayY[yId], ++yIdTotal, ++yId === dashArrayY.length && (yId = 0); } }(), isValidKey && decalCache.put(cacheKey, canvas || svgRoot), pattern.image = canvas, pattern.svgElement = svgRoot, pattern.svgWidth = pSize.width, pattern.svgHeight = pSize.height; }(pattern), pattern.rotation = decalOpt.rotation, pattern.scaleX = pattern.scaleY = isSVG ? 1 : 1 / dpr, decalMap.set(decalObject, pattern), decalObject.dirty = !1, pattern; } function getLineBlockLengthY(dash) { for(var blockLength = 0, i = 0; i < dash.length; ++i)blockLength += dash[i]; return dash.length % 2 == 1 ? 2 * blockLength : blockLength; } function parseXML(svg) { isString(svg) && (svg = new DOMParser().parseFromString(svg, 'text/xml')); var svgNode = svg; for(9 === svgNode.nodeType && (svgNode = svgNode.firstChild); 'svg' !== svgNode.nodeName.toLowerCase() || 1 !== svgNode.nodeType;)svgNode = svgNode.nextSibling; return svgNode; } var INHERITABLE_STYLE_ATTRIBUTES_MAP = { fill: 'fill', stroke: 'stroke', 'stroke-width': 'lineWidth', opacity: 'opacity', 'fill-opacity': 'fillOpacity', 'stroke-opacity': 'strokeOpacity', 'stroke-dasharray': 'lineDash', 'stroke-dashoffset': 'lineDashOffset', 'stroke-linecap': 'lineCap', 'stroke-linejoin': 'lineJoin', 'stroke-miterlimit': 'miterLimit', 'font-family': 'fontFamily', 'font-size': 'fontSize', 'font-style': 'fontStyle', 'font-weight': 'fontWeight', 'text-anchor': 'textAlign', visibility: 'visibility', display: 'display' }, INHERITABLE_STYLE_ATTRIBUTES_MAP_KEYS = keys(INHERITABLE_STYLE_ATTRIBUTES_MAP), SELF_STYLE_ATTRIBUTES_MAP = { 'alignment-baseline': 'textBaseline', 'stop-color': 'stopColor' }, SELF_STYLE_ATTRIBUTES_MAP_KEYS = keys(SELF_STYLE_ATTRIBUTES_MAP), SVGParser = function() { function SVGParser() { this._defs = {}, this._root = null; } return SVGParser.prototype.parse = function(xml, opt) { opt = opt || {}; var viewBoxRect, viewBoxTransform, svg = parseXML(xml); if (!svg) throw Error('Illegal svg'); this._defsUsePending = []; var root = new Group(); this._root = root; var named = [], viewBox = svg.getAttribute('viewBox') || '', width = parseFloat(svg.getAttribute('width') || opt.width), height = parseFloat(svg.getAttribute('height') || opt.height); isNaN(width) && (width = null), isNaN(height) && (height = null), parseAttributes(svg, root, null, !0, !1); for(var child = svg.firstChild; child;)this._parseNode(child, root, named, null, !1, !1), child = child.nextSibling; if (function(defs, defsUsePending) { for(var i = 0; i < defsUsePending.length; i++){ var item = defsUsePending[i]; item[0].style[item[1]] = defs[item[2]]; } }(this._defs, this._defsUsePending), this._defsUsePending = [], viewBox) { var viewBoxArr = splitNumberSequence(viewBox); viewBoxArr.length >= 4 && (viewBoxRect = { x: parseFloat(viewBoxArr[0] || 0), y: parseFloat(viewBoxArr[1] || 0), width: parseFloat(viewBoxArr[2]), height: parseFloat(viewBoxArr[3]) }); } if (viewBoxRect && null != width && null != height && (viewBoxTransform = makeViewBoxTransform(viewBoxRect, { x: 0, y: 0, width: width, height: height }), !opt.ignoreViewBox)) { var elRoot = root; (root = new Group()).add(elRoot), elRoot.scaleX = elRoot.scaleY = viewBoxTransform.scale, elRoot.x = viewBoxTransform.x, elRoot.y = viewBoxTransform.y; } return opt.ignoreRootClip || null == width || null == height || root.setClipPath(new Rect({ shape: { x: 0, y: 0, width: width, height: height } })), { root: root, width: width, height: height, viewBoxRect: viewBoxRect, viewBoxTransform: viewBoxTransform, named: named }; }, SVGParser.prototype._parseNode = function(xmlNode, parentGroup, named, namedFrom, isInDefs, isInText) { var el, nodeName = xmlNode.nodeName.toLowerCase(), namedFromForSub = namedFrom; if ('defs' === nodeName && (isInDefs = !0), 'text' === nodeName && (isInText = !0), 'defs' === nodeName || 'switch' === nodeName) el = parentGroup; else { if (!isInDefs) { var parser_1 = nodeParsers[nodeName]; if (parser_1 && hasOwn(nodeParsers, nodeName)) { el = parser_1.call(this, xmlNode, parentGroup); var nameAttr = xmlNode.getAttribute('name'); if (nameAttr) { var newNamed = { name: nameAttr, namedFrom: null, svgNodeTagLower: nodeName, el: el }; named.push(newNamed), 'g' === nodeName && (namedFromForSub = newNamed); } else namedFrom && named.push({ name: namedFrom.name, namedFrom: namedFrom, svgNodeTagLower: nodeName, el: el }); parentGroup.add(el); } } var parser = paintServerParsers[nodeName]; if (parser && hasOwn(paintServerParsers, nodeName)) { var def = parser.call(this, xmlNode), id = xmlNode.getAttribute('id'); id && (this._defs[id] = def); } } if (el && el.isGroup) for(var child = xmlNode.firstChild; child;)1 === child.nodeType ? this._parseNode(child, el, named, namedFromForSub, isInDefs, isInText) : 3 === child.nodeType && isInText && this._parseText(child, el), child = child.nextSibling; }, SVGParser.prototype._parseText = function(xmlNode, parentGroup) { var text = new TSpan({ style: { text: xmlNode.textContent }, silent: !0, x: this._textX || 0, y: this._textY || 0 }); inheritStyle(parentGroup, text), parseAttributes(xmlNode, text, this._defsUsePending, !1, !1), function(text, parentGroup) { var parentSelfStyle = parentGroup.__selfStyle; if (parentSelfStyle) { var textBaseline = parentSelfStyle.textBaseline, zrTextBaseline = textBaseline; textBaseline && 'auto' !== textBaseline ? 'baseline' === textBaseline ? zrTextBaseline = 'alphabetic' : 'before-edge' === textBaseline || 'text-before-edge' === textBaseline ? zrTextBaseline = 'top' : 'after-edge' === textBaseline || 'text-after-edge' === textBaseline ? zrTextBaseline = 'bottom' : ('central' === textBaseline || 'mathematical' === textBaseline) && (zrTextBaseline = 'middle') : zrTextBaseline = 'alphabetic', text.style.textBaseline = zrTextBaseline; } var parentInheritedStyle = parentGroup.__inheritedStyle; if (parentInheritedStyle) { var textAlign = parentInheritedStyle.textAlign, zrTextAlign = textAlign; textAlign && ('middle' === textAlign && (zrTextAlign = 'center'), text.style.textAlign = zrTextAlign); } }(text, parentGroup); var textStyle = text.style, fontSize = textStyle.fontSize; fontSize && fontSize < 9 && (textStyle.fontSize = 9, text.scaleX *= fontSize / 9, text.scaleY *= fontSize / 9); var font = (textStyle.fontSize || textStyle.fontFamily) && [ textStyle.fontStyle, textStyle.fontWeight, (textStyle.fontSize || 12) + 'px', textStyle.fontFamily || 'sans-serif' ].join(' '); textStyle.font = font; var rect = text.getBoundingRect(); return this._textX += rect.width, parentGroup.add(text), text; }, SVGParser.internalField = void (nodeParsers = { g: function(xmlNode, parentGroup) { var g = new Group(); return inheritStyle(parentGroup, g), parseAttributes(xmlNode, g, this._defsUsePending, !1, !1), g; }, rect: function(xmlNode, parentGroup) { var rect = new Rect(); return inheritStyle(parentGroup, rect), parseAttributes(xmlNode, rect, this._defsUsePending, !1, !1), rect.setShape({ x: parseFloat(xmlNode.getAttribute('x') || '0'), y: parseFloat(xmlNode.getAttribute('y') || '0'), width: parseFloat(xmlNode.getAttribute('width') || '0'), height: parseFloat(xmlNode.getAttribute('height') || '0') }), rect.silent = !0, rect; }, circle: function(xmlNode, parentGroup) { var circle = new Circle(); return inheritStyle(parentGroup, circle), parseAttributes(xmlNode, circle, this._defsUsePending, !1, !1), circle.setShape({ cx: parseFloat(xmlNode.getAttribute('cx') || '0'), cy: parseFloat(xmlNode.getAttribute('cy') || '0'), r: parseFloat(xmlNode.getAttribute('r') || '0') }), circle.silent = !0, circle; }, line: function(xmlNode, parentGroup) { var line = new Line(); return inheritStyle(parentGroup, line), parseAttributes(xmlNode, line, this._defsUsePending, !1, !1), line.setShape({ x1: parseFloat(xmlNode.getAttribute('x1') || '0'), y1: parseFloat(xmlNode.getAttribute('y1') || '0'), x2: parseFloat(xmlNode.getAttribute('x2') || '0'), y2: parseFloat(xmlNode.getAttribute('y2') || '0') }), line.silent = !0, line; }, ellipse: function(xmlNode, parentGroup) { var ellipse = new Ellipse(); return inheritStyle(parentGroup, ellipse), parseAttributes(xmlNode, ellipse, this._defsUsePending, !1, !1), ellipse.setShape({ cx: parseFloat(xmlNode.getAttribute('cx') || '0'), cy: parseFloat(xmlNode.getAttribute('cy') || '0'), rx: parseFloat(xmlNode.getAttribute('rx') || '0'), ry: parseFloat(xmlNode.getAttribute('ry') || '0') }), ellipse.silent = !0, ellipse; }, polygon: function(xmlNode, parentGroup) { var pointsArr, pointsStr = xmlNode.getAttribute('points'); pointsStr && (pointsArr = parsePoints(pointsStr)); var polygon = new Polygon({ shape: { points: pointsArr || [] }, silent: !0 }); return inheritStyle(parentGroup, polygon), parseAttributes(xmlNode, polygon, this._defsUsePending, !1, !1), polygon; }, polyline: function(xmlNode, parentGroup) { var pointsArr, pointsStr = xmlNode.getAttribute('points'); pointsStr && (pointsArr = parsePoints(pointsStr)); var polyline = new Polyline({ shape: { points: pointsArr || [] }, silent: !0 }); return inheritStyle(parentGroup, polyline), parseAttributes(xmlNode, polyline, this._defsUsePending, !1, !1), polyline; }, image: function(xmlNode, parentGroup) { var img = new ZRImage(); return inheritStyle(parentGroup, img), parseAttributes(xmlNode, img, this._defsUsePending, !1, !1), img.setStyle({ image: xmlNode.getAttribute('xlink:href'), x: +xmlNode.getAttribute('x'), y: +xmlNode.getAttribute('y'), width: +xmlNode.getAttribute('width'), height: +xmlNode.getAttribute('height') }), img.silent = !0, img; }, text: function(xmlNode, parentGroup) { var x = xmlNode.getAttribute('x') || '0', y = xmlNode.getAttribute('y') || '0', dx = xmlNode.getAttribute('dx') || '0', dy = xmlNode.getAttribute('dy') || '0'; this._textX = parseFloat(x) + parseFloat(dx), this._textY = parseFloat(y) + parseFloat(dy); var g = new Group(); return inheritStyle(parentGroup, g), parseAttributes(xmlNode, g, this._defsUsePending, !1, !0), g; }, tspan: function(xmlNode, parentGroup) { var x = xmlNode.getAttribute('x'), y = xmlNode.getAttribute('y'); null != x && (this._textX = parseFloat(x)), null != y && (this._textY = parseFloat(y)); var dx = xmlNode.getAttribute('dx') || '0', dy = xmlNode.getAttribute('dy') || '0', g = new Group(); return inheritStyle(parentGroup, g), parseAttributes(xmlNode, g, this._defsUsePending, !1, !0), this._textX += parseFloat(dx), this._textY += parseFloat(dy), g; }, path: function(xmlNode, parentGroup) { var str, path = (str = xmlNode.getAttribute('d') || '', new SVGPath(createPathOptions(str, void 0))); return inheritStyle(parentGroup, path), parseAttributes(xmlNode, path, this._defsUsePending, !1, !1), path.silent = !0, path; } }), SVGParser; }(), paintServerParsers = { lineargradient: function(xmlNode) { var x1 = parseInt(xmlNode.getAttribute('x1') || '0', 10), y1 = parseInt(xmlNode.getAttribute('y1') || '0', 10), x2 = parseInt(xmlNode.getAttribute('x2') || '10', 10), y2 = parseInt(xmlNode.getAttribute('y2') || '0', 10), gradient = new LinearGradient(x1, y1, x2, y2); return parsePaintServerUnit(xmlNode, gradient), parseGradientColorStops(xmlNode, gradient), gradient; }, radialgradient: function(xmlNode) { var cx = parseInt(xmlNode.getAttribute('cx') || '0', 10), cy = parseInt(xmlNode.getAttribute('cy') || '0', 10), r = parseInt(xmlNode.getAttribute('r') || '0', 10), gradient = new RadialGradient(cx, cy, r); return parsePaintServerUnit(xmlNode, gradient), parseGradientColorStops(xmlNode, gradient), gradient; } }; function parsePaintServerUnit(xmlNode, gradient) { 'userSpaceOnUse' === xmlNode.getAttribute('gradientUnits') && (gradient.global = !0); } function parseGradientColorStops(xmlNode, gradient) { for(var stop = xmlNode.firstChild; stop;){ if (1 === stop.nodeType && 'stop' === stop.nodeName.toLocaleLowerCase()) { var offsetStr = stop.getAttribute('offset'), offset = void 0; offset = offsetStr && offsetStr.indexOf('%') > 0 ? parseInt(offsetStr, 10) / 100 : offsetStr ? parseFloat(offsetStr) : 0; var styleVals = {}; parseInlineStyle(stop, styleVals, styleVals); var stopColor = styleVals.stopColor || stop.getAttribute('stop-color') || '#000000'; gradient.colorStops.push({ offset: offset, color: stopColor }); } stop = stop.nextSibling; } } function inheritStyle(parent, child) { parent && parent.__inheritedStyle && (child.__inheritedStyle || (child.__inheritedStyle = {}), defaults(child.__inheritedStyle, parent.__inheritedStyle)); } function parsePoints(pointsString) { for(var list = splitNumberSequence(pointsString), points = [], i = 0; i < list.length; i += 2){ var x = parseFloat(list[i]), y = parseFloat(list[i + 1]); points.push([ x, y ]); } return points; } function parseAttributes(xmlNode, el, defsUsePending, onlyInlineStyle, isTextGroup) { var disp = el, inheritedStyle = disp.__inheritedStyle = disp.__inheritedStyle || {}, selfStyle = {}; 1 !== xmlNode.nodeType || (function(xmlNode, node) { var transform = xmlNode.getAttribute('transform'); if (transform) { transform = transform.replace(/,/g, ' '); var transformOps_1 = [], mt = null; transform.replace(transformRegex, function(str, type, value) { return transformOps_1.push(type, value), ''; }); for(var i = transformOps_1.length - 1; i > 0; i -= 2){ var value = transformOps_1[i], type = transformOps_1[i - 1], valueArr = void 0; switch(mt = mt || create$1(), type){ case 'translate': translate(mt, mt, [ parseFloat((valueArr = splitNumberSequence(value))[0]), parseFloat(valueArr[1] || '0') ]); break; case 'scale': scale$1(mt, mt, [ parseFloat((valueArr = splitNumberSequence(value))[0]), parseFloat(valueArr[1] || valueArr[0]) ]); break; case 'rotate': rotate(mt, mt, -parseFloat((valueArr = splitNumberSequence(value))[0]) / 180 * Math.PI); break; case 'skew': valueArr = splitNumberSequence(value), console.warn('Skew transform is not supported yet'); break; case 'matrix': valueArr = splitNumberSequence(value), mt[0] = parseFloat(valueArr[0]), mt[1] = parseFloat(valueArr[1]), mt[2] = parseFloat(valueArr[2]), mt[3] = parseFloat(valueArr[3]), mt[4] = parseFloat(valueArr[4]), mt[5] = parseFloat(valueArr[5]); } } node.setLocalTransform(mt); } }(xmlNode, el), parseInlineStyle(xmlNode, inheritedStyle, selfStyle), onlyInlineStyle || function(xmlNode, inheritableStyleResult, selfStyleResult) { for(var i = 0; i < INHERITABLE_STYLE_ATTRIBUTES_MAP_KEYS.length; i++){ var svgAttrName = INHERITABLE_STYLE_ATTRIBUTES_MAP_KEYS[i], attrValue = xmlNode.getAttribute(svgAttrName); null != attrValue && (inheritableStyleResult[INHERITABLE_STYLE_ATTRIBUTES_MAP[svgAttrName]] = attrValue); } for(var i = 0; i < SELF_STYLE_ATTRIBUTES_MAP_KEYS.length; i++){ var svgAttrName = SELF_STYLE_ATTRIBUTES_MAP_KEYS[i], attrValue = xmlNode.getAttribute(svgAttrName); null != attrValue && (selfStyleResult[SELF_STYLE_ATTRIBUTES_MAP[svgAttrName]] = attrValue); } }(xmlNode, inheritedStyle, selfStyle)), disp.style = disp.style || {}, null != inheritedStyle.fill && (disp.style.fill = getFillStrokeStyle(disp, 'fill', inheritedStyle.fill, defsUsePending)), null != inheritedStyle.stroke && (disp.style.stroke = getFillStrokeStyle(disp, 'stroke', inheritedStyle.stroke, defsUsePending)), each([ 'lineWidth', 'opacity', 'fillOpacity', 'strokeOpacity', 'miterLimit', 'fontSize' ], function(propName) { null != inheritedStyle[propName] && (disp.style[propName] = parseFloat(inheritedStyle[propName])); }), each([ 'lineDashOffset', 'lineCap', 'lineJoin', 'fontWeight', 'fontFamily', 'fontStyle', 'textAlign' ], function(propName) { null != inheritedStyle[propName] && (disp.style[propName] = inheritedStyle[propName]); }), isTextGroup && (disp.__selfStyle = selfStyle), inheritedStyle.lineDash && (disp.style.lineDash = map(splitNumberSequence(inheritedStyle.lineDash), function(str) { return parseFloat(str); })), ('hidden' === inheritedStyle.visibility || 'collapse' === inheritedStyle.visibility) && (disp.invisible = !0), 'none' === inheritedStyle.display && (disp.ignore = !0), disp.z = -10000, disp.z2 = -1000; } var urlRegex = /^url\(\s*#(.*?)\)/; function getFillStrokeStyle(el, method, str, defsUsePending) { var urlMatch = str && str.match(urlRegex); if (urlMatch) { var url = trim(urlMatch[1]); defsUsePending.push([ el, method, url ]); return; } return 'none' === str && (str = null), str; } var numberReg$1 = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g; function splitNumberSequence(rawStr) { return rawStr.match(numberReg$1) || []; } var transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.eE,]*)\)/g, styleRegex = /([^\s:;]+)\s*:\s*([^:;]+)/g; function parseInlineStyle(xmlNode, inheritableStyleResult, selfStyleResult) { var styleRegResult, style = xmlNode.getAttribute('style'); if (style) for(styleRegex.lastIndex = 0; null != (styleRegResult = styleRegex.exec(style));){ var svgStlAttr = styleRegResult[1], zrInheritableStlAttr = hasOwn(INHERITABLE_STYLE_ATTRIBUTES_MAP, svgStlAttr) ? INHERITABLE_STYLE_ATTRIBUTES_MAP[svgStlAttr] : null; zrInheritableStlAttr && (inheritableStyleResult[zrInheritableStlAttr] = styleRegResult[2]); var zrSelfStlAttr = hasOwn(SELF_STYLE_ATTRIBUTES_MAP, svgStlAttr) ? SELF_STYLE_ATTRIBUTES_MAP[svgStlAttr] : null; zrSelfStlAttr && (selfStyleResult[zrSelfStlAttr] = styleRegResult[2]); } } function makeViewBoxTransform(viewBoxRect, boundingRect) { var scale = Math.min(boundingRect.width / viewBoxRect.width, boundingRect.height / viewBoxRect.height); return { scale: scale, x: -(viewBoxRect.x + viewBoxRect.width / 2) * scale + (boundingRect.x + boundingRect.width / 2), y: -(viewBoxRect.y + viewBoxRect.height / 2) * scale + (boundingRect.y + boundingRect.height / 2) }; } function isAroundEqual$1(a, b) { return 1e-8 > Math.abs(a - b); } function contain$1(points, x, y) { var w = 0, p = points[0]; if (!p) return !1; for(var i = 1; i < points.length; i++){ var p2 = points[i]; w += windingLine(p[0], p[1], p2[0], p2[1], x, y), p = p2; } var p0 = points[0]; return isAroundEqual$1(p[0], p0[0]) && isAroundEqual$1(p[1], p0[1]) || (w += windingLine(p[0], p[1], p0[0], p0[1], x, y)), 0 !== w; } var TMP_TRANSFORM = [], Region = function() { function Region(name) { this.name = name; } return Region.prototype.getCenter = function() {}, Region; }(), GeoJSONRegion = function(_super) { function GeoJSONRegion(name, geometries, cp) { var _this = _super.call(this, name) || this; if (_this.type = 'geoJSON', _this.geometries = geometries, cp) cp = [ cp[0], cp[1] ]; else { var rect = _this.getBoundingRect(); cp = [ rect.x + rect.width / 2, rect.y + rect.height / 2 ]; } return _this._center = cp, _this; } return __extends(GeoJSONRegion, _super), GeoJSONRegion.prototype.getBoundingRect = function() { var rect = this._rect; if (rect) return rect; for(var MAX_NUMBER = Number.MAX_VALUE, min$1 = [ MAX_NUMBER, MAX_NUMBER ], max$1 = [ -MAX_NUMBER, -MAX_NUMBER ], min2 = [], max2 = [], geometries = this.geometries, i = 0; i < geometries.length; i++)'polygon' === geometries[i].type && (fromPoints(geometries[i].exterior, min2, max2), min(min$1, min$1, min2), max(max$1, max$1, max2)); return 0 === i && (min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0), this._rect = new BoundingRect(min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]); }, GeoJSONRegion.prototype.contain = function(coord) { var rect = this.getBoundingRect(), geometries = this.geometries; if (!rect.contain(coord[0], coord[1])) return !1; loopGeo: for(var i = 0, len = geometries.length; i < len; i++)if ('polygon' === geometries[i].type) { var exterior = geometries[i].exterior, interiors = geometries[i].interiors; if (contain$1(exterior, coord[0], coord[1])) { for(var k = 0; k < (interiors ? interiors.length : 0); k++)if (contain$1(interiors[k], coord[0], coord[1])) continue loopGeo; return !0; } } return !1; }, GeoJSONRegion.prototype.transformTo = function(x, y, width, height) { var rect = this.getBoundingRect(), aspect = rect.width / rect.height; width ? height || (height = width / aspect) : width = aspect * height; for(var target = new BoundingRect(x, y, width, height), transform = rect.calculateTransform(target), geometries = this.geometries, i = 0; i < geometries.length; i++)if ('polygon' === geometries[i].type) { for(var exterior = geometries[i].exterior, interiors = geometries[i].interiors, p = 0; p < exterior.length; p++)applyTransform(exterior[p], exterior[p], transform); for(var h = 0; h < (interiors ? interiors.length : 0); h++)for(var p = 0; p < interiors[h].length; p++)applyTransform(interiors[h][p], interiors[h][p], transform); } (rect = this._rect).copy(target), this._center = [ rect.x + rect.width / 2, rect.y + rect.height / 2 ]; }, GeoJSONRegion.prototype.cloneShallow = function(name) { null == name && (name = this.name); var newRegion = new GeoJSONRegion(name, this.geometries, this._center); return newRegion._rect = this._rect, newRegion.transformTo = null, newRegion; }, GeoJSONRegion.prototype.getCenter = function() { return this._center; }, GeoJSONRegion.prototype.setCenter = function(center) { this._center = center; }, GeoJSONRegion; }(Region), GeoSVGRegion = function(_super) { function GeoSVGRegion(name, elOnlyForCalculate) { var _this = _super.call(this, name) || this; return _this.type = 'geoSVG', _this._elOnlyForCalculate = elOnlyForCalculate, _this; } return __extends(GeoSVGRegion, _super), GeoSVGRegion.prototype.getCenter = function() { var center = this._center; return center || (center = this._center = this._calculateCenter()), center; }, GeoSVGRegion.prototype._calculateCenter = function() { for(var el = this._elOnlyForCalculate, rect = el.getBoundingRect(), center = [ rect.x + rect.width / 2, rect.y + rect.height / 2 ], mat = identity(TMP_TRANSFORM), target = el; target && !target.isGeoSVGGraphicRoot;)mul$1(mat, target.getLocalTransform(), mat), target = target.parent; return invert(mat, mat), applyTransform(center, center, mat), center; }, GeoSVGRegion; }(Region), REGION_AVAILABLE_SVG_TAG_MAP = createHashMap([ 'rect', 'circle', 'line', 'ellipse', 'polygon', 'polyline', 'path', 'text', 'tspan', 'g' ]), GeoSVGResource = function() { function GeoSVGResource(mapName, svg) { this.type = 'geoSVG', this._usedGraphicMap = createHashMap(), this._freedGraphics = [], this._mapName = mapName, this._parsedXML = parseXML(svg); } return GeoSVGResource.prototype.load = function() { var firstGraphic = this._firstGraphic; if (!firstGraphic) { firstGraphic = this._firstGraphic = this._buildGraphic(this._parsedXML), this._freedGraphics.push(firstGraphic), this._boundingRect = this._firstGraphic.boundingRect.clone(); var named, regions, regionsMap, _a = (named = firstGraphic.named, regions = [], regionsMap = createHashMap(), each(named, function(namedItem) { if (null == namedItem.namedFrom) { var region = new GeoSVGRegion(namedItem.name, namedItem.el); regions.push(region), regionsMap.set(namedItem.name, region); } }), { regions: regions, regionsMap: regionsMap }), regions1 = _a.regions, regionsMap1 = _a.regionsMap; this._regions = regions1, this._regionsMap = regionsMap1; } return { boundingRect: this._boundingRect, regions: this._regions, regionsMap: this._regionsMap }; }, GeoSVGResource.prototype._buildGraphic = function(svgXML) { try { rootFromParse = (result = svgXML && new SVGParser().parse(svgXML, { ignoreViewBox: !0, ignoreRootClip: !0 }) || {}).root, assert(null != rootFromParse); } catch (e) { throw Error('Invalid svg format\n' + e.message); } var result, rootFromParse, root = new Group(); root.add(rootFromParse), root.isGeoSVGGraphicRoot = !0; var svgWidth = result.width, svgHeight = result.height, viewBoxRect = result.viewBoxRect, boundingRect = this._boundingRect; if (!boundingRect) { var bRectX = void 0, bRectY = void 0, bRectWidth = void 0, bRectHeight = void 0; if (null != svgWidth ? (bRectX = 0, bRectWidth = svgWidth) : viewBoxRect && (bRectX = viewBoxRect.x, bRectWidth = viewBoxRect.width), null != svgHeight ? (bRectY = 0, bRectHeight = svgHeight) : viewBoxRect && (bRectY = viewBoxRect.y, bRectHeight = viewBoxRect.height), null == bRectX || null == bRectY) { var calculatedBoundingRect = rootFromParse.getBoundingRect(); null == bRectX && (bRectX = calculatedBoundingRect.x, bRectWidth = calculatedBoundingRect.width), null == bRectY && (bRectY = calculatedBoundingRect.y, bRectHeight = calculatedBoundingRect.height); } boundingRect = this._boundingRect = new BoundingRect(bRectX, bRectY, bRectWidth, bRectHeight); } if (viewBoxRect) { var viewBoxTransform = makeViewBoxTransform(viewBoxRect, boundingRect); rootFromParse.scaleX = rootFromParse.scaleY = viewBoxTransform.scale, rootFromParse.x = viewBoxTransform.x, rootFromParse.y = viewBoxTransform.y; } root.setClipPath(new Rect({ shape: boundingRect.plain() })); var named = []; return each(result.named, function(namedItem) { var el; null != REGION_AVAILABLE_SVG_TAG_MAP.get(namedItem.svgNodeTagLower) && (named.push(namedItem), (el = namedItem.el).silent = !1, el.isGroup && el.traverse(function(child) { child.silent = !1; })); }), { root: root, boundingRect: boundingRect, named: named }; }, GeoSVGResource.prototype.useGraphic = function(hostKey) { var usedRootMap = this._usedGraphicMap, svgGraphic = usedRootMap.get(hostKey); return svgGraphic || (svgGraphic = this._freedGraphics.pop() || this._buildGraphic(this._parsedXML), usedRootMap.set(hostKey, svgGraphic)), svgGraphic; }, GeoSVGResource.prototype.freeGraphic = function(hostKey) { var usedRootMap = this._usedGraphicMap, svgGraphic = usedRootMap.get(hostKey); svgGraphic && (usedRootMap.removeKey(hostKey), this._freedGraphics.push(svgGraphic)); }, GeoSVGResource; }(); function decodePolygon(coordinate, encodeOffsets, encodeScale) { for(var result = [], prevX = encodeOffsets[0], prevY = encodeOffsets[1], i = 0; i < coordinate.length; i += 2){ var x = coordinate.charCodeAt(i) - 64, y = coordinate.charCodeAt(i + 1) - 64; x = x >> 1 ^ -(1 & x), y = y >> 1 ^ -(1 & y), x += prevX, y += prevY, prevX = x, prevY = y, result.push([ x / encodeScale, y / encodeScale ]); } return result; } function parseGeoJSON(geoJson, nameProperty) { return map(filter((geoJson = function(json) { if (!json.UTF8Encoding) return json; var jsonCompressed = json, encodeScale = jsonCompressed.UTF8Scale; null == encodeScale && (encodeScale = 1024); for(var features = jsonCompressed.features, f = 0; f < features.length; f++){ var geometry = features[f].geometry; if ('Polygon' === geometry.type) for(var coordinates = geometry.coordinates, c = 0; c < coordinates.length; c++)coordinates[c] = decodePolygon(coordinates[c], geometry.encodeOffsets[c], encodeScale); else if ('MultiPolygon' === geometry.type) for(var coordinates = geometry.coordinates, c = 0; c < coordinates.length; c++)for(var coordinate = coordinates[c], c2 = 0; c2 < coordinate.length; c2++)coordinate[c2] = decodePolygon(coordinate[c2], geometry.encodeOffsets[c][c2], encodeScale); } return jsonCompressed.UTF8Encoding = !1, jsonCompressed; }(geoJson)).features, function(featureObj) { return featureObj.geometry && featureObj.properties && featureObj.geometry.coordinates.length > 0; }), function(featureObj) { var properties = featureObj.properties, geo = featureObj.geometry, geometries = []; if ('Polygon' === geo.type) { var coordinates = geo.coordinates; geometries.push({ type: 'polygon', exterior: coordinates[0], interiors: coordinates.slice(1) }); } if ('MultiPolygon' === geo.type) { var coordinates = geo.coordinates; each(coordinates, function(item) { item[0] && geometries.push({ type: 'polygon', exterior: item[0], interiors: item.slice(1) }); }); } var region = new GeoJSONRegion(properties[nameProperty || 'name'], geometries, properties.cp); return region.properties = properties, region; }); } for(var geoCoord = [ 126, 25 ], points$1 = [ [ [ 0, 3.5 ], [ 7, 11.2 ], [ 15, 11.9 ], [ 30, 7 ], [ 42, 0.7 ], [ 52, 0.7 ], [ 56, 7.7 ], [ 59, 0.7 ], [ 64, 0.7 ], [ 64, 0 ], [ 5, 0 ], [ 0, 3.5 ] ], [ [ 13, 16.1 ], [ 19, 14.7 ], [ 16, 21.7 ], [ 11, 23.1 ], [ 13, 16.1 ] ], [ [ 12, 32.2 ], [ 14, 38.5 ], [ 15, 38.5 ], [ 13, 32.2 ], [ 12, 32.2 ] ], [ [ 16, 47.6 ], [ 12, 53.2 ], [ 13, 53.2 ], [ 18, 47.6 ], [ 16, 47.6 ] ], [ [ 6, 64.4 ], [ 8, 70 ], [ 9, 70 ], [ 8, 64.4 ], [ 6, 64.4 ] ], [ [ 23, 82.6 ], [ 29, 79.8 ], [ 30, 79.8 ], [ 25, 82.6 ], [ 23, 82.6 ] ], [ [ 37, 70.7 ], [ 43, 62.3 ], [ 44, 62.3 ], [ 39, 70.7 ], [ 37, 70.7 ] ], [ [ 48, 51.1 ], [ 51, 45.5 ], [ 53, 45.5 ], [ 50, 51.1 ], [ 48, 51.1 ] ], [ [ 51, 35 ], [ 51, 28.7 ], [ 53, 28.7 ], [ 53, 35 ], [ 51, 35 ] ], [ [ 52, 22.4 ], [ 55, 17.5 ], [ 56, 17.5 ], [ 53, 22.4 ], [ 52, 22.4 ] ], [ [ 58, 12.6 ], [ 62, 7 ], [ 63, 7 ], [ 60, 12.6 ], [ 58, 12.6 ] ], [ [ 0, 3.5 ], [ 0, 93.1 ], [ 64, 93.1 ], [ 64, 0 ], [ 63, 0 ], [ 63, 92.4 ], [ 1, 92.4 ], [ 1, 3.5 ], [ 0, 3.5 ] ] ], i = 0; i < points$1.length; i++)for(var k = 0; k < points$1[i].length; k++)points$1[i][k][0] /= 10.5, points$1[i][k][1] /= -14, points$1[i][k][0] += geoCoord[0], points$1[i][k][1] += geoCoord[1]; var coordsOffsetMap = { 南海诸岛: [ 32, 80 ], 广东: [ 0, -10 ], 香港: [ 10, 5 ], 澳门: [ -10, 10 ], 天津: [ 5, 5 ] }, geoCoordMap = { Russia: [ 100, 60 ], 'United States': [ -99, 38 ], 'United States of America': [ -99, 38 ] }, points$2 = [ [ [ 123.45165252685547, 25.73527164402261 ], [ 123.49731445312499, 25.73527164402261 ], [ 123.49731445312499, 25.750734064600884 ], [ 123.45165252685547, 25.750734064600884 ], [ 123.45165252685547, 25.73527164402261 ] ] ], GeoJSONResource = function() { function GeoJSONResource(mapName, geoJSON, specialAreas) { this.type = 'geoJSON', this._parsedMap = createHashMap(), this._mapName = mapName, this._specialAreas = specialAreas, this._geoJSON = isString(geoJSON) ? 'undefined' != typeof JSON && JSON.parse ? JSON.parse(geoJSON) : Function('return (' + geoJSON + ');')() : geoJSON; } return GeoJSONResource.prototype.load = function(nameMap, nameProperty) { nameProperty = nameProperty || 'name'; var parsed = this._parsedMap.get(nameProperty); if (!parsed) { var rawRegions = this._parseToRegions(nameProperty); parsed = this._parsedMap.set(nameProperty, { regions: rawRegions, boundingRect: function(regions) { for(var rect, i = 0; i < regions.length; i++){ var regionRect = regions[i].getBoundingRect(); (rect = rect || regionRect.clone()).union(regionRect); } return rect; }(rawRegions) }); } var regionsMap = createHashMap(), finalRegions = []; return each(parsed.regions, function(region) { var regionName = region.name; nameMap && nameMap.hasOwnProperty(regionName) && (region = region.cloneShallow(regionName = nameMap[regionName])), finalRegions.push(region), regionsMap.set(regionName, region); }), { regions: finalRegions, boundingRect: parsed.boundingRect || new BoundingRect(0, 0, 0, 0), regionsMap: regionsMap }; }, GeoJSONResource.prototype._parseToRegions = function(nameProperty) { var regions, rawRegions, mapName = this._mapName, geoJSON = this._geoJSON; try { rawRegions = geoJSON ? parseGeoJSON(geoJSON, nameProperty) : []; } catch (e) { throw Error('Invalid geoJson format\n' + e.message); } return regions = rawRegions, 'china' === mapName && regions.push(new GeoJSONRegion('南海诸岛', map(points$1, function(exterior) { return { type: 'polygon', exterior: exterior }; }), geoCoord)), each(rawRegions, function(region) { var regionName = region.name; (function(mapType, region) { if ('china' === mapType) { var coordFix = coordsOffsetMap[region.name]; if (coordFix) { var cp = region.getCenter(); cp[0] += coordFix[0] / 10.5, cp[1] += -coordFix[1] / 14, region.setCenter(cp); } } })(mapName, region), function(mapType, region) { if ('world' === mapType) { var geoCoord = geoCoordMap[region.name]; if (geoCoord) { var cp = [ geoCoord[0], geoCoord[1] ]; region.setCenter(cp); } } }(mapName, region), 'china' === mapName && '台湾' === region.name && region.geometries.push({ type: 'polygon', exterior: points$2[0] }); var specialArea = this._specialAreas && this._specialAreas[regionName]; specialArea && region.transformTo(specialArea.left, specialArea.top, specialArea.width, specialArea.height); }, this), rawRegions; }, GeoJSONResource.prototype.getMapForUser = function() { return { geoJson: this._geoJSON, geoJSON: this._geoJSON, specialAreas: this._specialAreas }; }, GeoJSONResource; }(), storage = createHashMap(), geoSourceManager = { registerMap: function(mapName, rawDef, rawSpecialAreas) { if (rawDef.svg) { var resource = new GeoSVGResource(mapName, rawDef.svg); storage.set(mapName, resource); } else { var geoJSON = rawDef.geoJson || rawDef.geoJSON; geoJSON && !rawDef.features ? rawSpecialAreas = rawDef.specialAreas : geoJSON = rawDef; var resource = new GeoJSONResource(mapName, geoJSON, rawSpecialAreas); storage.set(mapName, resource); } }, getGeoResource: function(mapName) { return storage.get(mapName); }, getMapForUser: function(mapName) { var resource = storage.get(mapName); return resource && 'geoJSON' === resource.type && resource.getMapForUser(); }, load: function(mapName, nameMap, nameProperty) { var resource = storage.get(mapName); if (!resource) { console.error('Map ' + mapName + ' not exists. The GeoJSON of the map must be provided.'); return; } return resource.load(nameMap, nameProperty); } }, hasWindow = 'undefined' != typeof window, PRIORITY = { PROCESSOR: { FILTER: 1000, SERIES_FILTER: 800, STATISTIC: 5000 }, VISUAL: { LAYOUT: 1000, PROGRESSIVE_LAYOUT: 1100, GLOBAL: 2000, CHART: 3000, POST_CHART_LAYOUT: 4600, COMPONENT: 4000, BRUSH: 5000, CHART_ITEM: 4500, ARIA: 6000, DECAL: 7000 } }, IN_MAIN_PROCESS_KEY = '__flagInMainProcess', OPTION_UPDATED_KEY = '__optionUpdated', STATUS_NEEDS_UPDATE_KEY = '__needsUpdateStatus', ACTION_REG = /^[a-zA-Z0-9_]+$/, CONNECT_STATUS_KEY = '__connectUpdateStatus'; function createRegisterEventWithLowercaseECharts(method) { return function() { for(var args = [], _i = 0; _i < arguments.length; _i++)args[_i] = arguments[_i]; if (this.isDisposed()) { disposedWarning(this.id); return; } return toLowercaseNameAndCallEventful(this, method, args); }; } function createRegisterEventWithLowercaseMessageCenter(method) { return function() { for(var args = [], _i = 0; _i < arguments.length; _i++)args[_i] = arguments[_i]; return toLowercaseNameAndCallEventful(this, method, args); }; } function toLowercaseNameAndCallEventful(host, method, args) { return args[0] = args[0] && args[0].toLowerCase(), Eventful.prototype[method].apply(host, args); } var MessageCenter = function(_super) { function MessageCenter() { return null !== _super && _super.apply(this, arguments) || this; } return __extends(MessageCenter, _super), MessageCenter; }(Eventful), messageCenterProto = MessageCenter.prototype; messageCenterProto.on = createRegisterEventWithLowercaseMessageCenter('on'), messageCenterProto.off = createRegisterEventWithLowercaseMessageCenter('off'); var ECharts = function(_super) { function ECharts(dom, theme, opts) { var _this = _super.call(this, new ECEventProcessor()) || this; _this._chartsViews = [], _this._chartsMap = {}, _this._componentsViews = [], _this._componentsMap = {}, _this._pendingActions = [], opts = opts || {}, 'string' == typeof theme && (theme = themeStorage[theme]), _this._dom = dom; var defaultRenderer = 'canvas', defaultUseDirtyRect = !1, root = hasWindow ? window : global; defaultRenderer = root.__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer; var devUseDirtyRect = root.__ECHARTS__DEFAULT__USE_DIRTY_RECT__; defaultUseDirtyRect = null == devUseDirtyRect ? defaultUseDirtyRect : devUseDirtyRect; var zr = _this._zr = init(dom, { renderer: opts.renderer || defaultRenderer, devicePixelRatio: opts.devicePixelRatio, width: opts.width, height: opts.height, useDirtyRect: null == opts.useDirtyRect ? defaultUseDirtyRect : opts.useDirtyRect }); _this._throttledZrFlush = throttle(bind(zr.flush, zr), 17), (theme = clone(theme)) && globalBackwardCompat(theme, !0), _this._theme = theme, _this._locale = function(locale) { if (!isString(locale)) return merge(clone(locale), clone(localeStorage.EN), !1); var localeObj = localeStorage[locale.toUpperCase()] || {}; return 'ZH' === locale || 'EN' === locale ? clone(localeObj) : merge(clone(localeObj), clone(localeStorage.EN), !1); }(opts.locale || SYSTEM_LANG), _this._coordSysMgr = new CoordinateSystemManager(); var api = _this._api = createExtensionAPI(_this); function prioritySortFunc(a, b) { return a.__prio - b.__prio; } return sort(visualFuncs, prioritySortFunc), sort(dataProcessorFuncs, prioritySortFunc), _this._scheduler = new Scheduler(_this, api, dataProcessorFuncs, visualFuncs), _this._messageCenter = new MessageCenter(), _this._labelManager = new LabelManager(), _this._initEvents(), _this.resize = bind(_this.resize, _this), zr.animation.on('frame', _this._onframe, _this), bindRenderedEvent(zr, _this), bindMouseEvent(zr, _this), setAsPrimitive(_this), _this; } return __extends(ECharts, _super), ECharts.prototype._onframe = function() { if (!this._disposed) { applyChangedStates(this); var scheduler = this._scheduler; if (this[OPTION_UPDATED_KEY]) { var silent = this[OPTION_UPDATED_KEY].silent; this[IN_MAIN_PROCESS_KEY] = !0, prepare(this), updateMethods.update.call(this), this._zr.flush(), this[IN_MAIN_PROCESS_KEY] = !1, this[OPTION_UPDATED_KEY] = !1, flushPendingActions.call(this, silent), triggerUpdatedEvent.call(this, silent); } else if (scheduler.unfinished) { var remainTime = 1, ecModel = this._model, api = this._api; scheduler.unfinished = !1; do { var startTime = +new Date(); scheduler.performSeriesTasks(ecModel), scheduler.performDataProcessorTasks(ecModel), updateStreamModes(this, ecModel), scheduler.performVisualTasks(ecModel), renderSeries(this, this._model, api, 'remain'), remainTime -= +new Date() - startTime; }while (remainTime > 0 && scheduler.unfinished) scheduler.unfinished || this._zr.flush(); } } }, ECharts.prototype.getDom = function() { return this._dom; }, ECharts.prototype.getId = function() { return this.id; }, ECharts.prototype.getZr = function() { return this._zr; }, ECharts.prototype.setOption = function(option, notMerge, lazyUpdate) { if (assert(!this[IN_MAIN_PROCESS_KEY], '`setOption` should not be called during main process.'), this._disposed) { disposedWarning(this.id); return; } if (isObject(notMerge) && (lazyUpdate = notMerge.lazyUpdate, silent = notMerge.silent, replaceMerge = notMerge.replaceMerge, transitionOpt = notMerge.transition, notMerge = notMerge.notMerge), this[IN_MAIN_PROCESS_KEY] = !0, !this._model || notMerge) { var silent, replaceMerge, transitionOpt, optionManager = new OptionManager(this._api), theme = this._theme, ecModel = this._model = new GlobalModel(); ecModel.scheduler = this._scheduler, ecModel.init(null, null, null, theme, this._locale, optionManager); } this._model.setOption(option, { replaceMerge: replaceMerge }, optionPreprocessorFuncs), setTransitionOpt(this, transitionOpt), lazyUpdate ? (this[OPTION_UPDATED_KEY] = { silent: silent }, this[IN_MAIN_PROCESS_KEY] = !1, this.getZr().wakeUp()) : (prepare(this), updateMethods.update.call(this), this._zr.flush(), this[OPTION_UPDATED_KEY] = !1, this[IN_MAIN_PROCESS_KEY] = !1, flushPendingActions.call(this, silent), triggerUpdatedEvent.call(this, silent)); }, ECharts.prototype.setTheme = function() { console.error('ECharts#setTheme() is DEPRECATED in ECharts 3.0'); }, ECharts.prototype.getModel = function() { return this._model; }, ECharts.prototype.getOption = function() { return this._model && this._model.getOption(); }, ECharts.prototype.getWidth = function() { return this._zr.getWidth(); }, ECharts.prototype.getHeight = function() { return this._zr.getHeight(); }, ECharts.prototype.getDevicePixelRatio = function() { return this._zr.painter.dpr || hasWindow && window.devicePixelRatio || 1; }, ECharts.prototype.getRenderedCanvas = function(opts) { if (env1.canvasSupported) return (opts = extend({}, opts || {})).pixelRatio = opts.pixelRatio || this.getDevicePixelRatio(), opts.backgroundColor = opts.backgroundColor || this._model.get('backgroundColor'), this._zr.painter.getRenderedCanvas(opts); }, ECharts.prototype.getSvgDataURL = function() { if (env1.svgSupported) { var zr = this._zr; return each(zr.storage.getDisplayList(), function(el) { el.stopAnimation(null, !0); }), zr.painter.toDataURL(); } }, ECharts.prototype.getDataURL = function(opts) { if (this._disposed) { disposedWarning(this.id); return; } var excludeComponents = (opts = opts || {}).excludeComponents, ecModel = this._model, excludesComponentViews = [], self1 = this; each(excludeComponents, function(componentType) { ecModel.eachComponent({ mainType: componentType }, function(component) { var view = self1._componentsMap[component.__viewId]; view.group.ignore || (excludesComponentViews.push(view), view.group.ignore = !0); }); }); var url = 'svg' === this._zr.painter.getType() ? this.getSvgDataURL() : this.getRenderedCanvas(opts).toDataURL('image/' + (opts && opts.type || 'png')); return each(excludesComponentViews, function(view) { view.group.ignore = !1; }), url; }, ECharts.prototype.getConnectedDataURL = function(opts) { if (this._disposed) { disposedWarning(this.id); return; } if (env1.canvasSupported) { var isSvg = 'svg' === opts.type, groupId = this.group, mathMin = Math.min, mathMax = Math.max, MAX_NUMBER = 1 / 0; if (!connectedGroups[groupId]) return this.getDataURL(opts); var left_1 = MAX_NUMBER, top_1 = MAX_NUMBER, right_1 = -MAX_NUMBER, bottom_1 = -MAX_NUMBER, canvasList_1 = [], dpr_1 = opts && opts.pixelRatio || this.getDevicePixelRatio(); each(instances$1, function(chart, id) { if (chart.group === groupId) { var canvas = isSvg ? chart.getZr().painter.getSvgDom().innerHTML : chart.getRenderedCanvas(clone(opts)), boundingRect = chart.getDom().getBoundingClientRect(); left_1 = mathMin(boundingRect.left, left_1), top_1 = mathMin(boundingRect.top, top_1), right_1 = mathMax(boundingRect.right, right_1), bottom_1 = mathMax(boundingRect.bottom, bottom_1), canvasList_1.push({ dom: canvas, left: boundingRect.left, top: boundingRect.top }); } }), left_1 *= dpr_1, top_1 *= dpr_1; var width = (right_1 *= dpr_1) - left_1, height = (bottom_1 *= dpr_1) - top_1, targetCanvas = createCanvas(), zr_1 = init(targetCanvas, { renderer: isSvg ? 'svg' : 'canvas' }); if (zr_1.resize({ width: width, height: height }), !isSvg) return opts.connectedBackgroundColor && zr_1.add(new Rect({ shape: { x: 0, y: 0, width: width, height: height }, style: { fill: opts.connectedBackgroundColor } })), each(canvasList_1, function(item) { var img = new ZRImage({ style: { x: item.left * dpr_1 - left_1, y: item.top * dpr_1 - top_1, image: item.dom } }); zr_1.add(img); }), zr_1.refreshImmediately(), targetCanvas.toDataURL('image/' + (opts && opts.type || 'png')); var content_1 = ''; return each(canvasList_1, function(item) { content_1 += '' + item.dom + ''; }), zr_1.painter.getSvgRoot().innerHTML = content_1, opts.connectedBackgroundColor && zr_1.painter.setBackgroundColor(opts.connectedBackgroundColor), zr_1.refreshImmediately(), zr_1.painter.toDataURL(); } }, ECharts.prototype.convertToPixel = function(finder, value) { return doConvertPixel(this, 'convertToPixel', finder, value); }, ECharts.prototype.convertFromPixel = function(finder, value) { return doConvertPixel(this, 'convertFromPixel', finder, value); }, ECharts.prototype.containPixel = function(finder, value) { var result; if (this._disposed) { disposedWarning(this.id); return; } return each(parseFinder(this._model, finder), function(models, key) { key.indexOf('Models') >= 0 && each(models, function(model) { var coordSys = model.coordinateSystem; if (coordSys && coordSys.containPoint) result = result || !!coordSys.containPoint(value); else if ('seriesModels' === key) { var view = this._chartsMap[model.__viewId]; view && view.containPoint ? result = result || view.containPoint(value, model) : console.warn(key + ': ' + (view ? 'The found component do not support containPoint.' : 'No view mapping to the found component.')); } else console.warn(key + ': containPoint is not supported'); }, this); }, this), !!result; }, ECharts.prototype.getVisual = function(finder, visualType) { var parsedFinder = parseFinder(this._model, finder, { defaultMainType: 'series' }), seriesModel = parsedFinder.seriesModel; seriesModel || console.warn('There is no specified seires model'); var data = seriesModel.getData(), dataIndexInside = parsedFinder.hasOwnProperty('dataIndexInside') ? parsedFinder.dataIndexInside : parsedFinder.hasOwnProperty('dataIndex') ? data.indexOfRawIndex(parsedFinder.dataIndex) : null; return null != dataIndexInside ? getItemVisualFromData(data, dataIndexInside, visualType) : getVisualFromData(data, visualType); }, ECharts.prototype.getViewOfComponentModel = function(componentModel) { return this._componentsMap[componentModel.__viewId]; }, ECharts.prototype.getViewOfSeriesModel = function(seriesModel) { return this._chartsMap[seriesModel.__viewId]; }, ECharts.prototype._initEvents = function() { var _this = this; each(MOUSE_EVENT_NAMES, function(eveName) { var handler = function(e) { var params, ecModel = _this.getModel(), el = e.target, isGlobalOut = 'globalout' === eveName; if (isGlobalOut ? params = {} : el && findEventDispatcher(el, function(parent) { var ecData = getECData(parent); if (ecData && null != ecData.dataIndex) { var dataModel = ecData.dataModel || ecModel.getSeriesByIndex(ecData.seriesIndex); return params = dataModel && dataModel.getDataParams(ecData.dataIndex, ecData.dataType) || {}, !0; } if (ecData.eventData) return params = extend({}, ecData.eventData), !0; }, !0), params) { var componentType = params.componentType, componentIndex = params.componentIndex; ('markLine' === componentType || 'markPoint' === componentType || 'markArea' === componentType) && (componentType = 'series', componentIndex = params.seriesIndex); var model = componentType && null != componentIndex && ecModel.getComponent(componentType, componentIndex), view = model && _this['series' === model.mainType ? '_chartsMap' : '_componentsMap'][model.__viewId]; isGlobalOut || model && view || console.warn('model or view can not be found by params'), params.event = e, params.type = eveName, _this._$eventProcessor.eventInfo = { targetEl: el, packedEvent: params, model: model, view: view }, _this.trigger(eveName, params); } }; handler.zrEventfulCallAtLast = !0, _this._zr.on(eveName, handler, _this); }), each(eventActionMap, function(actionType, eventType) { _this._messageCenter.on(eventType, function(event) { this.trigger(eventType, event); }, _this); }), each([ 'selectchanged' ], function(eventType) { _this._messageCenter.on(eventType, function(event) { this.trigger(eventType, event); }, _this); }), function(messageCenter, ecIns, api) { messageCenter.on('selectchanged', function(params) { var ecModel = api.getModel(); params.isFromClick ? (handleSeriesLegacySelectEvents('map', 'selectchanged', ecIns, ecModel, params), handleSeriesLegacySelectEvents('pie', 'selectchanged', ecIns, ecModel, params)) : 'select' === params.fromAction ? (handleSeriesLegacySelectEvents('map', 'selected', ecIns, ecModel, params), handleSeriesLegacySelectEvents('pie', 'selected', ecIns, ecModel, params)) : 'unselect' === params.fromAction && (handleSeriesLegacySelectEvents('map', 'unselected', ecIns, ecModel, params), handleSeriesLegacySelectEvents('pie', 'unselected', ecIns, ecModel, params)); }); }(this._messageCenter, this, this._api); }, ECharts.prototype.isDisposed = function() { return this._disposed; }, ECharts.prototype.clear = function() { if (this._disposed) { disposedWarning(this.id); return; } this.setOption({ series: [] }, !0); }, ECharts.prototype.dispose = function() { if (this._disposed) { disposedWarning(this.id); return; } this._disposed = !0, setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, ''); var api = this._api, ecModel = this._model; each(this._componentsViews, function(component) { component.dispose(ecModel, api); }), each(this._chartsViews, function(chart) { chart.dispose(ecModel, api); }), this._zr.dispose(), delete instances$1[this.id]; }, ECharts.prototype.resize = function(opts) { if (assert(!this[IN_MAIN_PROCESS_KEY], '`resize` should not be called during main process.'), this._disposed) { disposedWarning(this.id); return; } this._zr.resize(opts); var ecModel = this._model; if (this._loadingFX && this._loadingFX.resize(), ecModel) { var optionChanged = ecModel.resetOption('media'), silent = opts && opts.silent; this[IN_MAIN_PROCESS_KEY] = !0, optionChanged && prepare(this), updateMethods.update.call(this, { type: 'resize', animation: extend({ duration: 0 }, opts && opts.animation) }), this[IN_MAIN_PROCESS_KEY] = !1, flushPendingActions.call(this, silent), triggerUpdatedEvent.call(this, silent); } }, ECharts.prototype.showLoading = function(name, cfg) { if (this._disposed) { disposedWarning(this.id); return; } if (isObject(name) && (cfg = name, name = ''), name = name || 'default', this.hideLoading(), !loadingEffects[name]) { console.warn('Loading effects ' + name + ' not exists.'); return; } var el = loadingEffects[name](this._api, cfg), zr = this._zr; this._loadingFX = el, zr.add(el); }, ECharts.prototype.hideLoading = function() { if (this._disposed) { disposedWarning(this.id); return; } this._loadingFX && this._zr.remove(this._loadingFX), this._loadingFX = null; }, ECharts.prototype.makeActionFromEvent = function(eventObj) { var payload = extend({}, eventObj); return payload.type = eventActionMap[eventObj.type], payload; }, ECharts.prototype.dispatchAction = function(payload, opt) { if (this._disposed) { disposedWarning(this.id); return; } if (isObject(opt) || (opt = { silent: !!opt }), actions[payload.type] && this._model) { if (this[IN_MAIN_PROCESS_KEY]) { this._pendingActions.push(payload); return; } var silent = opt.silent; doDispatchAction.call(this, payload, silent); var flush = opt.flush; flush ? this._zr.flush() : !1 !== flush && env1.browser.weChat && this._throttledZrFlush(), flushPendingActions.call(this, silent), triggerUpdatedEvent.call(this, silent); } }, ECharts.prototype.updateLabelLayout = function() { var labelManager = this._labelManager; labelManager.updateLayoutConfig(this._api), labelManager.layout(this._api), labelManager.processLabelsOverall(); }, ECharts.prototype.appendData = function(params) { if (this._disposed) { disposedWarning(this.id); return; } var seriesIndex = params.seriesIndex, seriesModel = this.getModel().getSeriesByIndex(seriesIndex); assert(params.data && seriesModel), seriesModel.appendData(params), this._scheduler.unfinished = !0, this.getZr().wakeUp(); }, ECharts.internalField = function() { function applyElementStates(el) { for(var newStates = [], oldStates = el.currentStates, i = 0; i < oldStates.length; i++){ var stateName = oldStates[i]; 'emphasis' === stateName || 'blur' === stateName || 'select' === stateName || newStates.push(stateName); } el.selected && el.states.select && newStates.push('select'), 2 === el.hoverState && el.states.emphasis ? newStates.push('emphasis') : 1 === el.hoverState && el.states.blur && newStates.push('blur'), el.useStates(newStates); } function updateZ(model, view) { model.preventAutoZ || function _updateZ(el, z, zlevel, maxZ2) { var label = el.getTextContent(), labelLine = el.getTextGuideLine(); if (el.isGroup) for(var children = el.childrenRef(), i = 0; i < children.length; i++)maxZ2 = Math.max(_updateZ(children[i], z, zlevel, maxZ2), maxZ2); else el.z = z, el.zlevel = zlevel, maxZ2 = Math.max(el.z2, maxZ2); if (label && (label.z = z, label.zlevel = zlevel, isFinite(maxZ2) && (label.z2 = maxZ2 + 2)), labelLine) { var textGuideLineConfig = el.textGuideLineConfig; labelLine.z = z, labelLine.zlevel = zlevel, isFinite(maxZ2) && (labelLine.z2 = maxZ2 + (textGuideLineConfig && textGuideLineConfig.showAbove ? 1 : -1)); } return maxZ2; }(view.group, model.get('z') || 0, model.get('zlevel') || 0, -1 / 0); } function clearStates(model, view) { view.group.traverse(function(el) { if (!isElementRemoved(el)) { var textContent = el.getTextContent(), textGuide = el.getTextGuideLine(); el.stateTransition && (el.stateTransition = null), textContent && textContent.stateTransition && (textContent.stateTransition = null), textGuide && textGuide.stateTransition && (textGuide.stateTransition = null), el.hasState() ? (el.prevStates = el.currentStates, el.clearStates()) : el.prevStates && (el.prevStates = null); } }); } function updateStates(model, view) { var stateAnimationModel = model.getModel('stateAnimation'), enableAnimation = model.isAnimationEnabled(), duration = stateAnimationModel.get('duration'), stateTransition = duration > 0 ? { duration: duration, delay: stateAnimationModel.get('delay'), easing: stateAnimationModel.get('easing') } : null; view.group.traverse(function(el) { if (el.states && el.states.emphasis && !isElementRemoved(el)) { if (el instanceof Path) { var store, selectState; (store = getSavedStates(el)).normalFill = el.style.fill, store.normalStroke = el.style.stroke, selectState = el.states.select || {}, store.selectFill = selectState.style && selectState.style.fill || null, store.selectStroke = selectState.style && selectState.style.stroke || null; } if (el.__dirty) { var prevStates = el.prevStates; prevStates && el.useStates(prevStates); } if (enableAnimation) { el.stateTransition = stateTransition; var textContent = el.getTextContent(), textGuide = el.getTextGuideLine(); textContent && (textContent.stateTransition = stateTransition), textGuide && (textGuide.stateTransition = stateTransition); } el.__dirty && applyElementStates(el); } }); } prepare = function(ecIns) { var scheduler = ecIns._scheduler; scheduler.restorePipelines(ecIns._model), scheduler.prepareStageTasks(), prepareView(ecIns, !0), prepareView(ecIns, !1), scheduler.plan(); }, prepareView = function(ecIns, isComponent) { for(var ecModel = ecIns._model, scheduler = ecIns._scheduler, viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews, viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap, zr = ecIns._zr, api = ecIns._api, i = 0; i < viewList.length; i++)viewList[i].__alive = !1; function doPrepare(model) { var requireNewView = model.__requireNewView; model.__requireNewView = !1; var viewId = '_ec_' + model.id + '_' + model.type, view = !requireNewView && viewMap[viewId]; if (!view) { var classType = parseClassType(model.type), Clazz = isComponent ? ComponentView.getClass(classType.main, classType.sub) : ChartView.getClass(classType.sub); assert(Clazz, classType.sub + ' does not exist.'), (view = new Clazz()).init(ecModel, api), viewMap[viewId] = view, viewList.push(view), zr.add(view.group); } model.__viewId = view.__id = viewId, view.__alive = !0, view.__model = model, view.group.__ecComponentInfo = { mainType: model.mainType, index: model.componentIndex }, isComponent || scheduler.prepareView(view, model, ecModel, api); } isComponent ? ecModel.eachComponent(function(componentType, model) { 'series' !== componentType && doPrepare(model); }) : ecModel.eachSeries(doPrepare); for(var i = 0; i < viewList.length;){ var view = viewList[i]; view.__alive ? i++ : (isComponent || view.renderTask.dispose(), zr.remove(view.group), view.dispose(ecModel, api), viewList.splice(i, 1), viewMap[view.__id] === view && delete viewMap[view.__id], view.__id = view.group.__ecComponentInfo = null); } }, updateDirectly = function(ecIns, method, payload, mainType, subType) { var excludeSeriesIdMap, ecModel = ecIns._model; if (ecModel.setUpdatePayload(payload), !mainType) { each([].concat(ecIns._componentsViews).concat(ecIns._chartsViews), callView); return; } var query = {}; query[mainType + 'Id'] = payload[mainType + 'Id'], query[mainType + 'Index'] = payload[mainType + 'Index'], query[mainType + 'Name'] = payload[mainType + 'Name']; var condition = { mainType: mainType, query: query }; subType && (condition.subType = subType); var excludeSeriesId = payload.excludeSeriesId; function callView(view) { view && view.__alive && view[method] && view[method](view.__model, ecModel, ecIns._api, payload); } null != excludeSeriesId && (excludeSeriesIdMap = createHashMap(), each(normalizeToArray(excludeSeriesId), function(id) { var modelId = convertOptionIdName(id, null); null != modelId && excludeSeriesIdMap.set(modelId, !0); })), isHighDownPayload(payload) && allLeaveBlur(ecIns._api), ecModel && ecModel.eachComponent(condition, function(model) { if (!excludeSeriesIdMap || null == excludeSeriesIdMap.get(model.id)) { if (isHighDownPayload(payload)) { if (model instanceof SeriesModel) payload.type !== HIGHLIGHT_ACTION_TYPE || payload.notBlur || function(seriesModel, payload, api) { var seriesIndex = seriesModel.seriesIndex, data = seriesModel.getData(payload.dataType), dataIndex = queryDataIndex(data, payload); dataIndex = (isArray(dataIndex) ? dataIndex[0] : dataIndex) || 0; var el = data.getItemGraphicEl(dataIndex); if (!el) for(var count = data.count(), current = 0; !el && current < count;)el = data.getItemGraphicEl(current++); if (el) { var ecData = getECData(el); blurSeries(seriesIndex, ecData.focus, ecData.blurScope, api); } else { var focus_1 = seriesModel.get([ 'emphasis', 'focus' ]), blurScope = seriesModel.get([ 'emphasis', 'blurScope' ]); null != focus_1 && blurSeries(seriesIndex, focus_1, blurScope, api); } }(model, payload, ecIns._api); else { var _a = findComponentHighDownDispatchers(model.mainType, model.componentIndex, payload.name, ecIns._api), focusSelf = _a.focusSelf, dispatchers = _a.dispatchers; payload.type === HIGHLIGHT_ACTION_TYPE && focusSelf && !payload.notBlur && blurComponent(model.mainType, model.componentIndex, ecIns._api), dispatchers && each(dispatchers, function(dispatcher) { payload.type === HIGHLIGHT_ACTION_TYPE ? enterEmphasis(dispatcher) : leaveEmphasis(dispatcher); }); } } else isSelectChangePayload(payload) && model instanceof SeriesModel && (function(seriesModel, payload, api) { if (isSelectChangePayload(payload)) { var dataType = payload.dataType, dataIndex = queryDataIndex(seriesModel.getData(dataType), payload); isArray(dataIndex) || (dataIndex = [ dataIndex ]), seriesModel[payload.type === TOGGLE_SELECT_ACTION_TYPE ? 'toggleSelect' : payload.type === SELECT_ACTION_TYPE ? 'select' : 'unselect'](dataIndex, dataType); } }(model, payload, ecIns._api), updateSeriesElementSelection(model), markStatusToUpdate(ecIns)); callView(ecIns['series' === mainType ? '_chartsMap' : '_componentsMap'][model.__viewId]); } }, ecIns); }, updateMethods = { prepareAndUpdate: function(payload) { prepare(this), updateMethods.update.call(this, payload); }, update: function(payload) { var ecModel = this._model, api = this._api, zr = this._zr, coordSysMgr = this._coordSysMgr, scheduler = this._scheduler; if (ecModel) { ecModel.setUpdatePayload(payload), scheduler.restoreData(ecModel, payload), scheduler.performSeriesTasks(ecModel), coordSysMgr.create(ecModel, api), scheduler.performDataProcessorTasks(ecModel, payload), updateStreamModes(this, ecModel), coordSysMgr.update(ecModel, api), clearColorPalette(ecModel), scheduler.performVisualTasks(ecModel, payload), render(this, ecModel, api, payload); var backgroundColor = ecModel.get('backgroundColor') || 'transparent', darkMode = ecModel.get('darkMode'); if (env1.canvasSupported) zr.setBackgroundColor(backgroundColor), null != darkMode && 'auto' !== darkMode && zr.setDarkMode(darkMode); else { var colorArr = parse(backgroundColor); backgroundColor = stringify(colorArr, 'rgb'), 0 === colorArr[3] && (backgroundColor = 'transparent'); } performPostUpdateFuncs(ecModel, api); } }, updateTransform: function(payload) { var _this = this, ecModel = this._model, api = this._api; if (ecModel) { ecModel.setUpdatePayload(payload); var componentDirtyList = []; ecModel.eachComponent(function(componentType, componentModel) { if ('series' !== componentType) { var componentView = _this.getViewOfComponentModel(componentModel); if (componentView && componentView.__alive) { if (componentView.updateTransform) { var result = componentView.updateTransform(componentModel, ecModel, api, payload); result && result.update && componentDirtyList.push(componentView); } else componentDirtyList.push(componentView); } } }); var seriesDirtyMap = createHashMap(); ecModel.eachSeries(function(seriesModel) { var chartView = _this._chartsMap[seriesModel.__viewId]; if (chartView.updateTransform) { var result = chartView.updateTransform(seriesModel, ecModel, api, payload); result && result.update && seriesDirtyMap.set(seriesModel.uid, 1); } else seriesDirtyMap.set(seriesModel.uid, 1); }), clearColorPalette(ecModel), this._scheduler.performVisualTasks(ecModel, payload, { setDirty: !0, dirtyMap: seriesDirtyMap }), renderSeries(this, ecModel, api, payload, seriesDirtyMap), performPostUpdateFuncs(ecModel, this._api); } }, updateView: function(payload) { var ecModel = this._model; ecModel && (ecModel.setUpdatePayload(payload), ChartView.markUpdateMethod(payload, 'updateView'), clearColorPalette(ecModel), this._scheduler.performVisualTasks(ecModel, payload, { setDirty: !0 }), render(this, this._model, this._api, payload), performPostUpdateFuncs(ecModel, this._api)); }, updateVisual: function(payload) { var _this = this, ecModel = this._model; ecModel && (ecModel.setUpdatePayload(payload), ecModel.eachSeries(function(seriesModel) { seriesModel.getData().clearAllVisual(); }), ChartView.markUpdateMethod(payload, 'updateVisual'), clearColorPalette(ecModel), this._scheduler.performVisualTasks(ecModel, payload, { visualType: 'visual', setDirty: !0 }), ecModel.eachComponent(function(componentType, componentModel) { if ('series' !== componentType) { var componentView = _this.getViewOfComponentModel(componentModel); componentView && componentView.__alive && componentView.updateVisual(componentModel, ecModel, _this._api, payload); } }), ecModel.eachSeries(function(seriesModel) { _this._chartsMap[seriesModel.__viewId].updateVisual(seriesModel, ecModel, _this._api, payload); }), performPostUpdateFuncs(ecModel, this._api)); }, updateLayout: function(payload) { updateMethods.update.call(this, payload); } }, doConvertPixel = function(ecIns, methodName, finder, value) { if (ecIns._disposed) { disposedWarning(ecIns.id); return; } for(var result, ecModel = ecIns._model, coordSysList = ecIns._coordSysMgr.getCoordinateSystems(), parsedFinder = parseFinder(ecModel, finder), i = 0; i < coordSysList.length; i++){ var coordSys = coordSysList[i]; if (coordSys[methodName] && null != (result = coordSys[methodName](ecModel, parsedFinder, value))) return result; } console.warn('No coordinate system that supports ' + methodName + ' found by the given finder.'); }, updateStreamModes = function(ecIns, ecModel) { var chartsMap = ecIns._chartsMap, scheduler = ecIns._scheduler; ecModel.eachSeries(function(seriesModel) { scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]); }); }, doDispatchAction = function(payload, silent) { var eventObj, _this = this, ecModel = this.getModel(), payloadType = payload.type, escapeConnect = payload.escapeConnect, actionWrap = actions[payloadType], actionInfo = actionWrap.actionInfo, cptTypeTmp = (actionInfo.update || 'update').split(':'), updateMethod = cptTypeTmp.pop(), cptType = null != cptTypeTmp[0] && parseClassType(cptTypeTmp[0]); this[IN_MAIN_PROCESS_KEY] = !0; var payloads = [ payload ], batched = !1; payload.batch && (batched = !0, payloads = map(payload.batch, function(item) { return (item = defaults(extend({}, item), payload)).batch = null, item; })); var eventObjBatch = [], isSelectChange = isSelectChangePayload(payload), isHighDown = isHighDownPayload(payload); if (each(payloads, function(batchItem) { if ((eventObj = (eventObj = actionWrap.action(batchItem, _this._model, _this._api)) || extend({}, batchItem)).type = actionInfo.event || eventObj.type, eventObjBatch.push(eventObj), isHighDown) { var _a = preParseFinder(payload), queryOptionMap = _a.queryOptionMap; updateDirectly(_this, updateMethod, batchItem, _a.mainTypeSpecified ? queryOptionMap.keys()[0] : 'series'), markStatusToUpdate(_this); } else isSelectChange ? (updateDirectly(_this, updateMethod, batchItem, 'series'), markStatusToUpdate(_this)) : cptType && updateDirectly(_this, updateMethod, batchItem, cptType.main, cptType.sub); }), 'none' === updateMethod || isHighDown || isSelectChange || cptType || (this[OPTION_UPDATED_KEY] ? (prepare(this), updateMethods.update.call(this, payload), this[OPTION_UPDATED_KEY] = !1) : updateMethods[updateMethod].call(this, payload)), eventObj = batched ? { type: actionInfo.event || payloadType, escapeConnect: escapeConnect, batch: eventObjBatch } : eventObjBatch[0], this[IN_MAIN_PROCESS_KEY] = !1, !silent) { var messageCenter = this._messageCenter; if (messageCenter.trigger(eventObj.type, eventObj), isSelectChange) { var ret, newObj = { type: 'selectchanged', escapeConnect: escapeConnect, selected: (ret = [], ecModel.eachSeries(function(seriesModel) { each(seriesModel.getAllData(), function(_a) { _a.data; var type = _a.type, dataIndices = seriesModel.getSelectedDataIndices(); if (dataIndices.length > 0) { var item = { dataIndex: dataIndices, seriesIndex: seriesModel.seriesIndex }; null != type && (item.dataType = type), ret.push(item); } }); }), ret), isFromClick: payload.isFromClick || !1, fromAction: payload.type, fromActionPayload: payload }; messageCenter.trigger(newObj.type, newObj); } } }, flushPendingActions = function(silent) { for(var pendingActions = this._pendingActions; pendingActions.length;){ var payload = pendingActions.shift(); doDispatchAction.call(this, payload, silent); } }, triggerUpdatedEvent = function(silent) { silent || this.trigger('updated'); }, bindRenderedEvent = function(zr, ecIns) { zr.on('rendered', function(params) { ecIns.trigger('rendered', params), !zr.animation.isFinished() || ecIns[OPTION_UPDATED_KEY] || ecIns._scheduler.unfinished || ecIns._pendingActions.length || ecIns.trigger('finished'); }); }, bindMouseEvent = function(zr, ecIns) { zr.on('mouseover', function(e) { var api, ecData, _a, dispatchers, focusSelf, dispatcher = findEventDispatcher(e.target, isHighDownDispatcher); dispatcher && (api = ecIns._api, isHighDownDispatcher(dispatcher) || error('param should be highDownDispatcher'), dispatchers = (_a = findComponentHighDownDispatchers((ecData = getECData(dispatcher)).componentMainType, ecData.componentIndex, ecData.componentHighDownName, api)).dispatchers, focusSelf = _a.focusSelf, dispatchers ? (focusSelf && blurComponent(ecData.componentMainType, ecData.componentIndex, api), each(dispatchers, function(dispatcher) { return enterEmphasisWhenMouseOver(dispatcher, e); })) : (blurSeries(ecData.seriesIndex, ecData.focus, ecData.blurScope, api), 'self' === ecData.focus && blurComponent(ecData.componentMainType, ecData.componentIndex, api), enterEmphasisWhenMouseOver(dispatcher, e)), markStatusToUpdate(ecIns)); }).on('mouseout', function(e) { var api, ecData, dispatchers, dispatcher = findEventDispatcher(e.target, isHighDownDispatcher); dispatcher && (api = ecIns._api, isHighDownDispatcher(dispatcher) || error('param should be highDownDispatcher'), allLeaveBlur(api), (dispatchers = findComponentHighDownDispatchers((ecData = getECData(dispatcher)).componentMainType, ecData.componentIndex, ecData.componentHighDownName, api).dispatchers) ? each(dispatchers, function(dispatcher) { return leaveEmphasisWhenMouseOut(dispatcher, e); }) : leaveEmphasisWhenMouseOut(dispatcher, e), markStatusToUpdate(ecIns)); }).on('click', function(e) { var dispatcher = findEventDispatcher(e.target, function(target) { return null != getECData(target).dataIndex; }, !0); if (dispatcher) { var actionType = dispatcher.selected ? 'unselect' : 'select', ecData = getECData(dispatcher); ecIns._api.dispatchAction({ type: actionType, dataType: ecData.dataType, dataIndexInside: ecData.dataIndex, seriesIndex: ecData.seriesIndex, isFromClick: !0 }); } }); }, clearColorPalette = function(ecModel) { ecModel.clearColorPalette(), ecModel.eachSeries(function(seriesModel) { seriesModel.clearColorPalette(); }); }, render = function(ecIns, ecModel, api, payload) { renderComponents(ecIns, ecModel, api, payload), each(ecIns._chartsViews, function(chart) { chart.__alive = !1; }), renderSeries(ecIns, ecModel, api, payload), each(ecIns._chartsViews, function(chart) { chart.__alive || chart.remove(ecModel, api); }); }, renderComponents = function(ecIns, ecModel, api, payload, dirtyList) { each(dirtyList || ecIns._componentsViews, function(componentView) { var componentModel = componentView.__model; clearStates(componentModel, componentView), componentView.render(componentModel, ecModel, api, payload), updateZ(componentModel, componentView), updateStates(componentModel, componentView); }); }, renderSeries = function(ecIns, ecModel, api, payload, dirtyMap) { var storage, elCount, scheduler = ecIns._scheduler, labelManager = ecIns._labelManager; labelManager.clearLabels(); var unfinished = !1; ecModel.eachSeries(function(seriesModel) { var blendMode, chartView = ecIns._chartsMap[seriesModel.__viewId]; chartView.__alive = !0; var renderTask = chartView.renderTask; scheduler.updatePayload(renderTask, payload), clearStates(seriesModel, chartView), dirtyMap && dirtyMap.get(seriesModel.uid) && renderTask.dirty(), renderTask.perform(scheduler.getPerformArgs(renderTask)) && (unfinished = !0), seriesModel.__transientTransitionOpt = null, chartView.group.silent = !!seriesModel.get('silent'), blendMode = seriesModel.get('blendMode') || null, !env1.canvasSupported && blendMode && 'source-over' !== blendMode && console.warn('Only canvas support blendMode'), chartView.group.traverse(function(el) { el.isGroup || (el.style.blend = blendMode), el.eachPendingDisplayable && el.eachPendingDisplayable(function(displayable) { displayable.style.blend = blendMode; }); }), updateSeriesElementSelection(seriesModel), labelManager.addLabelsOfSeries(chartView); }), scheduler.unfinished = unfinished || scheduler.unfinished, labelManager.updateLayoutConfig(api), labelManager.layout(api), labelManager.processLabelsOverall(), ecModel.eachSeries(function(seriesModel) { var chartView = ecIns._chartsMap[seriesModel.__viewId]; updateZ(seriesModel, chartView), updateStates(seriesModel, chartView); }), storage = ecIns._zr.storage, elCount = 0, storage.traverse(function(el) { !el.isGroup && elCount++; }), !(elCount > ecModel.get('hoverLayerThreshold')) || env1.node || env1.worker || ecModel.eachSeries(function(seriesModel) { if (!seriesModel.preventUsingHoverLayer) { var chartView = ecIns._chartsMap[seriesModel.__viewId]; chartView.__alive && chartView.group.traverse(function(el) { el.states.emphasis && (el.states.emphasis.hoverLayer = !0); }); } }); }, performPostUpdateFuncs = function(ecModel, api) { each(postUpdateFuncs, function(func) { func(ecModel, api); }); }, markStatusToUpdate = function(ecIns) { ecIns[STATUS_NEEDS_UPDATE_KEY] = !0, ecIns.getZr().wakeUp(); }, applyChangedStates = function(ecIns) { ecIns[STATUS_NEEDS_UPDATE_KEY] && (ecIns.getZr().storage.traverse(function(el) { isElementRemoved(el) || applyElementStates(el); }), ecIns[STATUS_NEEDS_UPDATE_KEY] = !1); }, createExtensionAPI = function(ecIns) { return new (function(_super) { function class_1() { return null !== _super && _super.apply(this, arguments) || this; } return __extends(class_1, _super), class_1.prototype.getCoordinateSystems = function() { return ecIns._coordSysMgr.getCoordinateSystems(); }, class_1.prototype.getComponentByElement = function(el) { for(; el;){ var modelInfo = el.__ecComponentInfo; if (null != modelInfo) return ecIns._model.getComponent(modelInfo.mainType, modelInfo.index); el = el.parent; } }, class_1.prototype.enterEmphasis = function(el, highlightDigit) { enterEmphasis(el, highlightDigit), markStatusToUpdate(ecIns); }, class_1.prototype.leaveEmphasis = function(el, highlightDigit) { leaveEmphasis(el, highlightDigit), markStatusToUpdate(ecIns); }, class_1.prototype.enterBlur = function(el) { traverseUpdateState(el, singleEnterBlur), markStatusToUpdate(ecIns); }, class_1.prototype.leaveBlur = function(el) { traverseUpdateState(el, singleLeaveBlur), markStatusToUpdate(ecIns); }, class_1.prototype.enterSelect = function(el) { traverseUpdateState(el, singleEnterSelect), markStatusToUpdate(ecIns); }, class_1.prototype.leaveSelect = function(el) { traverseUpdateState(el, singleLeaveSelect), markStatusToUpdate(ecIns); }, class_1.prototype.getModel = function() { return ecIns.getModel(); }, class_1.prototype.getViewOfComponentModel = function(componentModel) { return ecIns.getViewOfComponentModel(componentModel); }, class_1.prototype.getViewOfSeriesModel = function(seriesModel) { return ecIns.getViewOfSeriesModel(seriesModel); }, class_1; }(ExtensionAPI))(ecIns); }, enableConnect = function(chart) { function updateConnectedChartsStatus(charts, status) { for(var i = 0; i < charts.length; i++)charts[i][CONNECT_STATUS_KEY] = status; } each(eventActionMap, function(actionType, eventType) { chart._messageCenter.on(eventType, function(event) { if (connectedGroups[chart.group] && 0 !== chart[CONNECT_STATUS_KEY] && (!event || !event.escapeConnect)) { var action_1 = chart.makeActionFromEvent(event), otherCharts_1 = []; each(instances$1, function(otherChart) { otherChart !== chart && otherChart.group === chart.group && otherCharts_1.push(otherChart); }), updateConnectedChartsStatus(otherCharts_1, 0), each(otherCharts_1, function(otherChart) { 1 !== otherChart[CONNECT_STATUS_KEY] && otherChart.dispatchAction(action_1); }), updateConnectedChartsStatus(otherCharts_1, 2); } }); }); }, setTransitionOpt = function(chart, transitionOpt) { var ecModel = chart._model; each(normalizeToArray(transitionOpt), function(transOpt) { var errMsg, fromOpt = transOpt.from, toOpt = transOpt.to; null == toOpt && throwError(errMsg = '`transition.to` must be specified.'); var finderOpt = { includeMainTypes: [ 'series' ], enableAll: !1, enableNone: !1 }, fromResult = fromOpt ? parseFinder(ecModel, fromOpt, finderOpt) : null, toSeries = parseFinder(ecModel, toOpt, finderOpt).seriesModel; null == toSeries && (errMsg = '', errMsg = '`transition` is only supported on series.'), fromResult && fromResult.seriesModel !== toSeries && (errMsg = '', errMsg = '`transition.from` and `transition.to` must be specified to the same series.'), null != errMsg && throwError(errMsg), toSeries.__transientTransitionOpt = { from: fromOpt ? fromOpt.dimension : null, to: toOpt.dimension, dividingMethod: transOpt.dividingMethod }; }); }; }(), ECharts; }(Eventful), echartsProto = ECharts.prototype; echartsProto.on = createRegisterEventWithLowercaseECharts('on'), echartsProto.off = createRegisterEventWithLowercaseECharts('off'), echartsProto.one = function(eventName, cb, ctx) { var self1 = this; deprecateLog('ECharts#one is deprecated.'), this.on.call(this, eventName, function wrapped() { for(var args2 = [], _i = 0; _i < arguments.length; _i++)args2[_i] = arguments[_i]; cb && cb.apply && cb.apply(this, args2), self1.off(eventName, wrapped); }, ctx); }; var MOUSE_EVENT_NAMES = [ 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove', 'mousedown', 'mouseup', 'globalout', 'contextmenu' ]; function disposedWarning(id) { console.warn('Instance ' + id + ' has been disposed'); } var actions = {}, eventActionMap = {}, dataProcessorFuncs = [], optionPreprocessorFuncs = [], postInitFuncs = [], postUpdateFuncs = [], visualFuncs = [], themeStorage = {}, loadingEffects = {}, instances$1 = {}, connectedGroups = {}, idBase = +new Date() - 0, groupIdBase = +new Date() - 0, DOM_ATTRIBUTE_KEY = '_echarts_instance_'; function disConnect(groupId) { connectedGroups[groupId] = !1; } function getInstanceByDom(dom) { return instances$1[dom.getAttribute ? dom.getAttribute(DOM_ATTRIBUTE_KEY) : dom[DOM_ATTRIBUTE_KEY]]; } function registerPreprocessor(preprocessorFunc) { 0 > indexOf(optionPreprocessorFuncs, preprocessorFunc) && optionPreprocessorFuncs.push(preprocessorFunc); } function registerProcessor(priority, processor) { normalizeRegister(dataProcessorFuncs, priority, processor, 2000); } function registerPostInit(postInitFunc) { 0 > indexOf(postInitFuncs, postInitFunc) && postInitFunc && postInitFuncs.push(postInitFunc); } function registerPostUpdate(postUpdateFunc) { 0 > indexOf(postUpdateFuncs, postUpdateFunc) && postUpdateFunc && postUpdateFuncs.push(postUpdateFunc); } function registerAction(actionInfo, eventName, action) { 'function' == typeof eventName && (action = eventName, eventName = ''); var actionType = isObject(actionInfo) ? actionInfo.type : [ actionInfo, actionInfo = { event: eventName } ][0]; actionInfo.event = (actionInfo.event || actionType).toLowerCase(), eventActionMap[eventName = actionInfo.event] || (assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName)), actions[actionType] || (actions[actionType] = { action: action, actionInfo: actionInfo }), eventActionMap[eventName] = actionType); } function registerCoordinateSystem(type, coordSysCreator) { CoordinateSystemManager.register(type, coordSysCreator); } function registerLayout(priority, layoutTask) { normalizeRegister(visualFuncs, priority, layoutTask, 1000, 'layout'); } function registerVisual(priority, visualTask) { normalizeRegister(visualFuncs, priority, visualTask, 3000, 'visual'); } var registeredTasks = []; function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) { if ((isFunction(priority) || isObject(priority)) && (fn = priority, priority = defaultPriority), isNaN(priority) || null == priority) throw Error('Illegal priority'); if (each(targetList, function(wrap) { assert(wrap.__raw !== fn); }), !(indexOf(registeredTasks, fn) >= 0)) { registeredTasks.push(fn); var stageHandler = Scheduler.wrapStageHandler(fn, visualType); stageHandler.__prio = priority, stageHandler.__raw = fn, targetList.push(stageHandler); } } function registerLoading(name, loadingFx) { loadingEffects[name] = loadingFx; } function registerMap(mapName, geoJson, specialAreas) { geoSourceManager.registerMap(mapName, geoJson, specialAreas); } var registerTransform = function(externalTransform) { var type = (externalTransform = clone(externalTransform)).type; type || throwError('Must have a `type` when `registerTransform`.'); var typeParsed = type.split(':'); 2 !== typeParsed.length && throwError('Name must include namespace like "ns:regression".'); var isBuiltIn = !1; 'echarts' === typeParsed[0] && (type = typeParsed[1], isBuiltIn = !0), externalTransform.__isBuiltIn = isBuiltIn, externalTransformMap.set(type, externalTransform); }; registerVisual(2000, { createOnAllSeries: !0, performRawSeries: !0, reset: function(seriesModel, ecModel) { var data = seriesModel.getData(), stylePath = seriesModel.visualStyleAccessPath || 'itemStyle', styleModel = seriesModel.getModel(stylePath), globalStyle = getStyleMapper(seriesModel, stylePath)(styleModel), decalOption = styleModel.getShallow('decal'); decalOption && (data.setVisual('decal', decalOption), decalOption.dirty = !0); var colorKey = getDefaultColorKey(seriesModel, stylePath), color = globalStyle[colorKey], colorCallback = isFunction(color) ? color : null, hasAutoColor = 'auto' === globalStyle.fill || 'auto' === globalStyle.stroke; if (!globalStyle[colorKey] || colorCallback || hasAutoColor) { var colorPalette = seriesModel.getColorFromPalette(seriesModel.name, null, ecModel.getSeriesCount()); globalStyle[colorKey] || (globalStyle[colorKey] = colorPalette, data.setVisual('colorFromPalette', !0)), globalStyle.fill = 'auto' === globalStyle.fill || 'function' == typeof globalStyle.fill ? colorPalette : globalStyle.fill, globalStyle.stroke = 'auto' === globalStyle.stroke || 'function' == typeof globalStyle.stroke ? colorPalette : globalStyle.stroke; } if (data.setVisual('style', globalStyle), data.setVisual('drawType', colorKey), !ecModel.isSeriesFiltered(seriesModel) && colorCallback) return data.setVisual('colorFromPalette', !1), { dataEach: function(data, idx) { var dataParams = seriesModel.getDataParams(idx), itemStyle = extend({}, globalStyle); itemStyle[colorKey] = colorCallback(dataParams), data.setItemVisual(idx, 'style', itemStyle); } }; } }), registerVisual(4500, { createOnAllSeries: !0, performRawSeries: !0, reset: function(seriesModel, ecModel) { if (!(seriesModel.ignoreStyleOnData || ecModel.isSeriesFiltered(seriesModel))) { var data = seriesModel.getData(), stylePath = seriesModel.visualStyleAccessPath || 'itemStyle', getStyle = getStyleMapper(seriesModel, stylePath), colorKey = data.getVisual('drawType'); return { dataEach: data.hasItemOption ? function(data, idx) { var rawItem = data.getRawDataItem(idx); if (rawItem && rawItem[stylePath]) { sharedModel.option = rawItem[stylePath]; var style = getStyle(sharedModel); extend(data.ensureUniqueItemVisual(idx, 'style'), style), sharedModel.option.decal && (data.setItemVisual(idx, 'decal', sharedModel.option.decal), sharedModel.option.decal.dirty = !0), colorKey in style && data.setItemVisual(idx, 'colorFromPalette', !1); } } : null }; } } }), registerVisual(4500, { performRawSeries: !0, overallReset: function(ecModel) { var paletteScopeGroupByType = createHashMap(); ecModel.eachSeries(function(seriesModel) { if (seriesModel.useColorPaletteOnData) { var colorScope = paletteScopeGroupByType.get(seriesModel.type); colorScope || (colorScope = {}, paletteScopeGroupByType.set(seriesModel.type, colorScope)), inner$3(seriesModel).scope = colorScope; } }), ecModel.eachSeries(function(seriesModel) { if (!(!seriesModel.useColorPaletteOnData || ecModel.isSeriesFiltered(seriesModel))) { var dataAll = seriesModel.getRawData(), idxMap = {}, data = seriesModel.getData(), colorScope = inner$3(seriesModel).scope, stylePath = seriesModel.visualStyleAccessPath || 'itemStyle', colorKey = getDefaultColorKey(seriesModel, stylePath); data.each(function(idx) { idxMap[data.getRawIndex(idx)] = idx; }), dataAll.each(function(rawIdx) { var idx = idxMap[rawIdx]; if (data.getItemVisual(idx, 'colorFromPalette')) { var itemStyle = data.ensureUniqueItemVisual(idx, 'style'), name_1 = dataAll.getName(rawIdx) || rawIdx + '', dataCount = dataAll.count(); itemStyle[colorKey] = seriesModel.getColorFromPalette(name_1, colorScope, dataCount); } }); } }); } }), registerVisual(2000, { createOnAllSeries: !0, performRawSeries: !0, reset: function(seriesModel, ecModel) { var data = seriesModel.getData(); if (seriesModel.legendSymbol && data.setVisual('legendSymbol', seriesModel.legendSymbol), seriesModel.hasSymbolVisual) { var symbolType = seriesModel.get('symbol'), symbolSize = seriesModel.get('symbolSize'), keepAspect = seriesModel.get('symbolKeepAspect'), symbolRotate = seriesModel.get('symbolRotate'), symbolOffset = seriesModel.get('symbolOffset'), hasSymbolTypeCallback = isFunction(symbolType), hasSymbolSizeCallback = isFunction(symbolSize), hasSymbolRotateCallback = isFunction(symbolRotate), hasSymbolOffsetCallback = isFunction(symbolOffset), seriesSymbol = !hasSymbolTypeCallback && symbolType ? symbolType : seriesModel.defaultSymbol; if (data.setVisual({ legendSymbol: seriesModel.legendSymbol || seriesSymbol, symbol: seriesSymbol, symbolSize: hasSymbolSizeCallback ? null : symbolSize, symbolKeepAspect: keepAspect, symbolRotate: hasSymbolRotateCallback ? null : symbolRotate, symbolOffset: hasSymbolOffsetCallback ? null : symbolOffset }), !ecModel.isSeriesFiltered(seriesModel)) return { dataEach: hasSymbolTypeCallback || hasSymbolSizeCallback || hasSymbolRotateCallback || hasSymbolOffsetCallback ? function(data, idx) { var rawValue = seriesModel.getRawValue(idx), params = seriesModel.getDataParams(idx); hasSymbolTypeCallback && data.setItemVisual(idx, 'symbol', symbolType(rawValue, params)), hasSymbolSizeCallback && data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params)), hasSymbolRotateCallback && data.setItemVisual(idx, 'symbolRotate', symbolRotate(rawValue, params)), hasSymbolOffsetCallback && data.setItemVisual(idx, 'symbolOffset', symbolOffset(rawValue, params)); } : null }; } } }), registerVisual(4500, { createOnAllSeries: !0, performRawSeries: !0, reset: function(seriesModel, ecModel) { if (!(!seriesModel.hasSymbolVisual || ecModel.isSeriesFiltered(seriesModel))) return { dataEach: seriesModel.getData().hasItemOption ? function(data, idx) { var itemModel = data.getItemModel(idx), itemSymbolType = itemModel.getShallow('symbol', !0), itemSymbolSize = itemModel.getShallow('symbolSize', !0), itemSymbolRotate = itemModel.getShallow('symbolRotate', !0), itemSymbolOffset = itemModel.getShallow('symbolOffset', !0), itemSymbolKeepAspect = itemModel.getShallow('symbolKeepAspect', !0); null != itemSymbolType && data.setItemVisual(idx, 'symbol', itemSymbolType), null != itemSymbolSize && data.setItemVisual(idx, 'symbolSize', itemSymbolSize), null != itemSymbolRotate && data.setItemVisual(idx, 'symbolRotate', itemSymbolRotate), null != itemSymbolOffset && data.setItemVisual(idx, 'symbolOffset', itemSymbolOffset), null != itemSymbolKeepAspect && data.setItemVisual(idx, 'symbolKeepAspect', itemSymbolKeepAspect); } : null }; } }), registerVisual(7000, function(ecModel, api) { ecModel.eachRawSeries(function(seriesModel) { if (!ecModel.isSeriesFiltered(seriesModel)) { var data = seriesModel.getData(); data.hasItemVisual() && data.each(function(idx) { var decal = data.getItemVisual(idx, 'decal'); decal && (data.ensureUniqueItemVisual(idx, 'style').decal = createOrUpdatePatternFromDecal(decal, api)); }); var decal = data.getVisual('decal'); decal && (data.getVisual('style').decal = createOrUpdatePatternFromDecal(decal, api)); } }); }), registerPreprocessor(globalBackwardCompat), registerProcessor(900, function(ecModel) { var stackInfoMap = createHashMap(); ecModel.eachSeries(function(seriesModel) { var stack = seriesModel.get('stack'); if (stack) { var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []), data = seriesModel.getData(), stackInfo = { stackResultDimension: data.getCalculationInfo('stackResultDimension'), stackedOverDimension: data.getCalculationInfo('stackedOverDimension'), stackedDimension: data.getCalculationInfo('stackedDimension'), stackedByDimension: data.getCalculationInfo('stackedByDimension'), isStackedByIndex: data.getCalculationInfo('isStackedByIndex'), data: data, seriesModel: seriesModel }; if (!stackInfo.stackedDimension || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)) return; stackInfoList.length && data.setCalculationInfo('stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel), stackInfoList.push(stackInfo); } }), stackInfoMap.each(calculateStack); }), loadingFx = function(api, opts) { defaults(opts = opts || {}, { text: 'loading', textColor: '#000', fontSize: 12, fontWeight: 'normal', fontStyle: 'normal', fontFamily: 'sans-serif', maskColor: 'rgba(255, 255, 255, 0.8)', showSpinner: !0, color: '#5470c6', spinnerRadius: 10, lineWidth: 5, zlevel: 0 }); var arc, group = new Group(), mask = new Rect({ style: { fill: opts.maskColor }, zlevel: opts.zlevel, z: 10000 }); group.add(mask); var textContent = new ZRText({ style: { text: opts.text, fill: opts.textColor, fontSize: opts.fontSize, fontWeight: opts.fontWeight, fontStyle: opts.fontStyle, fontFamily: opts.fontFamily }, zlevel: opts.zlevel, z: 10001 }), labelRect = new Rect({ style: { fill: 'none' }, textContent: textContent, textConfig: { position: 'right', distance: 10 }, zlevel: opts.zlevel, z: 10001 }); return group.add(labelRect), opts.showSpinner && ((arc = new Arc({ shape: { startAngle: -PI$3 / 2, endAngle: -PI$3 / 2 + 0.1, r: opts.spinnerRadius }, style: { stroke: opts.color, lineCap: 'round', lineWidth: opts.lineWidth }, zlevel: opts.zlevel, z: 10001 })).animateShape(!0).when(1000, { endAngle: 3 * PI$3 / 2 }).start('circularInOut'), arc.animateShape(!0).when(1000, { startAngle: 3 * PI$3 / 2 }).delay(300).start('circularInOut'), group.add(arc)), group.resize = function() { var textWidth = textContent.getBoundingRect().width, r = opts.showSpinner ? opts.spinnerRadius : 0, cx = (api.getWidth() - 2 * r - (opts.showSpinner && textWidth ? 10 : 0) - textWidth) / 2 - (opts.showSpinner && textWidth ? 0 : 5 + textWidth / 2) + (opts.showSpinner ? 0 : textWidth / 2) + (textWidth ? 0 : r), cy = api.getHeight() / 2; opts.showSpinner && arc.setShape({ cx: cx, cy: cy }), labelRect.setShape({ x: cx - r, y: cy - r, width: 2 * r, height: 2 * r }), mask.setShape({ x: 0, y: 0, width: api.getWidth(), height: api.getHeight() }); }, group.resize(), group; }, loadingEffects.default = loadingFx, registerAction({ type: HIGHLIGHT_ACTION_TYPE, event: HIGHLIGHT_ACTION_TYPE, update: HIGHLIGHT_ACTION_TYPE }, noop), registerAction({ type: DOWNPLAY_ACTION_TYPE, event: DOWNPLAY_ACTION_TYPE, update: DOWNPLAY_ACTION_TYPE }, noop), registerAction({ type: SELECT_ACTION_TYPE, event: SELECT_ACTION_TYPE, update: SELECT_ACTION_TYPE }, noop), registerAction({ type: UNSELECT_ACTION_TYPE, event: UNSELECT_ACTION_TYPE, update: UNSELECT_ACTION_TYPE }, noop), registerAction({ type: TOGGLE_SELECT_ACTION_TYPE, event: TOGGLE_SELECT_ACTION_TYPE, update: TOGGLE_SELECT_ACTION_TYPE }, noop), theme = { color: colorAll, colorLayer: [ [ '#37A2DA', '#ffd85c', '#fd7b5f' ], [ '#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5' ], [ '#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF' ], colorAll ] }, themeStorage.light = theme, themeStorage.dark = theme1; var extensions = [], extensionRegisters = { registerPreprocessor: registerPreprocessor, registerProcessor: registerProcessor, registerPostInit: registerPostInit, registerPostUpdate: registerPostUpdate, registerAction: registerAction, registerCoordinateSystem: registerCoordinateSystem, registerLayout: registerLayout, registerVisual: registerVisual, registerTransform: registerTransform, registerLoading: registerLoading, registerMap: registerMap, PRIORITY: PRIORITY, ComponentModel: ComponentModel, ComponentView: ComponentView, SeriesModel: SeriesModel, ChartView: ChartView, registerComponentModel: function(ComponentModelClass) { ComponentModel.registerClass(ComponentModelClass); }, registerComponentView: function(ComponentViewClass) { ComponentView.registerClass(ComponentViewClass); }, registerSeriesModel: function(SeriesModelClass) { SeriesModel.registerClass(SeriesModelClass); }, registerChartView: function(ChartViewClass) { ChartView.registerClass(ChartViewClass); }, registerSubTypeDefaulter: function(componentType, defaulter) { ComponentModel.registerSubTypeDefaulter(componentType, defaulter); }, registerPainter: function(painterType, PainterCtor) { painterCtors[painterType] = PainterCtor; } }; function use(ext) { if (isArray(ext)) { each(ext, function(singleExt) { use(singleExt); }); return; } indexOf(extensions, ext) >= 0 || (extensions.push(ext), isFunction(ext) && (ext = { install: ext }), ext.install(extensionRegisters)); } function dataIndexMapValueLength(valNumOrArrLengthMoreThan2) { return null == valNumOrArrLengthMoreThan2 ? 0 : valNumOrArrLengthMoreThan2.length || 1; } function defaultKeyGetter(item) { return item; } var DataDiffer = function() { function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context, diffMode) { this._old = oldArr, this._new = newArr, this._oldKeyGetter = oldKeyGetter || defaultKeyGetter, this._newKeyGetter = newKeyGetter || defaultKeyGetter, this.context = context, this._diffModeMultiple = 'multiple' === diffMode; } return DataDiffer.prototype.add = function(func) { return this._add = func, this; }, DataDiffer.prototype.update = function(func) { return this._update = func, this; }, DataDiffer.prototype.updateManyToOne = function(func) { return this._updateManyToOne = func, this; }, DataDiffer.prototype.updateOneToMany = function(func) { return this._updateOneToMany = func, this; }, DataDiffer.prototype.remove = function(func) { return this._remove = func, this; }, DataDiffer.prototype.execute = function() { this[this._diffModeMultiple ? '_executeMultiple' : '_executeOneToOne'](); }, DataDiffer.prototype._executeOneToOne = function() { var oldArr = this._old, newArr = this._new, newDataIndexMap = {}, oldDataKeyArr = Array(oldArr.length), newDataKeyArr = Array(newArr.length); this._initIndexMap(oldArr, null, oldDataKeyArr, '_oldKeyGetter'), this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter'); for(var i = 0; i < oldArr.length; i++){ var oldKey = oldDataKeyArr[i], newIdxMapVal = newDataIndexMap[oldKey], newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal); if (newIdxMapValLen > 1) { var newIdx = newIdxMapVal.shift(); 1 === newIdxMapVal.length && (newDataIndexMap[oldKey] = newIdxMapVal[0]), this._update && this._update(newIdx, i); } else 1 === newIdxMapValLen ? (newDataIndexMap[oldKey] = null, this._update && this._update(newIdxMapVal, i)) : this._remove && this._remove(i); } this._performRestAdd(newDataKeyArr, newDataIndexMap); }, DataDiffer.prototype._executeMultiple = function() { var oldArr = this._old, newArr = this._new, oldDataIndexMap = {}, newDataIndexMap = {}, oldDataKeyArr = [], newDataKeyArr = []; this._initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter'), this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter'); for(var i = 0; i < oldDataKeyArr.length; i++){ var oldKey = oldDataKeyArr[i], oldIdxMapVal = oldDataIndexMap[oldKey], newIdxMapVal = newDataIndexMap[oldKey], oldIdxMapValLen = dataIndexMapValueLength(oldIdxMapVal), newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal); if (oldIdxMapValLen > 1 && 1 === newIdxMapValLen) this._updateManyToOne && this._updateManyToOne(newIdxMapVal, oldIdxMapVal), newDataIndexMap[oldKey] = null; else if (1 === oldIdxMapValLen && newIdxMapValLen > 1) this._updateOneToMany && this._updateOneToMany(newIdxMapVal, oldIdxMapVal), newDataIndexMap[oldKey] = null; else if (1 === oldIdxMapValLen && 1 === newIdxMapValLen) this._update && this._update(newIdxMapVal, oldIdxMapVal), newDataIndexMap[oldKey] = null; else if (oldIdxMapValLen > 1) for(var i_1 = 0; i_1 < oldIdxMapValLen; i_1++)this._remove && this._remove(oldIdxMapVal[i_1]); else this._remove && this._remove(oldIdxMapVal); } this._performRestAdd(newDataKeyArr, newDataIndexMap); }, DataDiffer.prototype._performRestAdd = function(newDataKeyArr, newDataIndexMap) { for(var i = 0; i < newDataKeyArr.length; i++){ var newKey = newDataKeyArr[i], newIdxMapVal = newDataIndexMap[newKey], idxMapValLen = dataIndexMapValueLength(newIdxMapVal); if (idxMapValLen > 1) for(var j = 0; j < idxMapValLen; j++)this._add && this._add(newIdxMapVal[j]); else 1 === idxMapValLen && this._add && this._add(newIdxMapVal); newDataIndexMap[newKey] = null; } }, DataDiffer.prototype._initIndexMap = function(arr, map, keyArr, keyGetterName) { for(var cbModeMultiple = this._diffModeMultiple, i = 0; i < arr.length; i++){ var key = '_ec_' + this[keyGetterName](arr[i], i); if (cbModeMultiple || (keyArr[i] = key), map) { var idxMapVal = map[key], idxMapValLen = dataIndexMapValueLength(idxMapVal); 0 === idxMapValLen ? (map[key] = i, cbModeMultiple && keyArr.push(key)) : 1 === idxMapValLen ? map[key] = [ idxMapVal, i ] : idxMapVal.push(i); } } }, DataDiffer; }(); function getOrCreateEncodeArr(encode, dim) { return encode.hasOwnProperty(dim) || (encode[dim] = []), encode[dim]; } function getDimensionTypeByAxis(axisType) { return 'category' === axisType ? 'ordinal' : 'time' === axisType ? 'time' : 'float'; } var DataDimensionInfo = function(opt) { this.otherDims = {}, null != opt && extend(this, opt); }, mathFloor = Math.floor, UNDEFINED = 'undefined', dataCtors = { float: typeof Float64Array === UNDEFINED ? Array : Float64Array, int: typeof Int32Array === UNDEFINED ? Array : Int32Array, ordinal: Array, number: Array, time: Array }, CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array, CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array, CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array, TRANSFERABLE_PROPERTIES = [ 'hasItemOption', '_nameList', '_idList', '_invertedIndicesMap', '_rawData', '_dimValueGetter', '_count', '_rawCount', '_nameDimIdx', '_idDimIdx', '_nameRepeatCount' ], CLONE_PROPERTIES = [ '_extent', '_approximateExtent', '_rawExtent' ], List = function() { function List(dimensions, hostModel) { this.type = 'list', this._count = 0, this._rawCount = 0, this._storage = {}, this._storageArr = [], this._nameList = [], this._idList = [], this._visual = {}, this._layout = {}, this._itemVisuals = [], this._itemLayouts = [], this._graphicEls = [], this._rawExtent = {}, this._extent = {}, this._approximateExtent = {}, this._calculationInfo = {}, this.hasItemOption = !0, this.TRANSFERABLE_METHODS = [ 'cloneShallow', 'downSample', 'lttbDownSample', 'map' ], this.CHANGABLE_METHODS = [ 'filterSelf', 'selectRange' ], this.DOWNSAMPLE_METHODS = [ 'downSample', 'lttbDownSample' ], this.getRawIndex = getRawIndexWithoutIndices, dimensions = dimensions || [ 'x', 'y' ]; for(var data, summary, encode, notExtraCoordDimMap, defaultedLabel, defaultedTooltip, userOutput, dataDimsOnCoord, encodeFirstDimNotExtra, encodeLabel, encodeTooltip, dimensionInfos = {}, dimensionNames = [], invertedIndicesMap = {}, i = 0; i < dimensions.length; i++){ var dimInfoInput = dimensions[i], dimensionInfo = isString(dimInfoInput) ? new DataDimensionInfo({ name: dimInfoInput }) : dimInfoInput instanceof DataDimensionInfo ? dimInfoInput : new DataDimensionInfo(dimInfoInput), dimensionName = dimensionInfo.name; dimensionInfo.type = dimensionInfo.type || 'float', dimensionInfo.coordDim || (dimensionInfo.coordDim = dimensionName, dimensionInfo.coordDimIndex = 0); var otherDims = dimensionInfo.otherDims = dimensionInfo.otherDims || {}; dimensionNames.push(dimensionName), dimensionInfos[dimensionName] = dimensionInfo, dimensionInfo.index = i, dimensionInfo.createInvertedIndices && (invertedIndicesMap[dimensionName] = []), 0 === otherDims.itemName && (this._nameDimIdx = i, this._nameOrdinalMeta = dimensionInfo.ordinalMeta), 0 === otherDims.itemId && (this._idDimIdx = i, this._idOrdinalMeta = dimensionInfo.ordinalMeta); } this.dimensions = dimensionNames, this._dimensionInfos = dimensionInfos, this.hostModel = hostModel, this._dimensionsSummary = (data = this, encode = (summary = {}).encode = {}, notExtraCoordDimMap = createHashMap(), defaultedLabel = [], defaultedTooltip = [], userOutput = summary.userOutput = { dimensionNames: data.dimensions.slice(), encode: {} }, each(data.dimensions, function(dimName) { var dimItem = data.getDimensionInfo(dimName), coordDim = dimItem.coordDim; if (coordDim) { assert(null == VISUAL_DIMENSIONS.get(coordDim)); var dimType, coordDimIndex = dimItem.coordDimIndex; getOrCreateEncodeArr(encode, coordDim)[coordDimIndex] = dimName, dimItem.isExtraCoord || (notExtraCoordDimMap.set(coordDim, 1), 'ordinal' === (dimType = dimItem.type) || 'time' === dimType || (defaultedLabel[0] = dimName), getOrCreateEncodeArr(userOutput.encode, coordDim)[coordDimIndex] = dimItem.index), dimItem.defaultTooltip && defaultedTooltip.push(dimName); } VISUAL_DIMENSIONS.each(function(v, otherDim) { var encodeArr = getOrCreateEncodeArr(encode, otherDim), dimIndex = dimItem.otherDims[otherDim]; null != dimIndex && !1 !== dimIndex && (encodeArr[dimIndex] = dimItem.name); }); }), dataDimsOnCoord = [], encodeFirstDimNotExtra = {}, notExtraCoordDimMap.each(function(v, coordDim) { var dimArr = encode[coordDim]; encodeFirstDimNotExtra[coordDim] = dimArr[0], dataDimsOnCoord = dataDimsOnCoord.concat(dimArr); }), summary.dataDimsOnCoord = dataDimsOnCoord, summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra, (encodeLabel = encode.label) && encodeLabel.length && (defaultedLabel = encodeLabel.slice()), (encodeTooltip = encode.tooltip) && encodeTooltip.length ? defaultedTooltip = encodeTooltip.slice() : defaultedTooltip.length || (defaultedTooltip = defaultedLabel.slice()), encode.defaultedLabel = defaultedLabel, encode.defaultedTooltip = defaultedTooltip, summary), this._invertedIndicesMap = invertedIndicesMap, this.userOutput = this._dimensionsSummary.userOutput; } return List.prototype.getDimension = function(dim) { return 'number' != typeof dim && (isNaN(dim) || this._dimensionInfos.hasOwnProperty(dim)) || (dim = this.dimensions[dim]), dim; }, List.prototype.getDimensionInfo = function(dim) { return this._dimensionInfos[this.getDimension(dim)]; }, List.prototype.getDimensionsOnCoord = function() { return this._dimensionsSummary.dataDimsOnCoord.slice(); }, List.prototype.mapDimension = function(coordDim, idx) { var dimensionsSummary = this._dimensionsSummary; if (null == idx) return dimensionsSummary.encodeFirstDimNotExtra[coordDim]; var dims = dimensionsSummary.encode[coordDim]; return dims ? dims[idx] : null; }, List.prototype.mapDimensionsAll = function(coordDim) { return (this._dimensionsSummary.encode[coordDim] || []).slice(); }, List.prototype.initData = function(data, nameList, dimValueGetter) { var notProvider = isSourceInstance(data) || isArrayLike(data), provider = notProvider ? new DefaultDataProvider(data, this.dimensions.length) : data; assert(notProvider || isFunction(provider.getItem) && isFunction(provider.count), 'Inavlid data provider.'), this._rawData = provider; var sourceFormat = provider.getSource().sourceFormat; this._storage = {}, this._indices = null, this._dontMakeIdFromName = null != this._idDimIdx || sourceFormat === SOURCE_FORMAT_TYPED_ARRAY || !!provider.fillStorage, this._nameList = (nameList || []).slice(), this._idList = [], this._nameRepeatCount = {}, dimValueGetter || (this.hasItemOption = !1), this.defaultDimValueGetter = defaultDimValueGetters[sourceFormat], this._dimValueGetter = dimValueGetter = dimValueGetter || this.defaultDimValueGetter, this._dimValueGetterArrayRows = defaultDimValueGetters.arrayRows, this._rawExtent = {}, this._initDataFromProvider(0, provider.count()), provider.pure && (this.hasItemOption = !1); }, List.prototype.getProvider = function() { return this._rawData; }, List.prototype.appendData = function(data) { assert(!this._indices, 'appendData can only be called on raw data.'); var rawData = this._rawData, start = this.count(); rawData.appendData(data); var end = rawData.count(); rawData.persistent || (end += start), this._initDataFromProvider(start, end, !0); }, List.prototype.appendValues = function(values, names) { for(var storage = this._storage, dimensions = this.dimensions, dimLen = dimensions.length, rawExtent = this._rawExtent, start = this.count(), end = start + Math.max(values.length, names ? names.length : 0), i = 0; i < dimLen; i++){ var dim = dimensions[i]; rawExtent[dim] || (rawExtent[dim] = getInitialExtent()), prepareStorage(storage, this._dimensionInfos[dim], end, !0); } for(var rawExtentArr = map(dimensions, function(dim) { return rawExtent[dim]; }), storageArr = this._storageArr = map(dimensions, function(dim) { return storage[dim]; }), emptyDataItem = [], idx = start; idx < end; idx++){ for(var sourceIdx = idx - start, dimIdx = 0; dimIdx < dimLen; dimIdx++){ var dim = dimensions[dimIdx], val = this._dimValueGetterArrayRows(values[sourceIdx] || emptyDataItem, dim, sourceIdx, dimIdx); storageArr[dimIdx][idx] = val; var dimRawExtent = rawExtentArr[dimIdx]; val < dimRawExtent[0] && (dimRawExtent[0] = val), val > dimRawExtent[1] && (dimRawExtent[1] = val); } names && (this._nameList[idx] = names[sourceIdx], this._dontMakeIdFromName || makeIdFromName(this, idx)); } this._rawCount = this._count = end, this._extent = {}, prepareInvertedIndex(this); }, List.prototype._initDataFromProvider = function(start, end, append) { if (!(start >= end)) { for(var rawData = this._rawData, storage = this._storage, dimensions = this.dimensions, dimLen = dimensions.length, dimensionInfoMap = this._dimensionInfos, nameList = this._nameList, idList = this._idList, rawExtent = this._rawExtent, isFormatOriginal = rawData.getSource().sourceFormat === SOURCE_FORMAT_ORIGINAL, i = 0; i < dimLen; i++){ var dim = dimensions[i]; rawExtent[dim] || (rawExtent[dim] = getInitialExtent()), prepareStorage(storage, dimensionInfoMap[dim], end, append); } var storageArr = this._storageArr = map(dimensions, function(dim) { return storage[dim]; }), rawExtentArr = map(dimensions, function(dim) { return rawExtent[dim]; }); if (rawData.fillStorage) rawData.fillStorage(start, end, storageArr, rawExtentArr); else for(var dataItem = [], idx = start; idx < end; idx++){ dataItem = rawData.getItem(idx, dataItem); for(var dimIdx = 0; dimIdx < dimLen; dimIdx++){ var dim = dimensions[dimIdx], dimStorage = storageArr[dimIdx], val = this._dimValueGetter(dataItem, dim, idx, dimIdx); dimStorage[idx] = val; var dimRawExtent = rawExtentArr[dimIdx]; val < dimRawExtent[0] && (dimRawExtent[0] = val), val > dimRawExtent[1] && (dimRawExtent[1] = val); } if (isFormatOriginal && !rawData.pure && dataItem) { var itemName = dataItem.name; null == nameList[idx] && null != itemName && (nameList[idx] = convertOptionIdName(itemName, null)); var itemId = dataItem.id; null == idList[idx] && null != itemId && (idList[idx] = convertOptionIdName(itemId, null)); } this._dontMakeIdFromName || makeIdFromName(this, idx); } !rawData.persistent && rawData.clean && rawData.clean(), this._rawCount = this._count = end, this._extent = {}, prepareInvertedIndex(this); } }, List.prototype.count = function() { return this._count; }, List.prototype.getIndices = function() { var newIndices, indices = this._indices; if (indices) { var Ctor = indices.constructor, thisCount = this._count; if (Ctor === Array) { newIndices = new Ctor(thisCount); for(var i = 0; i < thisCount; i++)newIndices[i] = indices[i]; } else newIndices = new Ctor(indices.buffer, 0, thisCount); } else { var Ctor = getIndicesCtor(this); newIndices = new Ctor(this.count()); for(var i = 0; i < newIndices.length; i++)newIndices[i] = i; } return newIndices; }, List.prototype.getByDimIdx = function(dimIdx, idx) { if (!(idx >= 0 && idx < this._count)) return NaN; var dimStore = this._storageArr[dimIdx]; return dimStore ? dimStore[this.getRawIndex(idx)] : NaN; }, List.prototype.get = function(dim, idx) { if (!(idx >= 0 && idx < this._count)) return NaN; var dimStore = this._storage[dim]; return dimStore ? dimStore[this.getRawIndex(idx)] : NaN; }, List.prototype.getByRawIndex = function(dim, rawIdx) { if (!(rawIdx >= 0 && rawIdx < this._rawCount)) return NaN; var dimStore = this._storage[dim]; return dimStore ? dimStore[rawIdx] : NaN; }, List.prototype.getValues = function(dimensions, idx) { var values = []; isArray(dimensions) || (idx = dimensions, dimensions = this.dimensions); for(var i = 0, len = dimensions.length; i < len; i++)values.push(this.get(dimensions[i], idx)); return values; }, List.prototype.hasValue = function(idx) { for(var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord, i = 0, len = dataDimsOnCoord.length; i < len; i++)if (isNaN(this.get(dataDimsOnCoord[i], idx))) return !1; return !0; }, List.prototype.getDataExtent = function(dim) { dim = this.getDimension(dim); var dimExtent, dimData = this._storage[dim], initialExtent = getInitialExtent(); if (!dimData) return initialExtent; var currEnd = this.count(); if (!this._indices) return this._rawExtent[dim].slice(); if (dimExtent = this._extent[dim]) return dimExtent.slice(); for(var min = (dimExtent = initialExtent)[0], max = dimExtent[1], i = 0; i < currEnd; i++){ var value = dimData[this.getRawIndex(i)]; value < min && (min = value), value > max && (max = value); } return dimExtent = [ min, max ], this._extent[dim] = dimExtent, dimExtent; }, List.prototype.getApproximateExtent = function(dim) { return dim = this.getDimension(dim), this._approximateExtent[dim] || this.getDataExtent(dim); }, List.prototype.setApproximateExtent = function(extent, dim) { dim = this.getDimension(dim), this._approximateExtent[dim] = extent.slice(); }, List.prototype.getCalculationInfo = function(key) { return this._calculationInfo[key]; }, List.prototype.setCalculationInfo = function(key, value) { isObject(key) ? extend(this._calculationInfo, key) : this._calculationInfo[key] = value; }, List.prototype.getSum = function(dim) { var dimData = this._storage[dim], sum = 0; if (dimData) for(var i = 0, len = this.count(); i < len; i++){ var value = this.get(dim, i); isNaN(value) || (sum += value); } return sum; }, List.prototype.getMedian = function(dim) { var dimDataArray = []; this.each(dim, function(val) { isNaN(val) || dimDataArray.push(val); }); var sortedDimDataArray = dimDataArray.sort(function(a, b) { return a - b; }), len = this.count(); return 0 === len ? 0 : len % 2 == 1 ? sortedDimDataArray[(len - 1) / 2] : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2; }, List.prototype.rawIndexOf = function(dim, value) { var invertedIndices = dim && this._invertedIndicesMap[dim]; if (!invertedIndices) throw Error('Do not supported yet'); var rawIndex = invertedIndices[value]; return null == rawIndex || isNaN(rawIndex) ? -1 : rawIndex; }, List.prototype.indexOfName = function(name) { for(var i = 0, len = this.count(); i < len; i++)if (this.getName(i) === name) return i; return -1; }, List.prototype.indexOfRawIndex = function(rawIndex) { if (rawIndex >= this._rawCount || rawIndex < 0) return -1; if (!this._indices) return rawIndex; var indices = this._indices, rawDataIndex = indices[rawIndex]; if (null != rawDataIndex && rawDataIndex < this._count && rawDataIndex === rawIndex) return rawIndex; for(var left = 0, right = this._count - 1; left <= right;){ var mid = (left + right) / 2 | 0; if (indices[mid] < rawIndex) left = mid + 1; else { if (!(indices[mid] > rawIndex)) return mid; right = mid - 1; } } return -1; }, List.prototype.indicesOfNearest = function(dim, value, maxDistance) { var dimData = this._storage[dim], nearestIndices = []; if (!dimData) return nearestIndices; null == maxDistance && (maxDistance = 1 / 0); for(var minDist = 1 / 0, minDiff = -1, nearestIndicesLen = 0, i = 0, len = this.count(); i < len; i++){ var diff = value - dimData[this.getRawIndex(i)], dist = Math.abs(diff); dist <= maxDistance && ((dist < minDist || dist === minDist && diff >= 0 && minDiff < 0) && (minDist = dist, minDiff = diff, nearestIndicesLen = 0), diff === minDiff && (nearestIndices[nearestIndicesLen++] = i)); } return nearestIndices.length = nearestIndicesLen, nearestIndices; }, List.prototype.getRawDataItem = function(idx) { if (this._rawData.persistent) return this._rawData.getItem(this.getRawIndex(idx)); for(var val = [], i = 0; i < this.dimensions.length; i++){ var dim = this.dimensions[i]; val.push(this.get(dim, idx)); } return val; }, List.prototype.getName = function(idx) { var rawIndex = this.getRawIndex(idx), name = this._nameList[rawIndex]; return null == name && null != this._nameDimIdx && (name = getIdNameFromStore(this, this._nameDimIdx, this._nameOrdinalMeta, rawIndex)), null == name && (name = ''), name; }, List.prototype.getId = function(idx) { return getId(this, this.getRawIndex(idx)); }, List.prototype.each = function(dims, cb, ctx, ctxCompat) { var _this = this; if (this._count) { 'function' == typeof dims && (ctxCompat = ctx, ctx = cb, cb = dims, dims = []); var fCtx = ctx || ctxCompat || this, dimNames = map(normalizeDimensions(dims), this.getDimension, this); validateDimensions(this, dimNames); for(var dimSize = dimNames.length, dimIndices = map(dimNames, function(dimName) { return _this._dimensionInfos[dimName].index; }), storageArr = this._storageArr, i = 0, len = this.count(); i < len; i++){ var rawIdx = this.getRawIndex(i); switch(dimSize){ case 0: cb.call(fCtx, i); break; case 1: cb.call(fCtx, storageArr[dimIndices[0]][rawIdx], i); break; case 2: cb.call(fCtx, storageArr[dimIndices[0]][rawIdx], storageArr[dimIndices[1]][rawIdx], i); break; default: for(var k = 0, value = []; k < dimSize; k++)value[k] = storageArr[dimIndices[k]][rawIdx]; value[k] = i, cb.apply(fCtx, value); } } } }, List.prototype.filterSelf = function(dims, cb, ctx, ctxCompat) { var _this = this; if (this._count) { 'function' == typeof dims && (ctxCompat = ctx, ctx = cb, cb = dims, dims = []); var fCtx = ctx || ctxCompat || this, dimNames = map(normalizeDimensions(dims), this.getDimension, this); validateDimensions(this, dimNames); for(var count = this.count(), newIndices = new (getIndicesCtor(this))(count), value = [], dimSize = dimNames.length, offset = 0, dimIndices = map(dimNames, function(dimName) { return _this._dimensionInfos[dimName].index; }), dim0 = dimIndices[0], storageArr = this._storageArr, i = 0; i < count; i++){ var keep = void 0, rawIdx = this.getRawIndex(i); if (0 === dimSize) keep = cb.call(fCtx, i); else if (1 === dimSize) { var val = storageArr[dim0][rawIdx]; keep = cb.call(fCtx, val, i); } else { for(var k = 0; k < dimSize; k++)value[k] = storageArr[dimIndices[k]][rawIdx]; value[k] = i, keep = cb.apply(fCtx, value); } keep && (newIndices[offset++] = rawIdx); } return offset < count && (this._indices = newIndices), this._count = offset, this._extent = {}, this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices, this; } }, List.prototype.selectRange = function(range) { var _this = this, len = this._count; if (len) { var dimensions = []; for(var dim in range)range.hasOwnProperty(dim) && dimensions.push(dim); validateDimensions(this, dimensions); var dimSize = dimensions.length; if (dimSize) { var originalCount = this.count(), newIndices = new (getIndicesCtor(this))(originalCount), offset = 0, dim0 = dimensions[0], dimIndices = map(dimensions, function(dimName) { return _this._dimensionInfos[dimName].index; }), min = range[dim0][0], max = range[dim0][1], storageArr = this._storageArr, quickFinished = !1; if (!this._indices) { var idx = 0; if (1 === dimSize) { for(var dimStorage = storageArr[dimIndices[0]], i = 0; i < len; i++){ var val = dimStorage[i]; (val >= min && val <= max || isNaN(val)) && (newIndices[offset++] = idx), idx++; } quickFinished = !0; } else if (2 === dimSize) { for(var dimStorage = storageArr[dimIndices[0]], dimStorage2 = storageArr[dimIndices[1]], min2 = range[dimensions[1]][0], max2 = range[dimensions[1]][1], i = 0; i < len; i++){ var val = dimStorage[i], val2 = dimStorage2[i]; (val >= min && val <= max || isNaN(val)) && (val2 >= min2 && val2 <= max2 || isNaN(val2)) && (newIndices[offset++] = idx), idx++; } quickFinished = !0; } } if (!quickFinished) { if (1 === dimSize) for(var i = 0; i < originalCount; i++){ var rawIndex = this.getRawIndex(i), val = storageArr[dimIndices[0]][rawIndex]; (val >= min && val <= max || isNaN(val)) && (newIndices[offset++] = rawIndex); } else for(var i = 0; i < originalCount; i++){ for(var keep = !0, rawIndex = this.getRawIndex(i), k = 0; k < dimSize; k++){ var dimk = dimensions[k], val = storageArr[dimIndices[k]][rawIndex]; (val < range[dimk][0] || val > range[dimk][1]) && (keep = !1); } keep && (newIndices[offset++] = this.getRawIndex(i)); } } return offset < originalCount && (this._indices = newIndices), this._count = offset, this._extent = {}, this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices, this; } } }, List.prototype.mapArray = function(dims, cb, ctx, ctxCompat) { 'function' == typeof dims && (ctxCompat = ctx, ctx = cb, cb = dims, dims = []), ctx = ctx || ctxCompat || this; var result = []; return this.each(dims, function() { result.push(cb && cb.apply(this, arguments)); }, ctx), result; }, List.prototype.map = function(dims, cb, ctx, ctxCompat) { var fCtx = ctx || ctxCompat || this, dimNames = map(normalizeDimensions(dims), this.getDimension, this); validateDimensions(this, dimNames); var list = cloneListForMapAndSample(this, dimNames), storage = list._storage; list._indices = this._indices, list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices; for(var tmpRetValue = [], dimSize = dimNames.length, dataCount = this.count(), values = [], rawExtent = list._rawExtent, dataIndex = 0; dataIndex < dataCount; dataIndex++){ for(var dimIndex = 0; dimIndex < dimSize; dimIndex++)values[dimIndex] = this.get(dimNames[dimIndex], dataIndex); values[dimSize] = dataIndex; var retValue = cb && cb.apply(fCtx, values); if (null != retValue) { 'object' != typeof retValue && (tmpRetValue[0] = retValue, retValue = tmpRetValue); for(var rawIndex = this.getRawIndex(dataIndex), i = 0; i < retValue.length; i++){ var dim = dimNames[i], val = retValue[i], rawExtentOnDim = rawExtent[dim], dimStore = storage[dim]; dimStore && (dimStore[rawIndex] = val), val < rawExtentOnDim[0] && (rawExtentOnDim[0] = val), val > rawExtentOnDim[1] && (rawExtentOnDim[1] = val); } } } return list; }, List.prototype.downSample = function(dimension, rate, sampleValue, sampleIndex) { for(var list = cloneListForMapAndSample(this, [ dimension ]), targetStorage = list._storage, frameValues = [], frameSize = mathFloor(1 / rate), dimStore = targetStorage[dimension], len = this.count(), rawExtentOnDim = list._rawExtent[dimension], newIndices = new (getIndicesCtor(this))(len), offset = 0, i = 0; i < len; i += frameSize){ frameSize > len - i && (frameSize = len - i, frameValues.length = frameSize); for(var k = 0; k < frameSize; k++){ var dataIdx = this.getRawIndex(i + k); frameValues[k] = dimStore[dataIdx]; } var value = sampleValue(frameValues), sampleFrameIdx = this.getRawIndex(Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)); dimStore[sampleFrameIdx] = value, value < rawExtentOnDim[0] && (rawExtentOnDim[0] = value), value > rawExtentOnDim[1] && (rawExtentOnDim[1] = value), newIndices[offset++] = sampleFrameIdx; } return list._count = offset, list._indices = newIndices, list.getRawIndex = getRawIndexWithIndices, list; }, List.prototype.lttbDownSample = function(valueDimension, rate) { var maxArea, area, nextRawIndex, list = cloneListForMapAndSample(this, []), dimStore = list._storage[valueDimension], len = this.count(), newIndices = new (getIndicesCtor(this))(len), sampledIndex = 0, frameSize = mathFloor(1 / rate), currentRawIndex = this.getRawIndex(0); newIndices[sampledIndex++] = currentRawIndex; for(var i = 1; i < len - 1; i += frameSize){ for(var nextFrameStart = Math.min(i + frameSize, len - 1), nextFrameEnd = Math.min(i + 2 * frameSize, len), avgX = (nextFrameEnd + nextFrameStart) / 2, avgY = 0, idx = nextFrameStart; idx < nextFrameEnd; idx++){ var rawIndex = this.getRawIndex(idx), y = dimStore[rawIndex]; isNaN(y) || (avgY += y); } avgY /= nextFrameEnd - nextFrameStart; var frameStart = i, frameEnd = Math.min(i + frameSize, len), pointAX = i - 1, pointAY = dimStore[currentRawIndex]; maxArea = -1, nextRawIndex = frameStart; for(var idx = frameStart; idx < frameEnd; idx++){ var rawIndex = this.getRawIndex(idx), y = dimStore[rawIndex]; !isNaN(y) && (area = Math.abs((pointAX - avgX) * (y - pointAY) - (pointAX - idx) * (avgY - pointAY))) > maxArea && (maxArea = area, nextRawIndex = rawIndex); } newIndices[sampledIndex++] = nextRawIndex, currentRawIndex = nextRawIndex; } return newIndices[sampledIndex++] = this.getRawIndex(len - 1), list._count = sampledIndex, list._indices = newIndices, list.getRawIndex = getRawIndexWithIndices, list; }, List.prototype.getItemModel = function(idx) { var hostModel = this.hostModel, dataItem = this.getRawDataItem(idx); return new Model(dataItem, hostModel, hostModel && hostModel.ecModel); }, List.prototype.diff = function(otherList) { var thisList = this; return new DataDiffer(otherList ? otherList.getIndices() : [], this.getIndices(), function(idx) { return getId(otherList, idx); }, function(idx) { return getId(thisList, idx); }); }, List.prototype.getVisual = function(key) { var visual = this._visual; return visual && visual[key]; }, List.prototype.setVisual = function(kvObj, val) { this._visual = this._visual || {}, isObject(kvObj) ? extend(this._visual, kvObj) : this._visual[kvObj] = val; }, List.prototype.getItemVisual = function(idx, key) { var itemVisual = this._itemVisuals[idx], val = itemVisual && itemVisual[key]; return null == val ? this.getVisual(key) : val; }, List.prototype.hasItemVisual = function() { return this._itemVisuals.length > 0; }, List.prototype.ensureUniqueItemVisual = function(idx, key) { var itemVisuals = this._itemVisuals, itemVisual = itemVisuals[idx]; itemVisual || (itemVisual = itemVisuals[idx] = {}); var val = itemVisual[key]; return null == val && (isArray(val = this.getVisual(key)) ? val = val.slice() : isObject(val) && (val = extend({}, val)), itemVisual[key] = val), val; }, List.prototype.setItemVisual = function(idx, key, value) { var itemVisual = this._itemVisuals[idx] || {}; this._itemVisuals[idx] = itemVisual, isObject(key) ? extend(itemVisual, key) : itemVisual[key] = value; }, List.prototype.clearAllVisual = function() { this._visual = {}, this._itemVisuals = []; }, List.prototype.setLayout = function(key, val) { if (isObject(key)) { for(var name_1 in key)key.hasOwnProperty(name_1) && this.setLayout(name_1, key[name_1]); return; } this._layout[key] = val; }, List.prototype.getLayout = function(key) { return this._layout[key]; }, List.prototype.getItemLayout = function(idx) { return this._itemLayouts[idx]; }, List.prototype.setItemLayout = function(idx, layout, merge) { this._itemLayouts[idx] = merge ? extend(this._itemLayouts[idx] || {}, layout) : layout; }, List.prototype.clearItemLayouts = function() { this._itemLayouts.length = 0; }, List.prototype.setItemGraphicEl = function(idx, el) { var hostModel = this.hostModel; if (el) { var ecData = getECData(el); ecData.dataIndex = idx, ecData.dataType = this.dataType, ecData.seriesIndex = hostModel && hostModel.seriesIndex, 'group' === el.type && el.traverse(setItemDataAndSeriesIndex, el); } this._graphicEls[idx] = el; }, List.prototype.getItemGraphicEl = function(idx) { return this._graphicEls[idx]; }, List.prototype.eachItemGraphicEl = function(cb, context) { each(this._graphicEls, function(el, idx) { el && cb && cb.call(context, el, idx); }); }, List.prototype.cloneShallow = function(list) { if (!list) { var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this); list = new List(dimensionInfoList, this.hostModel); } if (list._storage = this._storage, list._storageArr = this._storageArr, transferProperties(list, this), this._indices) { var Ctor = this._indices.constructor; if (Ctor === Array) { var thisCount = this._indices.length; list._indices = new Ctor(thisCount); for(var i = 0; i < thisCount; i++)list._indices[i] = this._indices[i]; } else list._indices = new Ctor(this._indices); } else list._indices = null; return list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices, list; }, List.prototype.wrapMethod = function(methodName, injectFunction) { var originalMethod = this[methodName]; 'function' == typeof originalMethod && (this.__wrappedMethods = this.__wrappedMethods || [], this.__wrappedMethods.push(methodName), this[methodName] = function() { var res = originalMethod.apply(this, arguments); return injectFunction.apply(this, [ res ].concat(slice(arguments))); }); }, List.internalField = function() { function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) { return parseDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]); } defaultDimValueGetters = { arrayRows: getDimValueSimply, objectRows: function(dataItem, dimName, dataIndex, dimIndex) { return parseDataValue(dataItem[dimName], this._dimensionInfos[dimName]); }, keyedColumns: getDimValueSimply, original: function(dataItem, dimName, dataIndex, dimIndex) { var value = dataItem && (null == dataItem.value ? dataItem : dataItem.value); return !(!this._rawData.pure && isObject(dataItem)) || dataItem instanceof Array || (this.hasItemOption = !0), parseDataValue(value instanceof Array ? value[dimIndex] : value, this._dimensionInfos[dimName]); }, typedArray: function(dataItem, dimName, dataIndex, dimIndex) { return dataItem[dimIndex]; } }, prepareInvertedIndex = function(list) { var invertedIndicesMap = list._invertedIndicesMap; each(invertedIndicesMap, function(invertedIndices, dim) { var ordinalMeta = list._dimensionInfos[dim].ordinalMeta; if (ordinalMeta) { invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array(ordinalMeta.categories.length); for(var i = 0; i < invertedIndices.length; i++)invertedIndices[i] = -1; for(var i = 0; i < list._count; i++)invertedIndices[list.get(dim, i)] = i; } }); }, getIdNameFromStore = function(list, dimIdx, ordinalMeta, rawIndex) { var val, chunk = list._storageArr[dimIdx]; return chunk && (val = chunk[rawIndex], ordinalMeta && ordinalMeta.categories.length && (val = ordinalMeta.categories[val])), convertOptionIdName(val, null); }, getIndicesCtor = function(list) { return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array; }, prepareStorage = function(storage, dimInfo, end, append) { var DataCtor = dataCtors[dimInfo.type], dim = dimInfo.name; if (append) { var oldStore = storage[dim], oldLen = oldStore && oldStore.length; if (oldLen !== end) { for(var newStore = new DataCtor(end), j = 0; j < oldLen; j++)newStore[j] = oldStore[j]; storage[dim] = newStore; } } else storage[dim] = new DataCtor(end); }, getRawIndexWithoutIndices = function(idx) { return idx; }, getRawIndexWithIndices = function(idx) { return idx < this._count && idx >= 0 ? this._indices[idx] : -1; }, getId = function(list, rawIndex) { var id = list._idList[rawIndex]; return null == id && null != list._idDimIdx && (id = getIdNameFromStore(list, list._idDimIdx, list._idOrdinalMeta, rawIndex)), null == id && (id = 'e\0\0' + rawIndex), id; }, normalizeDimensions = function(dimensions) { return isArray(dimensions) || (dimensions = null != dimensions ? [ dimensions ] : []), dimensions; }, validateDimensions = function(list, dims) { for(var i = 0; i < dims.length; i++)list._dimensionInfos[dims[i]] || console.error('Unkown dimension ' + dims[i]); }, cloneListForMapAndSample = function(original, excludeDimensions) { var allDimensions = original.dimensions, list = new List(map(allDimensions, original.getDimensionInfo, original), original.hostModel); transferProperties(list, original); for(var storage = list._storage = {}, originalStorage = original._storage, storageArr = list._storageArr = [], i = 0; i < allDimensions.length; i++){ var dim = allDimensions[i]; originalStorage[dim] && (indexOf(excludeDimensions, dim) >= 0 ? (storage[dim] = function(originalChunk) { var Ctor = originalChunk.constructor; return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk); }(originalStorage[dim]), list._rawExtent[dim] = getInitialExtent(), list._extent[dim] = null) : storage[dim] = originalStorage[dim], storageArr.push(storage[dim])); } return list; }, getInitialExtent = function() { return [ 1 / 0, -1 / 0 ]; }, setItemDataAndSeriesIndex = function(child) { var childECData = getECData(child), thisECData = getECData(this); childECData.seriesIndex = thisECData.seriesIndex, childECData.dataIndex = thisECData.dataIndex, childECData.dataType = thisECData.dataType; }, transferProperties = function(target, source) { each(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function(propName) { source.hasOwnProperty(propName) && (target[propName] = source[propName]); }), target.__wrappedMethods = source.__wrappedMethods, each(CLONE_PROPERTIES, function(propName) { target[propName] = clone(source[propName]); }), target._calculationInfo = extend({}, source._calculationInfo); }, makeIdFromName = function(list, idx) { var nameList = list._nameList, idList = list._idList, nameDimIdx = list._nameDimIdx, idDimIdx = list._idDimIdx, name = nameList[idx], id = idList[idx]; if (null == name && null != nameDimIdx && (nameList[idx] = name = getIdNameFromStore(list, nameDimIdx, list._nameOrdinalMeta, idx)), null == id && null != idDimIdx && (idList[idx] = id = getIdNameFromStore(list, idDimIdx, list._idOrdinalMeta, idx)), null == id && null != name) { var nameRepeatCount = list._nameRepeatCount, nmCnt = nameRepeatCount[name] = (nameRepeatCount[name] || 0) + 1; id = name, nmCnt > 1 && (id += '__ec__' + nmCnt), idList[idx] = id; } }; }(), List; }(); function genName(name, map, fromZero) { if (fromZero || null != map.get(name)) { for(var i = 0; null != map.get(name + i);)i++; name += i; } return map.set(name, !0), name; } function createDimensions(source, opt) { return function(sysDims, source, opt) { isSourceInstance(source) || (source = createSourceFromSeriesDataOption(source)), opt = opt || {}, sysDims = (sysDims || []).slice(); for(var dimsDef = (opt.dimsDef || []).slice(), dataDimNameMap = createHashMap(), coordDimNameMap = createHashMap(), result = [], dimCount = (source1 = source, sysDims1 = sysDims, optDimCount = opt.dimCount, dimCount1 = Math.max(source1.dimensionsDetectedCount || 1, sysDims1.length, dimsDef.length, optDimCount || 0), each(sysDims1, function(sysDimItem) { var sysDimItemDimsDef; isObject(sysDimItem) && (sysDimItemDimsDef = sysDimItem.dimsDef) && (dimCount1 = Math.max(dimCount1, sysDimItemDimsDef.length)); }), dimCount1), i = 0; i < dimCount; i++){ var dimDefItemRaw = dimsDef[i], dimDefItem = dimsDef[i] = extend({}, isObject(dimDefItemRaw) ? dimDefItemRaw : { name: dimDefItemRaw }), userDimName = dimDefItem.name, resultItem = result[i] = new DataDimensionInfo(); null != userDimName && null == dataDimNameMap.get(userDimName) && (resultItem.name = resultItem.displayName = userDimName, dataDimNameMap.set(userDimName, i)), null != dimDefItem.type && (resultItem.type = dimDefItem.type), null != dimDefItem.displayName && (resultItem.displayName = dimDefItem.displayName); } var encodeDef = opt.encodeDef; !encodeDef && opt.encodeDefaulter && (encodeDef = opt.encodeDefaulter(source, dimCount)); var encodeDefMap = createHashMap(encodeDef); encodeDefMap.each(function(dataDimsRaw, coordDim) { var dataDims = normalizeToArray(dataDimsRaw).slice(); if (1 === dataDims.length && !isString(dataDims[0]) && dataDims[0] < 0) { encodeDefMap.set(coordDim, !1); return; } var validDataDims = encodeDefMap.set(coordDim, []); each(dataDims, function(resultDimIdxOrName, idx) { var resultDimIdx = isString(resultDimIdxOrName) ? dataDimNameMap.get(resultDimIdxOrName) : resultDimIdxOrName; null != resultDimIdx && resultDimIdx < dimCount && (validDataDims[idx] = resultDimIdx, applyDim(result[resultDimIdx], coordDim, idx)); }); }); var availDimIdx = 0; function applyDim(resultItem, coordDim, coordDimIndex) { null != VISUAL_DIMENSIONS.get(coordDim) ? resultItem.otherDims[coordDim] = coordDimIndex : (resultItem.coordDim = coordDim, resultItem.coordDimIndex = coordDimIndex, coordDimNameMap.set(coordDim, !0)); } each(sysDims, function(sysDimItemRaw) { if (isString(sysDimItemRaw)) coordDim = sysDimItemRaw, sysDimItem = {}; else { coordDim = (sysDimItem = sysDimItemRaw).name; var coordDim, sysDimItemDimsDef, sysDimItemOtherDims, sysDimItem, ordinalMeta = sysDimItem.ordinalMeta; sysDimItem.ordinalMeta = null, (sysDimItem = clone(sysDimItem)).ordinalMeta = ordinalMeta, sysDimItemDimsDef = sysDimItem.dimsDef, sysDimItemOtherDims = sysDimItem.otherDims, sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex = sysDimItem.dimsDef = sysDimItem.otherDims = null; } var dataDims = encodeDefMap.get(coordDim); if (!1 !== dataDims) { if (!(dataDims = normalizeToArray(dataDims)).length) for(var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++){ for(; availDimIdx < result.length && null != result[availDimIdx].coordDim;)availDimIdx++; availDimIdx < result.length && dataDims.push(availDimIdx++); } each(dataDims, function(resultDimIdx, coordDimIndex) { var resultItem = result[resultDimIdx]; if (applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex), null == resultItem.name && sysDimItemDimsDef) { var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex]; isObject(sysDimItemDimsDefItem) || (sysDimItemDimsDefItem = { name: sysDimItemDimsDefItem }), resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name, resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip; } sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims); }); } }); var generateCoord = opt.generateCoord, generateCoordCount = opt.generateCoordCount, fromZero = null != generateCoordCount; generateCoordCount = generateCoord ? generateCoordCount || 1 : 0; for(var extra = generateCoord || 'value', resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++){ var source1, sysDims1, optDimCount, dimCount1, source2, dimIndex, resultItem = result[resultDimIdx] = result[resultDimIdx] || new DataDimensionInfo(); null == resultItem.coordDim && (resultItem.coordDim = genName(extra, coordDimNameMap, fromZero), resultItem.coordDimIndex = 0, (!generateCoord || generateCoordCount <= 0) && (resultItem.isExtraCoord = !0), generateCoordCount--), null == resultItem.name && (resultItem.name = genName(resultItem.coordDim, dataDimNameMap, !1)), null == resultItem.type && (source2 = source, dimIndex = resultDimIdx, doGuessOrdinal(source2.data, source2.sourceFormat, source2.seriesLayoutBy, source2.dimensionsDefine, source2.startIndex, dimIndex) === BE_ORDINAL.Must || resultItem.isExtraCoord && (null != resultItem.otherDims.itemName || null != resultItem.otherDims.seriesName)) && (resultItem.type = 'ordinal'); } return result; }((opt = opt || {}).coordDimensions || [], source, { dimsDef: opt.dimensionsDefine || source.dimensionsDefine, encodeDef: opt.encodeDefine || source.encodeDefine, dimCount: opt.dimensionsCount, encodeDefaulter: opt.encodeDefaulter, generateCoord: opt.generateCoord, generateCoordCount: opt.generateCoordCount }); } var CoordSysInfo = function(coordSysName) { this.coordSysDims = [], this.axisMap = createHashMap(), this.categoryAxisMap = createHashMap(), this.coordSysName = coordSysName; }, fetchers = { cartesian2d: function(seriesModel, result, axisMap, categoryAxisMap) { var xAxisModel = seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0], yAxisModel = seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0]; if (!xAxisModel) throw Error('xAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('xAxisId'), 0) + '" not found'); if (!yAxisModel) throw Error('yAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('yAxisId'), 0) + '" not found'); result.coordSysDims = [ 'x', 'y' ], axisMap.set('x', xAxisModel), axisMap.set('y', yAxisModel), isCategory(xAxisModel) && (categoryAxisMap.set('x', xAxisModel), result.firstCategoryDimIndex = 0), isCategory(yAxisModel) && (categoryAxisMap.set('y', yAxisModel), null == result.firstCategoryDimIndex && (result.firstCategoryDimIndex = 1)); }, singleAxis: function(seriesModel, result, axisMap, categoryAxisMap) { var singleAxisModel = seriesModel.getReferringComponents('singleAxis', SINGLE_REFERRING).models[0]; if (!singleAxisModel) throw Error('singleAxis should be specified.'); result.coordSysDims = [ 'single' ], axisMap.set('single', singleAxisModel), isCategory(singleAxisModel) && (categoryAxisMap.set('single', singleAxisModel), result.firstCategoryDimIndex = 0); }, polar: function(seriesModel, result, axisMap, categoryAxisMap) { var polarModel = seriesModel.getReferringComponents('polar', SINGLE_REFERRING).models[0], radiusAxisModel = polarModel.findAxisModel('radiusAxis'), angleAxisModel = polarModel.findAxisModel('angleAxis'); if (!angleAxisModel) throw Error('angleAxis option not found'); if (!radiusAxisModel) throw Error('radiusAxis option not found'); result.coordSysDims = [ 'radius', 'angle' ], axisMap.set('radius', radiusAxisModel), axisMap.set('angle', angleAxisModel), isCategory(radiusAxisModel) && (categoryAxisMap.set('radius', radiusAxisModel), result.firstCategoryDimIndex = 0), isCategory(angleAxisModel) && (categoryAxisMap.set('angle', angleAxisModel), null == result.firstCategoryDimIndex && (result.firstCategoryDimIndex = 1)); }, geo: function(seriesModel, result, axisMap, categoryAxisMap) { result.coordSysDims = [ 'lng', 'lat' ]; }, parallel: function(seriesModel, result, axisMap, categoryAxisMap) { var ecModel = seriesModel.ecModel, parallelModel = ecModel.getComponent('parallel', seriesModel.get('parallelIndex')), coordSysDims = result.coordSysDims = parallelModel.dimensions.slice(); each(parallelModel.parallelAxisIndex, function(axisIndex, index) { var axisModel = ecModel.getComponent('parallelAxis', axisIndex), axisDim = coordSysDims[index]; axisMap.set(axisDim, axisModel), isCategory(axisModel) && (categoryAxisMap.set(axisDim, axisModel), null == result.firstCategoryDimIndex && (result.firstCategoryDimIndex = index)); }); } }; function isCategory(axisModel) { return 'category' === axisModel.get('type'); } function enableDataStack(seriesModel, dimensionInfoList, opt) { var stackedByDimInfo, stackedDimInfo, stackResultDimension, stackedOverDimension, byIndex = (opt = opt || {}).byIndex, stackedCoordDimension = opt.stackedCoordDimension, mayStack = !!(seriesModel && seriesModel.get('stack')); if (each(dimensionInfoList, function(dimensionInfo, index) { isString(dimensionInfo) && (dimensionInfoList[index] = dimensionInfo = { name: dimensionInfo }), !mayStack || dimensionInfo.isExtraCoord || (byIndex || stackedByDimInfo || !dimensionInfo.ordinalMeta || (stackedByDimInfo = dimensionInfo), stackedDimInfo || 'ordinal' === dimensionInfo.type || 'time' === dimensionInfo.type || stackedCoordDimension && stackedCoordDimension !== dimensionInfo.coordDim || (stackedDimInfo = dimensionInfo)); }), !stackedDimInfo || byIndex || stackedByDimInfo || (byIndex = !0), stackedDimInfo) { stackResultDimension = '__\0ecstackresult', stackedOverDimension = '__\0ecstackedover', stackedByDimInfo && (stackedByDimInfo.createInvertedIndices = !0); var stackedDimCoordDim_1 = stackedDimInfo.coordDim, stackedDimType = stackedDimInfo.type, stackedDimCoordIndex_1 = 0; each(dimensionInfoList, function(dimensionInfo) { dimensionInfo.coordDim === stackedDimCoordDim_1 && stackedDimCoordIndex_1++; }), dimensionInfoList.push({ name: stackResultDimension, coordDim: stackedDimCoordDim_1, coordDimIndex: stackedDimCoordIndex_1, type: stackedDimType, isExtraCoord: !0, isCalculationCoord: !0 }), stackedDimCoordIndex_1++, dimensionInfoList.push({ name: stackedOverDimension, coordDim: stackedOverDimension, coordDimIndex: stackedDimCoordIndex_1, type: stackedDimType, isExtraCoord: !0, isCalculationCoord: !0 }); } return { stackedDimension: stackedDimInfo && stackedDimInfo.name, stackedByDimension: stackedByDimInfo && stackedByDimInfo.name, isStackedByIndex: byIndex, stackedOverDimension: stackedOverDimension, stackResultDimension: stackResultDimension }; } function isDimensionStacked(data, stackedDim) { return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension'); } function getStackedDimension(data, targetDim) { return isDimensionStacked(data, targetDim) ? data.getCalculationInfo('stackResultDimension') : targetDim; } function createListFromArray(source, seriesModel, opt) { opt = opt || {}, isSourceInstance(source) || (source = createSourceFromSeriesDataOption(source)); var coordSysDimDefs, firstCategoryDimIndex, hasNameEncode, coordSysName = seriesModel.get('coordinateSystem'), registeredCoordSys = CoordinateSystemManager.get(coordSysName), coordSysInfo = function(seriesModel) { var coordSysName = seriesModel.get('coordinateSystem'), result = new CoordSysInfo(coordSysName), fetch = fetchers[coordSysName]; if (fetch) return fetch(seriesModel, result, result.axisMap, result.categoryAxisMap), result; }(seriesModel); coordSysInfo && coordSysInfo.coordSysDims && (coordSysDimDefs = map(coordSysInfo.coordSysDims, function(dim) { var dimInfo = { name: dim }, axisModel = coordSysInfo.axisMap.get(dim); if (axisModel) { var axisType = axisModel.get('type'); dimInfo.type = getDimensionTypeByAxis(axisType); } return dimInfo; })), coordSysDimDefs || (coordSysDimDefs = registeredCoordSys && (registeredCoordSys.getDimensionsInfo ? registeredCoordSys.getDimensionsInfo() : registeredCoordSys.dimensions.slice()) || [ 'x', 'y' ]); var useEncodeDefaulter = opt.useEncodeDefaulter, dimInfoList = createDimensions(source, { coordDimensions: coordSysDimDefs, generateCoord: opt.generateCoord, encodeDefaulter: isFunction(useEncodeDefaulter) ? useEncodeDefaulter : useEncodeDefaulter ? curry(makeSeriesEncodeForAxisCoordSys, coordSysDimDefs, seriesModel) : null }); coordSysInfo && each(dimInfoList, function(dimInfo, dimIndex) { var coordDim = dimInfo.coordDim, categoryAxisModel = coordSysInfo.categoryAxisMap.get(coordDim); categoryAxisModel && (null == firstCategoryDimIndex && (firstCategoryDimIndex = dimIndex), dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta(), opt.createInvertedIndices && (dimInfo.createInvertedIndices = !0)), null != dimInfo.otherDims.itemName && (hasNameEncode = !0); }), hasNameEncode || null == firstCategoryDimIndex || (dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0); var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList), list = new List(dimInfoList, seriesModel); list.setCalculationInfo(stackCalculationInfo); var dimValueGetter = null != firstCategoryDimIndex && function(source) { if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) { var sampleItem = function(data) { for(var i = 0; i < data.length && null == data[i];)i++; return data[i]; }(source.data || []); return null != sampleItem && !isArray(getDataItemValue(sampleItem)); } }(source) ? function(itemOpt, dimName, dataIndex, dimIndex) { return dimIndex === firstCategoryDimIndex ? dataIndex : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex); } : null; return list.hasItemOption = !1, list.initData(source, null, dimValueGetter), list; } var Scale = function() { function Scale(setting) { this._setting = setting || {}, this._extent = [ 1 / 0, -1 / 0 ]; } return Scale.prototype.getSetting = function(name) { return this._setting[name]; }, Scale.prototype.unionExtent = function(other) { var extent = this._extent; other[0] < extent[0] && (extent[0] = other[0]), other[1] > extent[1] && (extent[1] = other[1]); }, Scale.prototype.unionExtentFromData = function(data, dim) { this.unionExtent(data.getApproximateExtent(dim)); }, Scale.prototype.getExtent = function() { return this._extent.slice(); }, Scale.prototype.setExtent = function(start, end) { var thisExtent = this._extent; isNaN(start) || (thisExtent[0] = start), isNaN(end) || (thisExtent[1] = end); }, Scale.prototype.isInExtentRange = function(value) { return this._extent[0] <= value && this._extent[1] >= value; }, Scale.prototype.isBlank = function() { return this._isBlank; }, Scale.prototype.setBlank = function(isBlank) { this._isBlank = isBlank; }, Scale; }(); enableClassManagement(Scale); var OrdinalMeta = function() { function OrdinalMeta(opt) { this.categories = opt.categories || [], this._needCollect = opt.needCollect, this._deduplication = opt.deduplication; } return OrdinalMeta.createByAxisModel = function(axisModel) { var option = axisModel.option, data = option.data, categories = data && map(data, getName); return new OrdinalMeta({ categories: categories, needCollect: !categories, deduplication: !1 !== option.dedplication }); }, OrdinalMeta.prototype.getOrdinal = function(category) { return this._getOrCreateMap().get(category); }, OrdinalMeta.prototype.parseAndCollect = function(category) { var index, needCollect = this._needCollect; if ('string' != typeof category && !needCollect) return category; if (needCollect && !this._deduplication) return index = this.categories.length, this.categories[index] = category, index; var map = this._getOrCreateMap(); return null == (index = map.get(category)) && (needCollect ? (index = this.categories.length, this.categories[index] = category, map.set(category, index)) : index = NaN), index; }, OrdinalMeta.prototype._getOrCreateMap = function() { return this._map || (this._map = createHashMap(this.categories)); }, OrdinalMeta; }(); function getName(obj) { return isObject(obj) && null != obj.value ? obj.value : obj + ''; } function clamp(niceTickExtent, idx, extent) { niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]); } function contain$2(val, extent) { return val >= extent[0] && val <= extent[1]; } function normalize$1(val, extent) { return extent[1] === extent[0] ? 0.5 : (val - extent[0]) / (extent[1] - extent[0]); } function scale$2(val, extent) { return val * (extent[1] - extent[0]) + extent[0]; } var OrdinalScale = function(_super) { function OrdinalScale(setting) { var _this = _super.call(this, setting) || this; _this.type = 'ordinal'; var ordinalMeta = _this.getSetting('ordinalMeta'); return ordinalMeta || (ordinalMeta = new OrdinalMeta({})), isArray(ordinalMeta) && (ordinalMeta = new OrdinalMeta({ categories: map(ordinalMeta, function(item) { return isObject(item) ? item.value : item; }) })), _this._ordinalMeta = ordinalMeta, _this._extent = _this.getSetting('extent') || [ 0, ordinalMeta.categories.length - 1 ], _this; } return __extends(OrdinalScale, _super), OrdinalScale.prototype.parse = function(val) { return 'string' == typeof val ? this._ordinalMeta.getOrdinal(val) : Math.round(val); }, OrdinalScale.prototype.contain = function(rank) { return contain$2(rank = this.parse(rank), this._extent) && null != this._ordinalMeta.categories[rank]; }, OrdinalScale.prototype.normalize = function(val) { return normalize$1(val = this._getTickNumber(this.parse(val)), this._extent); }, OrdinalScale.prototype.scale = function(val) { return val = Math.round(scale$2(val, this._extent)), this.getRawOrdinalNumber(val); }, OrdinalScale.prototype.getTicks = function() { for(var ticks = [], extent = this._extent, rank = extent[0]; rank <= extent[1];)ticks.push({ value: rank }), rank++; return ticks; }, OrdinalScale.prototype.getMinorTicks = function(splitNumber) {}, OrdinalScale.prototype.setSortInfo = function(info) { if (null == info) { this._ordinalNumbersByTick = this._ticksByOrdinalNumber = null; return; } for(var infoOrdinalNumbers = info.ordinalNumbers, ordinalsByTick = this._ordinalNumbersByTick = [], ticksByOrdinal = this._ticksByOrdinalNumber = [], tickNum = 0, allCategoryLen = this._ordinalMeta.categories.length, len = Math.min(allCategoryLen, infoOrdinalNumbers.length); tickNum < len; ++tickNum){ var ordinalNumber = infoOrdinalNumbers[tickNum]; ordinalsByTick[tickNum] = ordinalNumber, ticksByOrdinal[ordinalNumber] = tickNum; } for(var unusedOrdinal = 0; tickNum < allCategoryLen; ++tickNum){ for(; null != ticksByOrdinal[unusedOrdinal];)unusedOrdinal++; ordinalsByTick.push(unusedOrdinal), ticksByOrdinal[unusedOrdinal] = tickNum; } }, OrdinalScale.prototype._getTickNumber = function(ordinal) { var ticksByOrdinalNumber = this._ticksByOrdinalNumber; return ticksByOrdinalNumber && ordinal >= 0 && ordinal < ticksByOrdinalNumber.length ? ticksByOrdinalNumber[ordinal] : ordinal; }, OrdinalScale.prototype.getRawOrdinalNumber = function(tickNumber) { var ordinalNumbersByTick = this._ordinalNumbersByTick; return ordinalNumbersByTick && tickNumber >= 0 && tickNumber < ordinalNumbersByTick.length ? ordinalNumbersByTick[tickNumber] : tickNumber; }, OrdinalScale.prototype.getLabel = function(tick) { if (!this.isBlank()) { var ordinalNumber = this.getRawOrdinalNumber(tick.value), cateogry = this._ordinalMeta.categories[ordinalNumber]; return null == cateogry ? '' : cateogry + ''; } }, OrdinalScale.prototype.count = function() { return this._extent[1] - this._extent[0] + 1; }, OrdinalScale.prototype.unionExtentFromData = function(data, dim) { this.unionExtent(data.getApproximateExtent(dim)); }, OrdinalScale.prototype.isInExtentRange = function(value) { return value = this._getTickNumber(value), this._extent[0] <= value && this._extent[1] >= value; }, OrdinalScale.prototype.getOrdinalMeta = function() { return this._ordinalMeta; }, OrdinalScale.prototype.niceTicks = function() {}, OrdinalScale.prototype.niceExtent = function() {}, OrdinalScale.type = 'ordinal', OrdinalScale; }(Scale); Scale.registerClass(OrdinalScale); var IntervalScale = function(_super) { function IntervalScale() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = 'interval', _this._interval = 0, _this._intervalPrecision = 2, _this; } return __extends(IntervalScale, _super), IntervalScale.prototype.parse = function(val) { return val; }, IntervalScale.prototype.contain = function(val) { return contain$2(val, this._extent); }, IntervalScale.prototype.normalize = function(val) { return normalize$1(val, this._extent); }, IntervalScale.prototype.scale = function(val) { return scale$2(val, this._extent); }, IntervalScale.prototype.setExtent = function(start, end) { var thisExtent = this._extent; isNaN(start) || (thisExtent[0] = parseFloat(start)), isNaN(end) || (thisExtent[1] = parseFloat(end)); }, IntervalScale.prototype.unionExtent = function(other) { var extent = this._extent; other[0] < extent[0] && (extent[0] = other[0]), other[1] > extent[1] && (extent[1] = other[1]), this.setExtent(extent[0], extent[1]); }, IntervalScale.prototype.getInterval = function() { return this._interval; }, IntervalScale.prototype.setInterval = function(interval) { this._interval = interval, this._niceExtent = this._extent.slice(), this._intervalPrecision = getPrecisionSafe(interval) + 2; }, IntervalScale.prototype.getTicks = function(expandToNicedExtent) { var interval = this._interval, extent = this._extent, niceTickExtent = this._niceExtent, intervalPrecision = this._intervalPrecision, ticks = []; if (!interval) return ticks; extent[0] < niceTickExtent[0] && (expandToNicedExtent ? ticks.push({ value: round(niceTickExtent[0] - interval, intervalPrecision) }) : ticks.push({ value: extent[0] })); for(var tick = niceTickExtent[0]; tick <= niceTickExtent[1] && (ticks.push({ value: tick }), (tick = round(tick + interval, intervalPrecision)) !== ticks[ticks.length - 1].value);)if (ticks.length > 10000) return []; var lastNiceTick = ticks.length ? ticks[ticks.length - 1].value : niceTickExtent[1]; return extent[1] > lastNiceTick && (expandToNicedExtent ? ticks.push({ value: round(lastNiceTick + interval, intervalPrecision) }) : ticks.push({ value: extent[1] })), ticks; }, IntervalScale.prototype.getMinorTicks = function(splitNumber) { for(var ticks = this.getTicks(!0), minorTicks = [], extent = this.getExtent(), i = 1; i < ticks.length; i++){ for(var nextTick = ticks[i], prevTick = ticks[i - 1], count = 0, minorTicksGroup = [], minorInterval = (nextTick.value - prevTick.value) / splitNumber; count < splitNumber - 1;){ var minorTick = round(prevTick.value + (count + 1) * minorInterval); minorTick > extent[0] && minorTick < extent[1] && minorTicksGroup.push(minorTick), count++; } minorTicks.push(minorTicksGroup); } return minorTicks; }, IntervalScale.prototype.getLabel = function(data, opt) { if (null == data) return ''; var precision = opt && opt.precision; return null == precision ? precision = getPrecisionSafe(data.value) || 0 : 'auto' === precision && (precision = this._intervalPrecision), addCommas(round(data.value, precision, !0)); }, IntervalScale.prototype.niceTicks = function(splitNumber, minInterval, maxInterval) { splitNumber = splitNumber || 5; var splitNumber1, result, span, interval, precision, extent = this._extent, span1 = extent[1] - extent[0]; if (isFinite(span1)) { span1 < 0 && (span1 = -span1, extent.reverse()); var interval1, niceTickExtent, result1 = (splitNumber1 = splitNumber, result = {}, span = extent[1] - extent[0], interval = result.interval = nice(span / splitNumber1, !0), null != minInterval && interval < minInterval && (interval = result.interval = minInterval), null != maxInterval && interval > maxInterval && (interval = result.interval = maxInterval), precision = result.intervalPrecision = getPrecisionSafe(interval) + 2, isFinite((niceTickExtent = result.niceTickExtent = [ round(Math.ceil(extent[0] / interval) * interval, precision), round(Math.floor(extent[1] / interval) * interval, precision) ])[0]) || (niceTickExtent[0] = extent[0]), isFinite(niceTickExtent[1]) || (niceTickExtent[1] = extent[1]), clamp(niceTickExtent, 0, extent), clamp(niceTickExtent, 1, extent), niceTickExtent[0] > niceTickExtent[1] && (niceTickExtent[0] = niceTickExtent[1]), result); this._intervalPrecision = result1.intervalPrecision, this._interval = result1.interval, this._niceExtent = result1.niceTickExtent; } }, IntervalScale.prototype.niceExtent = function(opt) { var extent = this._extent; if (extent[0] === extent[1]) { if (0 !== extent[0]) { var expandSize = extent[0]; opt.fixMax || (extent[1] += expandSize / 2), extent[0] -= expandSize / 2; } else extent[1] = 1; } isFinite(extent[1] - extent[0]) || (extent[0] = 0, extent[1] = 1), this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval); var interval = this._interval; opt.fixMin || (extent[0] = round(Math.floor(extent[0] / interval) * interval)), opt.fixMax || (extent[1] = round(Math.ceil(extent[1] / interval) * interval)); }, IntervalScale.type = 'interval', IntervalScale; }(Scale); Scale.registerClass(IntervalScale); var STACK_PREFIX = '__ec_stack_', LargeArr = 'undefined' != typeof Float32Array ? Float32Array : Array; function getSeriesStackId(seriesModel) { return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex; } function getAxisKey(axis) { return axis.dim + axis.index; } function prepareLayoutBarSeries(seriesType, ecModel) { var seriesModels = []; return ecModel.eachSeriesByType(seriesType, function(seriesModel) { isOnCartesian(seriesModel) && !isInLargeMode(seriesModel) && seriesModels.push(seriesModel); }), seriesModels; } function makeColumnLayout(barSeries) { var axisMinGaps = function(barSeries) { var axisValues = {}; each(barSeries, function(seriesModel) { var baseAxis = seriesModel.coordinateSystem.getBaseAxis(); if ('time' === baseAxis.type || 'value' === baseAxis.type) for(var data = seriesModel.getData(), key = baseAxis.dim + '_' + baseAxis.index, dim = data.mapDimension(baseAxis.dim), i = 0, cnt = data.count(); i < cnt; ++i){ var value = data.get(dim, i); axisValues[key] ? axisValues[key].push(value) : axisValues[key] = [ value ]; } }); var axisMinGaps = {}; for(var key in axisValues)if (axisValues.hasOwnProperty(key)) { var valuesInAxis = axisValues[key]; if (valuesInAxis) { valuesInAxis.sort(function(a, b) { return a - b; }); for(var min = null, j = 1; j < valuesInAxis.length; ++j){ var delta = valuesInAxis[j] - valuesInAxis[j - 1]; delta > 0 && (min = null === min ? delta : Math.min(min, delta)); } axisMinGaps[key] = min; } } return axisMinGaps; }(barSeries), seriesInfoList = []; return each(barSeries, function(seriesModel) { var bandWidth, baseAxis = seriesModel.coordinateSystem.getBaseAxis(), axisExtent = baseAxis.getExtent(); if ('category' === baseAxis.type) bandWidth = baseAxis.getBandWidth(); else if ('value' === baseAxis.type || 'time' === baseAxis.type) { var minGap = axisMinGaps[baseAxis.dim + '_' + baseAxis.index], extentSpan = Math.abs(axisExtent[1] - axisExtent[0]), scale = baseAxis.scale.getExtent(), scaleSpan = Math.abs(scale[1] - scale[0]); bandWidth = minGap ? extentSpan / scaleSpan * minGap : extentSpan; } else { var data = seriesModel.getData(); bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count(); } var barWidth = parsePercent$1(seriesModel.get('barWidth'), bandWidth), barMaxWidth = parsePercent$1(seriesModel.get('barMaxWidth'), bandWidth), barMinWidth = parsePercent$1(seriesModel.get('barMinWidth') || 1, bandWidth), barGap = seriesModel.get('barGap'), barCategoryGap = seriesModel.get('barCategoryGap'); seriesInfoList.push({ bandWidth: bandWidth, barWidth: barWidth, barMaxWidth: barMaxWidth, barMinWidth: barMinWidth, barGap: barGap, barCategoryGap: barCategoryGap, axisKey: getAxisKey(baseAxis), stackId: getSeriesStackId(seriesModel) }); }), doCalBarWidthAndOffset(seriesInfoList); } function doCalBarWidthAndOffset(seriesInfoList) { var columnsMap = {}; each(seriesInfoList, function(seriesInfo, idx) { var axisKey = seriesInfo.axisKey, bandWidth = seriesInfo.bandWidth, columnsOnAxis = columnsMap[axisKey] || { bandWidth: bandWidth, remainedWidth: bandWidth, autoWidthCount: 0, categoryGap: null, gap: '20%', stacks: {} }, stacks = columnsOnAxis.stacks; columnsMap[axisKey] = columnsOnAxis; var stackId = seriesInfo.stackId; !stacks[stackId] && columnsOnAxis.autoWidthCount++, stacks[stackId] = stacks[stackId] || { width: 0, maxWidth: 0 }; var barWidth = seriesInfo.barWidth; barWidth && !stacks[stackId].width && (stacks[stackId].width = barWidth, barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth), columnsOnAxis.remainedWidth -= barWidth); var barMaxWidth = seriesInfo.barMaxWidth; barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth); var barMinWidth = seriesInfo.barMinWidth; barMinWidth && (stacks[stackId].minWidth = barMinWidth); var barGap = seriesInfo.barGap; null != barGap && (columnsOnAxis.gap = barGap); var barCategoryGap = seriesInfo.barCategoryGap; null != barCategoryGap && (columnsOnAxis.categoryGap = barCategoryGap); }); var result = {}; return each(columnsMap, function(columnsOnAxis, coordSysName) { result[coordSysName] = {}; var lastColumn, stacks = columnsOnAxis.stacks, bandWidth = columnsOnAxis.bandWidth, categoryGapPercent = columnsOnAxis.categoryGap; null == categoryGapPercent && (categoryGapPercent = Math.max(35 - 4 * keys(stacks).length, 15) + '%'); var categoryGap = parsePercent$1(categoryGapPercent, bandWidth), barGapPercent = parsePercent$1(columnsOnAxis.gap, 1), remainedWidth = columnsOnAxis.remainedWidth, autoWidthCount = columnsOnAxis.autoWidthCount, autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent); autoWidth = Math.max(autoWidth, 0), each(stacks, function(column) { var maxWidth = column.maxWidth, minWidth = column.minWidth; if (column.width) { var finalWidth = column.width; maxWidth && (finalWidth = Math.min(finalWidth, maxWidth)), minWidth && (finalWidth = Math.max(finalWidth, minWidth)), column.width = finalWidth, remainedWidth -= finalWidth + barGapPercent * finalWidth, autoWidthCount--; } else { var finalWidth = autoWidth; maxWidth && maxWidth < finalWidth && (finalWidth = Math.min(maxWidth, remainedWidth)), minWidth && minWidth > finalWidth && (finalWidth = minWidth), finalWidth !== autoWidth && (column.width = finalWidth, remainedWidth -= finalWidth + barGapPercent * finalWidth, autoWidthCount--); } }), autoWidth = Math.max(autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent), 0); var widthSum = 0; each(stacks, function(column, idx) { column.width || (column.width = autoWidth), lastColumn = column, widthSum += column.width * (1 + barGapPercent); }), lastColumn && (widthSum -= lastColumn.width * barGapPercent); var offset = -widthSum / 2; each(stacks, function(column, stackId) { result[coordSysName][stackId] = result[coordSysName][stackId] || { bandWidth: bandWidth, offset: offset, width: column.width }, offset += column.width * (1 + barGapPercent); }); }), result; } function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) { if (barWidthAndOffset && axis) { var result = barWidthAndOffset[getAxisKey(axis)]; return null != result && null != seriesModel ? result[getSeriesStackId(seriesModel)] : result; } } function layout(seriesType, ecModel) { var seriesModels = prepareLayoutBarSeries(seriesType, ecModel), barWidthAndOffset = makeColumnLayout(seriesModels), lastStackCoords = {}; each(seriesModels, function(seriesModel) { var data = seriesModel.getData(), cartesian = seriesModel.coordinateSystem, baseAxis = cartesian.getBaseAxis(), stackId = getSeriesStackId(seriesModel), columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId], columnOffset = columnLayoutInfo.offset, columnWidth = columnLayoutInfo.width, valueAxis = cartesian.getOtherAxis(baseAxis), barMinHeight = seriesModel.get('barMinHeight') || 0; lastStackCoords[stackId] = lastStackCoords[stackId] || [], data.setLayout({ bandWidth: columnLayoutInfo.bandWidth, offset: columnOffset, size: columnWidth }); for(var valueDim = data.mapDimension(valueAxis.dim), baseDim = data.mapDimension(baseAxis.dim), stacked = isDimensionStacked(data, valueDim), isValueAxisH = valueAxis.isHorizontal(), valueAxisStart = getValueAxisStart(baseAxis, valueAxis), idx = 0, len = data.count(); idx < len; idx++){ var value = data.get(valueDim, idx), baseValue = data.get(baseDim, idx), sign = value >= 0 ? 'p' : 'n', baseCoord = valueAxisStart; stacked && (lastStackCoords[stackId][baseValue] || (lastStackCoords[stackId][baseValue] = { p: valueAxisStart, n: valueAxisStart }), baseCoord = lastStackCoords[stackId][baseValue][sign]); var x = void 0, y = void 0, width = void 0, height = void 0; if (isValueAxisH) { var coord = cartesian.dataToPoint([ value, baseValue ]); x = baseCoord, y = coord[1] + columnOffset, width = coord[0] - valueAxisStart, height = columnWidth, Math.abs(width) < barMinHeight && (width = (width < 0 ? -1 : 1) * barMinHeight), !isNaN(width) && stacked && (lastStackCoords[stackId][baseValue][sign] += width); } else { var coord = cartesian.dataToPoint([ baseValue, value ]); x = coord[0] + columnOffset, y = baseCoord, width = columnWidth, Math.abs(height = coord[1] - valueAxisStart) < barMinHeight && (height = (height <= 0 ? -1 : 1) * barMinHeight), !isNaN(height) && stacked && (lastStackCoords[stackId][baseValue][sign] += height); } data.setItemLayout(idx, { x: x, y: y, width: width, height: height }); } }); } var largeLayout = { seriesType: 'bar', plan: createRenderPlanner(), reset: function(seriesModel) { if (isOnCartesian(seriesModel) && isInLargeMode(seriesModel)) { var data = seriesModel.getData(), cartesian = seriesModel.coordinateSystem, coordLayout = cartesian.master.getRect(), baseAxis = cartesian.getBaseAxis(), valueAxis = cartesian.getOtherAxis(baseAxis), valueDim = data.mapDimension(valueAxis.dim), baseDim = data.mapDimension(baseAxis.dim), valueAxisHorizontal = valueAxis.isHorizontal(), valueDimIdx = valueAxisHorizontal ? 0 : 1, barWidth = retrieveColumnLayout(makeColumnLayout([ seriesModel ]), baseAxis, seriesModel).width; return barWidth > 0.5 || (barWidth = 0.5), { progress: function(params, data) { for(var dataIndex, count = params.count, largePoints = new LargeArr(2 * count), largeBackgroundPoints = new LargeArr(2 * count), largeDataIndices = new LargeArr(count), coord = [], valuePair = [], pointsOffset = 0, idxOffset = 0; null != (dataIndex = params.next());)valuePair[valueDimIdx] = data.get(valueDim, dataIndex), valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex), coord = cartesian.dataToPoint(valuePair, null, coord), largeBackgroundPoints[pointsOffset] = valueAxisHorizontal ? coordLayout.x + coordLayout.width : coord[0], largePoints[pointsOffset++] = coord[0], largeBackgroundPoints[pointsOffset] = valueAxisHorizontal ? coord[1] : coordLayout.y + coordLayout.height, largePoints[pointsOffset++] = coord[1], largeDataIndices[idxOffset++] = dataIndex; data.setLayout({ largePoints: largePoints, largeDataIndices: largeDataIndices, largeBackgroundPoints: largeBackgroundPoints, barWidth: barWidth, valueAxisStart: getValueAxisStart(baseAxis, valueAxis), backgroundStart: valueAxisHorizontal ? coordLayout.x : coordLayout.y, valueAxisHorizontal: valueAxisHorizontal }); } }; } } }; function isOnCartesian(seriesModel) { return seriesModel.coordinateSystem && 'cartesian2d' === seriesModel.coordinateSystem.type; } function isInLargeMode(seriesModel) { return seriesModel.pipelineContext && seriesModel.pipelineContext.large; } function getValueAxisStart(baseAxis, valueAxis, stacked) { return valueAxis.toGlobalCoord(valueAxis.dataToCoord('log' === valueAxis.type ? 1 : 0)); } var bisect = function(a, x, lo, hi) { for(; lo < hi;){ var mid = lo + hi >>> 1; a[mid][1] < x ? lo = mid + 1 : hi = mid; } return lo; }, TimeScale = function(_super) { function TimeScale(settings) { var _this = _super.call(this, settings) || this; return _this.type = 'time', _this; } return __extends(TimeScale, _super), TimeScale.prototype.getLabel = function(tick) { var useUTC = this.getSetting('useUTC'); return format(tick.value, fullLeveledFormatter[function(timeUnit) { switch(timeUnit){ case 'year': case 'month': return 'day'; case 'millisecond': return 'millisecond'; default: return 'second'; } }(getPrimaryTimeUnit(this._minLevelUnit))] || fullLeveledFormatter.second, useUTC, this.getSetting('locale')); }, TimeScale.prototype.getFormattedLabel = function(tick, idx, labelFormatter) { var isUTC = this.getSetting('useUTC'); return function(tick, idx, formatter, lang, isUTC) { var template = null; if ('string' == typeof formatter) template = formatter; else if ('function' == typeof formatter) template = formatter(tick.value, idx, { level: tick.level }); else { var defaults$1 = extend({}, defaultLeveledFormatter); if (tick.level > 0) for(var i = 0; i < primaryTimeUnits.length; ++i)defaults$1[primaryTimeUnits[i]] = "{primary|" + defaults$1[primaryTimeUnits[i]] + "}"; var mergedFormatter = formatter ? !1 === formatter.inherit ? formatter : defaults(formatter, defaults$1) : defaults$1, unit = getUnitFromValue(tick.value, isUTC); if (mergedFormatter[unit]) template = mergedFormatter[unit]; else if (mergedFormatter.inherit) { for(var targetId = timeUnits.indexOf(unit), i = targetId - 1; i >= 0; --i)if (mergedFormatter[unit]) { template = mergedFormatter[unit]; break; } template = template || defaults$1.none; } if (isArray(template)) { var levelId = null == tick.level ? 0 : tick.level >= 0 ? tick.level : template.length + tick.level; template = template[levelId = Math.min(levelId, template.length - 1)]; } } return format(new Date(tick.value), template, isUTC, lang); }(tick, idx, labelFormatter, this.getSetting('locale'), isUTC); }, TimeScale.prototype.getTicks = function(expandToNicedExtent) { var interval = this._interval, extent = this._extent, ticks = []; if (!interval) return ticks; ticks.push({ value: extent[0], level: 0 }); var useUTC = this.getSetting('useUTC'), innerTicks = function(bottomUnitName, approxInterval, isUTC, extent) { for(var iter = 0, levelsTicks = [], currentLevelTicks = [], tickCount = 0, lastLevelTickCount = 0, i = 0; i < timeUnits.length && iter++ < 10000; ++i){ var timeUnit, primaryTimeUnit = getPrimaryTimeUnit(timeUnits[i]); if ((timeUnit = timeUnits[i]) === getPrimaryTimeUnit(timeUnit) && (function(unitName, lastLevelTicks, levelTicks) { var newAddedTicks = [], isFirstLevel = !lastLevelTicks.length; if (!function(unit, valueA, valueB, isUTC) { var dateA = parseDate(valueA), dateB = parseDate(valueB), isSame = function(unit) { return getUnitValue(dateA, unit, isUTC) === getUnitValue(dateB, unit, isUTC); }, isSameYear = function() { return isSame('year'); }, isSameMonth = function() { return isSameYear() && isSame('month'); }, isSameDay = function() { return isSameMonth() && isSame('day'); }, isSameHour = function() { return isSameDay() && isSame('hour'); }, isSameMinute = function() { return isSameHour() && isSame('minute'); }, isSameSecond = function() { return isSameMinute() && isSame('second'); }; switch(unit){ case 'year': return isSameYear(); case 'month': return isSameMonth(); case 'day': return isSameDay(); case 'hour': return isSameHour(); case 'minute': return isSameMinute(); case 'second': return isSameSecond(); case 'millisecond': return isSameSecond() && isSame('millisecond'); } }(getPrimaryTimeUnit(unitName), extent[0], extent[1], isUTC)) { isFirstLevel && (lastLevelTicks = [ { value: function(date, unitName, isUTC) { var outDate = new Date(date); switch(getPrimaryTimeUnit(unitName)){ case 'year': case 'month': outDate[monthSetterName(isUTC)](0); case 'day': outDate[dateSetterName(isUTC)](1); case 'hour': outDate[hoursSetterName(isUTC)](0); case 'minute': outDate[minutesSetterName(isUTC)](0); case 'second': outDate[secondsSetterName(isUTC)](0), outDate[millisecondsSetterName(isUTC)](0); } return outDate.getTime(); }(new Date(extent[0]), unitName, isUTC) }, { value: extent[1] } ]); for(var i = 0; i < lastLevelTicks.length - 1; i++){ var approxInterval1, approxInterval2, approxInterval3, startTick = lastLevelTicks[i].value, endTick = lastLevelTicks[i + 1].value; if (startTick !== endTick) { var interval = void 0, getterName = void 0, setterName = void 0; switch(unitName){ case 'year': interval = Math.max(1, Math.round(approxInterval / 86400000 / 365)), getterName = fullYearGetterName(isUTC), setterName = isUTC ? 'setUTCFullYear' : 'setFullYear'; break; case 'half-year': case 'quarter': case 'month': approxInterval1 = approxInterval, interval = (approxInterval1 /= 2592000000) > 6 ? 6 : approxInterval1 > 3 ? 3 : approxInterval1 > 2 ? 2 : 1, getterName = monthGetterName(isUTC), setterName = monthSetterName(isUTC); break; case 'week': case 'half-week': case 'day': approxInterval2 = approxInterval, interval = (approxInterval2 /= 86400000) > 16 ? 16 : approxInterval2 > 7.5 ? 7 : approxInterval2 > 3.5 ? 4 : approxInterval2 > 1.5 ? 2 : 1, getterName = dateGetterName(isUTC), setterName = dateSetterName(isUTC); break; case 'half-day': case 'quarter-day': case 'hour': approxInterval3 = approxInterval, interval = (approxInterval3 /= 3600000) > 12 ? 12 : approxInterval3 > 6 ? 6 : approxInterval3 > 3.5 ? 4 : approxInterval3 > 2 ? 2 : 1, getterName = hoursGetterName(isUTC), setterName = hoursSetterName(isUTC); break; case 'minute': interval = getMinutesAndSecondsInterval(approxInterval, !0), getterName = minutesGetterName(isUTC), setterName = minutesSetterName(isUTC); break; case 'second': interval = getMinutesAndSecondsInterval(approxInterval, !1), getterName = secondsGetterName(isUTC), setterName = secondsSetterName(isUTC); break; case 'millisecond': interval = nice(approxInterval, !0), getterName = millisecondsGetterName(isUTC), setterName = millisecondsSetterName(isUTC); } (function(interval, minTimestamp, maxTimestamp, getMethodName, setMethodName, isDate, out) { for(var date = new Date(minTimestamp), dateTime = minTimestamp, d = date[getMethodName](); dateTime < maxTimestamp && dateTime <= extent[1];)out.push({ value: dateTime }), d += interval, date[setMethodName](d), dateTime = date.getTime(); out.push({ value: dateTime, notAdd: !0 }); })(interval, startTick, endTick, getterName, setterName, 0, newAddedTicks), 'year' === unitName && levelTicks.length > 1 && 0 === i && levelTicks.unshift({ value: levelTicks[0].value - interval }); } } for(var i = 0; i < newAddedTicks.length; i++)levelTicks.push(newAddedTicks[i]); } }(timeUnits[i], levelsTicks[levelsTicks.length - 1] || [], currentLevelTicks), primaryTimeUnit !== (timeUnits[i + 1] ? getPrimaryTimeUnit(timeUnits[i + 1]) : null))) { if (currentLevelTicks.length) { lastLevelTickCount = tickCount, currentLevelTicks.sort(function(a, b) { return a.value - b.value; }); for(var levelTicksRemoveDuplicated = [], i_1 = 0; i_1 < currentLevelTicks.length; ++i_1){ var tickValue = currentLevelTicks[i_1].value; (0 === i_1 || currentLevelTicks[i_1 - 1].value !== tickValue) && (levelTicksRemoveDuplicated.push(currentLevelTicks[i_1]), tickValue >= extent[0] && tickValue <= extent[1] && tickCount++); } var targetTickNum = (extent[1] - extent[0]) / approxInterval; if (tickCount > 1.5 * targetTickNum && lastLevelTickCount > targetTickNum / 1.5 || (levelsTicks.push(levelTicksRemoveDuplicated), tickCount > targetTickNum || bottomUnitName === timeUnits[i])) break; } currentLevelTicks = []; } } iter >= 10000 && warn('Exceed safe limit.'); for(var levelsTicksInExtent = filter(map(levelsTicks, function(levelTicks) { return filter(levelTicks, function(tick) { return tick.value >= extent[0] && tick.value <= extent[1] && !tick.notAdd; }); }), function(levelTicks) { return levelTicks.length > 0; }), ticks = [], maxLevel = levelsTicksInExtent.length - 1, i = 0; i < levelsTicksInExtent.length; ++i)for(var levelTicks = levelsTicksInExtent[i], k = 0; k < levelTicks.length; ++k)ticks.push({ value: levelTicks[k].value, level: maxLevel - i }); ticks.sort(function(a, b) { return a.value - b.value; }); for(var result = [], i = 0; i < ticks.length; ++i)(0 === i || ticks[i].value !== ticks[i - 1].value) && result.push(ticks[i]); return result; }(this._minLevelUnit, this._approxInterval, useUTC, extent); return (ticks = ticks.concat(innerTicks)).push({ value: extent[1], level: 0 }), ticks; }, TimeScale.prototype.niceExtent = function(opt) { var extent = this._extent; if (extent[0] === extent[1] && (extent[0] -= 86400000, extent[1] += 86400000), extent[1] === -1 / 0 && extent[0] === 1 / 0) { var d = new Date(); extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate()), extent[0] = extent[1] - 86400000; } this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval); }, TimeScale.prototype.niceTicks = function(approxTickNum, minInterval, maxInterval) { approxTickNum = approxTickNum || 10; var extent = this._extent, span = extent[1] - extent[0]; this._approxInterval = span / approxTickNum, null != minInterval && this._approxInterval < minInterval && (this._approxInterval = minInterval), null != maxInterval && this._approxInterval > maxInterval && (this._approxInterval = maxInterval); var scaleIntervalsLen = scaleIntervals.length, idx = Math.min(bisect(scaleIntervals, this._approxInterval, 0, scaleIntervalsLen), scaleIntervalsLen - 1); this._interval = scaleIntervals[idx][1], this._minLevelUnit = scaleIntervals[Math.max(idx - 1, 0)][0]; }, TimeScale.prototype.parse = function(val) { return 'number' == typeof val ? val : +parseDate(val); }, TimeScale.prototype.contain = function(val) { return contain$2(this.parse(val), this._extent); }, TimeScale.prototype.normalize = function(val) { return normalize$1(this.parse(val), this._extent); }, TimeScale.prototype.scale = function(val) { return scale$2(val, this._extent); }, TimeScale.type = 'time', TimeScale; }(IntervalScale), scaleIntervals = [ [ 'second', 1000 ], [ 'minute', 60000 ], [ 'hour', 3600000 ], [ 'quarter-day', 21600000 ], [ 'half-day', 43200000 ], [ 'day', 103680000 ], [ 'half-week', 302400000 ], [ 'week', 604800000 ], [ 'month', 2678400000 ], [ 'quarter', 8208000000 ], [ 'half-year', 15768000000 ], [ 'year', 31536000000 ] ]; function getMinutesAndSecondsInterval(approxInterval, isMinutes) { return (approxInterval /= isMinutes ? 60000 : 1000) > 30 ? 30 : approxInterval > 20 ? 20 : approxInterval > 15 ? 15 : approxInterval > 10 ? 10 : approxInterval > 5 ? 5 : approxInterval > 2 ? 2 : 1; } Scale.registerClass(TimeScale); var scaleProto = Scale.prototype, intervalScaleProto = IntervalScale.prototype, mathFloor$1 = Math.floor, mathCeil = Math.ceil, mathPow$1 = Math.pow, mathLog = Math.log, LogScale = function(_super) { function LogScale() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = 'log', _this.base = 10, _this._originalScale = new IntervalScale(), _this._interval = 0, _this; } return __extends(LogScale, _super), LogScale.prototype.getTicks = function(expandToNicedExtent) { var originalScale = this._originalScale, extent = this._extent, originalExtent = originalScale.getExtent(); return map(intervalScaleProto.getTicks.call(this, expandToNicedExtent), function(tick) { var val, originalVal, val1, originalVal1, val2 = tick.value, powVal = round(mathPow$1(this.base, val2)); return powVal = val2 === extent[0] && this._fixMin ? round(powVal, getPrecisionSafe(originalExtent[0])) : powVal, { value: powVal = val2 === extent[1] && this._fixMax ? round(powVal, getPrecisionSafe(originalExtent[1])) : powVal }; }, this); }, LogScale.prototype.setExtent = function(start, end) { var base = this.base; start = mathLog(start) / mathLog(base), end = mathLog(end) / mathLog(base), intervalScaleProto.setExtent.call(this, start, end); }, LogScale.prototype.getExtent = function() { var originalVal, originalVal1, base = this.base, extent = scaleProto.getExtent.call(this); extent[0] = mathPow$1(base, extent[0]), extent[1] = mathPow$1(base, extent[1]); var originalExtent = this._originalScale.getExtent(); return this._fixMin && (extent[0] = round(extent[0], getPrecisionSafe(originalExtent[0]))), this._fixMax && (extent[1] = round(extent[1], getPrecisionSafe(originalExtent[1]))), extent; }, LogScale.prototype.unionExtent = function(extent) { this._originalScale.unionExtent(extent); var base = this.base; extent[0] = mathLog(extent[0]) / mathLog(base), extent[1] = mathLog(extent[1]) / mathLog(base), scaleProto.unionExtent.call(this, extent); }, LogScale.prototype.unionExtentFromData = function(data, dim) { this.unionExtent(data.getApproximateExtent(dim)); }, LogScale.prototype.niceTicks = function(approxTickNum) { approxTickNum = approxTickNum || 10; var extent = this._extent, span = extent[1] - extent[0]; if (span !== 1 / 0 && !(span <= 0)) { var interval = quantity(span); for(approxTickNum / span * interval <= 0.5 && (interval *= 10); !isNaN(interval) && 1 > Math.abs(interval) && Math.abs(interval) > 0;)interval *= 10; var niceExtent = [ round(mathCeil(extent[0] / interval) * interval), round(mathFloor$1(extent[1] / interval) * interval) ]; this._interval = interval, this._niceExtent = niceExtent; } }, LogScale.prototype.niceExtent = function(opt) { intervalScaleProto.niceExtent.call(this, opt), this._fixMin = opt.fixMin, this._fixMax = opt.fixMax; }, LogScale.prototype.parse = function(val) { return val; }, LogScale.prototype.contain = function(val) { return contain$2(val = mathLog(val) / mathLog(this.base), this._extent); }, LogScale.prototype.normalize = function(val) { return normalize$1(val = mathLog(val) / mathLog(this.base), this._extent); }, LogScale.prototype.scale = function(val) { return val = scale$2(val, this._extent), mathPow$1(this.base, val); }, LogScale.type = 'log', LogScale; }(Scale), proto = LogScale.prototype; proto.getMinorTicks = intervalScaleProto.getMinorTicks, proto.getLabel = intervalScaleProto.getLabel, Scale.registerClass(LogScale); var ScaleRawExtentInfo = function() { function ScaleRawExtentInfo(scale, model, originalExtent) { this._prepareParams(scale, model, originalExtent); } return ScaleRawExtentInfo.prototype._prepareParams = function(scale, model, dataExtent) { dataExtent[1] < dataExtent[0] && (dataExtent = [ NaN, NaN ]), this._dataMin = dataExtent[0], this._dataMax = dataExtent[1]; var isOrdinal = this._isOrdinal = 'ordinal' === scale.type; this._needCrossZero = model.getNeedCrossZero && model.getNeedCrossZero(); var modelMinRaw = this._modelMinRaw = model.get('min', !0); isFunction(modelMinRaw) ? this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw({ min: dataExtent[0], max: dataExtent[1] })) : 'dataMin' !== modelMinRaw && (this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw)); var modelMaxRaw = this._modelMaxRaw = model.get('max', !0); if (isFunction(modelMaxRaw) ? this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw({ min: dataExtent[0], max: dataExtent[1] })) : 'dataMax' !== modelMaxRaw && (this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw)), isOrdinal) this._axisDataLen = model.getCategories().length; else { var boundaryGap = model.get('boundaryGap'), boundaryGapArr = isArray(boundaryGap) ? boundaryGap : [ boundaryGap || 0, boundaryGap || 0 ]; 'boolean' == typeof boundaryGapArr[0] || 'boolean' == typeof boundaryGapArr[1] ? (console.warn('Boolean type for boundaryGap is only allowed for ordinal axis. Please use string in percentage instead, e.g., "20%". Currently, boundaryGap is set to be 0.'), this._boundaryGapInner = [ 0, 0 ]) : this._boundaryGapInner = [ parsePercent(boundaryGapArr[0], 1), parsePercent(boundaryGapArr[1], 1) ]; } }, ScaleRawExtentInfo.prototype.calculate = function() { var value, value1, isOrdinal = this._isOrdinal, dataMin = this._dataMin, dataMax = this._dataMax, axisDataLen = this._axisDataLen, boundaryGapInner = this._boundaryGapInner, span = isOrdinal ? null : dataMax - dataMin || Math.abs(dataMin), min = 'dataMin' === this._modelMinRaw ? dataMin : this._modelMinNum, max = 'dataMax' === this._modelMaxRaw ? dataMax : this._modelMaxNum, minFixed = null != min, maxFixed = null != max; null == min && (min = isOrdinal ? axisDataLen ? 0 : NaN : dataMin - boundaryGapInner[0] * span), null == max && (max = isOrdinal ? axisDataLen ? axisDataLen - 1 : NaN : dataMax + boundaryGapInner[1] * span), null != min && isFinite(min) || (min = NaN), null != max && isFinite(max) || (max = NaN), min > max && (min = NaN, max = NaN); var isBlank = (value = min) != value || (value1 = max) != value1 || isOrdinal && !axisDataLen; this._needCrossZero && (min > 0 && max > 0 && !minFixed && (min = 0), min < 0 && max < 0 && !maxFixed && (max = 0)); var determinedMin = this._determinedMin, determinedMax = this._determinedMax; return null != determinedMin && (min = determinedMin, minFixed = !0), null != determinedMax && (max = determinedMax, maxFixed = !0), { min: min, max: max, minFixed: minFixed, maxFixed: maxFixed, isBlank: isBlank }; }, ScaleRawExtentInfo.prototype.modifyDataMinMax = function(minMaxName, val) { assert(!this.frozen), this[DATA_MIN_MAX_ATTR[minMaxName]] = val; }, ScaleRawExtentInfo.prototype.setDeterminedMinMax = function(minMaxName, val) { var attr = DETERMINED_MIN_MAX_ATTR[minMaxName]; assert(!this.frozen && null == this[attr]), this[attr] = val; }, ScaleRawExtentInfo.prototype.freeze = function() { this.frozen = !0; }, ScaleRawExtentInfo; }(), DETERMINED_MIN_MAX_ATTR = { min: '_determinedMin', max: '_determinedMax' }, DATA_MIN_MAX_ATTR = { min: '_dataMin', max: '_dataMax' }; function ensureScaleRawExtentInfo(scale, model, originalExtent) { var rawExtentInfo = scale.rawExtentInfo; return rawExtentInfo || (rawExtentInfo = new ScaleRawExtentInfo(scale, model, originalExtent), scale.rawExtentInfo = rawExtentInfo), rawExtentInfo; } function parseAxisModelMinMax(scale, minMax) { return null == minMax ? null : minMax != minMax ? NaN : scale.parse(minMax); } function getScaleExtent(scale, model) { var scaleType = scale.type, rawExtentResult = ensureScaleRawExtentInfo(scale, model, scale.getExtent()).calculate(); scale.setBlank(rawExtentResult.isBlank); var min = rawExtentResult.min, max = rawExtentResult.max, ecModel = model.ecModel; if (ecModel && 'time' === scaleType) { var barSeriesModels = prepareLayoutBarSeries('bar', ecModel), isBaseAxisAndHasBarSeries_1 = !1; if (each(barSeriesModels, function(seriesModel) { isBaseAxisAndHasBarSeries_1 = isBaseAxisAndHasBarSeries_1 || seriesModel.getBaseAxis() === model.axis; }), isBaseAxisAndHasBarSeries_1) { var adjustedScale = function(min, max, model, barWidthAndOffset) { var axisExtent = model.axis.getExtent(), axisLength = axisExtent[1] - axisExtent[0], barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis); if (void 0 === barsOnCurrentAxis) return { min: min, max: max }; var minOverflow = 1 / 0; each(barsOnCurrentAxis, function(item) { minOverflow = Math.min(item.offset, minOverflow); }); var maxOverflow = -1 / 0; each(barsOnCurrentAxis, function(item) { maxOverflow = Math.max(item.offset + item.width, maxOverflow); }); var totalOverFlow = (minOverflow = Math.abs(minOverflow)) + (maxOverflow = Math.abs(maxOverflow)), oldRange = max - min, overflowBuffer = oldRange / (1 - (minOverflow + maxOverflow) / axisLength) - oldRange; return max += overflowBuffer * (maxOverflow / totalOverFlow), { min: min -= overflowBuffer * (minOverflow / totalOverFlow), max: max }; }(min, max, model, makeColumnLayout(barSeriesModels)); min = adjustedScale.min, max = adjustedScale.max; } } return { extent: [ min, max ], fixMin: rawExtentResult.minFixed, fixMax: rawExtentResult.maxFixed }; } function niceScaleExtent(scale, model) { var extentInfo = getScaleExtent(scale, model), extent = extentInfo.extent, splitNumber = model.get('splitNumber'); scale instanceof LogScale && (scale.base = model.get('logBase')); var scaleType = scale.type; scale.setExtent(extent[0], extent[1]), scale.niceExtent({ splitNumber: splitNumber, fixMin: extentInfo.fixMin, fixMax: extentInfo.fixMax, minInterval: 'interval' === scaleType || 'time' === scaleType ? model.get('minInterval') : null, maxInterval: 'interval' === scaleType || 'time' === scaleType ? model.get('maxInterval') : null }); var interval = model.get('interval'); null != interval && scale.setInterval && scale.setInterval(interval); } function createScaleByModel(model, axisType) { if (axisType = axisType || model.get('type')) switch(axisType){ case 'category': return new OrdinalScale({ ordinalMeta: model.getOrdinalMeta ? model.getOrdinalMeta() : model.getCategories(), extent: [ 1 / 0, -1 / 0 ] }); case 'time': return new TimeScale({ locale: model.ecModel.getLocaleModel(), useUTC: model.ecModel.get('useUTC') }); default: return new (Scale.getClass(axisType) || IntervalScale)(); } } function makeLabelFormatter(axis) { var labelFormatter = axis.getLabelModel().get('formatter'), categoryTickStart = 'category' === axis.type ? axis.scale.getExtent()[0] : null; return 'time' === axis.scale.type ? function(tick, idx) { return axis.scale.getFormattedLabel(tick, idx, labelFormatter); } : 'string' == typeof labelFormatter ? function(tick) { var label = axis.scale.getLabel(tick); return labelFormatter.replace('{value}', null != label ? label : ''); } : 'function' != typeof labelFormatter ? function(tick) { return axis.scale.getLabel(tick); } : function(tick, idx) { return null != categoryTickStart && (idx = tick.value - categoryTickStart), labelFormatter(getAxisRawValue(axis, tick), idx, null != tick.level ? { level: tick.level } : null); }; } function getAxisRawValue(axis, tick) { return 'category' === axis.type ? axis.scale.getLabel(tick) : tick.value; } function getOptionCategoryInterval(model) { var interval = model.get('interval'); return null == interval ? 'auto' : interval; } function shouldShowAllLabels(axis) { return 'category' === axis.type && 0 === getOptionCategoryInterval(axis.getLabelModel()); } function getDataDimensionsOnAxis(data, axisDim) { var dataDimMap = {}; return each(data.mapDimensionsAll(axisDim), function(dataDim) { dataDimMap[getStackedDimension(data, dataDim)] = !0; }), keys(dataDimMap); } var AxisModelCommonMixin = function() { function AxisModelCommonMixin() {} return AxisModelCommonMixin.prototype.getNeedCrossZero = function() { return !this.option.scale; }, AxisModelCommonMixin.prototype.getCoordSysModel = function() {}, AxisModelCommonMixin; }(), helper = Object.freeze({ __proto__: null, createList: function(seriesModel) { return createListFromArray(seriesModel.getSource(), seriesModel); }, getLayoutRect: getLayoutRect, dataStack: { isDimensionStacked: isDimensionStacked, enableDataStack: enableDataStack, getStackedDimension: getStackedDimension }, createScale: function(dataExtent, option) { var axisModel = option; option instanceof Model || (axisModel = new Model(option)); var scale = createScaleByModel(axisModel); return scale.setExtent(dataExtent[0], dataExtent[1]), niceScaleExtent(scale, axisModel), scale; }, mixinAxisModelCommonMethods: function(Model) { mixin(Model, AxisModelCommonMixin); }, getECData: getECData, createTextStyle: function(textStyleModel, opts) { return createTextStyle(textStyleModel, null, null, 'normal' !== (opts = opts || {}).state); }, createDimensions: createDimensions, createSymbol: createSymbol, enableHoverEmphasis: enableHoverEmphasis }), number = Object.freeze({ __proto__: null, linearMap: linearMap, round: round, asc: asc, getPrecision: getPrecision, getPrecisionSafe: getPrecisionSafe, getPixelPrecision: getPixelPrecision, getPercentWithPrecision: getPercentWithPrecision, MAX_SAFE_INTEGER: 9007199254740991, remRadian: remRadian, isRadianAroundZero: isRadianAroundZero, parseDate: parseDate, quantity: quantity, quantityExponent: quantityExponent, nice: nice, quantile: quantile, reformIntervals: reformIntervals, isNumeric: isNumeric, numericToNumber: numericToNumber }), time = Object.freeze({ __proto__: null, parse: parseDate, format: format }), graphic$1 = Object.freeze({ __proto__: null, extendShape: extendShape, extendPath: extendPath, makePath: makePath, makeImage: makeImage, mergePath: mergePath$1, resizePath: resizePath, createIcon: createIcon, updateProps: updateProps, initProps: initProps, getTransform: getTransform, clipPointsByRect: clipPointsByRect, clipRectByRect: clipRectByRect, registerShape: registerShape, getShapeClass: getShapeClass, Group: Group, Image: ZRImage, Text: ZRText, Circle: Circle, Ellipse: Ellipse, Sector: Sector, Ring: Ring, Polygon: Polygon, Polyline: Polyline, Rect: Rect, Line: Line, BezierCurve: BezierCurve, Arc: Arc, IncrementalDisplayable: IncrementalDisplayable, CompoundPath: CompoundPath, LinearGradient: LinearGradient, RadialGradient: RadialGradient, BoundingRect: BoundingRect }), format$1 = Object.freeze({ __proto__: null, addCommas: addCommas, toCamelCase: toCamelCase, normalizeCssArray: normalizeCssArray, encodeHTML: encodeHTML, formatTpl: formatTpl, getTooltipMarker: getTooltipMarker, formatTime: function(tpl, value, isUTC) { deprecateReplaceLog('echarts.format.formatTime', 'echarts.time.format'), ('week' === tpl || 'month' === tpl || 'quarter' === tpl || 'half-year' === tpl || 'year' === tpl) && (tpl = 'MM-dd\nyyyy'); var date = parseDate(value), utc = isUTC ? 'UTC' : '', y = date['get' + utc + 'FullYear'](), M = date['get' + utc + 'Month']() + 1, d = date['get' + utc + 'Date'](), h = date['get' + utc + 'Hours'](), m = date['get' + utc + 'Minutes'](), s = date['get' + utc + 'Seconds'](), S = date['get' + utc + 'Milliseconds'](); return tpl = tpl.replace('MM', pad(M, 2)).replace('M', M).replace('yyyy', y).replace('yy', y % 100 + '').replace('dd', pad(d, 2)).replace('d', d).replace('hh', pad(h, 2)).replace('h', h).replace('mm', pad(m, 2)).replace('m', m).replace('ss', pad(s, 2)).replace('s', s).replace('SSS', pad(S, 3)); }, capitalFirst: function(str) { return str ? str.charAt(0).toUpperCase() + str.substr(1) : str; }, truncateText: truncateText, getTextRect: function(text, font, align, verticalAlign, padding, rich, truncate, lineHeight) { return deprecateLog('getTextRect is deprecated.'), new ZRText({ style: { text: text, font: font, align: align, verticalAlign: verticalAlign, padding: padding, rich: rich, overflow: truncate ? 'truncate' : null, lineHeight: lineHeight } }).getBoundingRect(); } }), util$1 = Object.freeze({ __proto__: null, map: map, each: each, indexOf: indexOf, inherits: inherits, reduce: reduce, filter: filter, bind: bind, curry: curry, isArray: isArray, isString: isString, isObject: isObject, isFunction: isFunction, extend: extend, defaults: defaults, clone: clone, merge: merge }), inner$4 = makeInner(); function makeCategoryLabelsActually(axis, labelModel) { var result, labels, numericLabelInterval, labelsCache = getListCache(axis, 'labels'), optionLabelInterval = getOptionCategoryInterval(labelModel); return listCacheGet(labelsCache, optionLabelInterval) || (isFunction(optionLabelInterval) ? labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval) : (numericLabelInterval = 'auto' === optionLabelInterval ? null != (result = inner$4(axis).autoInterval) ? result : inner$4(axis).autoInterval = axis.calculateCategoryInterval() : optionLabelInterval, labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval)), listCacheSet(labelsCache, optionLabelInterval, { labels: labels, labelCategoryInterval: numericLabelInterval })); } function getListCache(axis, prop) { return inner$4(axis)[prop] || (inner$4(axis)[prop] = []); } function listCacheGet(cache, key) { for(var i = 0; i < cache.length; i++)if (cache[i].key === key) return cache[i].value; } function listCacheSet(cache, key, value) { return cache.push({ key: key, value: value }), value; } function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) { var labelFormatter = makeLabelFormatter(axis), ordinalScale = axis.scale, ordinalExtent = ordinalScale.getExtent(), labelModel = axis.getLabelModel(), result = [], step = Math.max((categoryInterval || 0) + 1, 1), startTick = ordinalExtent[0], tickCount = ordinalScale.count(); 0 !== startTick && step > 1 && tickCount / step > 2 && (startTick = Math.round(Math.ceil(startTick / step) * step)); var showAllLabel = shouldShowAllLabels(axis), includeMinLabel = labelModel.get('showMinLabel') || showAllLabel, includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel; includeMinLabel && startTick !== ordinalExtent[0] && addItem(ordinalExtent[0]); for(var tickValue = startTick; tickValue <= ordinalExtent[1]; tickValue += step)addItem(tickValue); function addItem(tickValue) { var tickObj = { value: tickValue }; result.push(onlyTick ? tickValue : { formattedLabel: labelFormatter(tickObj), rawLabel: ordinalScale.getLabel(tickObj), tickValue: tickValue }); } return includeMaxLabel && tickValue - step !== ordinalExtent[1] && addItem(ordinalExtent[1]), result; } function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) { var ordinalScale = axis.scale, labelFormatter = makeLabelFormatter(axis), result = []; return each(ordinalScale.getTicks(), function(tick) { var rawLabel = ordinalScale.getLabel(tick), tickValue = tick.value; categoryInterval(tick.value, rawLabel) && result.push(onlyTick ? tickValue : { formattedLabel: labelFormatter(tick), rawLabel: rawLabel, tickValue: tickValue }); }), result; } var NORMALIZED_EXTENT = [ 0, 1 ], Axis = function() { function Axis(dim, scale, extent) { this.onBand = !1, this.inverse = !1, this.dim = dim, this.scale = scale, this._extent = extent || [ 0, 0 ]; } return Axis.prototype.contain = function(coord) { var extent = this._extent, min = Math.min(extent[0], extent[1]), max = Math.max(extent[0], extent[1]); return coord >= min && coord <= max; }, Axis.prototype.containData = function(data) { return this.scale.contain(data); }, Axis.prototype.getExtent = function() { return this._extent.slice(); }, Axis.prototype.getPixelPrecision = function(dataExtent) { return getPixelPrecision(dataExtent || this.scale.getExtent(), this._extent); }, Axis.prototype.setExtent = function(start, end) { var extent = this._extent; extent[0] = start, extent[1] = end; }, Axis.prototype.dataToCoord = function(data, clamp) { var extent = this._extent, scale = this.scale; return data = scale.normalize(data), this.onBand && 'ordinal' === scale.type && fixExtentWithBands(extent = extent.slice(), scale.count()), linearMap(data, NORMALIZED_EXTENT, extent, clamp); }, Axis.prototype.coordToData = function(coord, clamp) { var extent = this._extent, scale = this.scale; this.onBand && 'ordinal' === scale.type && fixExtentWithBands(extent = extent.slice(), scale.count()); var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp); return this.scale.scale(t); }, Axis.prototype.pointToData = function(point, clamp) {}, Axis.prototype.getTicksCoords = function(opt) { var tickModel = (opt = opt || {}).tickModel || this.getTickModel(), ticks = ('category' === this.type ? function(axis, tickModel) { var ticks, tickCategoryInterval, ticksCache = getListCache(axis, 'ticks'), optionTickInterval = getOptionCategoryInterval(tickModel), result = listCacheGet(ticksCache, optionTickInterval); if (result) return result; if ((!tickModel.get('show') || axis.scale.isBlank()) && (ticks = []), isFunction(optionTickInterval)) ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, !0); else if ('auto' === optionTickInterval) { var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel()); tickCategoryInterval = labelsResult.labelCategoryInterval, ticks = map(labelsResult.labels, function(labelItem) { return labelItem.tickValue; }); } else ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval = optionTickInterval, !0); return listCacheSet(ticksCache, optionTickInterval, { ticks: ticks, tickCategoryInterval: tickCategoryInterval }); }(this, tickModel) : { ticks: map(this.scale.getTicks(), function(tick) { return tick.value; }) }).ticks, ticksCoords = map(ticks, function(tickVal) { return { coord: this.dataToCoord('ordinal' === this.scale.type ? this.scale.getRawOrdinalNumber(tickVal) : tickVal), tickValue: tickVal }; }, this); return function(axis, ticksCoords, alignWithLabel, clamp) { var last, diffSize, ticksLen = ticksCoords.length; if (axis.onBand && !alignWithLabel && ticksLen) { var axisExtent = axis.getExtent(); if (1 === ticksLen) ticksCoords[0].coord = axisExtent[0], last = ticksCoords[1] = { coord: axisExtent[0] }; else { var crossLen = ticksCoords[ticksLen - 1].tickValue - ticksCoords[0].tickValue, shift_1 = (ticksCoords[ticksLen - 1].coord - ticksCoords[0].coord) / crossLen; each(ticksCoords, function(ticksItem) { ticksItem.coord -= shift_1 / 2; }), diffSize = 1 + axis.scale.getExtent()[1] - ticksCoords[ticksLen - 1].tickValue, last = { coord: ticksCoords[ticksLen - 1].coord + shift_1 * diffSize }, ticksCoords.push(last); } var inverse = axisExtent[0] > axisExtent[1]; littleThan(ticksCoords[0].coord, axisExtent[0]) && (clamp ? ticksCoords[0].coord = axisExtent[0] : ticksCoords.shift()), clamp && littleThan(axisExtent[0], ticksCoords[0].coord) && ticksCoords.unshift({ coord: axisExtent[0] }), littleThan(axisExtent[1], last.coord) && (clamp ? last.coord = axisExtent[1] : ticksCoords.pop()), clamp && littleThan(last.coord, axisExtent[1]) && ticksCoords.push({ coord: axisExtent[1] }); } function littleThan(a, b) { return a = round(a), b = round(b), inverse ? a > b : a < b; } }(this, ticksCoords, tickModel.get('alignWithLabel'), opt.clamp), ticksCoords; }, Axis.prototype.getMinorTicksCoords = function() { if ('ordinal' === this.scale.type) return []; var splitNumber = this.model.getModel('minorTick').get('splitNumber'); return splitNumber > 0 && splitNumber < 100 || (splitNumber = 5), map(this.scale.getMinorTicks(splitNumber), function(minorTicksGroup) { return map(minorTicksGroup, function(minorTick) { return { coord: this.dataToCoord(minorTick), tickValue: minorTick }; }, this); }, this); }, Axis.prototype.getViewLabels = function() { var labelModel, result, axis, ticks, labelFormatter; return ('category' === this.type ? (result = makeCategoryLabelsActually(this, labelModel = this.getLabelModel()), !labelModel.get('show') || this.scale.isBlank() ? { labels: [], labelCategoryInterval: result.labelCategoryInterval } : result) : (axis = this, ticks = axis.scale.getTicks(), labelFormatter = makeLabelFormatter(axis), { labels: map(ticks, function(tick, idx) { return { formattedLabel: labelFormatter(tick, idx), rawLabel: axis.scale.getLabel(tick), tickValue: tick.value }; }) })).labels; }, Axis.prototype.getLabelModel = function() { return this.model.getModel('axisLabel'); }, Axis.prototype.getTickModel = function() { return this.model.getModel('axisTick'); }, Axis.prototype.getBandWidth = function() { var axisExtent = this._extent, dataExtent = this.scale.getExtent(), len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0); return 0 === len && (len = 1), Math.abs(Math.abs(axisExtent[1] - axisExtent[0])) / len; }, Axis.prototype.calculateCategoryInterval = function() { return function(axis) { var labelModel, params = (labelModel = axis.getLabelModel(), { axisRotate: axis.getRotate ? axis.getRotate() : axis.isHorizontal && !axis.isHorizontal() ? 90 : 0, labelRotate: labelModel.get('rotate') || 0, font: labelModel.getFont() }), labelFormatter = makeLabelFormatter(axis), rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI, ordinalScale = axis.scale, ordinalExtent = ordinalScale.getExtent(), tickCount = ordinalScale.count(); if (ordinalExtent[1] - ordinalExtent[0] < 1) return 0; var step = 1; tickCount > 40 && (step = Math.max(1, Math.floor(tickCount / 40))); for(var tickValue = ordinalExtent[0], unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue), maxW = 0, maxH = 0; tickValue <= ordinalExtent[1]; tickValue += step){ var width = 0, height = 0, rect = getBoundingRect(labelFormatter({ value: tickValue }), params.font, 'center', 'top'); width = 1.3 * rect.width, height = 1.3 * rect.height, maxW = Math.max(maxW, width, 7), maxH = Math.max(maxH, height, 7); } var dw = maxW / Math.abs(unitSpan * Math.cos(rotation)), dh = maxH / Math.abs(unitSpan * Math.sin(rotation)); isNaN(dw) && (dw = 1 / 0), isNaN(dh) && (dh = 1 / 0); var interval = Math.max(0, Math.floor(Math.min(dw, dh))), cache = inner$4(axis.model), axisExtent = axis.getExtent(), lastAutoInterval = cache.lastAutoInterval, lastTickCount = cache.lastTickCount; return null != lastAutoInterval && null != lastTickCount && 1 >= Math.abs(lastAutoInterval - interval) && 1 >= Math.abs(lastTickCount - tickCount) && lastAutoInterval > interval && cache.axisExtent0 === axisExtent[0] && cache.axisExtent1 === axisExtent[1] ? interval = lastAutoInterval : (cache.lastTickCount = tickCount, cache.lastAutoInterval = interval, cache.axisExtent0 = axisExtent[0], cache.axisExtent1 = axisExtent[1]), interval; }(this); }, Axis; }(); function fixExtentWithBands(extent, nTick) { var margin = (extent[1] - extent[0]) / nTick / 2; extent[0] += margin, extent[1] -= margin; } function createElement(name) { return document.createElementNS('http://www.w3.org/2000/svg', name); } function extractCommon(basePath, newArr, oldArr, diagonalPath, equals) { for(var newLen = newArr.length, oldLen = oldArr.length, newPos = basePath.newPos, oldPos = newPos - diagonalPath, commonCount = 0; newPos + 1 < newLen && oldPos + 1 < oldLen && equals(newArr[newPos + 1], oldArr[oldPos + 1]);)newPos++, oldPos++, commonCount++; return commonCount && basePath.components.push({ count: commonCount, added: !1, removed: !1, indices: [] }), basePath.newPos = newPos, oldPos; } function pushComponent(components, added, removed) { var last = components[components.length - 1]; last && last.added === added && last.removed === removed ? components[components.length - 1] = { count: last.count + 1, added: added, removed: removed, indices: [] } : components.push({ count: 1, added: added, removed: removed, indices: [] }); } var NONE = 'none', mathRound = Math.round, mathSin$4 = Math.sin, mathCos$4 = Math.cos, PI$4 = Math.PI, PI2$7 = 2 * Math.PI, degree = 180 / PI$4; function round3(val) { return mathRound(1e3 * val) / 1e3; } function round4(val) { return mathRound(1e4 * val) / 1e4; } function isAroundZero$1(val) { return val < 1e-4 && val > -0.0001; } function setTransform(svgEl, m) { m && attr(svgEl, 'transform', 'matrix(' + round3(m[0]) + ',' + round3(m[1]) + ',' + round3(m[2]) + ',' + round3(m[3]) + ',' + round4(m[4]) + ',' + round4(m[5]) + ')'); } function attr(el, key, val) { val && ('linear' === val.type || 'radial' === val.type) || el.setAttribute(key, val); } function bindStyle(svgEl, style, el) { var fill, stroke, opacity = null == style.opacity ? 1 : style.opacity; if (el instanceof ZRImage) { svgEl.style.opacity = opacity + ''; return; } if (null != (fill = style.fill) && fill !== NONE) { var fill1 = style.fill; attr(svgEl, 'fill', fill1 = 'transparent' === fill1 ? NONE : fill1), attr(svgEl, 'fill-opacity', (null != style.fillOpacity ? style.fillOpacity * opacity : opacity) + ''); } else attr(svgEl, 'fill', NONE); if (null != (stroke = style.stroke) && stroke !== NONE) { var stroke1 = style.stroke; attr(svgEl, 'stroke', stroke1 = 'transparent' === stroke1 ? NONE : stroke1); var strokeWidth = style.lineWidth, strokeScale_1 = style.strokeNoScale ? el.getLineScale() : 1; attr(svgEl, 'stroke-width', (strokeScale_1 ? strokeWidth / strokeScale_1 : 0) + ''), attr(svgEl, 'paint-order', style.strokeFirst ? 'stroke' : 'fill'), attr(svgEl, 'stroke-opacity', (null != style.strokeOpacity ? style.strokeOpacity * opacity : opacity) + ''); var lineDash = style.lineDash && strokeWidth > 0 && normalizeLineDash(style.lineDash, strokeWidth); if (lineDash) { var lineDashOffset = style.lineDashOffset; strokeScale_1 && 1 !== strokeScale_1 && (lineDash = map(lineDash, function(rawVal) { return rawVal / strokeScale_1; }), lineDashOffset && (lineDashOffset /= strokeScale_1, lineDashOffset = mathRound(lineDashOffset))), attr(svgEl, 'stroke-dasharray', lineDash.join(',')), attr(svgEl, 'stroke-dashoffset', (lineDashOffset || 0) + ''); } else attr(svgEl, 'stroke-dasharray', ''); style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap), style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin), style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit + ''); } else attr(svgEl, 'stroke', NONE); } var SVGPathRebuilder = function() { function SVGPathRebuilder() {} return SVGPathRebuilder.prototype.reset = function() { this._d = [], this._str = ''; }, SVGPathRebuilder.prototype.moveTo = function(x, y) { this._add('M', x, y); }, SVGPathRebuilder.prototype.lineTo = function(x, y) { this._add('L', x, y); }, SVGPathRebuilder.prototype.bezierCurveTo = function(x, y, x2, y2, x3, y3) { this._add('C', x, y, x2, y2, x3, y3); }, SVGPathRebuilder.prototype.quadraticCurveTo = function(x, y, x2, y2) { this._add('Q', x, y, x2, y2); }, SVGPathRebuilder.prototype.arc = function(cx, cy, r, startAngle, endAngle, anticlockwise) { this.ellipse(cx, cy, r, r, 0, startAngle, endAngle, anticlockwise); }, SVGPathRebuilder.prototype.ellipse = function(cx, cy, rx, ry, psi, startAngle, endAngle, anticlockwise) { var firstCmd = 0 === this._d.length, dTheta = endAngle - startAngle, clockwise = !anticlockwise, dThetaPositive = Math.abs(dTheta), isCircle = isAroundZero$1(dThetaPositive - PI2$7) || (clockwise ? dTheta >= PI2$7 : -dTheta >= PI2$7), unifiedTheta = dTheta > 0 ? dTheta % PI2$7 : dTheta % PI2$7 + PI2$7, large = !1; large = !!isCircle || !isAroundZero$1(dThetaPositive) && unifiedTheta >= PI$4 == !!clockwise; var x0 = round4(cx + rx * mathCos$4(startAngle)), y0 = round4(cy + ry * mathSin$4(startAngle)); isCircle && (dTheta = clockwise ? PI2$7 - 1e-4 : -PI2$7 + 1e-4, large = !0, firstCmd && this._d.push('M', x0, y0)); var x = round4(cx + rx * mathCos$4(startAngle + dTheta)), y = round4(cy + ry * mathSin$4(startAngle + dTheta)); if (isNaN(x0) || isNaN(y0) || isNaN(rx) || isNaN(ry) || isNaN(psi) || isNaN(degree) || isNaN(x) || isNaN(y)) return ''; this._d.push('A', round4(rx), round4(ry), mathRound(psi * degree), +large, +clockwise, x, y); }, SVGPathRebuilder.prototype.rect = function(x, y, w, h) { this._add('M', x, y), this._add('L', x + w, y), this._add('L', x + w, y + h), this._add('L', x, y + h), this._add('L', x, y); }, SVGPathRebuilder.prototype.closePath = function() { this._d.length > 0 && this._add('Z'); }, SVGPathRebuilder.prototype._add = function(cmd, a, b, c, d, e, f, g, h) { this._d.push(cmd); for(var i = 1; i < arguments.length; i++){ var val = arguments[i]; if (isNaN(val)) { this._invalid = !0; return; } this._d.push(round4(val)); } }, SVGPathRebuilder.prototype.generateStr = function() { this._str = this._invalid ? '' : this._d.join(' '), this._d = []; }, SVGPathRebuilder.prototype.getStr = function() { return this._str; }, SVGPathRebuilder; }(), svgPath = { brush: function(el) { var style = el.style, svgEl = el.__svgEl; svgEl || (svgEl = createElement('path'), el.__svgEl = svgEl), el.path || el.createPathProxy(); var path = el.path; el.shapeChanged() && (path.beginPath(), el.buildPath(path, el.shape), el.pathUpdated()); var pathVersion = path.getVersion(), elExt = el, svgPathBuilder = elExt.__svgPathBuilder; (elExt.__svgPathVersion !== pathVersion || !svgPathBuilder || el.style.strokePercent < 1) && (svgPathBuilder || (svgPathBuilder = elExt.__svgPathBuilder = new SVGPathRebuilder()), svgPathBuilder.reset(), path.rebuildPath(svgPathBuilder, el.style.strokePercent), svgPathBuilder.generateStr(), elExt.__svgPathVersion = pathVersion), attr(svgEl, 'd', svgPathBuilder.getStr()), bindStyle(svgEl, style, el), setTransform(svgEl, el.transform); } }, svgImage = { brush: function(el) { var style = el.style, image = style.image; if (image instanceof HTMLImageElement ? image = image.src : image instanceof HTMLCanvasElement && (image = image.toDataURL()), image) { var x = style.x || 0, y = style.y || 0, dw = style.width, dh = style.height, svgEl = el.__svgEl; svgEl || (svgEl = createElement('image'), el.__svgEl = svgEl), image !== el.__imageSrc && (function(el, key, val) { el.setAttributeNS('http://www.w3.org/1999/xlink', key, val); }(svgEl, 'href', image), el.__imageSrc = image), attr(svgEl, 'width', dw + ''), attr(svgEl, 'height', dh + ''), attr(svgEl, 'x', x + ''), attr(svgEl, 'y', y + ''), bindStyle(svgEl, style, el), setTransform(svgEl, el.transform); } } }, TEXT_ALIGN_TO_ANCHOR = { left: 'start', right: 'end', center: 'middle', middle: 'middle' }, svgText = { brush: function(el) { var y, lineHeight, textBaseline, style = el.style, text = style.text; if (null != text && (text += ''), !(!text || isNaN(style.x) || isNaN(style.y))) { var textSvgEl = el.__svgEl; textSvgEl || (!function(el, key, val) { el.setAttributeNS('http://www.w3.org/XML/1998/namespace', key, val); }(textSvgEl = createElement('text'), 'xml:space', 'preserve'), el.__svgEl = textSvgEl); var font = style.font || DEFAULT_FONT; textSvgEl.style.font = font, textSvgEl.textContent = text, bindStyle(textSvgEl, style, el), setTransform(textSvgEl, el.transform); var x = style.x || 0, y1 = (y = style.y || 0, lineHeight = getLineHeight(font), 'top' === (textBaseline = style.textBaseline) ? y += lineHeight / 2 : 'bottom' === textBaseline && (y -= lineHeight / 2), y), textAlign = TEXT_ALIGN_TO_ANCHOR[style.textAlign] || style.textAlign; attr(textSvgEl, 'dominant-baseline', 'central'), attr(textSvgEl, 'text-anchor', textAlign), attr(textSvgEl, 'x', x + ''), attr(textSvgEl, 'y', y1 + ''); } } }, Definable = function() { function Definable(zrId, svgRoot, tagNames, markLabel, domName) { this.nextId = 0, this._domName = '_dom', this.createElement = createElement, this._zrId = zrId, this._svgRoot = svgRoot, this._tagNames = 'string' == typeof tagNames ? [ tagNames ] : tagNames, this._markLabel = markLabel, domName && (this._domName = domName); } return Definable.prototype.getDefs = function(isForceCreating) { var svgRoot = this._svgRoot, defs = this._svgRoot.getElementsByTagName('defs'); if (0 !== defs.length) return defs[0]; if (!isForceCreating) return null; var defs_1 = svgRoot.insertBefore(this.createElement('defs'), svgRoot.firstChild); return defs_1.contains || (defs_1.contains = function(el) { var children = defs_1.children; if (!children) return !1; for(var i = children.length - 1; i >= 0; --i)if (children[i] === el) return !0; return !1; }), defs_1; }, Definable.prototype.doUpdate = function(target, onUpdate) { if (target) { var defs = this.getDefs(!1); if (target[this._domName] && defs.contains(target[this._domName])) 'function' == typeof onUpdate && onUpdate(target); else { var dom = this.add(target); dom && (target[this._domName] = dom); } } }, Definable.prototype.add = function(target) { return null; }, Definable.prototype.addDom = function(dom) { var defs = this.getDefs(!0); dom.parentNode !== defs && defs.appendChild(dom); }, Definable.prototype.removeDom = function(target) { var defs = this.getDefs(!1); defs && target[this._domName] && (defs.removeChild(target[this._domName]), target[this._domName] = null); }, Definable.prototype.getDoms = function() { var defs = this.getDefs(!1); if (!defs) return []; var doms = []; return each(this._tagNames, function(tagName) { for(var tags = defs.getElementsByTagName(tagName), i = 0; i < tags.length; i++)doms.push(tags[i]); }), doms; }, Definable.prototype.markAllUnused = function() { var doms = this.getDoms(), that = this; each(doms, function(dom) { dom[that._markLabel] = '0'; }); }, Definable.prototype.markDomUsed = function(dom) { dom && (dom[this._markLabel] = '1'); }, Definable.prototype.markDomUnused = function(dom) { dom && (dom[this._markLabel] = '0'); }, Definable.prototype.isDomUnused = function(dom) { return dom && '1' !== dom[this._markLabel]; }, Definable.prototype.removeUnused = function() { var _this = this, defs = this.getDefs(!1); defs && each(this.getDoms(), function(dom) { _this.isDomUnused(dom) && defs.removeChild(dom); }); }, Definable.prototype.getSvgProxy = function(displayable) { return displayable instanceof Path ? svgPath : displayable instanceof ZRImage ? svgImage : displayable instanceof TSpan ? svgText : svgPath; }, Definable.prototype.getSvgElement = function(displayable) { return displayable.__svgEl; }, Definable; }(); function isLinearGradient(value) { return 'linear' === value.type; } function isRadialGradient(value) { return 'radial' === value.type; } function isGradient(value) { return value && ('linear' === value.type || 'radial' === value.type); } var GradientManager = function(_super) { function GradientManager(zrId, svgRoot) { return _super.call(this, zrId, svgRoot, [ 'linearGradient', 'radialGradient' ], '__gradient_in_use__') || this; } return __extends(GradientManager, _super), GradientManager.prototype.addWithoutUpdate = function(svgElement, displayable) { if (displayable && displayable.style) { var that_1 = this; each([ 'fill', 'stroke' ], function(fillOrStroke) { var value = displayable.style[fillOrStroke]; if (isGradient(value)) { var defs = that_1.getDefs(!0), dom = void 0; value.__dom ? (dom = value.__dom, defs.contains(value.__dom) || that_1.addDom(dom)) : dom = that_1.add(value), that_1.markUsed(displayable); var id = dom.getAttribute('id'); svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')'); } }); } }, GradientManager.prototype.add = function(gradient) { var dom; if (isLinearGradient(gradient)) dom = this.createElement('linearGradient'); else { if (!isRadialGradient(gradient)) return logError('Illegal gradient type.'), null; dom = this.createElement('radialGradient'); } return gradient.id = gradient.id || this.nextId++, dom.setAttribute('id', 'zr' + this._zrId + '-gradient-' + gradient.id), this.updateDom(gradient, dom), this.addDom(dom), dom; }, GradientManager.prototype.update = function(gradient) { if (isGradient(gradient)) { var that = this; this.doUpdate(gradient, function() { var dom = gradient.__dom; if (dom) { var tagName = dom.tagName, type = gradient.type; 'linear' === type && 'linearGradient' === tagName || 'radial' === type && 'radialGradient' === tagName ? that.updateDom(gradient, gradient.__dom) : (that.removeDom(gradient), that.add(gradient)); } }); } }, GradientManager.prototype.updateDom = function(gradient, dom) { if (isLinearGradient(gradient)) dom.setAttribute('x1', gradient.x + ''), dom.setAttribute('y1', gradient.y + ''), dom.setAttribute('x2', gradient.x2 + ''), dom.setAttribute('y2', gradient.y2 + ''); else if (isRadialGradient(gradient)) dom.setAttribute('cx', gradient.x + ''), dom.setAttribute('cy', gradient.y + ''), dom.setAttribute('r', gradient.r + ''); else { logError('Illegal gradient type.'); return; } gradient.global ? dom.setAttribute('gradientUnits', 'userSpaceOnUse') : dom.setAttribute('gradientUnits', 'objectBoundingBox'), dom.innerHTML = ''; for(var colors = gradient.colorStops, i = 0, len = colors.length; i < len; ++i){ var stop_1 = this.createElement('stop'); stop_1.setAttribute('offset', 100 * colors[i].offset + '%'); var color$1 = colors[i].color; if (color$1.indexOf('rgba') > -1) { var opacity = parse(color$1)[3], hex = toHex(color$1); stop_1.setAttribute('stop-color', '#' + hex), stop_1.setAttribute('stop-opacity', opacity + ''); } else stop_1.setAttribute('stop-color', colors[i].color); dom.appendChild(stop_1); } gradient.__dom = dom; }, GradientManager.prototype.markUsed = function(displayable) { if (displayable.style) { var gradient = displayable.style.fill; gradient && gradient.__dom && _super.prototype.markDomUsed.call(this, gradient.__dom), (gradient = displayable.style.stroke) && gradient.__dom && _super.prototype.markDomUsed.call(this, gradient.__dom); } }, GradientManager; }(Definable); function isPattern(value) { return value && (!!value.image || !!value.svgElement); } var patternDomMap = new WeakMap(), PatternManager = function(_super) { function PatternManager(zrId, svgRoot) { return _super.call(this, zrId, svgRoot, [ 'pattern' ], '__pattern_in_use__') || this; } return __extends(PatternManager, _super), PatternManager.prototype.addWithoutUpdate = function(svgElement, displayable) { if (displayable && displayable.style) { var that_1 = this; each([ 'fill', 'stroke' ], function(fillOrStroke) { var pattern = displayable.style[fillOrStroke]; if (isPattern(pattern)) { var defs = that_1.getDefs(!0), dom = patternDomMap.get(pattern); dom ? defs.contains(dom) || that_1.addDom(dom) : dom = that_1.add(pattern), that_1.markUsed(displayable); var id = dom.getAttribute('id'); svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')'); } }); } }, PatternManager.prototype.add = function(pattern) { if (isPattern(pattern)) { var dom = this.createElement('pattern'); return pattern.id = null == pattern.id ? this.nextId++ : pattern.id, dom.setAttribute('id', 'zr' + this._zrId + '-pattern-' + pattern.id), dom.setAttribute('x', '0'), dom.setAttribute('y', '0'), dom.setAttribute('patternUnits', 'userSpaceOnUse'), this.updateDom(pattern, dom), this.addDom(dom), dom; } }, PatternManager.prototype.update = function(pattern) { if (isPattern(pattern)) { var that = this; this.doUpdate(pattern, function() { var dom = patternDomMap.get(pattern); that.updateDom(pattern, dom); }); } }, PatternManager.prototype.updateDom = function(pattern, patternDom) { var svgElement = pattern.svgElement; if (svgElement instanceof SVGElement) svgElement.parentNode !== patternDom && (patternDom.innerHTML = '', patternDom.appendChild(svgElement), patternDom.setAttribute('width', pattern.svgWidth + ''), patternDom.setAttribute('height', pattern.svgHeight + '')); else { var img = void 0, prevImage = patternDom.getElementsByTagName('image'); if (prevImage.length) { if (pattern.image) img = prevImage[0]; else { patternDom.removeChild(prevImage[0]); return; } } else pattern.image && (img = this.createElement('image')); if (img) { var imageSrc = void 0; if ('string' == typeof pattern.image ? imageSrc = pattern.image : pattern.image instanceof HTMLImageElement ? imageSrc = pattern.image.src : pattern.image instanceof HTMLCanvasElement && (imageSrc = pattern.image.toDataURL()), imageSrc) { img.setAttribute('href', imageSrc), img.setAttribute('x', '0'), img.setAttribute('y', '0'); var createdImage = createOrUpdateImage(imageSrc, img, { dirty: function() {} }, function(img) { patternDom.setAttribute('width', img.width + ''), patternDom.setAttribute('height', img.height + ''); }); createdImage && createdImage.width && createdImage.height && (patternDom.setAttribute('width', createdImage.width + ''), patternDom.setAttribute('height', createdImage.height + '')), patternDom.appendChild(img); } } } var x = pattern.x || 0, y = pattern.y || 0, rotation = (pattern.rotation || 0) / Math.PI * 180, scaleX = pattern.scaleX || 1, scaleY = pattern.scaleY || 1; patternDom.setAttribute('patternTransform', "translate(" + x + ", " + y + ") rotate(" + rotation + ") scale(" + scaleX + ", " + scaleY + ")"), patternDomMap.set(pattern, patternDom); }, PatternManager.prototype.markUsed = function(displayable) { displayable.style && (isPattern(displayable.style.fill) && _super.prototype.markDomUsed.call(this, patternDomMap.get(displayable.style.fill)), isPattern(displayable.style.stroke) && _super.prototype.markDomUsed.call(this, patternDomMap.get(displayable.style.stroke))); }, PatternManager; }(Definable); function hasClipPath(displayable) { var clipPaths = displayable.__clipPaths; return clipPaths && clipPaths.length > 0; } var ClippathManager = function(_super) { function ClippathManager(zrId, svgRoot) { var _this = _super.call(this, zrId, svgRoot, 'clipPath', '__clippath_in_use__') || this; return _this._refGroups = {}, _this._keyDuplicateCount = {}, _this; } return __extends(ClippathManager, _super), ClippathManager.prototype.markAllUnused = function() { for(var key in _super.prototype.markAllUnused.call(this), this._refGroups)this.markDomUnused(this._refGroups[key]); this._keyDuplicateCount = {}; }, ClippathManager.prototype._getClipPathGroup = function(displayable, prevDisplayable) { if (hasClipPath(displayable)) { var clipPaths = displayable.__clipPaths, keyDuplicateCount = this._keyDuplicateCount, clipPathKey = function(clipPaths) { var key = []; if (clipPaths) for(var i = 0; i < clipPaths.length; i++){ var clipPath = clipPaths[i]; key.push(clipPath.id); } return key.join(','); }(clipPaths); return isClipPathChanged(clipPaths, prevDisplayable && prevDisplayable.__clipPaths) && (keyDuplicateCount[clipPathKey] = keyDuplicateCount[clipPathKey] || 0, keyDuplicateCount[clipPathKey] && (clipPathKey += '-' + keyDuplicateCount[clipPathKey]), keyDuplicateCount[clipPathKey]++), this._refGroups[clipPathKey] || (this._refGroups[clipPathKey] = this.createElement('g')); } }, ClippathManager.prototype.update = function(displayable, prevDisplayable) { var clipGroup = this._getClipPathGroup(displayable, prevDisplayable); return clipGroup && (this.markDomUsed(clipGroup), this.updateDom(clipGroup, displayable.__clipPaths)), clipGroup; }, ClippathManager.prototype.updateDom = function(parentEl, clipPaths) { if (clipPaths && clipPaths.length > 0) { var defs = this.getDefs(!0), clipPath = clipPaths[0], clipPathEl = void 0, id = void 0; clipPath._dom ? (id = clipPath._dom.getAttribute('id'), clipPathEl = clipPath._dom, defs.contains(clipPathEl) || defs.appendChild(clipPathEl)) : (id = 'zr' + this._zrId + '-clip-' + this.nextId, ++this.nextId, (clipPathEl = this.createElement('clipPath')).setAttribute('id', id), defs.appendChild(clipPathEl), clipPath._dom = clipPathEl), this.getSvgProxy(clipPath).brush(clipPath); var pathEl = this.getSvgElement(clipPath); clipPathEl.innerHTML = '', clipPathEl.appendChild(pathEl), parentEl.setAttribute('clip-path', 'url(#' + id + ')'), clipPaths.length > 1 && this.updateDom(clipPathEl, clipPaths.slice(1)); } else parentEl && parentEl.setAttribute('clip-path', 'none'); }, ClippathManager.prototype.markUsed = function(displayable) { var _this = this; displayable.__clipPaths && each(displayable.__clipPaths, function(clipPath) { clipPath._dom && _super.prototype.markDomUsed.call(_this, clipPath._dom); }); }, ClippathManager.prototype.removeUnused = function() { _super.prototype.removeUnused.call(this); var newRefGroupsMap = {}; for(var key in this._refGroups){ var group = this._refGroups[key]; this.isDomUnused(group) ? group.parentNode && group.parentNode.removeChild(group) : newRefGroupsMap[key] = group; } this._refGroups = newRefGroupsMap; }, ClippathManager; }(Definable), ShadowManager = function(_super) { function ShadowManager(zrId, svgRoot) { var _this = _super.call(this, zrId, svgRoot, [ 'filter' ], '__filter_in_use__', '_shadowDom') || this; return _this._shadowDomMap = {}, _this._shadowDomPool = [], _this; } return __extends(ShadowManager, _super), ShadowManager.prototype._getFromPool = function() { var shadowDom = this._shadowDomPool.pop(); if (!shadowDom) { (shadowDom = this.createElement('filter')).setAttribute('id', 'zr' + this._zrId + '-shadow-' + this.nextId++); var domChild = this.createElement('feDropShadow'); shadowDom.appendChild(domChild), this.addDom(shadowDom); } return shadowDom; }, ShadowManager.prototype.update = function(svgElement, displayable) { var style; if ((style = displayable.style) && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY)) { var style1, globalScale, shadowKey = (style1 = displayable.style, globalScale = displayable.getGlobalScale(), [ style1.shadowColor, (style1.shadowBlur || 0).toFixed(2), (style1.shadowOffsetX || 0).toFixed(2), (style1.shadowOffsetY || 0).toFixed(2), globalScale[0], globalScale[1] ].join(',')), shadowDom = displayable._shadowDom = this._shadowDomMap[shadowKey]; shadowDom || (shadowDom = this._getFromPool(), this._shadowDomMap[shadowKey] = shadowDom), this.updateDom(svgElement, displayable, shadowDom); } else this.remove(svgElement, displayable); }, ShadowManager.prototype.remove = function(svgElement, displayable) { null != displayable._shadowDom && (displayable._shadowDom = null, svgElement.style.filter = ''); }, ShadowManager.prototype.updateDom = function(svgElement, displayable, shadowDom) { var domChild = shadowDom.children[0], style = displayable.style, globalScale = displayable.getGlobalScale(), scaleX = globalScale[0], scaleY = globalScale[1]; if (scaleX && scaleY) { var offsetX = style.shadowOffsetX || 0, offsetY = style.shadowOffsetY || 0, blur = style.shadowBlur, color = style.shadowColor; domChild.setAttribute('dx', offsetX / scaleX + ''), domChild.setAttribute('dy', offsetY / scaleY + ''), domChild.setAttribute('flood-color', color), domChild.setAttribute('stdDeviation', blur / 2 / scaleX + ' ' + blur / 2 / scaleY), shadowDom.setAttribute('x', '-100%'), shadowDom.setAttribute('y', '-100%'), shadowDom.setAttribute('width', '300%'), shadowDom.setAttribute('height', '300%'), displayable._shadowDom = shadowDom; var id = shadowDom.getAttribute('id'); svgElement.style.filter = 'url(#' + id + ')'; } }, ShadowManager.prototype.removeUnused = function() { if (this.getDefs(!1)) { var shadowDomsPool = this._shadowDomPool; for(var key in this._shadowDomMap){ var dom = this._shadowDomMap[key]; shadowDomsPool.push(dom); } this._shadowDomMap = {}; } }, ShadowManager; }(Definable); function parseInt10(val) { return parseInt(val, 10); } function getSvgProxy(el) { return el instanceof Path ? svgPath : el instanceof ZRImage ? svgImage : el instanceof TSpan ? svgText : svgPath; } function checkParentAvailable(parent, child) { return child && parent && child.parentNode !== parent; } function insertAfter(parent, child, prevSibling) { if (checkParentAvailable(parent, child) && prevSibling) { var nextSibling = prevSibling.nextSibling; nextSibling ? parent.insertBefore(child, nextSibling) : parent.appendChild(child); } } function prepend(parent, child) { if (checkParentAvailable(parent, child)) { var firstChild = parent.firstChild; firstChild ? parent.insertBefore(child, firstChild) : parent.appendChild(child); } } function getSvgElement(displayable) { return displayable.__svgEl; } var SVGPainter = function() { function SVGPainter(root, storage, opts, zrId) { this.type = 'svg', this.refreshHover = createMethodNotSupport('refreshHover'), this.pathToImage = createMethodNotSupport('pathToImage'), this.configLayer = createMethodNotSupport('configLayer'), this.root = root, this.storage = storage, this._opts = opts = extend({}, opts || {}); var svgDom = createElement('svg'); svgDom.setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns', 'http://www.w3.org/2000/svg'), svgDom.setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:xlink', 'http://www.w3.org/1999/xlink'), svgDom.setAttribute('version', '1.1'), svgDom.setAttribute('baseProfile', 'full'), svgDom.style.cssText = 'user-select:none;position:absolute;left:0;top:0;'; var bgRoot = createElement('g'); svgDom.appendChild(bgRoot); var svgRoot = createElement('g'); svgDom.appendChild(svgRoot), this._gradientManager = new GradientManager(zrId, svgRoot), this._patternManager = new PatternManager(zrId, svgRoot), this._clipPathManager = new ClippathManager(zrId, svgRoot), this._shadowManager = new ShadowManager(zrId, svgRoot); var viewport = document.createElement('div'); viewport.style.cssText = 'overflow:hidden;position:relative', this._svgDom = svgDom, this._svgRoot = svgRoot, this._backgroundRoot = bgRoot, this._viewport = viewport, root.appendChild(viewport), viewport.appendChild(svgDom), this.resize(opts.width, opts.height), this._visibleList = []; } return SVGPainter.prototype.getType = function() { return 'svg'; }, SVGPainter.prototype.getViewportRoot = function() { return this._viewport; }, SVGPainter.prototype.getSvgDom = function() { return this._svgDom; }, SVGPainter.prototype.getSvgRoot = function() { return this._svgRoot; }, SVGPainter.prototype.getViewportRootOffset = function() { var viewportRoot = this.getViewportRoot(); if (viewportRoot) return { offsetLeft: viewportRoot.offsetLeft || 0, offsetTop: viewportRoot.offsetTop || 0 }; }, SVGPainter.prototype.refresh = function() { var list = this.storage.getDisplayList(!0); this._paintList(list); }, SVGPainter.prototype.setBackgroundColor = function(backgroundColor) { this._backgroundRoot && this._backgroundNode && this._backgroundRoot.removeChild(this._backgroundNode); var bgNode = createElement('rect'); bgNode.setAttribute('width', this.getWidth()), bgNode.setAttribute('height', this.getHeight()), bgNode.setAttribute('x', 0), bgNode.setAttribute('y', 0), bgNode.setAttribute('id', 0), bgNode.style.fill = backgroundColor, this._backgroundRoot.appendChild(bgNode), this._backgroundNode = bgNode; }, SVGPainter.prototype.createSVGElement = function(tag) { return createElement(tag); }, SVGPainter.prototype.paintOne = function(el) { var svgProxy = getSvgProxy(el); return svgProxy && svgProxy.brush(el), getSvgElement(el); }, SVGPainter.prototype._paintList = function(list) { var prevSvgElement, topPrevSvgElement, prevDisplayable, currentClipGroup, gradientManager = this._gradientManager, patternManager = this._patternManager, clipPathManager = this._clipPathManager, shadowManager = this._shadowManager; gradientManager.markAllUnused(), patternManager.markAllUnused(), clipPathManager.markAllUnused(), shadowManager.markAllUnused(); for(var svgRoot = this._svgRoot, visibleList = this._visibleList, listLen = list.length, newVisibleList = [], i = 0; i < listLen; i++){ var displayable = list[i], svgProxy = getSvgProxy(displayable), svgElement = getSvgElement(displayable); !displayable.invisible && ((displayable.__dirty || !svgElement) && (svgProxy && svgProxy.brush(displayable), (svgElement = getSvgElement(displayable)) && displayable.style && (gradientManager.update(displayable.style.fill), gradientManager.update(displayable.style.stroke), patternManager.update(displayable.style.fill), patternManager.update(displayable.style.stroke), shadowManager.update(svgElement, displayable)), displayable.__dirty = 0), svgElement && newVisibleList.push(displayable)); } for(var diff = function(oldArr, newArr, equals) { equals || (equals = function(a, b) { return a === b; }), oldArr = oldArr.slice(); var newLen = (newArr = newArr.slice()).length, oldLen = oldArr.length, editLength = 1, maxEditLength = newLen + oldLen, bestPath = [ { newPos: -1, components: [] } ], oldPos = extractCommon(bestPath[0], newArr, oldArr, 0, equals); if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) { for(var indices = [], i = 0; i < newArr.length; i++)indices.push(i); return [ { indices: indices, count: newArr.length, added: !1, removed: !1 } ]; } for(; editLength <= maxEditLength;){ var ret = function() { for(var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2){ var basePath, addPath = bestPath[diagonalPath - 1], removePath = bestPath[diagonalPath + 1], oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; addPath && (bestPath[diagonalPath - 1] = void 0); var canAdd = addPath && addPath.newPos + 1 < newLen, canRemove = removePath && 0 <= oldPos && oldPos < oldLen; if (!canAdd && !canRemove) { bestPath[diagonalPath] = void 0; continue; } if (!canAdd || canRemove && addPath.newPos < removePath.newPos ? pushComponent((basePath = { newPos: removePath.newPos, components: removePath.components.slice(0) }).components, !1, !0) : (basePath = addPath, basePath.newPos++, pushComponent(basePath.components, !0, !1)), oldPos = extractCommon(basePath, newArr, oldArr, diagonalPath, equals), basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) return function(components) { for(var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0; componentPos < componentLen; componentPos++){ var component = components[componentPos]; if (component.removed) { for(var i = oldPos; i < oldPos + component.count; i++)component.indices.push(i); oldPos += component.count; } else { for(var indices = [], i = newPos; i < newPos + component.count; i++)indices.push(i); component.indices = indices, newPos += component.count, component.added || (oldPos += component.count); } } return components; }(basePath.components); bestPath[diagonalPath] = basePath; } editLength++; }(); if (ret) return ret; } }(visibleList, newVisibleList, void 0), i = 0; i < diff.length; i++){ var item = diff[i]; if (item.removed) for(var k = 0; k < item.count; k++){ var child, child1, displayable = visibleList[item.indices[k]], svgElement = getSvgElement(displayable); hasClipPath(displayable) ? (child = svgElement) && child.parentNode && child.parentNode.removeChild(child) : (child1 = svgElement) && svgRoot && child1.parentNode === svgRoot && svgRoot.removeChild(child1); } } for(var i = 0; i < diff.length; i++){ var item = diff[i]; if (!item.removed) for(var k = 0; k < item.count; k++){ var displayable = newVisibleList[item.indices[k]], clipGroup = clipPathManager.update(displayable, prevDisplayable); clipGroup !== currentClipGroup && (prevSvgElement = topPrevSvgElement, clipGroup && (prevSvgElement ? insertAfter(svgRoot, clipGroup, prevSvgElement) : prepend(svgRoot, clipGroup), topPrevSvgElement = clipGroup, prevSvgElement = null), currentClipGroup = clipGroup); var svgElement = getSvgElement(displayable); prevSvgElement ? insertAfter(currentClipGroup || svgRoot, svgElement, prevSvgElement) : prepend(currentClipGroup || svgRoot, svgElement), prevSvgElement = svgElement || prevSvgElement, currentClipGroup || (topPrevSvgElement = prevSvgElement), gradientManager.markUsed(displayable), gradientManager.addWithoutUpdate(svgElement, displayable), patternManager.markUsed(displayable), patternManager.addWithoutUpdate(svgElement, displayable), clipPathManager.markUsed(displayable), prevDisplayable = displayable; } } gradientManager.removeUnused(), patternManager.removeUnused(), clipPathManager.removeUnused(), shadowManager.removeUnused(), this._visibleList = newVisibleList; }, SVGPainter.prototype.resize = function(width, height) { var viewport = this._viewport; viewport.style.display = 'none'; var opts = this._opts; if (null != width && (opts.width = width), null != height && (opts.height = height), width = this._getSize(0), height = this._getSize(1), viewport.style.display = '', this._width !== width || this._height !== height) { this._width = width, this._height = height; var viewportStyle = viewport.style; viewportStyle.width = width + 'px', viewportStyle.height = height + 'px'; var svgRoot = this._svgDom; svgRoot.setAttribute('width', width + ''), svgRoot.setAttribute('height', height + ''); } this._backgroundNode && (this._backgroundNode.setAttribute('width', width), this._backgroundNode.setAttribute('height', height)); }, SVGPainter.prototype.getWidth = function() { return this._width; }, SVGPainter.prototype.getHeight = function() { return this._height; }, SVGPainter.prototype._getSize = function(whIdx) { var opts = this._opts, wh = [ 'width', 'height' ][whIdx], cwh = [ 'clientWidth', 'clientHeight' ][whIdx], plt = [ 'paddingLeft', 'paddingTop' ][whIdx], prb = [ 'paddingRight', 'paddingBottom' ][whIdx]; if (null != opts[wh] && 'auto' !== opts[wh]) return parseFloat(opts[wh]); var root = this.root, stl = document.defaultView.getComputedStyle(root); return (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh])) - (parseInt10(stl[plt]) || 0) - (parseInt10(stl[prb]) || 0) | 0; }, SVGPainter.prototype.dispose = function() { this.root.innerHTML = '', this._svgRoot = this._backgroundRoot = this._svgDom = this._backgroundNode = this._viewport = this.storage = null; }, SVGPainter.prototype.clear = function() { var viewportNode = this._viewport; viewportNode && viewportNode.parentNode && viewportNode.parentNode.removeChild(viewportNode); }, SVGPainter.prototype.toDataURL = function() { this.refresh(); var svgDom = this._svgDom; return 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent((svgDom.outerHTML || (svgDom.parentNode && svgDom.parentNode).innerHTML).replace(/>\n\r<')); }, SVGPainter; }(); function createMethodNotSupport(method) { return function() { logError('In SVG mode painter not support method "' + method + '"'); }; } function returnFalse() { return !1; } function createDom(id, painter, dpr) { var newDom = createCanvas(), width = painter.getWidth(), height = painter.getHeight(), newDomStyle = newDom.style; return newDomStyle && (newDomStyle.position = 'absolute', newDomStyle.left = '0', newDomStyle.top = '0', newDomStyle.width = width + 'px', newDomStyle.height = height + 'px', newDom.setAttribute('data-zr-dom-id', id)), newDom.width = width * dpr, newDom.height = height * dpr, newDom; } var Layer = function(_super) { function Layer(id, painter, dpr) { var dom, _this = _super.call(this) || this; _this.motionBlur = !1, _this.lastFrameAlpha = 0.7, _this.dpr = 1, _this.virtual = !1, _this.config = {}, _this.incremental = !1, _this.zlevel = 0, _this.maxRepaintRectCount = 5, _this.__dirty = !0, _this.__firstTimePaint = !0, _this.__used = !1, _this.__drawIndex = 0, _this.__startIndex = 0, _this.__endIndex = 0, _this.__prevStartIndex = null, _this.__prevEndIndex = null, dpr = dpr || devicePixelRatio, 'string' == typeof id ? dom = createDom(id, painter, dpr) : isObject(id) && (id = (dom = id).id), _this.id = id, _this.dom = dom; var domStyle = dom.style; return domStyle && (dom.onselectstart = returnFalse, domStyle.webkitUserSelect = 'none', domStyle.userSelect = 'none', domStyle.webkitTapHighlightColor = 'rgba(0,0,0,0)', domStyle['-webkit-touch-callout'] = 'none', domStyle.padding = '0', domStyle.margin = '0', domStyle.borderWidth = '0'), _this.domBack = null, _this.ctxBack = null, _this.painter = painter, _this.config = null, _this.dpr = dpr, _this; } return __extends(Layer, _super), Layer.prototype.getElementCount = function() { return this.__endIndex - this.__startIndex; }, Layer.prototype.afterBrush = function() { this.__prevStartIndex = this.__startIndex, this.__prevEndIndex = this.__endIndex; }, Layer.prototype.initContext = function() { this.ctx = this.dom.getContext('2d'), this.ctx.dpr = this.dpr; }, Layer.prototype.setUnpainted = function() { this.__firstTimePaint = !0; }, Layer.prototype.createBackBuffer = function() { var dpr = this.dpr; this.domBack = createDom('back-' + this.id, this.painter, dpr), this.ctxBack = this.domBack.getContext('2d'), 1 !== dpr && this.ctxBack.scale(dpr, dpr); }, Layer.prototype.createRepaintRects = function(displayList, prevList, viewWidth, viewHeight) { if (this.__firstTimePaint) return this.__firstTimePaint = !1, null; var hasIntersections, mergedRepaintRects = [], maxRepaintRectCount = this.maxRepaintRectCount, full = !1, pendingRect = new BoundingRect(0, 0, 0, 0); function addRectToMergePool(rect) { if (!(!rect.isFinite() || rect.isZero())) { if (0 === mergedRepaintRects.length) { var boundingRect = new BoundingRect(0, 0, 0, 0); boundingRect.copy(rect), mergedRepaintRects.push(boundingRect); } else { for(var isMerged = !1, minDeltaArea = 1 / 0, bestRectToMergeIdx = 0, i = 0; i < mergedRepaintRects.length; ++i){ var mergedRect = mergedRepaintRects[i]; if (mergedRect.intersect(rect)) { var pendingRect_1 = new BoundingRect(0, 0, 0, 0); pendingRect_1.copy(mergedRect), pendingRect_1.union(rect), mergedRepaintRects[i] = pendingRect_1, isMerged = !0; break; } if (full) { pendingRect.copy(rect), pendingRect.union(mergedRect); var aArea = rect.width * rect.height, bArea = mergedRect.width * mergedRect.height, deltaArea = pendingRect.width * pendingRect.height - aArea - bArea; deltaArea < minDeltaArea && (minDeltaArea = deltaArea, bestRectToMergeIdx = i); } } if (full && (mergedRepaintRects[bestRectToMergeIdx].union(rect), isMerged = !0), !isMerged) { var boundingRect = new BoundingRect(0, 0, 0, 0); boundingRect.copy(rect), mergedRepaintRects.push(boundingRect); } full || (full = mergedRepaintRects.length >= maxRepaintRectCount); } } } for(var i = this.__startIndex; i < this.__endIndex; ++i){ var el = displayList[i]; if (el) { var shouldPaint = el.shouldBePainted(viewWidth, viewHeight, !0, !0), prevRect = el.__isRendered && (el.__dirty & Element.REDARAW_BIT || !shouldPaint) ? el.getPrevPaintRect() : null; prevRect && addRectToMergePool(prevRect); var curRect = shouldPaint && (el.__dirty & Element.REDARAW_BIT || !el.__isRendered) ? el.getPaintRect() : null; curRect && addRectToMergePool(curRect); } } for(var i = this.__prevStartIndex; i < this.__prevEndIndex; ++i){ var el = prevList[i], shouldPaint = el.shouldBePainted(viewWidth, viewHeight, !0, !0); if (el && (!shouldPaint || !el.__zr) && el.__isRendered) { var prevRect = el.getPrevPaintRect(); prevRect && addRectToMergePool(prevRect); } } do { hasIntersections = !1; for(var i = 0; i < mergedRepaintRects.length;){ if (mergedRepaintRects[i].isZero()) { mergedRepaintRects.splice(i, 1); continue; } for(var j = i + 1; j < mergedRepaintRects.length;)mergedRepaintRects[i].intersect(mergedRepaintRects[j]) ? (hasIntersections = !0, mergedRepaintRects[i].union(mergedRepaintRects[j]), mergedRepaintRects.splice(j, 1)) : j++; i++; } }while (hasIntersections) return this._paintRects = mergedRepaintRects, mergedRepaintRects; }, Layer.prototype.debugGetPaintRects = function() { return (this._paintRects || []).slice(); }, Layer.prototype.resize = function(width, height) { var dpr = this.dpr, dom = this.dom, domStyle = dom.style, domBack = this.domBack; domStyle && (domStyle.width = width + 'px', domStyle.height = height + 'px'), dom.width = width * dpr, dom.height = height * dpr, domBack && (domBack.width = width * dpr, domBack.height = height * dpr, 1 !== dpr && this.ctxBack.scale(dpr, dpr)); }, Layer.prototype.clear = function(clearAll, clearColor, repaintRects) { var dom = this.dom, ctx = this.ctx, width = dom.width, height = dom.height; clearColor = clearColor || this.clearColor; var haveMotionBLur = this.motionBlur && !clearAll, lastFrameAlpha = this.lastFrameAlpha, dpr = this.dpr, self1 = this; haveMotionBLur && (this.domBack || this.createBackBuffer(), this.ctxBack.globalCompositeOperation = 'copy', this.ctxBack.drawImage(dom, 0, 0, width / dpr, height / dpr)); var domBack = this.domBack; function doClear(x, y, width, height) { if (ctx.clearRect(x, y, width, height), clearColor && 'transparent' !== clearColor) { var clearColorGradientOrPattern = void 0; isGradientObject(clearColor) ? (clearColorGradientOrPattern = clearColor.__canvasGradient || getCanvasGradient(ctx, clearColor, { x: 0, y: 0, width: width, height: height }), clearColor.__canvasGradient = clearColorGradientOrPattern) : isPatternObject(clearColor) && (clearColorGradientOrPattern = createCanvasPattern(ctx, clearColor, { dirty: function() { self1.setUnpainted(), self1.__painter.refresh(); } })), ctx.save(), ctx.fillStyle = clearColorGradientOrPattern || clearColor, ctx.fillRect(x, y, width, height), ctx.restore(); } haveMotionBLur && (ctx.save(), ctx.globalAlpha = lastFrameAlpha, ctx.drawImage(domBack, x, y, width, height), ctx.restore()); } !repaintRects || haveMotionBLur ? doClear(0, 0, width, height) : repaintRects.length && each(repaintRects, function(rect) { doClear(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr); }); }, Layer; }(Eventful); function parseInt10$1(val) { return parseInt(val, 10); } var CanvasPainter = function() { function CanvasPainter(root, storage, opts, id) { this.type = 'canvas', this._zlevelList = [], this._prevDisplayList = [], this._layers = {}, this._layerConfig = {}, this._needsManuallyCompositing = !1, this.type = 'canvas'; var singleCanvas = !root.nodeName || 'CANVAS' === root.nodeName.toUpperCase(); this._opts = opts = extend({}, opts || {}), this.dpr = opts.devicePixelRatio || devicePixelRatio, this._singleCanvas = singleCanvas, this.root = root; var rootStyle = root.style; rootStyle && (rootStyle.webkitTapHighlightColor = 'transparent', rootStyle.webkitUserSelect = 'none', rootStyle.userSelect = 'none', rootStyle['-webkit-touch-callout'] = 'none', root.innerHTML = ''), this.storage = storage; var zlevelList = this._zlevelList; this._prevDisplayList = []; var layers = this._layers; if (singleCanvas) { var rootCanvas = root, width = rootCanvas.width, height = rootCanvas.height; null != opts.width && (width = opts.width), null != opts.height && (height = opts.height), this.dpr = opts.devicePixelRatio || 1, rootCanvas.width = width * this.dpr, rootCanvas.height = height * this.dpr, this._width = width, this._height = height; var mainLayer = new Layer(rootCanvas, this, this.dpr); mainLayer.__builtin__ = !0, mainLayer.initContext(), layers[314159] = mainLayer, mainLayer.zlevel = 314159, zlevelList.push(314159), this._domRoot = root; } else { this._width = this._getSize(0), this._height = this._getSize(1); var width1, height1, domRoot, domRoot1 = this._domRoot = (width1 = this._width, height1 = this._height, (domRoot = document.createElement('div')).style.cssText = [ 'position:relative', 'width:' + width1 + 'px', 'height:' + height1 + 'px', 'padding:0', 'margin:0', 'border-width:0' ].join(';') + ';', domRoot); root.appendChild(domRoot1); } } return CanvasPainter.prototype.getType = function() { return 'canvas'; }, CanvasPainter.prototype.isSingleCanvas = function() { return this._singleCanvas; }, CanvasPainter.prototype.getViewportRoot = function() { return this._domRoot; }, CanvasPainter.prototype.getViewportRootOffset = function() { var viewportRoot = this.getViewportRoot(); if (viewportRoot) return { offsetLeft: viewportRoot.offsetLeft || 0, offsetTop: viewportRoot.offsetTop || 0 }; }, CanvasPainter.prototype.refresh = function(paintAll) { var list = this.storage.getDisplayList(!0), prevList = this._prevDisplayList, zlevelList = this._zlevelList; this._redrawId = Math.random(), this._paintList(list, prevList, paintAll, this._redrawId); for(var i = 0; i < zlevelList.length; i++){ var z = zlevelList[i], layer = this._layers[z]; if (!layer.__builtin__ && layer.refresh) { var clearColor = 0 === i ? this._backgroundColor : null; layer.refresh(clearColor); } } return this._opts.useDirtyRect && (this._prevDisplayList = list.slice()), this; }, CanvasPainter.prototype.refreshHover = function() { this._paintHoverList(this.storage.getDisplayList(!1)); }, CanvasPainter.prototype._paintHoverList = function(list) { var ctx, len = list.length, hoverLayer = this._hoverlayer; if (hoverLayer && hoverLayer.clear(), len) { for(var scope = { inHover: !0, viewWidth: this._width, viewHeight: this._height }, i = 0; i < len; i++){ var el = list[i]; el.__inHover && (hoverLayer || (hoverLayer = this._hoverlayer = this.getLayer(1e5)), ctx || (ctx = hoverLayer.ctx).save(), brush(ctx, el, scope, i === len - 1)); } ctx && ctx.restore(); } }, CanvasPainter.prototype.getHoverLayer = function() { return this.getLayer(1e5); }, CanvasPainter.prototype.paintOne = function(ctx, el) { brushSingle(ctx, el); }, CanvasPainter.prototype._paintList = function(list, prevList, paintAll, redrawId) { if (this._redrawId === redrawId) { paintAll = paintAll || !1, this._updateLayerStatus(list); var _a = this._doPaintList(list, prevList, paintAll), finished = _a.finished, needsRefreshHover = _a.needsRefreshHover; if (this._needsManuallyCompositing && this._compositeManually(), needsRefreshHover && this._paintHoverList(list), finished) this.eachLayer(function(layer) { layer.afterBrush && layer.afterBrush(); }); else { var self_1 = this; requestAnimationFrame(function() { self_1._paintList(list, prevList, paintAll, redrawId); }); } } }, CanvasPainter.prototype._compositeManually = function() { var ctx = this.getLayer(314159).ctx, width = this._domRoot.width, height = this._domRoot.height; ctx.clearRect(0, 0, width, height), this.eachBuiltinLayer(function(layer) { layer.virtual && ctx.drawImage(layer.dom, 0, 0, width, height); }); }, CanvasPainter.prototype._doPaintList = function(list, prevList, paintAll) { for(var _this = this, layerList = [], useDirtyRect = this._opts.useDirtyRect, zi = 0; zi < this._zlevelList.length; zi++){ var zlevel = this._zlevelList[zi], layer = this._layers[zlevel]; layer.__builtin__ && layer !== this._hoverlayer && (layer.__dirty || paintAll) && layerList.push(layer); } for(var finished = !0, needsRefreshHover = !1, this_1 = this, k = 0; k < layerList.length; k++)!function(k) { var i, layer = layerList[k], ctx = layer.ctx, repaintRects = useDirtyRect && layer.createRepaintRects(list, prevList, this_1._width, this_1._height); ctx.save(); var start = paintAll ? layer.__startIndex : layer.__drawIndex, useTimer = !paintAll && layer.incremental && Date.now, startTime = useTimer && Date.now(), clearColor = layer.zlevel === this_1._zlevelList[0] ? this_1._backgroundColor : null; if (layer.__startIndex === layer.__endIndex) layer.clear(!1, clearColor, repaintRects); else if (start === layer.__startIndex) { var firstEl = list[start]; firstEl.incremental && firstEl.notClear && !paintAll || layer.clear(!1, clearColor, repaintRects); } -1 === start && (console.error('For some unknown reason. drawIndex is -1'), start = layer.__startIndex); var repaint = function(repaintRect) { var scope = { inHover: !1, allClipped: !1, prevEl: null, viewWidth: _this._width, viewHeight: _this._height }; for(i = start; i < layer.__endIndex; i++){ var el = list[i]; if (el.__inHover && (needsRefreshHover = !0), _this._doPaintEl(el, layer, useDirtyRect, repaintRect, scope, i === layer.__endIndex - 1), useTimer && Date.now() - startTime > 15) break; } scope.prevElClipPaths && ctx.restore(); }; if (repaintRects) { if (0 === repaintRects.length) i = layer.__endIndex; else for(var dpr = this_1.dpr, r = 0; r < repaintRects.length; ++r){ var rect = repaintRects[r]; ctx.save(), ctx.beginPath(), ctx.rect(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr), ctx.clip(), repaint(rect), ctx.restore(); } } else ctx.save(), repaint(), ctx.restore(); layer.__drawIndex = i, layer.__drawIndex < layer.__endIndex && (finished = !1); }(k); return env1.wxa && each(this._layers, function(layer) { layer && layer.ctx && layer.ctx.draw && layer.ctx.draw(); }), { finished: finished, needsRefreshHover: needsRefreshHover }; }, CanvasPainter.prototype._doPaintEl = function(el, currentLayer, useDirtyRect, repaintRect, scope, isLast) { var ctx = currentLayer.ctx; if (useDirtyRect) { var paintRect = el.getPaintRect(); (!repaintRect || paintRect && paintRect.intersect(repaintRect)) && (brush(ctx, el, scope, isLast), el.setPrevPaintRect(paintRect)); } else brush(ctx, el, scope, isLast); }, CanvasPainter.prototype.getLayer = function(zlevel, virtual) { this._singleCanvas && !this._needsManuallyCompositing && (zlevel = 314159); var layer = this._layers[zlevel]; return layer || ((layer = new Layer('zr_' + zlevel, this, this.dpr)).zlevel = zlevel, layer.__builtin__ = !0, this._layerConfig[zlevel] ? merge(layer, this._layerConfig[zlevel], !0) : this._layerConfig[zlevel - 0.01] && merge(layer, this._layerConfig[zlevel - 0.01], !0), virtual && (layer.virtual = virtual), this.insertLayer(zlevel, layer), layer.initContext()), layer; }, CanvasPainter.prototype.insertLayer = function(zlevel, layer) { var layersMap = this._layers, zlevelList = this._zlevelList, len = zlevelList.length, domRoot = this._domRoot, prevLayer = null, i = -1; if (layersMap[zlevel]) { logError('ZLevel ' + zlevel + ' has been used already'); return; } if (!(layer && (layer.__builtin__ || 'function' == typeof layer.resize && 'function' == typeof layer.refresh))) { logError('Layer of zlevel ' + zlevel + ' is not valid'); return; } if (len > 0 && zlevel > zlevelList[0]) { for(i = 0; i < len - 1 && (!(zlevelList[i] < zlevel) || !(zlevelList[i + 1] > zlevel)); i++); prevLayer = layersMap[zlevelList[i]]; } if (zlevelList.splice(i + 1, 0, zlevel), layersMap[zlevel] = layer, !layer.virtual) { if (prevLayer) { var prevDom = prevLayer.dom; prevDom.nextSibling ? domRoot.insertBefore(layer.dom, prevDom.nextSibling) : domRoot.appendChild(layer.dom); } else domRoot.firstChild ? domRoot.insertBefore(layer.dom, domRoot.firstChild) : domRoot.appendChild(layer.dom); } layer.__painter = this; }, CanvasPainter.prototype.eachLayer = function(cb, context) { for(var zlevelList = this._zlevelList, i = 0; i < zlevelList.length; i++){ var z = zlevelList[i]; cb.call(context, this._layers[z], z); } }, CanvasPainter.prototype.eachBuiltinLayer = function(cb, context) { for(var zlevelList = this._zlevelList, i = 0; i < zlevelList.length; i++){ var z = zlevelList[i], layer = this._layers[z]; layer.__builtin__ && cb.call(context, layer, z); } }, CanvasPainter.prototype.eachOtherLayer = function(cb, context) { for(var zlevelList = this._zlevelList, i = 0; i < zlevelList.length; i++){ var z = zlevelList[i], layer = this._layers[z]; layer.__builtin__ || cb.call(context, layer, z); } }, CanvasPainter.prototype.getLayers = function() { return this._layers; }, CanvasPainter.prototype._updateLayerStatus = function(list) { function updatePrevLayer(idx) { prevLayer && (prevLayer.__endIndex !== idx && (prevLayer.__dirty = !0), prevLayer.__endIndex = idx); } if (this.eachBuiltinLayer(function(layer, z) { layer.__dirty = layer.__used = !1; }), this._singleCanvas) for(var prevZlevel, i, i_1 = 1; i_1 < list.length; i_1++){ var el = list[i_1]; if (el.zlevel !== list[i_1 - 1].zlevel || el.incremental) { this._needsManuallyCompositing = !0; break; } } var prevLayer = null, incrementalLayerCount = 0; for(i = 0; i < list.length; i++){ var el = list[i], zlevel = el.zlevel, layer = void 0; prevZlevel !== zlevel && (prevZlevel = zlevel, incrementalLayerCount = 0), el.incremental ? ((layer = this.getLayer(zlevel + 0.001, this._needsManuallyCompositing)).incremental = !0, incrementalLayerCount = 1) : layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? 0.01 : 0), this._needsManuallyCompositing), layer.__builtin__ || logError('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id), layer !== prevLayer && (layer.__used = !0, layer.__startIndex !== i && (layer.__dirty = !0), layer.__startIndex = i, layer.incremental ? layer.__drawIndex = -1 : layer.__drawIndex = i, updatePrevLayer(i), prevLayer = layer), el.__dirty & Element.REDARAW_BIT && !el.__inHover && (layer.__dirty = !0, layer.incremental && layer.__drawIndex < 0 && (layer.__drawIndex = i)); } updatePrevLayer(i), this.eachBuiltinLayer(function(layer, z) { !layer.__used && layer.getElementCount() > 0 && (layer.__dirty = !0, layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0), layer.__dirty && layer.__drawIndex < 0 && (layer.__drawIndex = layer.__startIndex); }); }, CanvasPainter.prototype.clear = function() { return this.eachBuiltinLayer(this._clearLayer), this; }, CanvasPainter.prototype._clearLayer = function(layer) { layer.clear(); }, CanvasPainter.prototype.setBackgroundColor = function(backgroundColor) { this._backgroundColor = backgroundColor, each(this._layers, function(layer) { layer.setUnpainted(); }); }, CanvasPainter.prototype.configLayer = function(zlevel, config) { if (config) { var layerConfig = this._layerConfig; layerConfig[zlevel] ? merge(layerConfig[zlevel], config, !0) : layerConfig[zlevel] = config; for(var i = 0; i < this._zlevelList.length; i++){ var _zlevel = this._zlevelList[i]; (_zlevel === zlevel || _zlevel === zlevel + 0.01) && merge(this._layers[_zlevel], layerConfig[zlevel], !0); } } }, CanvasPainter.prototype.delLayer = function(zlevel) { var layers = this._layers, zlevelList = this._zlevelList, layer = layers[zlevel]; layer && (layer.dom.parentNode.removeChild(layer.dom), delete layers[zlevel], zlevelList.splice(indexOf(zlevelList, zlevel), 1)); }, CanvasPainter.prototype.resize = function(width, height) { if (this._domRoot.style) { var domRoot = this._domRoot; domRoot.style.display = 'none'; var opts = this._opts; if (null != width && (opts.width = width), null != height && (opts.height = height), width = this._getSize(0), height = this._getSize(1), domRoot.style.display = '', this._width !== width || height !== this._height) { for(var id in domRoot.style.width = width + 'px', domRoot.style.height = height + 'px', this._layers)this._layers.hasOwnProperty(id) && this._layers[id].resize(width, height); this.refresh(!0); } this._width = width, this._height = height; } else { if (null == width || null == height) return; this._width = width, this._height = height, this.getLayer(314159).resize(width, height); } return this; }, CanvasPainter.prototype.clearLayer = function(zlevel) { var layer = this._layers[zlevel]; layer && layer.clear(); }, CanvasPainter.prototype.dispose = function() { this.root.innerHTML = '', this.root = this.storage = this._domRoot = this._layers = null; }, CanvasPainter.prototype.getRenderedCanvas = function(opts) { if (opts = opts || {}, this._singleCanvas && !this._compositeManually) return this._layers[314159].dom; var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr); imageLayer.initContext(), imageLayer.clear(!1, opts.backgroundColor || this._backgroundColor); var ctx = imageLayer.ctx; if (opts.pixelRatio <= this.dpr) { this.refresh(); var width_1 = imageLayer.dom.width, height_1 = imageLayer.dom.height; this.eachLayer(function(layer) { layer.__builtin__ ? ctx.drawImage(layer.dom, 0, 0, width_1, height_1) : layer.renderToCanvas && (ctx.save(), layer.renderToCanvas(ctx), ctx.restore()); }); } else for(var scope = { inHover: !1, viewWidth: this._width, viewHeight: this._height }, displayList = this.storage.getDisplayList(!0), i = 0, len = displayList.length; i < len; i++)brush(ctx, displayList[i], scope, i === len - 1); return imageLayer.dom; }, CanvasPainter.prototype.getWidth = function() { return this._width; }, CanvasPainter.prototype.getHeight = function() { return this._height; }, CanvasPainter.prototype._getSize = function(whIdx) { var opts = this._opts, wh = [ 'width', 'height' ][whIdx], cwh = [ 'clientWidth', 'clientHeight' ][whIdx], plt = [ 'paddingLeft', 'paddingTop' ][whIdx], prb = [ 'paddingRight', 'paddingBottom' ][whIdx]; if (null != opts[wh] && 'auto' !== opts[wh]) return parseFloat(opts[wh]); var root = this.root, stl = document.defaultView.getComputedStyle(root); return (root[cwh] || parseInt10$1(stl[wh]) || parseInt10$1(root.style[wh])) - (parseInt10$1(stl[plt]) || 0) - (parseInt10$1(stl[prb]) || 0) | 0; }, CanvasPainter.prototype.pathToImage = function(path, dpr) { dpr = dpr || this.dpr; var canvas = document.createElement('canvas'), ctx = canvas.getContext('2d'), rect = path.getBoundingRect(), style = path.style, shadowBlurSize = style.shadowBlur * dpr, shadowOffsetX = style.shadowOffsetX * dpr, shadowOffsetY = style.shadowOffsetY * dpr, lineWidth = path.hasStroke() ? style.lineWidth : 0, leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize), topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize), width = rect.width + leftMargin + Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize), height = rect.height + topMargin + Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize); canvas.width = width * dpr, canvas.height = height * dpr, ctx.scale(dpr, dpr), ctx.clearRect(0, 0, width, height), ctx.dpr = dpr; var pathTransform = { x: path.x, y: path.y, scaleX: path.scaleX, scaleY: path.scaleY, rotation: path.rotation, originX: path.originX, originY: path.originY }; path.x = leftMargin - rect.x, path.y = topMargin - rect.y, path.rotation = 0, path.scaleX = 1, path.scaleY = 1, path.updateTransform(), path && brush(ctx, path, { inHover: !1, viewWidth: this._width, viewHeight: this._height }, !0); var imgShape = new ZRImage({ style: { x: 0, y: 0, image: canvas } }); return extend(path, pathTransform), imgShape; }, CanvasPainter; }(), LineSeriesModel = function(_super) { function LineSeriesModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = LineSeriesModel.type, _this.hasSymbolVisual = !0, _this; } return __extends(LineSeriesModel, _super), LineSeriesModel.prototype.getInitialData = function(option) { var coordSys = option.coordinateSystem; if ('polar' !== coordSys && 'cartesian2d' !== coordSys) throw Error('Line not support coordinateSystem besides cartesian and polar'); return createListFromArray(this.getSource(), this, { useEncodeDefaulter: !0 }); }, LineSeriesModel.prototype.getLegendIcon = function(opt) { var group = new Group(), line = createSymbol('line', 0, opt.itemHeight / 2, opt.itemWidth, 0, opt.lineStyle.stroke, !1); group.add(line), line.setStyle(opt.lineStyle); var visualType = this.getData().getVisual('symbol'), symbolType = 'none' === visualType ? 'circle' : visualType, size = 0.8 * opt.itemHeight, symbol = createSymbol(symbolType, (opt.itemWidth - size) / 2, (opt.itemHeight - size) / 2, size, size, opt.itemStyle.fill, opt.symbolKeepAspect); return group.add(symbol), symbol.setStyle(opt.itemStyle), symbolType.indexOf('empty') > -1 && (symbol.style.stroke = symbol.style.fill, symbol.style.fill = '#fff', symbol.style.lineWidth = 2), group; }, LineSeriesModel.type = 'series.line', LineSeriesModel.dependencies = [ 'grid', 'polar' ], LineSeriesModel.defaultOption = { zlevel: 0, z: 3, coordinateSystem: 'cartesian2d', legendHoverLink: !0, clip: !0, label: { position: 'top' }, endLabel: { show: !1, valueAnimation: !0, distance: 8 }, lineStyle: { width: 2, type: 'solid' }, emphasis: { scale: !0, lineStyle: { width: 'bolder' } }, step: !1, smooth: !1, smoothMonotone: null, symbol: 'emptyCircle', symbolSize: 4, symbolRotate: null, showSymbol: !0, showAllSymbol: 'auto', connectNulls: !1, sampling: 'none', animationEasing: 'linear', progressive: 0, hoverLayerThreshold: 1 / 0 }, LineSeriesModel; }(SeriesModel); function getDefaultLabel(data, dataIndex) { var labelDims = data.mapDimensionsAll('defaultedLabel'), len = labelDims.length; if (1 === len) { var rawVal = retrieveRawValue(data, dataIndex, labelDims[0]); return null != rawVal ? rawVal + '' : null; } if (len) { for(var vals = [], i = 0; i < labelDims.length; i++)vals.push(retrieveRawValue(data, dataIndex, labelDims[i])); return vals.join(' '); } } function getDefaultInterpolatedLabel(data, interpolatedValue) { var labelDims = data.mapDimensionsAll('defaultedLabel'); if (!isArray(interpolatedValue)) return interpolatedValue + ''; for(var vals = [], i = 0; i < labelDims.length; i++){ var dimInfo = data.getDimensionInfo(labelDims[i]); dimInfo && vals.push(interpolatedValue[dimInfo.index]); } return vals.join(' '); } var Symbol = function(_super) { function Symbol(data, idx, seriesScope, opts) { var _this = _super.call(this) || this; return _this.updateData(data, idx, seriesScope, opts), _this; } return __extends(Symbol, _super), Symbol.prototype._createSymbol = function(symbolType, data, idx, symbolSize, keepAspect) { this.removeAll(); var symbolPath = createSymbol(symbolType, -1, -1, 2, 2, null, keepAspect); symbolPath.attr({ z2: 100, culling: !0, scaleX: symbolSize[0] / 2, scaleY: symbolSize[1] / 2 }), symbolPath.drift = driftSymbol, this._symbolType = symbolType, this.add(symbolPath); }, Symbol.prototype.stopSymbolAnimation = function(toLastFrame) { this.childAt(0).stopAnimation(null, toLastFrame); }, Symbol.prototype.getSymbolPath = function() { return this.childAt(0); }, Symbol.prototype.highlight = function() { enterEmphasis(this.childAt(0)); }, Symbol.prototype.downplay = function() { leaveEmphasis(this.childAt(0)); }, Symbol.prototype.setZ = function(zlevel, z) { var symbolPath = this.childAt(0); symbolPath.zlevel = zlevel, symbolPath.z = z; }, Symbol.prototype.setDraggable = function(draggable) { var symbolPath = this.childAt(0); symbolPath.draggable = draggable, symbolPath.cursor = draggable ? 'move' : symbolPath.cursor; }, Symbol.prototype.updateData = function(data, idx, seriesScope, opts) { this.silent = !1; var symbolType = data.getItemVisual(idx, 'symbol') || 'circle', seriesModel = data.hostModel, symbolSize = Symbol.getSymbolSize(data, idx), isInit = symbolType !== this._symbolType, disableAnimation = opts && opts.disableAnimation; if (isInit) { var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect'); this._createSymbol(symbolType, data, idx, symbolSize, keepAspect); } else { var symbolPath = this.childAt(0); symbolPath.silent = !1; var target = { scaleX: symbolSize[0] / 2, scaleY: symbolSize[1] / 2 }; disableAnimation ? symbolPath.attr(target) : updateProps(symbolPath, target, seriesModel, idx); } if (this._updateCommon(data, idx, symbolSize, seriesScope, opts), isInit) { var symbolPath = this.childAt(0); if (!disableAnimation) { var target = { scaleX: this._sizeX, scaleY: this._sizeY, style: { opacity: symbolPath.style.opacity } }; symbolPath.scaleX = symbolPath.scaleY = 0, symbolPath.style.opacity = 0, initProps(symbolPath, target, seriesModel, idx); } } disableAnimation && this.childAt(0).stopAnimation('remove'), this._seriesModel = seriesModel; }, Symbol.prototype._updateCommon = function(data, idx, symbolSize, seriesScope, opts) { var emphasisItemStyle, blurItemStyle, selectItemStyle, focus, blurScope, labelStatesModels, hoverScale, cursorStyle, symbolPath = this.childAt(0), seriesModel = data.hostModel; if (seriesScope && (emphasisItemStyle = seriesScope.emphasisItemStyle, blurItemStyle = seriesScope.blurItemStyle, selectItemStyle = seriesScope.selectItemStyle, focus = seriesScope.focus, blurScope = seriesScope.blurScope, labelStatesModels = seriesScope.labelStatesModels, hoverScale = seriesScope.hoverScale, cursorStyle = seriesScope.cursorStyle), !seriesScope || data.hasItemOption) { var itemModel = seriesScope && seriesScope.itemModel ? seriesScope.itemModel : data.getItemModel(idx), emphasisModel = itemModel.getModel('emphasis'); emphasisItemStyle = emphasisModel.getModel('itemStyle').getItemStyle(), selectItemStyle = itemModel.getModel([ 'select', 'itemStyle' ]).getItemStyle(), blurItemStyle = itemModel.getModel([ 'blur', 'itemStyle' ]).getItemStyle(), focus = emphasisModel.get('focus'), blurScope = emphasisModel.get('blurScope'), labelStatesModels = getLabelStatesModels(itemModel), hoverScale = emphasisModel.getShallow('scale'), cursorStyle = itemModel.getShallow('cursor'); } var symbolRotate = data.getItemVisual(idx, 'symbolRotate'); symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0); var symbolOffset = data.getItemVisual(idx, 'symbolOffset') || 0; symbolOffset && (isArray(symbolOffset) || (symbolOffset = [ symbolOffset, symbolOffset ]), symbolPath.x = parsePercent$1(symbolOffset[0], symbolSize[0]), symbolPath.y = parsePercent$1(retrieve2(symbolOffset[1], symbolOffset[0]) || 0, symbolSize[1])), cursorStyle && symbolPath.attr('cursor', cursorStyle); var symbolStyle = data.getItemVisual(idx, 'style'), visualColor = symbolStyle.fill; if (symbolPath instanceof ZRImage) { var pathStyle = symbolPath.style; symbolPath.useStyle(extend({ image: pathStyle.image, x: pathStyle.x, y: pathStyle.y, width: pathStyle.width, height: pathStyle.height }, symbolStyle)); } else symbolPath.__isEmptyBrush ? symbolPath.useStyle(extend({}, symbolStyle)) : symbolPath.useStyle(symbolStyle), symbolPath.style.decal = null, symbolPath.setColor(visualColor, opts && opts.symbolInnerColor), symbolPath.style.strokeNoScale = !0; var liftZ = data.getItemVisual(idx, 'liftZ'), z2Origin = this._z2; null != liftZ ? null == z2Origin && (this._z2 = symbolPath.z2, symbolPath.z2 += liftZ) : null != z2Origin && (symbolPath.z2 = z2Origin, this._z2 = null); var useNameLabel = opts && opts.useNameLabel; setLabelStyle(symbolPath, labelStatesModels, { labelFetcher: seriesModel, labelDataIndex: idx, defaultText: function(idx) { return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx); }, inheritColor: visualColor, defaultOpacity: symbolStyle.opacity }), this._sizeX = symbolSize[0] / 2, this._sizeY = symbolSize[1] / 2; var emphasisState = symbolPath.ensureState('emphasis'); if (emphasisState.style = emphasisItemStyle, symbolPath.ensureState('select').style = selectItemStyle, symbolPath.ensureState('blur').style = blurItemStyle, hoverScale) { var scaleRatio = Math.max(1.1, 3 / this._sizeY); emphasisState.scaleX = this._sizeX * scaleRatio, emphasisState.scaleY = this._sizeY * scaleRatio; } this.setSymbolScale(1), enableHoverEmphasis(this, focus, blurScope); }, Symbol.prototype.setSymbolScale = function(scale) { this.scaleX = this.scaleY = scale; }, Symbol.prototype.fadeOut = function(cb, opt) { var symbolPath = this.childAt(0), seriesModel = this._seriesModel, dataIndex = getECData(this).dataIndex, animationOpt = opt && opt.animation; if (this.silent = symbolPath.silent = !0, opt && opt.fadeLabel) { var textContent = symbolPath.getTextContent(); textContent && removeElement(textContent, { style: { opacity: 0 } }, seriesModel, { dataIndex: dataIndex, removeOpt: animationOpt, cb: function() { symbolPath.removeTextContent(); } }); } else symbolPath.removeTextContent(); removeElement(symbolPath, { style: { opacity: 0 }, scaleX: 0, scaleY: 0 }, seriesModel, { dataIndex: dataIndex, cb: cb, removeOpt: animationOpt }); }, Symbol.getSymbolSize = function(data, idx) { var symbolSize = data.getItemVisual(idx, 'symbolSize'); return isArray(symbolSize) ? symbolSize.slice() : [ +symbolSize, +symbolSize ]; }, Symbol; }(Group); function driftSymbol(dx, dy) { this.parent.drift(dx, dy); } function symbolNeedsDraw(data, point, idx, opt) { return point && !isNaN(point[0]) && !isNaN(point[1]) && !(opt.isIgnore && opt.isIgnore(idx)) && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1])) && 'none' !== data.getItemVisual(idx, 'symbol'); } function normalizeUpdateOpt(opt) { return null == opt || isObject(opt) || (opt = { isIgnore: opt }), opt || {}; } function makeSeriesScope(data) { var seriesModel = data.hostModel, emphasisModel = seriesModel.getModel('emphasis'); return { emphasisItemStyle: emphasisModel.getModel('itemStyle').getItemStyle(), blurItemStyle: seriesModel.getModel([ 'blur', 'itemStyle' ]).getItemStyle(), selectItemStyle: seriesModel.getModel([ 'select', 'itemStyle' ]).getItemStyle(), focus: emphasisModel.get('focus'), blurScope: emphasisModel.get('blurScope'), hoverScale: emphasisModel.get('scale'), labelStatesModels: getLabelStatesModels(seriesModel), cursorStyle: seriesModel.get('cursor') }; } var SymbolDraw = function() { function SymbolDraw(SymbolCtor) { this.group = new Group(), this._SymbolCtor = SymbolCtor || Symbol; } return SymbolDraw.prototype.updateData = function(data, opt) { opt = normalizeUpdateOpt(opt); var group = this.group, seriesModel = data.hostModel, oldData = this._data, SymbolCtor = this._SymbolCtor, disableAnimation = opt.disableAnimation, seriesScope = makeSeriesScope(data), symbolUpdateOpt = { disableAnimation: disableAnimation }, getSymbolPoint = opt.getSymbolPoint || function(idx) { return data.getItemLayout(idx); }; oldData || group.removeAll(), data.diff(oldData).add(function(newIdx) { var point = getSymbolPoint(newIdx); if (symbolNeedsDraw(data, point, newIdx, opt)) { var symbolEl = new SymbolCtor(data, newIdx, seriesScope, symbolUpdateOpt); symbolEl.setPosition(point), data.setItemGraphicEl(newIdx, symbolEl), group.add(symbolEl); } }).update(function(newIdx, oldIdx) { var symbolEl = oldData.getItemGraphicEl(oldIdx), point = getSymbolPoint(newIdx); if (!symbolNeedsDraw(data, point, newIdx, opt)) { group.remove(symbolEl); return; } if (symbolEl) { symbolEl.updateData(data, newIdx, seriesScope, symbolUpdateOpt); var target = { x: point[0], y: point[1] }; disableAnimation ? symbolEl.attr(target) : updateProps(symbolEl, target, seriesModel); } else (symbolEl = new SymbolCtor(data, newIdx)).setPosition(point); group.add(symbolEl), data.setItemGraphicEl(newIdx, symbolEl); }).remove(function(oldIdx) { var el = oldData.getItemGraphicEl(oldIdx); el && el.fadeOut(function() { group.remove(el); }); }).execute(), this._getSymbolPoint = getSymbolPoint, this._data = data; }, SymbolDraw.prototype.isPersistent = function() { return !0; }, SymbolDraw.prototype.updateLayout = function() { var _this = this, data = this._data; data && data.eachItemGraphicEl(function(el, idx) { var point = _this._getSymbolPoint(idx); el.setPosition(point), el.markRedraw(); }); }, SymbolDraw.prototype.incrementalPrepareUpdate = function(data) { this._seriesScope = makeSeriesScope(data), this._data = null, this.group.removeAll(); }, SymbolDraw.prototype.incrementalUpdate = function(taskParams, data, opt) { function updateIncrementalAndHover(el) { el.isGroup || (el.incremental = !0, el.ensureState('emphasis').hoverLayer = !0); } opt = normalizeUpdateOpt(opt); for(var idx = taskParams.start; idx < taskParams.end; idx++){ var point = data.getItemLayout(idx); if (symbolNeedsDraw(data, point, idx, opt)) { var el = new this._SymbolCtor(data, idx, this._seriesScope); el.traverse(updateIncrementalAndHover), el.setPosition(point), this.group.add(el), data.setItemGraphicEl(idx, el); } } }, SymbolDraw.prototype.remove = function(enableAnimation) { var group = this.group, data = this._data; data && enableAnimation ? data.eachItemGraphicEl(function(el) { el.fadeOut(function() { group.remove(el); }); }) : group.removeAll(); }, SymbolDraw; }(); function prepareDataCoordInfo(coordSys, data, valueOrigin) { var valueStart, extent, baseAxis = coordSys.getBaseAxis(), valueAxis = coordSys.getOtherAxis(baseAxis), valueStart1 = (valueStart = 0, extent = valueAxis.scale.getExtent(), 'start' === valueOrigin ? valueStart = extent[0] : 'end' === valueOrigin ? valueStart = extent[1] : extent[0] > 0 ? valueStart = extent[0] : extent[1] < 0 && (valueStart = extent[1]), valueStart), baseAxisDim = baseAxis.dim, valueAxisDim = valueAxis.dim, valueDim = data.mapDimension(valueAxisDim), baseDim = data.mapDimension(baseAxisDim), dims = map(coordSys.dimensions, function(coordDim) { return data.mapDimension(coordDim); }), stacked = !1, stackResultDim = data.getCalculationInfo('stackResultDimension'); return isDimensionStacked(data, dims[0]) && (stacked = !0, dims[0] = stackResultDim), isDimensionStacked(data, dims[1]) && (stacked = !0, dims[1] = stackResultDim), { dataDimsForPoint: dims, valueStart: valueStart1, valueAxisDim: valueAxisDim, baseAxisDim: baseAxisDim, stacked: !!stacked, valueDim: valueDim, baseDim: baseDim, baseDataOffset: 'x' === valueAxisDim || 'radius' === valueAxisDim ? 1 : 0, stackedOverDimension: data.getCalculationInfo('stackedOverDimension') }; } function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) { var value = NaN; dataCoordInfo.stacked && (value = data.get(data.getCalculationInfo('stackedOverDimension'), idx)), isNaN(value) && (value = dataCoordInfo.valueStart); var baseDataOffset = dataCoordInfo.baseDataOffset, stackedData = []; return stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx), stackedData[1 - baseDataOffset] = value, coordSys.dataToPoint(stackedData); } var supportFloat32Array = 'undefined' != typeof Float32Array, Float32ArrayCtor = supportFloat32Array ? Float32Array : Array; function createFloat32Array(arg) { return isArray(arg) ? supportFloat32Array ? new Float32Array(arg) : arg : new Float32ArrayCtor(arg); } var mathMin$5 = Math.min, mathMax$5 = Math.max; function isPointNull(x, y) { return isNaN(x) || isNaN(y); } function drawSegment(ctx, points, start, segLen, allLen, dir, smooth, smoothMonotone, connectNulls) { for(var prevX, prevY, cpx0, cpy0, cpx1, cpy1, idx = start, k = 0; k < segLen; k++){ var x = points[2 * idx], y = points[2 * idx + 1]; if (idx >= allLen || idx < 0) break; if (isPointNull(x, y)) { if (connectNulls) { idx += dir; continue; } break; } if (idx === start) ctx[dir > 0 ? 'moveTo' : 'lineTo'](x, y), cpx0 = x, cpy0 = y; else { var dx = x - prevX, dy = y - prevY; if (dx * dx + dy * dy < 0.5) { idx += dir; continue; } if (smooth > 0) { var nextIdx = idx + dir, nextX = points[2 * nextIdx], nextY = points[2 * nextIdx + 1], tmpK = k + 1; if (connectNulls) for(; isPointNull(nextX, nextY) && tmpK < segLen;)tmpK++, nextIdx += dir, nextX = points[2 * nextIdx], nextY = points[2 * nextIdx + 1]; var ratioNextSeg = 0.5, vx = 0, vy = 0, nextCpx0 = void 0, nextCpy0 = void 0; if (tmpK >= segLen || isPointNull(nextX, nextY)) cpx1 = x, cpy1 = y; else { vx = nextX - prevX, vy = nextY - prevY; var dx0 = x - prevX, dx1 = nextX - x, dy0 = y - prevY, dy1 = nextY - y, lenPrevSeg = void 0, lenNextSeg = void 0; 'x' === smoothMonotone ? (lenPrevSeg = Math.abs(dx0), lenNextSeg = Math.abs(dx1), cpx1 = x - lenPrevSeg * smooth, cpy1 = y, nextCpx0 = x + lenPrevSeg * smooth, nextCpy0 = y) : 'y' === smoothMonotone ? (lenPrevSeg = Math.abs(dy0), lenNextSeg = Math.abs(dy1), cpx1 = x, cpy1 = y - lenPrevSeg * smooth, nextCpx0 = x, nextCpy0 = y + lenPrevSeg * smooth) : (lenPrevSeg = Math.sqrt(dx0 * dx0 + dy0 * dy0), cpx1 = x - vx * smooth * (1 - (ratioNextSeg = (lenNextSeg = Math.sqrt(dx1 * dx1 + dy1 * dy1)) / (lenNextSeg + lenPrevSeg))), cpy1 = y - vy * smooth * (1 - ratioNextSeg), nextCpx0 = x + vx * smooth * ratioNextSeg, nextCpy0 = y + vy * smooth * ratioNextSeg, nextCpx0 = mathMin$5(nextCpx0, mathMax$5(nextX, x)), nextCpy0 = mathMin$5(nextCpy0, mathMax$5(nextY, y)), nextCpx0 = mathMax$5(nextCpx0, mathMin$5(nextX, x)), nextCpy0 = mathMax$5(nextCpy0, mathMin$5(nextY, y)), vx = nextCpx0 - x, vy = nextCpy0 - y, cpx1 = x - vx * lenPrevSeg / lenNextSeg, cpy1 = y - vy * lenPrevSeg / lenNextSeg, cpx1 = mathMin$5(cpx1, mathMax$5(prevX, x)), cpy1 = mathMin$5(cpy1, mathMax$5(prevY, y)), cpx1 = mathMax$5(cpx1, mathMin$5(prevX, x)), cpy1 = mathMax$5(cpy1, mathMin$5(prevY, y)), vx = x - cpx1, vy = y - cpy1, nextCpx0 = x + vx * lenNextSeg / lenPrevSeg, nextCpy0 = y + vy * lenNextSeg / lenPrevSeg); } ctx.bezierCurveTo(cpx0, cpy0, cpx1, cpy1, x, y), cpx0 = nextCpx0, cpy0 = nextCpy0; } else ctx.lineTo(x, y); } prevX = x, prevY = y, idx += dir; } return k; } var ECPolylineShape = function() { this.smooth = 0, this.smoothConstraint = !0; }, ECPolyline = function(_super) { function ECPolyline(opts) { var _this = _super.call(this, opts) || this; return _this.type = 'ec-polyline', _this; } return __extends(ECPolyline, _super), ECPolyline.prototype.getDefaultStyle = function() { return { stroke: '#000', fill: null }; }, ECPolyline.prototype.getDefaultShape = function() { return new ECPolylineShape(); }, ECPolyline.prototype.buildPath = function(ctx, shape) { var points = shape.points, i = 0, len = points.length / 2; if (shape.connectNulls) { for(; len > 0 && isPointNull(points[2 * len - 2], points[2 * len - 1]); len--); for(; i < len && isPointNull(points[2 * i], points[2 * i + 1]); i++); } for(; i < len;)i += drawSegment(ctx, points, i, len, len, 1, shape.smooth, shape.smoothMonotone, shape.connectNulls) + 1; }, ECPolyline.prototype.getPointOn = function(xOrY, dim) { this.path || (this.createPathProxy(), this.buildPath(this.path, this.shape)); for(var x0, y0, data = this.path.data, CMD = PathProxy.CMD, isDimX = 'x' === dim, roots = [], i = 0; i < data.length;){ var cmd = data[i++], x = void 0, y = void 0, x2 = void 0, y2 = void 0, x3 = void 0, y3 = void 0, t = void 0; switch(cmd){ case CMD.M: x0 = data[i++], y0 = data[i++]; break; case CMD.L: if (x = data[i++], y = data[i++], (t = isDimX ? (xOrY - x0) / (x - x0) : (xOrY - y0) / (y - y0)) <= 1 && t >= 0) { var val = isDimX ? (y - y0) * t + y0 : (x - x0) * t + x0; return isDimX ? [ xOrY, val ] : [ val, xOrY ]; } x0 = x, y0 = y; break; case CMD.C: x = data[i++], y = data[i++], x2 = data[i++], y2 = data[i++], x3 = data[i++], y3 = data[i++]; var nRoot = isDimX ? cubicRootAt(x0, x, x2, x3, xOrY, roots) : cubicRootAt(y0, y, y2, y3, xOrY, roots); if (nRoot > 0) for(var i_1 = 0; i_1 < nRoot; i_1++){ var t_1 = roots[i_1]; if (t_1 <= 1 && t_1 >= 0) { var val = isDimX ? cubicAt(y0, y, y2, y3, t_1) : cubicAt(x0, x, x2, x3, t_1); return isDimX ? [ xOrY, val ] : [ val, xOrY ]; } } x0 = x3, y0 = y3; } } }, ECPolyline; }(Path), ECPolygonShape = function(_super) { function ECPolygonShape() { return null !== _super && _super.apply(this, arguments) || this; } return __extends(ECPolygonShape, _super), ECPolygonShape; }(ECPolylineShape), ECPolygon = function(_super) { function ECPolygon(opts) { var _this = _super.call(this, opts) || this; return _this.type = 'ec-polygon', _this; } return __extends(ECPolygon, _super), ECPolygon.prototype.getDefaultShape = function() { return new ECPolygonShape(); }, ECPolygon.prototype.buildPath = function(ctx, shape) { var points = shape.points, stackedOnPoints = shape.stackedOnPoints, i = 0, len = points.length / 2, smoothMonotone = shape.smoothMonotone; if (shape.connectNulls) { for(; len > 0 && isPointNull(points[2 * len - 2], points[2 * len - 1]); len--); for(; i < len && isPointNull(points[2 * i], points[2 * i + 1]); i++); } for(; i < len;){ var k = drawSegment(ctx, points, i, len, len, 1, shape.smooth, smoothMonotone, shape.connectNulls); drawSegment(ctx, stackedOnPoints, i + k - 1, k, len, -1, shape.stackedOnSmooth, smoothMonotone, shape.connectNulls), i += k + 1, ctx.closePath(); } }, ECPolygon; }(Path); function createGridClipPath(cartesian, hasAnimation, seriesModel, done, during) { var rect = cartesian.getArea(), x = rect.x, y = rect.y, width = rect.width, height = rect.height, lineWidth = seriesModel.get([ 'lineStyle', 'width' ]) || 2; x -= lineWidth / 2, y -= lineWidth / 2, width += lineWidth, height += lineWidth, x = Math.floor(x), width = Math.round(width); var clipPath = new Rect({ shape: { x: x, y: y, width: width, height: height } }); if (hasAnimation) { var baseAxis = cartesian.getBaseAxis(), isHorizontal = baseAxis.isHorizontal(), isAxisInversed = baseAxis.inverse; isHorizontal ? (isAxisInversed && (clipPath.shape.x += width), clipPath.shape.width = 0) : (isAxisInversed || (clipPath.shape.y += height), clipPath.shape.height = 0); var duringCb = 'function' == typeof during ? function(percent) { during(percent, clipPath); } : null; initProps(clipPath, { shape: { width: width, height: height, x: x, y: y } }, seriesModel, null, done, duringCb); } return clipPath; } function createPolarClipPath(polar, hasAnimation, seriesModel) { var sectorArea = polar.getArea(), r0 = round(sectorArea.r0, 1), r = round(sectorArea.r, 1), clipPath = new Sector({ shape: { cx: round(polar.cx, 1), cy: round(polar.cy, 1), r0: r0, r: r, startAngle: sectorArea.startAngle, endAngle: sectorArea.endAngle, clockwise: sectorArea.clockwise } }); return hasAnimation && ('angle' === polar.getBaseAxis().dim ? clipPath.shape.endAngle = sectorArea.startAngle : clipPath.shape.r = r0, initProps(clipPath, { shape: { endAngle: sectorArea.endAngle, r: r } }, seriesModel)), clipPath; } function createClipPath(coordSys, hasAnimation, seriesModel, done, during) { if (coordSys) { if ('polar' === coordSys.type) return createPolarClipPath(coordSys, hasAnimation, seriesModel); if ('cartesian2d' === coordSys.type) return createGridClipPath(coordSys, hasAnimation, seriesModel, done, during); } return null; } function isCoordinateSystemType(coordSys, type) { return coordSys.type === type; } function isPointsSame(points1, points2) { if (points1.length === points2.length) { for(var i = 0; i < points1.length; i++)if (points1[i] !== points2[i]) return; return !0; } } function bboxFromPoints(points) { for(var minX = 1 / 0, minY = 1 / 0, maxX = -1 / 0, maxY = -1 / 0, i = 0; i < points.length;){ var x = points[i++], y = points[i++]; isNaN(x) || (minX = Math.min(x, minX), maxX = Math.max(x, maxX)), isNaN(y) || (minY = Math.min(y, minY), maxY = Math.max(y, maxY)); } return [ [ minX, minY ], [ maxX, maxY ] ]; } function getBoundingDiff(points1, points2) { var _a = bboxFromPoints(points1), min1 = _a[0], max1 = _a[1], _b = bboxFromPoints(points2), min2 = _b[0], max2 = _b[1]; return Math.max(Math.abs(min1[0] - min2[0]), Math.abs(min1[1] - min2[1]), Math.abs(max1[0] - max2[0]), Math.abs(max1[1] - max2[1])); } function getSmooth(smooth) { return 'number' == typeof smooth ? smooth : smooth ? 0.5 : 0; } function turnPointsIntoStep(points, coordSys, stepTurnAt) { for(var baseAxis = coordSys.getBaseAxis(), baseIndex = 'x' === baseAxis.dim || 'radius' === baseAxis.dim ? 0 : 1, stepPoints = [], i = 0, stepPt = [], pt = [], nextPt = []; i < points.length - 2; i += 2)switch(nextPt[0] = points[i + 2], nextPt[1] = points[i + 3], pt[0] = points[i], pt[1] = points[i + 1], stepPoints.push(pt[0], pt[1]), stepTurnAt){ case 'end': stepPt[baseIndex] = nextPt[baseIndex], stepPt[1 - baseIndex] = pt[1 - baseIndex], stepPoints.push(stepPt[0], stepPt[1]); break; case 'middle': var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2, stepPt2 = []; stepPt[baseIndex] = stepPt2[baseIndex] = middle, stepPt[1 - baseIndex] = pt[1 - baseIndex], stepPt2[1 - baseIndex] = nextPt[1 - baseIndex], stepPoints.push(stepPt[0], stepPt[1]), stepPoints.push(stepPt2[0], stepPt2[1]); break; default: stepPt[baseIndex] = pt[baseIndex], stepPt[1 - baseIndex] = nextPt[1 - baseIndex], stepPoints.push(stepPt[0], stepPt[1]); } return stepPoints.push(points[i++], points[i++]), stepPoints; } function getPointAtIndex(points, idx) { return [ points[2 * idx], points[2 * idx + 1] ]; } function createLineClipPath(lineView, coordSys, hasAnimation, seriesModel) { if (!isCoordinateSystemType(coordSys, 'cartesian2d')) return seriesModel.get([ 'endLabel', 'show' ]) && console.warn('endLabel is not supported for lines in polar systems.'), createPolarClipPath(coordSys, hasAnimation, seriesModel); var endLabelModel_1 = seriesModel.getModel('endLabel'), showEndLabel = endLabelModel_1.get('show'), valueAnimation_1 = endLabelModel_1.get('valueAnimation'), data_1 = seriesModel.getData(), labelAnimationRecord_1 = { lastFrameIndex: 0 }, during = showEndLabel ? function(percent, clipRect) { lineView._endLabelOnDuring(percent, clipRect, data_1, labelAnimationRecord_1, valueAnimation_1, endLabelModel_1, coordSys); } : null, isHorizontal = coordSys.getBaseAxis().isHorizontal(), clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel, function() { var endLabel = lineView._endLabel; endLabel && hasAnimation && null != labelAnimationRecord_1.originalX && endLabel.attr({ x: labelAnimationRecord_1.originalX, y: labelAnimationRecord_1.originalY }); }, during); if (!seriesModel.get('clip', !0)) { var rectShape = clipPath.shape, expandSize = Math.max(rectShape.width, rectShape.height); isHorizontal ? (rectShape.y -= expandSize, rectShape.height += 2 * expandSize) : (rectShape.x -= expandSize, rectShape.width += 2 * expandSize); } return during && during(1, clipPath), clipPath; } var LineView = function(_super) { function LineView() { return null !== _super && _super.apply(this, arguments) || this; } return __extends(LineView, _super), LineView.prototype.init = function() { var lineGroup = new Group(), symbolDraw = new SymbolDraw(); this.group.add(symbolDraw.group), this._symbolDraw = symbolDraw, this._lineGroup = lineGroup; }, LineView.prototype.render = function(seriesModel, ecModel, api) { var clipShapeForSymbol, _this = this, coordSys = seriesModel.coordinateSystem, group = this.group, data = seriesModel.getData(), lineStyleModel = seriesModel.getModel('lineStyle'), areaStyleModel = seriesModel.getModel('areaStyle'), points = data.getLayout('points') || [], isCoordSysPolar = 'polar' === coordSys.type, prevCoordSys = this._coordSys, symbolDraw = this._symbolDraw, polyline = this._polyline, polygon = this._polygon, lineGroup = this._lineGroup, hasAnimation = seriesModel.get('animation'), isAreaChart = !areaStyleModel.isEmpty(), valueOrigin = areaStyleModel.get('origin'), dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin), stackedOnPoints = isAreaChart && function(coordSys, data, dataCoordInfo) { if (!dataCoordInfo.valueDim) return []; for(var len = data.count(), points = createFloat32Array(2 * len), idx = 0; idx < len; idx++){ var pt = getStackedOnPoint(dataCoordInfo, coordSys, data, idx); points[2 * idx] = pt[0], points[2 * idx + 1] = pt[1]; } return points; }(coordSys, data, dataCoordInfo), showSymbol = seriesModel.get('showSymbol'), isIgnoreFunc = showSymbol && !isCoordSysPolar && function(seriesModel, data, coordSys) { var showAllSymbol = seriesModel.get('showAllSymbol'), isAuto = 'auto' === showAllSymbol; if (!showAllSymbol || isAuto) { var categoryAxis = coordSys.getAxesByScale('ordinal')[0]; if (!(!categoryAxis || isAuto && function(categoryAxis, data) { var axisExtent = categoryAxis.getExtent(), availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count(); isNaN(availSize) && (availSize = 0); for(var dataLen = data.count(), step = Math.max(1, Math.round(dataLen / 5)), dataIndex = 0; dataIndex < dataLen; dataIndex += step)if (1.5 * Symbol.getSymbolSize(data, dataIndex)[categoryAxis.isHorizontal() ? 1 : 0] > availSize) return !1; return !0; }(categoryAxis, data))) { var categoryDataDim = data.mapDimension(categoryAxis.dim), labelMap = {}; return each(categoryAxis.getViewLabels(), function(labelItem) { labelMap[categoryAxis.scale.getRawOrdinalNumber(labelItem.tickValue)] = 1; }), function(dataIndex) { return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex)); }; } } }(seriesModel, data, coordSys), oldData = this._data; oldData && oldData.eachItemGraphicEl(function(el, idx) { el.__temp && (group.remove(el), oldData.setItemGraphicEl(idx, null)); }), showSymbol || symbolDraw.remove(), group.add(lineGroup); var step = !isCoordSysPolar && seriesModel.get('step'); coordSys && coordSys.getArea && seriesModel.get('clip', !0) && (null != (clipShapeForSymbol = coordSys.getArea()).width ? (clipShapeForSymbol.x -= 0.1, clipShapeForSymbol.y -= 0.1, clipShapeForSymbol.width += 0.2, clipShapeForSymbol.height += 0.2) : clipShapeForSymbol.r0 && (clipShapeForSymbol.r0 -= 0.5, clipShapeForSymbol.r += 0.5)), this._clipShapeForSymbol = clipShapeForSymbol; var visualColor = function(data, coordSys) { var coordDim, visualMeta, visualMetaList = data.getVisual('visualMeta'); if (visualMetaList && visualMetaList.length && data.count()) { if ('cartesian2d' !== coordSys.type) { console.warn('Visual map on line style is only supported on cartesian2d.'); return; } for(var i = visualMetaList.length - 1; i >= 0; i--){ var dimIndex = visualMetaList[i].dimension, dimName = data.dimensions[dimIndex], dimInfo = data.getDimensionInfo(dimName); if ('x' === (coordDim = dimInfo && dimInfo.coordDim) || 'y' === coordDim) { visualMeta = visualMetaList[i]; break; } } if (!visualMeta) { console.warn('Visual map on line style only support x or y dimension.'); return; } var axis = coordSys.getAxis(coordDim), colorStops = map(visualMeta.stops, function(stop) { return { offset: 0, coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)), color: stop.color }; }), stopLen = colorStops.length, outerColors = visualMeta.outerColors.slice(); stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord && (colorStops.reverse(), outerColors.reverse()); var minCoord = colorStops[0].coord - 10, maxCoord = colorStops[stopLen - 1].coord + 10, coordSpan = maxCoord - minCoord; if (coordSpan < 1e-3) return 'transparent'; each(colorStops, function(stop) { stop.offset = (stop.coord - minCoord) / coordSpan; }), colorStops.push({ offset: stopLen ? colorStops[stopLen - 1].offset : 0.5, color: outerColors[1] || 'transparent' }), colorStops.unshift({ offset: stopLen ? colorStops[0].offset : 0.5, color: outerColors[0] || 'transparent' }); var gradient = new LinearGradient(0, 0, 0, 0, colorStops, !0); return gradient[coordDim] = minCoord, gradient[coordDim + '2'] = maxCoord, gradient; } }(data, coordSys) || data.getVisual('style')[data.getVisual('drawType')]; polyline && prevCoordSys.type === coordSys.type && step === this._step ? (isAreaChart && !polygon ? polygon = this._newPolygon(points, stackedOnPoints) : polygon && !isAreaChart && (lineGroup.remove(polygon), polygon = this._polygon = null), isCoordSysPolar || this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor)), lineGroup.setClipPath(createLineClipPath(this, coordSys, !1, seriesModel)), showSymbol && symbolDraw.updateData(data, { isIgnore: isIgnoreFunc, clipShape: clipShapeForSymbol, disableAnimation: !0, getSymbolPoint: function(idx) { return [ points[2 * idx], points[2 * idx + 1] ]; } }), isPointsSame(this._stackedOnPoints, stackedOnPoints) && isPointsSame(this._points, points) || (hasAnimation ? this._doUpdateAnimation(data, stackedOnPoints, coordSys, api, step, valueOrigin) : (step && (points = turnPointsIntoStep(points, coordSys, step), stackedOnPoints && (stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step))), polyline.setShape({ points: points }), polygon && polygon.setShape({ points: points, stackedOnPoints: stackedOnPoints })))) : (showSymbol && symbolDraw.updateData(data, { isIgnore: isIgnoreFunc, clipShape: clipShapeForSymbol, disableAnimation: !0, getSymbolPoint: function(idx) { return [ points[2 * idx], points[2 * idx + 1] ]; } }), hasAnimation && this._initSymbolLabelAnimation(data, coordSys, clipShapeForSymbol), step && (points = turnPointsIntoStep(points, coordSys, step), stackedOnPoints && (stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step))), polyline = this._newPolyline(points), isAreaChart && (polygon = this._newPolygon(points, stackedOnPoints)), isCoordSysPolar || this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor)), lineGroup.setClipPath(createLineClipPath(this, coordSys, !0, seriesModel))); var focus = seriesModel.get([ 'emphasis', 'focus' ]), blurScope = seriesModel.get([ 'emphasis', 'blurScope' ]); polyline.useStyle(defaults(lineStyleModel.getLineStyle(), { fill: 'none', stroke: visualColor, lineJoin: 'bevel' })), setStatesStylesFromModel(polyline, seriesModel, 'lineStyle'), polyline.style.lineWidth > 0 && 'bolder' === seriesModel.get([ 'emphasis', 'lineStyle', 'width' ]) && (polyline.getState('emphasis').style.lineWidth = +polyline.style.lineWidth + 1), getECData(polyline).seriesIndex = seriesModel.seriesIndex, enableHoverEmphasis(polyline, focus, blurScope); var smooth = getSmooth(seriesModel.get('smooth')), smoothMonotone = seriesModel.get('smoothMonotone'), connectNulls = seriesModel.get('connectNulls'); if (polyline.setShape({ smooth: smooth, smoothMonotone: smoothMonotone, connectNulls: connectNulls }), polygon) { var stackedOnSeries = data.getCalculationInfo('stackedOnSeries'), stackedOnSmooth = 0; polygon.useStyle(defaults(areaStyleModel.getAreaStyle(), { fill: visualColor, opacity: 0.7, lineJoin: 'bevel', decal: data.getVisual('style').decal })), stackedOnSeries && (stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'))), polygon.setShape({ smooth: smooth, stackedOnSmooth: stackedOnSmooth, smoothMonotone: smoothMonotone, connectNulls: connectNulls }), setStatesStylesFromModel(polygon, seriesModel, 'areaStyle'), getECData(polygon).seriesIndex = seriesModel.seriesIndex, enableHoverEmphasis(polygon, focus, blurScope); } var changePolyState = function(toState) { _this._changePolyState(toState); }; data.eachItemGraphicEl(function(el) { el && (el.onHoverStateChange = changePolyState); }), this._polyline.onHoverStateChange = changePolyState, this._data = data, this._coordSys = coordSys, this._stackedOnPoints = stackedOnPoints, this._points = points, this._step = step, this._valueOrigin = valueOrigin; }, LineView.prototype.dispose = function() {}, LineView.prototype.highlight = function(seriesModel, ecModel, api, payload) { var data = seriesModel.getData(), dataIndex = queryDataIndex(data, payload); if (this._changePolyState('emphasis'), dataIndex instanceof Array || null == dataIndex || !(dataIndex >= 0)) ChartView.prototype.highlight.call(this, seriesModel, ecModel, api, payload); else { var points = data.getLayout('points'), symbol = data.getItemGraphicEl(dataIndex); if (!symbol) { var x = points[2 * dataIndex], y = points[2 * dataIndex + 1]; if (isNaN(x) || isNaN(y) || this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(x, y)) return; (symbol = new Symbol(data, dataIndex)).x = x, symbol.y = y, symbol.setZ(seriesModel.get('zlevel'), seriesModel.get('z')); var symbolLabel = symbol.getSymbolPath().getTextContent(); symbolLabel && (symbolLabel.z2 = this._polyline.z2 + 1), symbol.__temp = !0, data.setItemGraphicEl(dataIndex, symbol), symbol.stopSymbolAnimation(!0), this.group.add(symbol); } symbol.highlight(); } }, LineView.prototype.downplay = function(seriesModel, ecModel, api, payload) { var data = seriesModel.getData(), dataIndex = queryDataIndex(data, payload); if (this._changePolyState('normal'), null != dataIndex && dataIndex >= 0) { var symbol = data.getItemGraphicEl(dataIndex); symbol && (symbol.__temp ? (data.setItemGraphicEl(dataIndex, null), this.group.remove(symbol)) : symbol.downplay()); } else ChartView.prototype.downplay.call(this, seriesModel, ecModel, api, payload); }, LineView.prototype._changePolyState = function(toState) { var polygon = this._polygon; setStatesFlag(this._polyline, toState), polygon && setStatesFlag(polygon, toState); }, LineView.prototype._newPolyline = function(points) { var polyline = this._polyline; return polyline && this._lineGroup.remove(polyline), polyline = new ECPolyline({ shape: { points: points }, segmentIgnoreThreshold: 2, z2: 10 }), this._lineGroup.add(polyline), this._polyline = polyline, polyline; }, LineView.prototype._newPolygon = function(points, stackedOnPoints) { var polygon = this._polygon; return polygon && this._lineGroup.remove(polygon), polygon = new ECPolygon({ shape: { points: points, stackedOnPoints: stackedOnPoints }, segmentIgnoreThreshold: 2 }), this._lineGroup.add(polygon), this._polygon = polygon, polygon; }, LineView.prototype._initSymbolLabelAnimation = function(data, coordSys, clipShape) { var isHorizontalOrRadial, isCoordSysPolar, baseAxis = coordSys.getBaseAxis(), isAxisInverse = baseAxis.inverse; 'cartesian2d' === coordSys.type ? (isHorizontalOrRadial = baseAxis.isHorizontal(), isCoordSysPolar = !1) : 'polar' === coordSys.type && (isHorizontalOrRadial = 'angle' === baseAxis.dim, isCoordSysPolar = !0); var seriesModel = data.hostModel, seriesDuration = seriesModel.get('animationDuration'); 'function' == typeof seriesDuration && (seriesDuration = seriesDuration(null)); var seriesDalay = seriesModel.get('animationDelay') || 0, seriesDalayValue = 'function' == typeof seriesDalay ? seriesDalay(null) : seriesDalay; data.eachItemGraphicEl(function(symbol, idx) { if (symbol) { var point = [ symbol.x, symbol.y ], start = void 0, end = void 0, current = void 0; if (isCoordSysPolar) { var coord = coordSys.pointToCoord(point); isHorizontalOrRadial ? (start = clipShape.startAngle, end = clipShape.endAngle, current = -coord[1] / 180 * Math.PI) : (start = clipShape.r0, end = clipShape.r, current = coord[0]); } else isHorizontalOrRadial ? (start = clipShape.x, end = clipShape.x + clipShape.width, current = symbol.x) : (start = clipShape.y + clipShape.height, end = clipShape.y, current = symbol.y); var ratio = end === start ? 0 : (current - start) / (end - start); isAxisInverse && (ratio = 1 - ratio); var delay = 'function' == typeof seriesDalay ? seriesDalay(idx) : seriesDuration * ratio + seriesDalayValue, symbolPath = symbol.getSymbolPath(), text = symbolPath.getTextContent(); symbol.attr({ scaleX: 0, scaleY: 0 }), symbol.animateTo({ scaleX: 1, scaleY: 1 }, { duration: 200, delay: delay }), text && text.animateFrom({ style: { opacity: 0 } }, { duration: 300, delay: delay }), symbolPath.disableLabelAnimation = !0; } }); }, LineView.prototype._initOrUpdateEndLabel = function(seriesModel, coordSys, inheritColor) { var endLabelModel = seriesModel.getModel('endLabel'); if (endLabelModel.get('show')) { var baseAxis, isHorizontal, isBaseInversed, data_2 = seriesModel.getData(), polyline = this._polyline, endLabel = this._endLabel; endLabel || ((endLabel = this._endLabel = new ZRText({ z2: 200 })).ignoreClip = !0, polyline.setTextContent(this._endLabel), polyline.disableLabelAnimation = !0); var dataIndex = function(points) { for(var x, y, len = points.length / 2; len > 0 && (x = points[2 * len - 2], y = points[2 * len - 1], isNaN(x) || isNaN(y)); len--); return len - 1; }(data_2.getLayout('points')); dataIndex >= 0 && (setLabelStyle(polyline, getLabelStatesModels(seriesModel, 'endLabel'), { inheritColor: inheritColor, labelFetcher: seriesModel, labelDataIndex: dataIndex, defaultText: function(dataIndex, opt, interpolatedValue) { return null != interpolatedValue ? getDefaultInterpolatedLabel(data_2, interpolatedValue) : getDefaultLabel(data_2, dataIndex); }, enableTextSetter: !0 }, (isHorizontal = (baseAxis = coordSys.getBaseAxis()).isHorizontal(), isBaseInversed = baseAxis.inverse, { normal: { align: endLabelModel.get('align') || (isHorizontal ? isBaseInversed ? 'right' : 'left' : 'center'), verticalAlign: endLabelModel.get('verticalAlign') || (isHorizontal ? 'middle' : isBaseInversed ? 'top' : 'bottom') } })), polyline.textConfig.position = null); } else this._endLabel && (this._polyline.removeTextContent(), this._endLabel = null); }, LineView.prototype._endLabelOnDuring = function(percent, clipRect, data, animationRecord, valueAnimation, endLabelModel, coordSys) { var endLabel = this._endLabel, polyline = this._polyline; if (endLabel) { percent < 1 && null == animationRecord.originalX && (animationRecord.originalX = endLabel.x, animationRecord.originalY = endLabel.y); var points = data.getLayout('points'), seriesModel = data.hostModel, connectNulls = seriesModel.get('connectNulls'), precision = endLabelModel.get('precision'), distance = endLabelModel.get('distance') || 0, baseAxis = coordSys.getBaseAxis(), isHorizontal = baseAxis.isHorizontal(), isBaseInversed = baseAxis.inverse, clipShape = clipRect.shape, xOrY = isBaseInversed ? isHorizontal ? clipShape.x : clipShape.y + clipShape.height : isHorizontal ? clipShape.x + clipShape.width : clipShape.y, distanceX = (isHorizontal ? distance : 0) * (isBaseInversed ? -1 : 1), distanceY = (isHorizontal ? 0 : -distance) * (isBaseInversed ? -1 : 1), dim = isHorizontal ? 'x' : 'y', dataIndexRange = function(points, xOrY, dim) { for(var a, b, len = points.length / 2, dimIdx = 'x' === dim ? 0 : 1, prevIndex = 0, nextIndex = -1, i = 0; i < len; i++)if (!(isNaN(b = points[2 * i + dimIdx]) || isNaN(points[2 * i + 1 - dimIdx]))) { if (0 === i) { a = b; continue; } if (a <= xOrY && b >= xOrY || a >= xOrY && b <= xOrY) { nextIndex = i; break; } prevIndex = i, a = b; } return { range: [ prevIndex, nextIndex ], t: (xOrY - a) / (b - a) }; }(points, xOrY, dim), indices = dataIndexRange.range, diff = indices[1] - indices[0], value = void 0; if (diff >= 1) { if (diff > 1 && !connectNulls) { var pt = getPointAtIndex(points, indices[0]); endLabel.attr({ x: pt[0] + distanceX, y: pt[1] + distanceY }), valueAnimation && (value = seriesModel.getRawValue(indices[0])); } else { var pt = polyline.getPointOn(xOrY, dim); pt && endLabel.attr({ x: pt[0] + distanceX, y: pt[1] + distanceY }); var startValue = seriesModel.getRawValue(indices[0]), endValue = seriesModel.getRawValue(indices[1]); valueAnimation && (value = interpolateRawValues(data, precision, startValue, endValue, dataIndexRange.t)); } animationRecord.lastFrameIndex = indices[0]; } else { var idx = 1 === percent || animationRecord.lastFrameIndex > 0 ? indices[0] : 0, pt = getPointAtIndex(points, idx); valueAnimation && (value = seriesModel.getRawValue(idx)), endLabel.attr({ x: pt[0] + distanceX, y: pt[1] + distanceY }); } valueAnimation && labelInner(endLabel).setLabelText(value); } }, LineView.prototype._doUpdateAnimation = function(data, stackedOnPoints, coordSys, api, step, valueOrigin) { var polyline = this._polyline, polygon = this._polygon, seriesModel = data.hostModel, diff = function(oldData, newData, oldStackedOnPoints, newStackedOnPoints, oldCoordSys, newCoordSys, oldValueOrigin, newValueOrigin) { var diffResult, diff = (diffResult = [], newData.diff(oldData).add(function(idx) { diffResult.push({ cmd: '+', idx: idx }); }).update(function(newIdx, oldIdx) { diffResult.push({ cmd: '=', idx: oldIdx, idx1: newIdx }); }).remove(function(idx) { diffResult.push({ cmd: '-', idx: idx }); }).execute(), diffResult), currPoints = [], nextPoints = [], currStackedPoints = [], nextStackedPoints = [], status = [], sortedIndices = [], rawIndices = [], newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin); prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin); for(var oldPoints = oldData.getLayout('points') || [], newPoints = newData.getLayout('points') || [], i = 0; i < diff.length; i++){ var diffItem = diff[i], pointAdded = !0, oldIdx2 = void 0, newIdx2 = void 0; switch(diffItem.cmd){ case '=': oldIdx2 = 2 * diffItem.idx, newIdx2 = 2 * diffItem.idx1; var currentX = oldPoints[oldIdx2], currentY = oldPoints[oldIdx2 + 1], nextX = newPoints[newIdx2], nextY = newPoints[newIdx2 + 1]; (isNaN(currentX) || isNaN(currentY)) && (currentX = nextX, currentY = nextY), currPoints.push(currentX, currentY), nextPoints.push(nextX, nextY), currStackedPoints.push(oldStackedOnPoints[oldIdx2], oldStackedOnPoints[oldIdx2 + 1]), nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]), rawIndices.push(newData.getRawIndex(diffItem.idx1)); break; case '+': var newIdx = diffItem.idx, newDataDimsForPoint = newDataOldCoordInfo.dataDimsForPoint, oldPt = oldCoordSys.dataToPoint([ newData.get(newDataDimsForPoint[0], newIdx), newData.get(newDataDimsForPoint[1], newIdx) ]); newIdx2 = 2 * newIdx, currPoints.push(oldPt[0], oldPt[1]), nextPoints.push(newPoints[newIdx2], newPoints[newIdx2 + 1]); var stackedOnPoint = getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, newIdx); currStackedPoints.push(stackedOnPoint[0], stackedOnPoint[1]), nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]), rawIndices.push(newData.getRawIndex(newIdx)); break; case '-': pointAdded = !1; } pointAdded && (status.push(diffItem), sortedIndices.push(sortedIndices.length)); } sortedIndices.sort(function(a, b) { return rawIndices[a] - rawIndices[b]; }); for(var len = currPoints.length, sortedCurrPoints = createFloat32Array(len), sortedNextPoints = createFloat32Array(len), sortedCurrStackedPoints = createFloat32Array(len), sortedNextStackedPoints = createFloat32Array(len), sortedStatus = [], i = 0; i < sortedIndices.length; i++){ var idx = sortedIndices[i], i2 = 2 * i, idx2 = 2 * idx; sortedCurrPoints[i2] = currPoints[idx2], sortedCurrPoints[i2 + 1] = currPoints[idx2 + 1], sortedNextPoints[i2] = nextPoints[idx2], sortedNextPoints[i2 + 1] = nextPoints[idx2 + 1], sortedCurrStackedPoints[i2] = currStackedPoints[idx2], sortedCurrStackedPoints[i2 + 1] = currStackedPoints[idx2 + 1], sortedNextStackedPoints[i2] = nextStackedPoints[idx2], sortedNextStackedPoints[i2 + 1] = nextStackedPoints[idx2 + 1], sortedStatus[i] = status[idx]; } return { current: sortedCurrPoints, next: sortedNextPoints, stackedOnCurrent: sortedCurrStackedPoints, stackedOnNext: sortedNextStackedPoints, status: sortedStatus }; }(this._data, data, this._stackedOnPoints, stackedOnPoints, this._coordSys, coordSys, this._valueOrigin, valueOrigin), current = diff.current, stackedOnCurrent = diff.stackedOnCurrent, next = diff.next, stackedOnNext = diff.stackedOnNext; if (step && (current = turnPointsIntoStep(diff.current, coordSys, step), stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step), next = turnPointsIntoStep(diff.next, coordSys, step), stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step)), getBoundingDiff(current, next) > 3000 || polygon && getBoundingDiff(stackedOnCurrent, stackedOnNext) > 3000) { polyline.setShape({ points: next }), polygon && polygon.setShape({ points: next, stackedOnPoints: stackedOnNext }); return; } polyline.shape.__points = diff.current, polyline.shape.points = current; var target = { shape: { points: next } }; diff.current !== current && (target.shape.__points = diff.next), polyline.stopAnimation(), updateProps(polyline, target, seriesModel), polygon && (polygon.setShape({ points: current, stackedOnPoints: stackedOnCurrent }), polygon.stopAnimation(), updateProps(polygon, { shape: { stackedOnPoints: stackedOnNext } }, seriesModel), polyline.shape.points !== polygon.shape.points && (polygon.shape.points = polyline.shape.points)); for(var updatedDataInfo = [], diffStatus = diff.status, i = 0; i < diffStatus.length; i++)if ('=' === diffStatus[i].cmd) { var el = data.getItemGraphicEl(diffStatus[i].idx1); el && updatedDataInfo.push({ el: el, ptIdx: i }); } polyline.animators && polyline.animators.length && polyline.animators[0].during(function() { polygon && polygon.dirtyShape(); for(var points = polyline.shape.__points, i = 0; i < updatedDataInfo.length; i++){ var el = updatedDataInfo[i].el, offset = 2 * updatedDataInfo[i].ptIdx; el.x = points[offset], el.y = points[offset + 1], el.markRedraw(); } }); }, LineView.prototype.remove = function(ecModel) { var group = this.group, oldData = this._data; this._lineGroup.removeAll(), this._symbolDraw.remove(!0), oldData && oldData.eachItemGraphicEl(function(el, idx) { el.__temp && (group.remove(el), oldData.setItemGraphicEl(idx, null)); }), this._polyline = this._polygon = this._coordSys = this._points = this._stackedOnPoints = this._endLabel = this._data = null; }, LineView.type = 'line', LineView; }(ChartView); function pointsLayout(seriesType, forceStoreInTypedArray) { return { seriesType: seriesType, plan: createRenderPlanner(), reset: function(seriesModel) { var data = seriesModel.getData(), coordSys = seriesModel.coordinateSystem, pipelineContext = seriesModel.pipelineContext, useTypedArray = forceStoreInTypedArray || pipelineContext.large; if (coordSys) { var dims = map(coordSys.dimensions, function(dim) { return data.mapDimension(dim); }).slice(0, 2), dimLen = dims.length, stackResultDim = data.getCalculationInfo('stackResultDimension'); isDimensionStacked(data, dims[0]) && (dims[0] = stackResultDim), isDimensionStacked(data, dims[1]) && (dims[1] = stackResultDim); var dimInfo0 = data.getDimensionInfo(dims[0]), dimInfo1 = data.getDimensionInfo(dims[1]), dimIdx0 = dimInfo0 && dimInfo0.index, dimIdx1 = dimInfo1 && dimInfo1.index; return dimLen && { progress: function(params, data) { for(var segCount = params.end - params.start, points = useTypedArray && createFloat32Array(segCount * dimLen), tmpIn = [], tmpOut = [], i = params.start, offset = 0; i < params.end; i++){ var point = void 0; if (1 === dimLen) { var x = data.getByDimIdx(dimIdx0, i); point = coordSys.dataToPoint(x, null, tmpOut); } else tmpIn[0] = data.getByDimIdx(dimIdx0, i), tmpIn[1] = data.getByDimIdx(dimIdx1, i), point = coordSys.dataToPoint(tmpIn, null, tmpOut); useTypedArray ? (points[offset++] = point[0], points[offset++] = point[1]) : data.setItemLayout(i, point.slice()); } useTypedArray && data.setLayout('points', points); } }; } } }; } var samplers = { average: function(frame) { for(var sum = 0, count = 0, i = 0; i < frame.length; i++)!isNaN(frame[i]) && (sum += frame[i], count++); return 0 === count ? NaN : sum / count; }, sum: function(frame) { for(var sum = 0, i = 0; i < frame.length; i++)sum += frame[i] || 0; return sum; }, max: function(frame) { for(var max = -1 / 0, i = 0; i < frame.length; i++)frame[i] > max && (max = frame[i]); return isFinite(max) ? max : NaN; }, min: function(frame) { for(var min = 1 / 0, i = 0; i < frame.length; i++)frame[i] < min && (min = frame[i]); return isFinite(min) ? min : NaN; }, nearest: function(frame) { return frame[0]; } }, indexSampler = function(frame) { return Math.round(frame.length / 2); }; function dataSample(seriesType) { return { seriesType: seriesType, reset: function(seriesModel, ecModel, api) { var data = seriesModel.getData(), sampling = seriesModel.get('sampling'), coordSys = seriesModel.coordinateSystem, count = data.count(); if (count > 10 && 'cartesian2d' === coordSys.type && sampling) { var baseAxis = coordSys.getBaseAxis(), valueAxis = coordSys.getOtherAxis(baseAxis), extent = baseAxis.getExtent(), dpr = api.getDevicePixelRatio(), rate = Math.round(count / (Math.abs(extent[1] - extent[0]) * (dpr || 1))); if (rate > 1) { 'lttb' === sampling && seriesModel.setData(data.lttbDownSample(data.mapDimension(valueAxis.dim), 1 / rate)); var sampler = void 0; 'string' == typeof sampling ? sampler = samplers[sampling] : 'function' == typeof sampling && (sampler = sampling), sampler && seriesModel.setData(data.downSample(data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler)); } } } }; } var BaseBarSeriesModel = function(_super) { function BaseBarSeriesModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = BaseBarSeriesModel.type, _this; } return __extends(BaseBarSeriesModel, _super), BaseBarSeriesModel.prototype.getInitialData = function(option, ecModel) { return createListFromArray(this.getSource(), this, { useEncodeDefaulter: !0 }); }, BaseBarSeriesModel.prototype.getMarkerPosition = function(value) { var coordSys = this.coordinateSystem; if (coordSys) { var pt = coordSys.dataToPoint(coordSys.clampData(value)), data = this.getData(), offset = data.getLayout('offset'), size = data.getLayout('size'), offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1; return pt[offsetIndex] += offset + size / 2, pt; } return [ NaN, NaN ]; }, BaseBarSeriesModel.type = 'series.__base_bar__', BaseBarSeriesModel.defaultOption = { zlevel: 0, z: 2, coordinateSystem: 'cartesian2d', legendHoverLink: !0, barMinHeight: 0, barMinAngle: 0, large: !1, largeThreshold: 400, progressive: 3e3, progressiveChunkMode: 'mod' }, BaseBarSeriesModel; }(SeriesModel); SeriesModel.registerClass(BaseBarSeriesModel); var BarSeriesModel = function(_super) { function BarSeriesModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = BarSeriesModel.type, _this; } return __extends(BarSeriesModel, _super), BarSeriesModel.prototype.getInitialData = function() { return createListFromArray(this.getSource(), this, { useEncodeDefaulter: !0, createInvertedIndices: !!this.get('realtimeSort', !0) || null }); }, BarSeriesModel.prototype.getProgressive = function() { return !!this.get('large') && this.get('progressive'); }, BarSeriesModel.prototype.getProgressiveThreshold = function() { var progressiveThreshold = this.get('progressiveThreshold'), largeThreshold = this.get('largeThreshold'); return largeThreshold > progressiveThreshold && (progressiveThreshold = largeThreshold), progressiveThreshold; }, BarSeriesModel.prototype.brushSelector = function(dataIndex, data, selectors) { return selectors.rect(data.getItemLayout(dataIndex)); }, BarSeriesModel.type = 'series.bar', BarSeriesModel.dependencies = [ 'grid', 'polar' ], BarSeriesModel.defaultOption = inheritDefaultOption(BaseBarSeriesModel.defaultOption, { clip: !0, roundCap: !1, showBackground: !1, backgroundStyle: { color: 'rgba(180, 180, 180, 0.2)', borderColor: null, borderWidth: 0, borderType: 'solid', borderRadius: 0, shadowBlur: 0, shadowColor: null, shadowOffsetX: 0, shadowOffsetY: 0, opacity: 1 }, select: { itemStyle: { borderColor: '#212121' } }, realtimeSort: !1 }), BarSeriesModel; }(BaseBarSeriesModel), SausageShape = function() { this.cx = 0, this.cy = 0, this.r0 = 0, this.r = 0, this.startAngle = 0, this.endAngle = 2 * Math.PI, this.clockwise = !0; }, SausagePath = function(_super) { function SausagePath(opts) { var _this = _super.call(this, opts) || this; return _this.type = 'sausage', _this; } return __extends(SausagePath, _super), SausagePath.prototype.getDefaultShape = function() { return new SausageShape(); }, SausagePath.prototype.buildPath = function(ctx, shape) { var x = shape.cx, y = shape.cy, r0 = Math.max(shape.r0 || 0, 0), r = Math.max(shape.r, 0), dr = (r - r0) * 0.5, rCenter = r0 + dr, startAngle = shape.startAngle, endAngle = shape.endAngle, clockwise = shape.clockwise, unitStartX = Math.cos(startAngle), unitStartY = Math.sin(startAngle), unitEndX = Math.cos(endAngle), unitEndY = Math.sin(endAngle); (clockwise ? endAngle - startAngle < 2 * Math.PI : startAngle - endAngle < 2 * Math.PI) && (ctx.moveTo(unitStartX * r0 + x, unitStartY * r0 + y), ctx.arc(unitStartX * rCenter + x, unitStartY * rCenter + y, dr, -Math.PI + startAngle, startAngle, !clockwise)), ctx.arc(x, y, r, startAngle, endAngle, !clockwise), ctx.moveTo(unitEndX * r + x, unitEndY * r + y), ctx.arc(unitEndX * rCenter + x, unitEndY * rCenter + y, dr, endAngle - 2 * Math.PI, endAngle - Math.PI, !clockwise), 0 !== r0 && (ctx.arc(x, y, r0, endAngle, startAngle, clockwise), ctx.moveTo(unitStartX * r0 + x, unitEndY * r0 + y)), ctx.closePath(); }, SausagePath; }(Path), _eventPos = [ 0, 0 ], mathMax$6 = Math.max, mathMin$6 = Math.min, BarView = function(_super) { function BarView() { var _this = _super.call(this) || this; return _this.type = BarView.type, _this._isFirstFrame = !0, _this; } return __extends(BarView, _super), BarView.prototype.render = function(seriesModel, ecModel, api, payload) { this._model = seriesModel, this._removeOnRenderedListener(api), this._updateDrawMode(seriesModel); var coordinateSystemType = seriesModel.get('coordinateSystem'); 'cartesian2d' === coordinateSystemType || 'polar' === coordinateSystemType ? this._isLargeDraw ? this._renderLarge(seriesModel, ecModel, api) : this._renderNormal(seriesModel, ecModel, api, payload) : warn('Only cartesian2d and polar supported for bar.'); }, BarView.prototype.incrementalPrepareRender = function(seriesModel) { this._clear(), this._updateDrawMode(seriesModel), this._updateLargeClip(seriesModel); }, BarView.prototype.incrementalRender = function(params, seriesModel) { this._incrementalRenderLarge(params, seriesModel); }, BarView.prototype._updateDrawMode = function(seriesModel) { var isLargeDraw = seriesModel.pipelineContext.large; (null == this._isLargeDraw || isLargeDraw !== this._isLargeDraw) && (this._isLargeDraw = isLargeDraw, this._clear()); }, BarView.prototype._renderNormal = function(seriesModel, ecModel, api, payload) { var isHorizontalOrRadial, group = this.group, data = seriesModel.getData(), oldData = this._data, coord = seriesModel.coordinateSystem, baseAxis = coord.getBaseAxis(); 'cartesian2d' === coord.type ? isHorizontalOrRadial = baseAxis.isHorizontal() : 'polar' === coord.type && (isHorizontalOrRadial = 'angle' === baseAxis.dim); var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null, realtimeSortCfg = function(seriesModel, coordSys) { var realtimeSortOption = seriesModel.get('realtimeSort', !0), baseAxis = coordSys.getBaseAxis(); if (realtimeSortOption && ('category' !== baseAxis.type && warn('`realtimeSort` will not work because this bar series is not based on a category axis.'), 'cartesian2d' !== coordSys.type && warn('`realtimeSort` will not work because this bar series is not on cartesian2d.')), realtimeSortOption && 'category' === baseAxis.type && 'cartesian2d' === coordSys.type) return { baseAxis: baseAxis, otherAxis: coordSys.getOtherAxis(baseAxis) }; }(seriesModel, coord); realtimeSortCfg && this._enableRealtimeSort(realtimeSortCfg, data, api); var needsClip = seriesModel.get('clip', !0) || realtimeSortCfg, coordSysClipArea = function(coord, data) { var coordSysClipArea = coord.getArea && coord.getArea(); if (isCoordinateSystemType(coord, 'cartesian2d')) { var baseAxis = coord.getBaseAxis(); if ('category' !== baseAxis.type || !baseAxis.onBand) { var expandWidth = data.getLayout('bandWidth'); baseAxis.isHorizontal() ? (coordSysClipArea.x -= expandWidth, coordSysClipArea.width += 2 * expandWidth) : (coordSysClipArea.y -= expandWidth, coordSysClipArea.height += 2 * expandWidth); } } return coordSysClipArea; }(coord, data); group.removeClipPath(); var roundCap = seriesModel.get('roundCap', !0), drawBackground = seriesModel.get('showBackground', !0), backgroundModel = seriesModel.getModel('backgroundStyle'), barBorderRadius = backgroundModel.get('borderRadius') || 0, bgEls = [], oldBgEls = this._backgroundEls, isInitSort = payload && payload.isInitSort, isChangeOrder = payload && 'changeAxisOrder' === payload.type; function createBackground(dataIndex) { var isHorizontalOrRadial1, bgLayout = getLayout[coord.type](data, dataIndex), bgEl = (isHorizontalOrRadial1 = isHorizontalOrRadial, new ('polar' === coord.type ? Sector : Rect)({ shape: createBackgroundShape(isHorizontalOrRadial1, bgLayout, coord), silent: !0, z2: 0 })); return bgEl.useStyle(backgroundModel.getItemStyle()), 'cartesian2d' === coord.type && bgEl.setShape('r', barBorderRadius), bgEls[dataIndex] = bgEl, bgEl; } data.diff(oldData).add(function(dataIndex) { var itemModel = data.getItemModel(dataIndex), layout = getLayout[coord.type](data, dataIndex, itemModel); if (drawBackground && createBackground(dataIndex), data.hasValue(dataIndex)) { var isClipped = !1; needsClip && (isClipped = clip[coord.type](coordSysClipArea, layout)); var el = elementCreator[coord.type](seriesModel, data, dataIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, !1, roundCap); updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, 'polar' === coord.type), isInitSort ? el.attr({ shape: layout }) : realtimeSortCfg ? updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, dataIndex, isHorizontalOrRadial, !1, !1) : initProps(el, { shape: layout }, seriesModel, dataIndex), data.setItemGraphicEl(dataIndex, el), group.add(el), el.ignore = isClipped; } }).update(function(newIndex, oldIndex) { var itemModel = data.getItemModel(newIndex), layout = getLayout[coord.type](data, newIndex, itemModel); if (drawBackground) { var bgEl = void 0; 0 === oldBgEls.length ? bgEl = createBackground(oldIndex) : ((bgEl = oldBgEls[oldIndex]).useStyle(backgroundModel.getItemStyle()), 'cartesian2d' === coord.type && bgEl.setShape('r', barBorderRadius), bgEls[newIndex] = bgEl), updateProps(bgEl, { shape: createBackgroundShape(isHorizontalOrRadial, getLayout[coord.type](data, newIndex), coord) }, animationModel, newIndex); } var el = oldData.getItemGraphicEl(oldIndex); if (!data.hasValue(newIndex)) { group.remove(el), el = null; return; } var isClipped = !1; needsClip && (isClipped = clip[coord.type](coordSysClipArea, layout)) && group.remove(el), el || (el = elementCreator[coord.type](seriesModel, data, newIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, !!el, roundCap)), isChangeOrder || updateStyle(el, data, newIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, 'polar' === coord.type), isInitSort ? el.attr({ shape: layout }) : realtimeSortCfg ? updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, newIndex, isHorizontalOrRadial, !0, isChangeOrder) : updateProps(el, { shape: layout }, seriesModel, newIndex, null), data.setItemGraphicEl(newIndex, el), el.ignore = isClipped, group.add(el); }).remove(function(dataIndex) { var el = oldData.getItemGraphicEl(dataIndex); el && removeElementWithFadeOut(el, seriesModel, dataIndex); }).execute(); var bgGroup = this._backgroundGroup || (this._backgroundGroup = new Group()); bgGroup.removeAll(); for(var i = 0; i < bgEls.length; ++i)bgGroup.add(bgEls[i]); group.add(bgGroup), this._backgroundEls = bgEls, this._data = data; }, BarView.prototype._renderLarge = function(seriesModel, ecModel, api) { this._clear(), createLarge(seriesModel, this.group), this._updateLargeClip(seriesModel); }, BarView.prototype._incrementalRenderLarge = function(params, seriesModel) { this._removeBackground(), createLarge(seriesModel, this.group, !0); }, BarView.prototype._updateLargeClip = function(seriesModel) { var clipPath = seriesModel.get('clip', !0) ? createClipPath(seriesModel.coordinateSystem, !1, seriesModel) : null; clipPath ? this.group.setClipPath(clipPath) : this.group.removeClipPath(); }, BarView.prototype._enableRealtimeSort = function(realtimeSortCfg, data, api) { var _this = this; if (data.count()) { var baseAxis = realtimeSortCfg.baseAxis; if (this._isFirstFrame) this._dispatchInitSort(data, realtimeSortCfg, api), this._isFirstFrame = !1; else { var orderMapping_1 = function(idx) { var el = data.getItemGraphicEl(idx); if (!el) return 0; var shape = el.shape; return (baseAxis.isHorizontal() ? Math.abs(shape.height) : Math.abs(shape.width)) || 0; }; this._onRendered = function() { _this._updateSortWithinSameData(data, orderMapping_1, baseAxis, api); }, api.getZr().on('rendered', this._onRendered); } } }, BarView.prototype._dataSort = function(data, baseAxis, orderMapping) { var info = []; return data.each(data.mapDimension(baseAxis.dim), function(ordinalNumber, dataIdx) { var mappedValue = orderMapping(dataIdx); mappedValue = null == mappedValue ? NaN : mappedValue, info.push({ dataIndex: dataIdx, mappedValue: mappedValue, ordinalNumber: ordinalNumber }); }), info.sort(function(a, b) { return b.mappedValue - a.mappedValue; }), { ordinalNumbers: map(info, function(item) { return item.ordinalNumber; }) }; }, BarView.prototype._isOrderChangedWithinSameData = function(data, orderMapping, baseAxis) { for(var scale = baseAxis.scale, ordinalDataDim = data.mapDimension(baseAxis.dim), lastValue = Number.MAX_VALUE, tickNum = 0, len = scale.getOrdinalMeta().categories.length; tickNum < len; ++tickNum){ var rawIdx = data.rawIndexOf(ordinalDataDim, scale.getRawOrdinalNumber(tickNum)), value = rawIdx < 0 ? Number.MIN_VALUE : orderMapping(data.indexOfRawIndex(rawIdx)); if (value > lastValue) return !0; lastValue = value; } return !1; }, BarView.prototype._isOrderDifferentInView = function(orderInfo, baseAxis) { for(var scale = baseAxis.scale, extent = scale.getExtent(), tickNum = Math.max(0, extent[0]), tickMax = Math.min(extent[1], scale.getOrdinalMeta().categories.length - 1); tickNum <= tickMax; ++tickNum)if (orderInfo.ordinalNumbers[tickNum] !== scale.getRawOrdinalNumber(tickNum)) return !0; }, BarView.prototype._updateSortWithinSameData = function(data, orderMapping, baseAxis, api) { if (this._isOrderChangedWithinSameData(data, orderMapping, baseAxis)) { var sortInfo = this._dataSort(data, baseAxis, orderMapping); this._isOrderDifferentInView(sortInfo, baseAxis) && (this._removeOnRenderedListener(api), api.dispatchAction({ type: 'changeAxisOrder', componentType: baseAxis.dim + 'Axis', axisId: baseAxis.index, sortInfo: sortInfo })); } }, BarView.prototype._dispatchInitSort = function(data, realtimeSortCfg, api) { var baseAxis = realtimeSortCfg.baseAxis, sortResult = this._dataSort(data, baseAxis, function(dataIdx) { return data.get(data.mapDimension(realtimeSortCfg.otherAxis.dim), dataIdx); }); api.dispatchAction({ type: 'changeAxisOrder', componentType: baseAxis.dim + 'Axis', isInitSort: !0, axisId: baseAxis.index, sortInfo: sortResult, animation: { duration: 0 } }); }, BarView.prototype.remove = function(ecModel, api) { this._clear(this._model), this._removeOnRenderedListener(api); }, BarView.prototype.dispose = function(ecModel, api) { this._removeOnRenderedListener(api); }, BarView.prototype._removeOnRenderedListener = function(api) { this._onRendered && (api.getZr().off('rendered', this._onRendered), this._onRendered = null); }, BarView.prototype._clear = function(model) { var group = this.group, data = this._data; model && model.isAnimationEnabled() && data && !this._isLargeDraw ? (this._removeBackground(), this._backgroundEls = [], data.eachItemGraphicEl(function(el) { removeElementWithFadeOut(el, model, getECData(el).dataIndex); })) : group.removeAll(), this._data = null, this._isFirstFrame = !0; }, BarView.prototype._removeBackground = function() { this.group.remove(this._backgroundGroup), this._backgroundGroup = null; }, BarView.type = 'bar', BarView; }(ChartView), clip = { cartesian2d: function(coordSysBoundingRect, layout) { var signWidth = layout.width < 0 ? -1 : 1, signHeight = layout.height < 0 ? -1 : 1; signWidth < 0 && (layout.x += layout.width, layout.width = -layout.width), signHeight < 0 && (layout.y += layout.height, layout.height = -layout.height); var coordSysX2 = coordSysBoundingRect.x + coordSysBoundingRect.width, coordSysY2 = coordSysBoundingRect.y + coordSysBoundingRect.height, x = mathMax$6(layout.x, coordSysBoundingRect.x), x2 = mathMin$6(layout.x + layout.width, coordSysX2), y = mathMax$6(layout.y, coordSysBoundingRect.y), y2 = mathMin$6(layout.y + layout.height, coordSysY2), xClipped = x2 < x, yClipped = y2 < y; return layout.x = xClipped && x > coordSysX2 ? x2 : x, layout.y = yClipped && y > coordSysY2 ? y2 : y, layout.width = xClipped ? 0 : x2 - x, layout.height = yClipped ? 0 : y2 - y, signWidth < 0 && (layout.x += layout.width, layout.width = -layout.width), signHeight < 0 && (layout.y += layout.height, layout.height = -layout.height), xClipped || yClipped; }, polar: function(coordSysClipArea, layout) { var signR = layout.r0 <= layout.r ? 1 : -1; if (signR < 0) { var tmp = layout.r; layout.r = layout.r0, layout.r0 = tmp; } var r = mathMin$6(layout.r, coordSysClipArea.r), r0 = mathMax$6(layout.r0, coordSysClipArea.r0); if (layout.r = r, layout.r0 = r0, signR < 0) { var tmp = layout.r; layout.r = layout.r0, layout.r0 = tmp; } return r - r0 < 0; } }, elementCreator = { cartesian2d: function(seriesModel, data, newIndex, layout, isHorizontal, animationModel, axisModel, isUpdate, roundCap) { var rect = new Rect({ shape: extend({}, layout), z2: 1 }); return rect.__dataIndex = newIndex, rect.name = 'item', animationModel && (rect.shape[isHorizontal ? 'height' : 'width'] = 0), rect; }, polar: function(seriesModel, data, newIndex, layout, isRadial, animationModel, axisModel, isUpdate, roundCap) { var clockwise = layout.startAngle < layout.endAngle, sector = new (!isRadial && roundCap ? SausagePath : Sector)({ shape: defaults({ clockwise: clockwise }, layout), z2: 1 }); if (sector.name = 'item', animationModel) { var sectorShape = sector.shape, animateProperty = isRadial ? 'r' : 'endAngle', animateTarget = {}; sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle, animateTarget[animateProperty] = layout[animateProperty], (isUpdate ? updateProps : initProps)(sector, { shape: animateTarget }, animationModel); } return sector; } }; function updateRealtimeAnimation(realtimeSortCfg, seriesAnimationModel, el, layout, newIndex, isHorizontal, isUpdate, isChangeOrder) { var seriesTarget, axisTarget; isHorizontal ? (axisTarget = { x: layout.x, width: layout.width }, seriesTarget = { y: layout.y, height: layout.height }) : (axisTarget = { y: layout.y, height: layout.height }, seriesTarget = { x: layout.x, width: layout.width }), isChangeOrder || (isUpdate ? updateProps : initProps)(el, { shape: seriesTarget }, seriesAnimationModel, newIndex, null), (isUpdate ? updateProps : initProps)(el, { shape: axisTarget }, seriesAnimationModel ? realtimeSortCfg.baseAxis.model : null, newIndex); } var getLayout = { cartesian2d: function(data, dataIndex, itemModel) { var borderColor, layout = data.getItemLayout(dataIndex), fixedLineWidth = itemModel && (borderColor = itemModel.get([ 'itemStyle', 'borderColor' ])) && 'none' !== borderColor ? Math.min(itemModel.get([ 'itemStyle', 'borderWidth' ]) || 0, isNaN(layout.width) ? Number.MAX_VALUE : Math.abs(layout.width), isNaN(layout.height) ? Number.MAX_VALUE : Math.abs(layout.height)) : 0, signX = layout.width > 0 ? 1 : -1, signY = layout.height > 0 ? 1 : -1; return { x: layout.x + signX * fixedLineWidth / 2, y: layout.y + signY * fixedLineWidth / 2, width: layout.width - signX * fixedLineWidth, height: layout.height - signY * fixedLineWidth }; }, polar: function(data, dataIndex, itemModel) { var layout = data.getItemLayout(dataIndex); return { cx: layout.cx, cy: layout.cy, r0: layout.r0, r: layout.r, startAngle: layout.startAngle, endAngle: layout.endAngle }; } }; function updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar) { var style = data.getItemVisual(dataIndex, 'style'); isPolar || el.setShape('r', itemModel.get([ 'itemStyle', 'borderRadius' ]) || 0), el.useStyle(style); var cursorStyle = itemModel.getShallow('cursor'); if (cursorStyle && el.attr('cursor', cursorStyle), !isPolar) { var labelPositionOutside = isHorizontal ? layout.height > 0 ? 'bottom' : 'top' : layout.width > 0 ? 'left' : 'right', labelStatesModels = getLabelStatesModels(itemModel); setLabelStyle(el, labelStatesModels, { labelFetcher: seriesModel, labelDataIndex: dataIndex, defaultText: getDefaultLabel(seriesModel.getData(), dataIndex), inheritColor: style.fill, defaultOpacity: style.opacity, defaultOutsidePosition: labelPositionOutside }), setLabelValueAnimation(el.getTextContent(), labelStatesModels, seriesModel.getRawValue(dataIndex), function(value) { return getDefaultInterpolatedLabel(data, value); }); } var emphasisModel = itemModel.getModel([ 'emphasis' ]); enableHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope')), setStatesStylesFromModel(el, itemModel), null != layout.startAngle && null != layout.endAngle && layout.startAngle === layout.endAngle && (el.style.fill = 'none', el.style.stroke = 'none', each(el.states, function(state) { state.style && (state.style.fill = state.style.stroke = 'none'); })); } var LagePathShape = function() {}, LargePath = function(_super) { function LargePath(opts) { var _this = _super.call(this, opts) || this; return _this.type = 'largeBar', _this; } return __extends(LargePath, _super), LargePath.prototype.getDefaultShape = function() { return new LagePathShape(); }, LargePath.prototype.buildPath = function(ctx, shape) { for(var points = shape.points, startPoint = this.__startPoint, baseDimIdx = this.__baseDimIdx, i = 0; i < points.length; i += 2)startPoint[baseDimIdx] = points[i + baseDimIdx], ctx.moveTo(startPoint[0], startPoint[1]), ctx.lineTo(points[i], points[i + 1]); }, LargePath; }(Path); function createLarge(seriesModel, group, incremental) { var el, globalStyle, data = seriesModel.getData(), startPoint = [], baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0; startPoint[1 - baseDimIdx] = data.getLayout('valueAxisStart'); var largeDataIndices = data.getLayout('largeDataIndices'), barWidth = data.getLayout('barWidth'), backgroundModel = seriesModel.getModel('backgroundStyle'); if (seriesModel.get('showBackground', !0)) { var el1, borderColor, itemStyle, points = data.getLayout('largeBackgroundPoints'), backgroundStartPoint = []; backgroundStartPoint[1 - baseDimIdx] = data.getLayout('backgroundStart'); var bgEl = new LargePath({ shape: { points: points }, incremental: !!incremental, silent: !0, z2: 0 }); bgEl.__startPoint = backgroundStartPoint, bgEl.__baseDimIdx = baseDimIdx, bgEl.__largeDataIndices = largeDataIndices, bgEl.__barWidth = barWidth, el1 = bgEl, borderColor = backgroundModel.get('borderColor') || backgroundModel.get('color'), itemStyle = backgroundModel.getItemStyle(), el1.useStyle(itemStyle), el1.style.fill = null, el1.style.stroke = borderColor, el1.style.lineWidth = data.getLayout('barWidth'), group.add(bgEl); } var el2 = new LargePath({ shape: { points: data.getLayout('largePoints') }, incremental: !!incremental }); el2.__startPoint = startPoint, el2.__baseDimIdx = baseDimIdx, el2.__largeDataIndices = largeDataIndices, el2.__barWidth = barWidth, group.add(el2), el = el2, globalStyle = data.getVisual('style'), el.useStyle(extend({}, globalStyle)), el.style.fill = null, el.style.stroke = globalStyle.fill, el.style.lineWidth = data.getLayout('barWidth'), getECData(el2).seriesIndex = seriesModel.seriesIndex, seriesModel.get('silent') || (el2.on('mousedown', largePathUpdateDataIndex), el2.on('mousemove', largePathUpdateDataIndex)); } var largePathUpdateDataIndex = throttle(function(event) { var dataIndex = function(largePath, x, y) { var baseDimIdx = largePath.__baseDimIdx, valueDimIdx = 1 - baseDimIdx, points = largePath.shape.points, largeDataIndices = largePath.__largeDataIndices, barWidthHalf = Math.abs(largePath.__barWidth / 2), startValueVal = largePath.__startPoint[valueDimIdx]; _eventPos[0] = x, _eventPos[1] = y; for(var pointerBaseVal = _eventPos[baseDimIdx], pointerValueVal = _eventPos[1 - baseDimIdx], baseLowerBound = pointerBaseVal - barWidthHalf, baseUpperBound = pointerBaseVal + barWidthHalf, i = 0, len = points.length / 2; i < len; i++){ var ii = 2 * i, barBaseVal = points[ii + baseDimIdx], barValueVal = points[ii + valueDimIdx]; if (barBaseVal >= baseLowerBound && barBaseVal <= baseUpperBound && (startValueVal <= barValueVal ? pointerValueVal >= startValueVal && pointerValueVal <= barValueVal : pointerValueVal >= barValueVal && pointerValueVal <= startValueVal)) return largeDataIndices[i]; } return -1; }(this, event.offsetX, event.offsetY); getECData(this).dataIndex = dataIndex >= 0 ? dataIndex : null; }, 30, !1); function createBackgroundShape(isHorizontalOrRadial, layout, coord) { if (isCoordinateSystemType(coord, 'cartesian2d')) { var coordLayout = coord.getArea(); return { x: isHorizontalOrRadial ? layout.x : coordLayout.x, y: isHorizontalOrRadial ? coordLayout.y : layout.y, width: isHorizontalOrRadial ? layout.width : coordLayout.width, height: isHorizontalOrRadial ? coordLayout.height : layout.height }; } var coordLayout = coord.getArea(); return { cx: coordLayout.cx, cy: coordLayout.cy, r0: isHorizontalOrRadial ? coordLayout.r0 : layout.r0, r: isHorizontalOrRadial ? coordLayout.r : layout.r, startAngle: isHorizontalOrRadial ? layout.startAngle : 0, endAngle: isHorizontalOrRadial ? layout.endAngle : 2 * Math.PI }; } var PI2$8 = 2 * Math.PI, RADIAN = Math.PI / 180; function pieLayout(seriesType, ecModel, api) { ecModel.eachSeriesByType(seriesType, function(seriesModel) { var data = seriesModel.getData(), valueDim = data.mapDimension('value'), viewRect = getLayoutRect(seriesModel.getBoxLayoutParams(), { width: api.getWidth(), height: api.getHeight() }), center = seriesModel.get('center'), radius = seriesModel.get('radius'); isArray(radius) || (radius = [ 0, radius ]), isArray(center) || (center = [ center, center ]); var width = parsePercent$1(viewRect.width, api.getWidth()), height = parsePercent$1(viewRect.height, api.getHeight()), size = Math.min(width, height), cx = parsePercent$1(center[0], width) + viewRect.x, cy = parsePercent$1(center[1], height) + viewRect.y, r0 = parsePercent$1(radius[0], size / 2), r = parsePercent$1(radius[1], size / 2), startAngle = -seriesModel.get('startAngle') * RADIAN, minAngle = seriesModel.get('minAngle') * RADIAN, validDataCount = 0; data.each(valueDim, function(value) { !isNaN(value) && validDataCount++; }); var sum = data.getSum(valueDim), unitRadian = Math.PI / (sum || validDataCount) * 2, clockwise = seriesModel.get('clockwise'), roseType = seriesModel.get('roseType'), stillShowZeroSum = seriesModel.get('stillShowZeroSum'), extent = data.getDataExtent(valueDim); extent[0] = 0; var restAngle = PI2$8, valueSumLargerThanMinAngle = 0, currentAngle = startAngle, dir = clockwise ? 1 : -1; if (data.setLayout({ viewRect: viewRect, r: r }), data.each(valueDim, function(value, idx) { if (isNaN(value)) { data.setItemLayout(idx, { angle: NaN, startAngle: NaN, endAngle: NaN, clockwise: clockwise, cx: cx, cy: cy, r0: r0, r: roseType ? NaN : r }); return; } (angle = 'area' !== roseType ? 0 === sum && stillShowZeroSum ? unitRadian : value * unitRadian : PI2$8 / validDataCount) < minAngle ? (angle = minAngle, restAngle -= minAngle) : valueSumLargerThanMinAngle += value; var angle, endAngle = currentAngle + dir * angle; data.setItemLayout(idx, { angle: angle, startAngle: currentAngle, endAngle: endAngle, clockwise: clockwise, cx: cx, cy: cy, r0: r0, r: roseType ? linearMap(value, extent, [ r0, r ]) : r }), currentAngle = endAngle; }), restAngle < PI2$8 && validDataCount) { if (restAngle <= 1e-3) { var angle_1 = PI2$8 / validDataCount; data.each(valueDim, function(value, idx) { if (!isNaN(value)) { var layout_1 = data.getItemLayout(idx); layout_1.angle = angle_1, layout_1.startAngle = startAngle + dir * idx * angle_1, layout_1.endAngle = startAngle + dir * (idx + 1) * angle_1; } }); } else unitRadian = restAngle / valueSumLargerThanMinAngle, currentAngle = startAngle, data.each(valueDim, function(value, idx) { if (!isNaN(value)) { var layout_2 = data.getItemLayout(idx), angle = layout_2.angle === minAngle ? minAngle : value * unitRadian; layout_2.startAngle = currentAngle, layout_2.endAngle = currentAngle + dir * angle, currentAngle += dir * angle; } }); } }); } function dataFilter(seriesType) { return { seriesType: seriesType, reset: function(seriesModel, ecModel) { var legendModels = ecModel.findComponents({ mainType: 'legend' }); if (legendModels && legendModels.length) { var data = seriesModel.getData(); data.filterSelf(function(idx) { for(var name = data.getName(idx), i = 0; i < legendModels.length; i++)if (!legendModels[i].isSelected(name)) return !1; return !0; }); } } }; } var RADIAN$1 = Math.PI / 180; function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight, viewLeft, viewTop, farthestX) { if (!(list.length < 2)) { for(var len = list.length, i = 0; i < len; i++)if ('outer' === list[i].position && 'labelLine' === list[i].labelAlignTo) { var dx = list[i].label.x - farthestX; list[i].linePoints[1][0] += dx, list[i].label.x = farthestX; } shiftLayoutOnY(list, viewTop, viewTop + viewHeight) && function(items) { for(var topSemi = { list: [], maxY: 0 }, bottomSemi = { list: [], maxY: 0 }, i = 0; i < items.length; i++)if ('none' === items[i].labelAlignTo) { var item = items[i], semi = item.label.y > cy ? bottomSemi : topSemi, dy = Math.abs(item.label.y - cy); if (dy > semi.maxY) { var dx = item.label.x - cx - item.len2 * dir, rA = r + item.len, rB = Math.abs(dx) < rA ? Math.sqrt(dy * dy / (1 - dx * dx / rA / rA)) : rA; semi.rB = rB, semi.maxY = dy; } semi.list.push(item); } recalculateXOnSemiToAlignOnEllipseCurve(topSemi), recalculateXOnSemiToAlignOnEllipseCurve(bottomSemi); }(list); } function recalculateXOnSemiToAlignOnEllipseCurve(semi) { for(var rB = semi.rB, rB2 = rB * rB, i = 0; i < semi.list.length; i++){ var item = semi.list[i], dy = Math.abs(item.label.y - cy), rA = r + item.len, dx = Math.sqrt((1 - Math.abs(dy * dy / rB2)) * (rA * rA)); item.label.x = cx + (dx + item.len2) * dir; } } } function isPositionCenter(sectorShape) { return 'center' === sectorShape.position; } function getSectorCornerRadius(model, shape) { var cornerRadius = model.get('borderRadius'); return null == cornerRadius ? null : (isArray(cornerRadius) || (cornerRadius = [ cornerRadius, cornerRadius ]), { innerCornerRadius: parsePercent(cornerRadius[0], shape.r0), cornerRadius: parsePercent(cornerRadius[1], shape.r) }); } var PiePiece = function(_super) { function PiePiece(data, idx, startAngle) { var _this = _super.call(this) || this; _this.z2 = 2; var text = new ZRText(); return _this.setTextContent(text), _this.updateData(data, idx, startAngle, !0), _this; } return __extends(PiePiece, _super), PiePiece.prototype.updateData = function(data, idx, startAngle, firstCreate) { var sector = this, seriesModel = data.hostModel, itemModel = data.getItemModel(idx), emphasisModel = itemModel.getModel('emphasis'), layout = data.getItemLayout(idx), sectorShape = extend(getSectorCornerRadius(itemModel.getModel('itemStyle'), layout) || {}, layout); if (isNaN(sectorShape.startAngle)) { sector.setShape(sectorShape); return; } firstCreate ? (sector.setShape(sectorShape), 'scale' === seriesModel.getShallow('animationType') ? (sector.shape.r = layout.r0, initProps(sector, { shape: { r: layout.r } }, seriesModel, idx)) : null != startAngle ? (sector.setShape({ startAngle: startAngle, endAngle: startAngle }), initProps(sector, { shape: { startAngle: layout.startAngle, endAngle: layout.endAngle } }, seriesModel, idx)) : (sector.shape.endAngle = layout.startAngle, updateProps(sector, { shape: { endAngle: layout.endAngle } }, seriesModel, idx))) : updateProps(sector, { shape: sectorShape }, seriesModel, idx), sector.useStyle(data.getItemVisual(idx, 'style')), setStatesStylesFromModel(sector, itemModel); var midAngle = (layout.startAngle + layout.endAngle) / 2, offset = seriesModel.get('selectedOffset'), dx = Math.cos(midAngle) * offset, dy = Math.sin(midAngle) * offset, cursorStyle = itemModel.getShallow('cursor'); cursorStyle && sector.attr('cursor', cursorStyle), this._updateLabel(seriesModel, data, idx), sector.ensureState('emphasis').shape = __assign({ r: layout.r + (emphasisModel.get('scale') && emphasisModel.get('scaleSize') || 0) }, getSectorCornerRadius(emphasisModel.getModel('itemStyle'), layout)), extend(sector.ensureState('select'), { x: dx, y: dy, shape: getSectorCornerRadius(itemModel.getModel([ 'select', 'itemStyle' ]), layout) }), extend(sector.ensureState('blur'), { shape: getSectorCornerRadius(itemModel.getModel([ 'blur', 'itemStyle' ]), layout) }); var labelLine = sector.getTextGuideLine(), labelText = sector.getTextContent(); labelLine && extend(labelLine.ensureState('select'), { x: dx, y: dy }), extend(labelText.ensureState('select'), { x: dx, y: dy }), enableHoverEmphasis(this, emphasisModel.get('focus'), emphasisModel.get('blurScope')); }, PiePiece.prototype._updateLabel = function(seriesModel, data, idx) { var itemModel = data.getItemModel(idx), labelLineModel = itemModel.getModel('labelLine'), style = data.getItemVisual(idx, 'style'), visualColor = style && style.fill, visualOpacity = style && style.opacity; setLabelStyle(this, getLabelStatesModels(itemModel), { labelFetcher: data.hostModel, labelDataIndex: idx, inheritColor: visualColor, defaultOpacity: visualOpacity, defaultText: seriesModel.getFormattedLabel(idx, 'normal') || data.getName(idx) }); var labelText = this.getTextContent(); this.setTextConfig({ position: null, rotation: null }), labelText.attr({ z2: 10 }); var labelPosition = seriesModel.get([ 'label', 'position' ]); if ('outside' !== labelPosition && 'outer' !== labelPosition) this.removeTextGuideLine(); else { var polyline = this.getTextGuideLine(); polyline || (polyline = new Polyline(), this.setTextGuideLine(polyline)), setLabelLineStyle(this, getLabelLineStatesModels(itemModel), { stroke: visualColor, opacity: retrieve3(labelLineModel.get([ 'lineStyle', 'opacity' ]), visualOpacity, 1) }); } }, PiePiece; }(Sector), PieView = function(_super) { function PieView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.ignoreLabelLineUpdate = !0, _this; } return __extends(PieView, _super), PieView.prototype.init = function() { var sectorGroup = new Group(); this._sectorGroup = sectorGroup; }, PieView.prototype.render = function(seriesModel, ecModel, api, payload) { var startAngle, data = seriesModel.getData(), oldData = this._data, group = this.group; if (!oldData && data.count() > 0) { for(var shape = data.getItemLayout(0), s = 1; isNaN(shape && shape.startAngle) && s < data.count(); ++s)shape = data.getItemLayout(s); shape && (startAngle = shape.startAngle); } data.diff(oldData).add(function(idx) { var piePiece = new PiePiece(data, idx, startAngle); data.setItemGraphicEl(idx, piePiece), group.add(piePiece); }).update(function(newIdx, oldIdx) { var piePiece = oldData.getItemGraphicEl(oldIdx); piePiece.updateData(data, newIdx, startAngle), piePiece.off('click'), group.add(piePiece), data.setItemGraphicEl(newIdx, piePiece); }).remove(function(idx) { removeElementWithFadeOut(oldData.getItemGraphicEl(idx), seriesModel, idx); }).execute(), function(seriesModel) { var cx, cy, data = seriesModel.getData(), labelLayoutList = [], hasLabelRotate = !1, minShowLabelRadian = (seriesModel.get('minShowLabelAngle') || 0) * RADIAN$1, viewRect = data.getLayout('viewRect'), r = data.getLayout('r'), viewWidth = viewRect.width, viewLeft = viewRect.x, viewTop = viewRect.y, viewHeight = viewRect.height; function setNotShow(el) { el.ignore = !0; } data.each(function(idx) { var textX, textY, linePoints, textAlign, labelRotate, sector = data.getItemGraphicEl(idx), sectorShape = sector.shape, label = sector.getTextContent(), labelLine = sector.getTextGuideLine(), itemModel = data.getItemModel(idx), labelModel = itemModel.getModel('label'), labelPosition = labelModel.get('position') || itemModel.get([ 'emphasis', 'label', 'position' ]), labelDistance = labelModel.get('distanceToLabelLine'), labelAlignTo = labelModel.get('alignTo'), edgeDistance = parsePercent$1(labelModel.get('edgeDistance'), viewWidth), bleedMargin = labelModel.get('bleedMargin'), labelLineModel = itemModel.getModel('labelLine'), labelLineLen = labelLineModel.get('length'); labelLineLen = parsePercent$1(labelLineLen, viewWidth); var labelLineLen2 = labelLineModel.get('length2'); if (labelLineLen2 = parsePercent$1(labelLineLen2, viewWidth), Math.abs(sectorShape.endAngle - sectorShape.startAngle) < minShowLabelRadian) { each(label.states, setNotShow), label.ignore = !0; return; } if (function(label) { if (!label.ignore) return !0; for(var key in label.states)if (!1 === label.states[key].ignore) return !0; return !1; }(label)) { var midAngle = (sectorShape.startAngle + sectorShape.endAngle) / 2, nx = Math.cos(midAngle), ny = Math.sin(midAngle); cx = sectorShape.cx, cy = sectorShape.cy; var isLabelInside = 'inside' === labelPosition || 'inner' === labelPosition; if ('center' === labelPosition) textX = sectorShape.cx, textY = sectorShape.cy, textAlign = 'center'; else { var x1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * nx : sectorShape.r * nx) + cx, y1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * ny : sectorShape.r * ny) + cy; if (textX = x1 + 3 * nx, textY = y1 + 3 * ny, !isLabelInside) { var x2 = x1 + nx * (labelLineLen + r - sectorShape.r), y2 = y1 + ny * (labelLineLen + r - sectorShape.r), x3 = x2 + (nx < 0 ? -1 : 1) * labelLineLen2; textX = 'edge' === labelAlignTo ? nx < 0 ? viewLeft + edgeDistance : viewLeft + viewWidth - edgeDistance : x3 + (nx < 0 ? -labelDistance : labelDistance), textY = y2, linePoints = [ [ x1, y1 ], [ x2, y2 ], [ x3, y2 ] ]; } textAlign = isLabelInside ? 'center' : 'edge' === labelAlignTo ? nx > 0 ? 'right' : 'left' : nx > 0 ? 'left' : 'right'; } var rotate = labelModel.get('rotate'); if (hasLabelRotate = !!(labelRotate = 'number' == typeof rotate ? rotate * (Math.PI / 180) : rotate ? nx < 0 ? -midAngle + Math.PI : -midAngle : 0), label.x = textX, label.y = textY, label.rotation = labelRotate, label.setStyle({ verticalAlign: 'middle' }), isLabelInside) { label.setStyle({ align: textAlign }); var selectState = label.states.select; selectState && (selectState.x += label.x, selectState.y += label.y); } else { var textRect = label.getBoundingRect().clone(); textRect.applyTransform(label.getComputedTransform()); var margin = (label.style.margin || 0) + 2.1; textRect.y -= margin / 2, textRect.height += margin, labelLayoutList.push({ label: label, labelLine: labelLine, position: labelPosition, len: labelLineLen, len2: labelLineLen2, minTurnAngle: labelLineModel.get('minTurnAngle'), maxSurfaceAngle: labelLineModel.get('maxSurfaceAngle'), surfaceNormal: new Point(nx, ny), linePoints: linePoints, textAlign: textAlign, labelDistance: labelDistance, labelAlignTo: labelAlignTo, edgeDistance: edgeDistance, bleedMargin: bleedMargin, rect: textRect }); } sector.setTextConfig({ inside: isLabelInside }); } }), !hasLabelRotate && seriesModel.get('avoidLabelOverlap') && function(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop) { for(var leftList = [], rightList = [], leftmostX = Number.MAX_VALUE, rightmostX = -Number.MAX_VALUE, i = 0; i < labelLayoutList.length; i++){ var label = labelLayoutList[i].label; isPositionCenter(labelLayoutList[i]) || (label.x < cx ? (leftmostX = Math.min(leftmostX, label.x), leftList.push(labelLayoutList[i])) : (rightmostX = Math.max(rightmostX, label.x), rightList.push(labelLayoutList[i]))); } adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight, viewLeft, viewTop, rightmostX), adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight, viewLeft, viewTop, leftmostX); for(var i = 0; i < labelLayoutList.length; i++){ var layout = labelLayoutList[i], label = layout.label; if (!isPositionCenter(layout)) { var linePoints = layout.linePoints; if (linePoints) { var isAlignToEdge = 'edge' === layout.labelAlignTo, realTextWidth = layout.rect.width, targetTextWidth = void 0; (targetTextWidth = isAlignToEdge ? label.x < cx ? linePoints[2][0] - layout.labelDistance - viewLeft - layout.edgeDistance : viewLeft + viewWidth - layout.edgeDistance - linePoints[2][0] - layout.labelDistance : label.x < cx ? label.x - viewLeft - layout.bleedMargin : viewLeft + viewWidth - label.x - layout.bleedMargin) < layout.rect.width && (layout.label.style.width = targetTextWidth, 'edge' === layout.labelAlignTo && (realTextWidth = targetTextWidth)); var dist = linePoints[1][0] - linePoints[2][0]; isAlignToEdge ? label.x < cx ? linePoints[2][0] = viewLeft + layout.edgeDistance + realTextWidth + layout.labelDistance : linePoints[2][0] = viewLeft + viewWidth - layout.edgeDistance - realTextWidth - layout.labelDistance : (label.x < cx ? linePoints[2][0] = label.x + layout.labelDistance : linePoints[2][0] = label.x - layout.labelDistance, linePoints[1][0] = linePoints[2][0] + dist), linePoints[1][1] = linePoints[2][1] = label.y; } } } }(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop); for(var i = 0; i < labelLayoutList.length; i++){ var layout = labelLayoutList[i], label = layout.label, labelLine = layout.labelLine, notShowLabel = isNaN(label.x) || isNaN(label.y); if (label) { label.setStyle({ align: layout.textAlign }), notShowLabel && (each(label.states, setNotShow), label.ignore = !0); var selectState = label.states.select; selectState && (selectState.x += label.x, selectState.y += label.y); } if (labelLine) { var linePoints = layout.linePoints; notShowLabel || !linePoints ? (each(labelLine.states, setNotShow), labelLine.ignore = !0) : (limitTurnAngle(linePoints, layout.minTurnAngle), function(linePoints, surfaceNormal, maxSurfaceAngle) { if (maxSurfaceAngle <= 180 && maxSurfaceAngle > 0) { maxSurfaceAngle = maxSurfaceAngle / 180 * Math.PI, pt0.fromArray(linePoints[0]), pt1.fromArray(linePoints[1]), pt2.fromArray(linePoints[2]), Point.sub(dir, pt1, pt0), Point.sub(dir2, pt2, pt1); var len1 = dir.len(), len2 = dir2.len(); if (!(len1 < 1e-3) && !(len2 < 1e-3) && (dir.scale(1 / len1), dir2.scale(1 / len2), dir.dot(surfaceNormal) < Math.cos(maxSurfaceAngle))) { var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, !1); tmpProjPoint.fromArray(tmpArr); var HALF_PI = Math.PI / 2, newAngle = HALF_PI + Math.acos(dir2.dot(surfaceNormal)) - maxSurfaceAngle; if (newAngle >= HALF_PI) Point.copy(tmpProjPoint, pt2); else { tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI / 2 - newAngle)); var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y); if (isNaN(t)) return; t < 0 ? Point.copy(tmpProjPoint, pt1) : t > 1 && Point.copy(tmpProjPoint, pt2); } tmpProjPoint.toArray(linePoints[1]); } } }(linePoints, layout.surfaceNormal, layout.maxSurfaceAngle), labelLine.setShape({ points: linePoints }), label.__hostTarget.textGuideLineConfig = { anchor: new Point(linePoints[0][0], linePoints[0][1]) }); } } }(seriesModel), 'expansion' !== seriesModel.get('animationTypeUpdate') && (this._data = data); }, PieView.prototype.dispose = function() {}, PieView.prototype.containPoint = function(point, seriesModel) { var itemLayout = seriesModel.getData().getItemLayout(0); if (itemLayout) { var dx = point[0] - itemLayout.cx, dy = point[1] - itemLayout.cy, radius = Math.sqrt(dx * dx + dy * dy); return radius <= itemLayout.r && radius >= itemLayout.r0; } }, PieView.type = 'pie', PieView; }(ChartView); function createListSimply(seriesModel, opt, nameList) { opt = isArray(opt) && { coordDimensions: opt } || extend({}, opt); var source = seriesModel.getSource(), dimensionsInfo = createDimensions(source, opt), list = new List(dimensionsInfo, seriesModel); return list.initData(source, nameList), list; } var LegendVisualProvider = function() { function LegendVisualProvider(getDataWithEncodedVisual, getRawData) { this._getDataWithEncodedVisual = getDataWithEncodedVisual, this._getRawData = getRawData; } return LegendVisualProvider.prototype.getAllNames = function() { var rawData = this._getRawData(); return rawData.mapArray(rawData.getName); }, LegendVisualProvider.prototype.containName = function(name) { return this._getRawData().indexOfName(name) >= 0; }, LegendVisualProvider.prototype.indexOfName = function(name) { return this._getDataWithEncodedVisual().indexOfName(name); }, LegendVisualProvider.prototype.getItemVisual = function(dataIndex, key) { return this._getDataWithEncodedVisual().getItemVisual(dataIndex, key); }, LegendVisualProvider; }(), PieSeriesModel = function(_super) { function PieSeriesModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.useColorPaletteOnData = !0, _this; } return __extends(PieSeriesModel, _super), PieSeriesModel.prototype.init = function(option) { _super.prototype.init.apply(this, arguments), this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this)), this._defaultLabelLine(option); }, PieSeriesModel.prototype.mergeOption = function() { _super.prototype.mergeOption.apply(this, arguments); }, PieSeriesModel.prototype.getInitialData = function() { return createListSimply(this, { coordDimensions: [ 'value' ], encodeDefaulter: curry(makeSeriesEncodeForNameBased, this) }); }, PieSeriesModel.prototype.getDataParams = function(dataIndex) { var data = this.getData(), params = _super.prototype.getDataParams.call(this, dataIndex), valueList = []; return data.each(data.mapDimension('value'), function(value) { valueList.push(value); }), params.percent = getPercentWithPrecision(valueList, dataIndex, data.hostModel.get('percentPrecision')), params.$vars.push('percent'), params; }, PieSeriesModel.prototype._defaultLabelLine = function(option) { defaultEmphasis(option, 'labelLine', [ 'show' ]); var labelLineNormalOpt = option.labelLine, labelLineEmphasisOpt = option.emphasis.labelLine; labelLineNormalOpt.show = labelLineNormalOpt.show && option.label.show, labelLineEmphasisOpt.show = labelLineEmphasisOpt.show && option.emphasis.label.show; }, PieSeriesModel.type = 'series.pie', PieSeriesModel.defaultOption = { zlevel: 0, z: 2, legendHoverLink: !0, center: [ '50%', '50%' ], radius: [ 0, '75%' ], clockwise: !0, startAngle: 90, minAngle: 0, minShowLabelAngle: 0, selectedOffset: 10, percentPrecision: 2, stillShowZeroSum: !0, left: 0, top: 0, right: 0, bottom: 0, width: null, height: null, label: { rotate: 0, show: !0, overflow: 'truncate', position: 'outer', alignTo: 'none', edgeDistance: '25%', bleedMargin: 10, distanceToLabelLine: 5 }, labelLine: { show: !0, length: 15, length2: 15, smooth: !1, minTurnAngle: 90, maxSurfaceAngle: 90, lineStyle: { width: 1, type: 'solid' } }, itemStyle: { borderWidth: 1 }, labelLayout: { hideOverlap: !0 }, emphasis: { scale: !0, scaleSize: 5 }, avoidLabelOverlap: !0, animationType: 'expansion', animationDuration: 1000, animationTypeUpdate: 'transition', animationEasingUpdate: 'cubicInOut', animationDurationUpdate: 500, animationEasing: 'cubicInOut' }, PieSeriesModel; }(SeriesModel), ScatterSeriesModel = function(_super) { function ScatterSeriesModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = ScatterSeriesModel.type, _this.hasSymbolVisual = !0, _this; } return __extends(ScatterSeriesModel, _super), ScatterSeriesModel.prototype.getInitialData = function(option, ecModel) { return createListFromArray(this.getSource(), this, { useEncodeDefaulter: !0 }); }, ScatterSeriesModel.prototype.getProgressive = function() { var progressive = this.option.progressive; return null == progressive ? this.option.large ? 5e3 : this.get('progressive') : progressive; }, ScatterSeriesModel.prototype.getProgressiveThreshold = function() { var progressiveThreshold = this.option.progressiveThreshold; return null == progressiveThreshold ? this.option.large ? 1e4 : this.get('progressiveThreshold') : progressiveThreshold; }, ScatterSeriesModel.prototype.brushSelector = function(dataIndex, data, selectors) { return selectors.point(data.getItemLayout(dataIndex)); }, ScatterSeriesModel.type = 'series.scatter', ScatterSeriesModel.dependencies = [ 'grid', 'polar', 'geo', 'singleAxis', 'calendar' ], ScatterSeriesModel.defaultOption = { coordinateSystem: 'cartesian2d', zlevel: 0, z: 2, legendHoverLink: !0, symbolSize: 10, large: !1, largeThreshold: 2000, itemStyle: { opacity: 0.8 }, emphasis: { scale: !0 }, clip: !0, select: { itemStyle: { borderColor: '#212121' } } }, ScatterSeriesModel; }(SeriesModel), LargeSymbolPathShape = function() {}, LargeSymbolPath = function(_super) { function LargeSymbolPath(opts) { return _super.call(this, opts) || this; } return __extends(LargeSymbolPath, _super), LargeSymbolPath.prototype.getDefaultShape = function() { return new LargeSymbolPathShape(); }, LargeSymbolPath.prototype.buildPath = function(path, shape) { var points = shape.points, size = shape.size, symbolProxy = this.symbolProxy, symbolProxyShape = symbolProxy.shape, ctx = path.getContext ? path.getContext() : path; if (ctx && size[0] < 4) { this._ctx = ctx; return; } this._ctx = null; for(var i = 0; i < points.length;){ var x = points[i++], y = points[i++]; !(isNaN(x) || isNaN(y)) && (!this.softClipShape || this.softClipShape.contain(x, y)) && (symbolProxyShape.x = x - size[0] / 2, symbolProxyShape.y = y - size[1] / 2, symbolProxyShape.width = size[0], symbolProxyShape.height = size[1], symbolProxy.buildPath(path, symbolProxyShape, !0)); } }, LargeSymbolPath.prototype.afterBrush = function() { var shape = this.shape, points = shape.points, size = shape.size, ctx = this._ctx; if (ctx) for(var i = 0; i < points.length;){ var x = points[i++], y = points[i++]; !(isNaN(x) || isNaN(y)) && (!this.softClipShape || this.softClipShape.contain(x, y)) && ctx.fillRect(x - size[0] / 2, y - size[1] / 2, size[0], size[1]); } }, LargeSymbolPath.prototype.findDataIndex = function(x, y) { for(var shape = this.shape, points = shape.points, size = shape.size, w = Math.max(size[0], 4), h = Math.max(size[1], 4), idx = points.length / 2 - 1; idx >= 0; idx--){ var i = 2 * idx, x0 = points[i] - w / 2, y0 = points[i + 1] - h / 2; if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) return idx; } return -1; }, LargeSymbolPath; }(Path), LargeSymbolDraw = function() { function LargeSymbolDraw() { this.group = new Group(); } return LargeSymbolDraw.prototype.isPersistent = function() { return !this._incremental; }, LargeSymbolDraw.prototype.updateData = function(data, opt) { this.group.removeAll(); var symbolEl = new LargeSymbolPath({ rectHover: !0, cursor: 'default' }); symbolEl.setShape({ points: data.getLayout('points') }), this._setCommon(symbolEl, data, !1, opt), this.group.add(symbolEl), this._incremental = null; }, LargeSymbolDraw.prototype.updateLayout = function(data) { if (!this._incremental) { var points = data.getLayout('points'); this.group.eachChild(function(child) { if (null != child.startIndex) { var len = (child.endIndex - child.startIndex) * 2, byteOffset = 8 * child.startIndex; points = new Float32Array(points.buffer, byteOffset, len); } child.setShape('points', points); }); } }, LargeSymbolDraw.prototype.incrementalPrepareUpdate = function(data) { this.group.removeAll(), this._clearIncremental(), data.count() > 2e6 ? (this._incremental || (this._incremental = new IncrementalDisplayable({ silent: !0 })), this.group.add(this._incremental)) : this._incremental = null; }, LargeSymbolDraw.prototype.incrementalUpdate = function(taskParams, data, opt) { var symbolEl; this._incremental ? (symbolEl = new LargeSymbolPath(), this._incremental.addDisplayable(symbolEl, !0)) : ((symbolEl = new LargeSymbolPath({ rectHover: !0, cursor: 'default', startIndex: taskParams.start, endIndex: taskParams.end })).incremental = !0, this.group.add(symbolEl)), symbolEl.setShape({ points: data.getLayout('points') }), this._setCommon(symbolEl, data, !!this._incremental, opt); }, LargeSymbolDraw.prototype._setCommon = function(symbolEl, data, isIncremental, opt) { var hostModel = data.hostModel; opt = opt || {}; var size = data.getVisual('symbolSize'); symbolEl.setShape('size', size instanceof Array ? size : [ size, size ]), symbolEl.softClipShape = opt.clipShape || null, symbolEl.symbolProxy = createSymbol(data.getVisual('symbol'), 0, 0, 0, 0), symbolEl.setColor = symbolEl.symbolProxy.setColor; var extrudeShadow = symbolEl.shape.size[0] < 4; symbolEl.useStyle(hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? [ 'color', 'shadowBlur', 'shadowColor' ] : [ 'color' ])); var globalStyle = data.getVisual('style'), visualColor = globalStyle && globalStyle.fill; if (visualColor && symbolEl.setColor(visualColor), !isIncremental) { var ecData_1 = getECData(symbolEl); ecData_1.seriesIndex = hostModel.seriesIndex, symbolEl.on('mousemove', function(e) { ecData_1.dataIndex = null; var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY); dataIndex >= 0 && (ecData_1.dataIndex = dataIndex + (symbolEl.startIndex || 0)); }); } }, LargeSymbolDraw.prototype.remove = function() { this._clearIncremental(), this._incremental = null, this.group.removeAll(); }, LargeSymbolDraw.prototype._clearIncremental = function() { var incremental = this._incremental; incremental && incremental.clearDisplaybles(); }, LargeSymbolDraw; }(), ScatterView = function(_super) { function ScatterView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = ScatterView.type, _this; } return __extends(ScatterView, _super), ScatterView.prototype.render = function(seriesModel, ecModel, api) { var data = seriesModel.getData(); this._updateSymbolDraw(data, seriesModel).updateData(data, { clipShape: this._getClipShape(seriesModel) }), this._finished = !0; }, ScatterView.prototype.incrementalPrepareRender = function(seriesModel, ecModel, api) { var data = seriesModel.getData(); this._updateSymbolDraw(data, seriesModel).incrementalPrepareUpdate(data), this._finished = !1; }, ScatterView.prototype.incrementalRender = function(taskParams, seriesModel, ecModel) { this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData(), { clipShape: this._getClipShape(seriesModel) }), this._finished = taskParams.end === seriesModel.getData().count(); }, ScatterView.prototype.updateTransform = function(seriesModel, ecModel, api) { var data = seriesModel.getData(); if (this.group.dirty(), !this._finished || data.count() > 1e4 || !this._symbolDraw.isPersistent()) return { update: !0 }; var res = pointsLayout('').reset(seriesModel, ecModel, api); res.progress && res.progress({ start: 0, end: data.count(), count: data.count() }, data), this._symbolDraw.updateLayout(data); }, ScatterView.prototype._getClipShape = function(seriesModel) { var coordSys = seriesModel.coordinateSystem, clipArea = coordSys && coordSys.getArea && coordSys.getArea(); return seriesModel.get('clip', !0) ? clipArea : null; }, ScatterView.prototype._updateSymbolDraw = function(data, seriesModel) { var symbolDraw = this._symbolDraw, isLargeDraw = seriesModel.pipelineContext.large; return symbolDraw && isLargeDraw === this._isLargeDraw || (symbolDraw && symbolDraw.remove(), symbolDraw = this._symbolDraw = isLargeDraw ? new LargeSymbolDraw() : new SymbolDraw(), this._isLargeDraw = isLargeDraw, this.group.removeAll()), this.group.add(symbolDraw.group), symbolDraw; }, ScatterView.prototype.remove = function(ecModel, api) { this._symbolDraw && this._symbolDraw.remove(!0), this._symbolDraw = null; }, ScatterView.prototype.dispose = function() {}, ScatterView.type = 'scatter', ScatterView; }(ChartView), GridModel = function(_super) { function GridModel() { return null !== _super && _super.apply(this, arguments) || this; } return __extends(GridModel, _super), GridModel.type = 'grid', GridModel.dependencies = [ 'xAxis', 'yAxis' ], GridModel.layoutMode = 'box', GridModel.defaultOption = { show: !1, zlevel: 0, z: 0, left: '10%', top: 60, right: '10%', bottom: 70, containLabel: !1, backgroundColor: 'rgba(0,0,0,0)', borderWidth: 1, borderColor: '#ccc' }, GridModel; }(ComponentModel), CartesianAxisModel = function(_super) { function CartesianAxisModel() { return null !== _super && _super.apply(this, arguments) || this; } return __extends(CartesianAxisModel, _super), CartesianAxisModel.prototype.getCoordSysModel = function() { return this.getReferringComponents('grid', SINGLE_REFERRING).models[0]; }, CartesianAxisModel.type = 'cartesian2dAxis', CartesianAxisModel; }(ComponentModel); mixin(CartesianAxisModel, AxisModelCommonMixin); var defaultOption = { show: !0, zlevel: 0, z: 0, inverse: !1, name: '', nameLocation: 'end', nameRotate: null, nameTruncate: { maxWidth: null, ellipsis: '...', placeholder: '.' }, nameTextStyle: {}, nameGap: 15, silent: !1, triggerEvent: !1, tooltip: { show: !1 }, axisPointer: {}, axisLine: { show: !0, onZero: !0, onZeroAxisIndex: null, lineStyle: { color: '#6E7079', width: 1, type: 'solid' }, symbol: [ 'none', 'none' ], symbolSize: [ 10, 15 ] }, axisTick: { show: !0, inside: !1, length: 5, lineStyle: { width: 1 } }, axisLabel: { show: !0, inside: !1, rotate: 0, showMinLabel: null, showMaxLabel: null, margin: 8, fontSize: 12 }, splitLine: { show: !0, lineStyle: { color: [ '#E0E6F1' ], width: 1, type: 'solid' } }, splitArea: { show: !1, areaStyle: { color: [ 'rgba(250,250,250,0.2)', 'rgba(210,219,238,0.2)' ] } } }, categoryAxis = merge({ boundaryGap: !0, deduplication: null, splitLine: { show: !1 }, axisTick: { alignWithLabel: !1, interval: 'auto' }, axisLabel: { interval: 'auto' } }, defaultOption), valueAxis = merge({ boundaryGap: [ 0, 0 ], axisLine: { show: 'auto' }, axisTick: { show: 'auto' }, splitNumber: 5, minorTick: { show: !1, splitNumber: 5, length: 3, lineStyle: {} }, minorSplitLine: { show: !1, lineStyle: { color: '#F4F7FD', width: 1 } } }, defaultOption), timeAxis = merge({ scale: !0, splitNumber: 6, axisLabel: { showMinLabel: !1, showMaxLabel: !1, rich: { primary: { fontWeight: 'bold' } } }, splitLine: { show: !1 } }, valueAxis), logAxis = defaults({ scale: !0, logBase: 10 }, valueAxis), axisDefault = { category: categoryAxis, value: valueAxis, time: timeAxis, log: logAxis }, AXIS_TYPES = { value: 1, category: 1, time: 1, log: 1 }; function axisModelCreator(registers, axisName, BaseAxisModelClass, extraDefaultOption) { each(AXIS_TYPES, function(v, axisType) { var defaultOption = merge(merge({}, axisDefault[axisType], !0), extraDefaultOption, !0), AxisModel = function(_super) { function AxisModel() { for(var args = [], _i = 0; _i < arguments.length; _i++)args[_i] = arguments[_i]; var _this = _super.apply(this, args) || this; return _this.type = axisName + 'Axis.' + axisType, _this; } return __extends(AxisModel, _super), AxisModel.prototype.mergeDefaultAndTheme = function(option, ecModel) { var layoutMode = fetchLayoutMode(this), inputPositionParams = layoutMode ? getLayoutParams(option) : {}; merge(option, ecModel.getTheme().get(axisType + 'Axis')), merge(option, this.getDefaultOption()), option.type = getAxisType(option), layoutMode && mergeLayoutParam(option, inputPositionParams, layoutMode); }, AxisModel.prototype.optionUpdated = function() { 'category' === this.option.type && (this.__ordinalMeta = OrdinalMeta.createByAxisModel(this)); }, AxisModel.prototype.getCategories = function(rawData) { var option = this.option; if ('category' === option.type) return rawData ? option.data : this.__ordinalMeta.categories; }, AxisModel.prototype.getOrdinalMeta = function() { return this.__ordinalMeta; }, AxisModel.type = axisName + 'Axis.' + axisType, AxisModel.defaultOption = defaultOption, AxisModel; }(BaseAxisModelClass); registers.registerComponentModel(AxisModel); }), registers.registerSubTypeDefaulter(axisName + 'Axis', getAxisType); } function getAxisType(option) { return option.type || (option.data ? 'category' : 'value'); } var Cartesian = function() { function Cartesian(name) { this.type = 'cartesian', this._dimList = [], this._axes = {}, this.name = name || ''; } return Cartesian.prototype.getAxis = function(dim) { return this._axes[dim]; }, Cartesian.prototype.getAxes = function() { return map(this._dimList, function(dim) { return this._axes[dim]; }, this); }, Cartesian.prototype.getAxesByScale = function(scaleType) { return scaleType = scaleType.toLowerCase(), filter(this.getAxes(), function(axis) { return axis.scale.type === scaleType; }); }, Cartesian.prototype.addAxis = function(axis) { var dim = axis.dim; this._axes[dim] = axis, this._dimList.push(dim); }, Cartesian; }(), cartesian2DDimensions = [ 'x', 'y' ]; function canCalculateAffineTransform(scale) { return 'interval' === scale.type || 'time' === scale.type; } var Cartesian2D = function(_super) { function Cartesian2D() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = 'cartesian2d', _this.dimensions = cartesian2DDimensions, _this; } return __extends(Cartesian2D, _super), Cartesian2D.prototype.calcAffineTransform = function() { this._transform = this._invTransform = null; var xAxisScale = this.getAxis('x').scale, yAxisScale = this.getAxis('y').scale; if (canCalculateAffineTransform(xAxisScale) && canCalculateAffineTransform(yAxisScale)) { var xScaleExtent = xAxisScale.getExtent(), yScaleExtent = yAxisScale.getExtent(), start = this.dataToPoint([ xScaleExtent[0], yScaleExtent[0] ]), end = this.dataToPoint([ xScaleExtent[1], yScaleExtent[1] ]), xScaleSpan = xScaleExtent[1] - xScaleExtent[0], yScaleSpan = yScaleExtent[1] - yScaleExtent[0]; if (xScaleSpan && yScaleSpan) { var scaleX = (end[0] - start[0]) / xScaleSpan, scaleY = (end[1] - start[1]) / yScaleSpan, translateX = start[0] - xScaleExtent[0] * scaleX, translateY = start[1] - yScaleExtent[0] * scaleY, m = this._transform = [ scaleX, 0, 0, scaleY, translateX, translateY ]; this._invTransform = invert([], m); } } }, Cartesian2D.prototype.getBaseAxis = function() { return this.getAxesByScale('ordinal')[0] || this.getAxesByScale('time')[0] || this.getAxis('x'); }, Cartesian2D.prototype.containPoint = function(point) { var axisX = this.getAxis('x'), axisY = this.getAxis('y'); return axisX.contain(axisX.toLocalCoord(point[0])) && axisY.contain(axisY.toLocalCoord(point[1])); }, Cartesian2D.prototype.containData = function(data) { return this.getAxis('x').containData(data[0]) && this.getAxis('y').containData(data[1]); }, Cartesian2D.prototype.dataToPoint = function(data, reserved, out) { out = out || []; var xVal = data[0], yVal = data[1]; if (this._transform && null != xVal && isFinite(xVal) && null != yVal && isFinite(yVal)) return applyTransform(out, data, this._transform); var xAxis = this.getAxis('x'), yAxis = this.getAxis('y'); return out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(xVal)), out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(yVal)), out; }, Cartesian2D.prototype.clampData = function(data, out) { var xScale = this.getAxis('x').scale, yScale = this.getAxis('y').scale, xAxisExtent = xScale.getExtent(), yAxisExtent = yScale.getExtent(), x = xScale.parse(data[0]), y = yScale.parse(data[1]); return (out = out || [])[0] = Math.min(Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x), Math.max(xAxisExtent[0], xAxisExtent[1])), out[1] = Math.min(Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y), Math.max(yAxisExtent[0], yAxisExtent[1])), out; }, Cartesian2D.prototype.pointToData = function(point, out) { if (out = out || [], this._invTransform) return applyTransform(out, point, this._invTransform); var xAxis = this.getAxis('x'), yAxis = this.getAxis('y'); return out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0])), out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1])), out; }, Cartesian2D.prototype.getOtherAxis = function(axis) { return this.getAxis('x' === axis.dim ? 'y' : 'x'); }, Cartesian2D.prototype.getArea = function() { var xExtent = this.getAxis('x').getGlobalExtent(), yExtent = this.getAxis('y').getGlobalExtent(), x = Math.min(xExtent[0], xExtent[1]), y = Math.min(yExtent[0], yExtent[1]), width = Math.max(xExtent[0], xExtent[1]) - x, height = Math.max(yExtent[0], yExtent[1]) - y; return new BoundingRect(x, y, width, height); }, Cartesian2D; }(Cartesian), Axis2D = function(_super) { function Axis2D(dim, scale, coordExtent, axisType, position) { var _this = _super.call(this, dim, scale, coordExtent) || this; return _this.index = 0, _this.type = axisType || 'value', _this.position = position || 'bottom', _this; } return __extends(Axis2D, _super), Axis2D.prototype.isHorizontal = function() { var position = this.position; return 'top' === position || 'bottom' === position; }, Axis2D.prototype.getGlobalExtent = function(asc) { var ret = this.getExtent(); return ret[0] = this.toGlobalCoord(ret[0]), ret[1] = this.toGlobalCoord(ret[1]), asc && ret[0] > ret[1] && ret.reverse(), ret; }, Axis2D.prototype.pointToData = function(point, clamp) { return this.coordToData(this.toLocalCoord(point['x' === this.dim ? 0 : 1]), clamp); }, Axis2D.prototype.setCategorySortInfo = function(info) { if ('category' !== this.type) return !1; this.model.option.categorySortInfo = info, this.scale.setSortInfo(info); }, Axis2D; }(Axis); function layout$1(gridModel, axisModel, opt) { opt = opt || {}; var grid = gridModel.coordinateSystem, axis = axisModel.axis, layout = {}, otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0], rawAxisPosition = axis.position, axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition, axisDim = axis.dim, rect = grid.getRect(), rectBound = [ rect.x, rect.x + rect.width, rect.y, rect.y + rect.height ], idx = { left: 0, right: 1, top: 0, bottom: 1, onZero: 2 }, axisOffset = axisModel.get('offset') || 0, posBound = 'x' === axisDim ? [ rectBound[2] - axisOffset, rectBound[3] + axisOffset ] : [ rectBound[0] - axisOffset, rectBound[1] + axisOffset ]; if (otherAxisOnZeroOf) { var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0)); posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]); } layout.position = [ 'y' === axisDim ? posBound[idx[axisPosition]] : rectBound[0], 'x' === axisDim ? posBound[idx[axisPosition]] : rectBound[3] ], layout.rotation = Math.PI / 2 * ('x' === axisDim ? 0 : 1), layout.labelDirection = layout.tickDirection = layout.nameDirection = ({ top: -1, bottom: 1, left: -1, right: 1 })[rawAxisPosition], layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0, axisModel.get([ 'axisTick', 'inside' ]) && (layout.tickDirection = -layout.tickDirection), retrieve(opt.labelInside, axisModel.get([ 'axisLabel', 'inside' ])) && (layout.labelDirection = -layout.labelDirection); var labelRotate = axisModel.get([ 'axisLabel', 'rotate' ]); return layout.labelRotate = 'top' === axisPosition ? -labelRotate : labelRotate, layout.z2 = 1, layout; } function isCartesian2DSeries(seriesModel) { return 'cartesian2d' === seriesModel.get('coordinateSystem'); } function findAxisModels(seriesModel) { var axisModelMap = { xAxisModel: null, yAxisModel: null }; return each(axisModelMap, function(v, key) { var axisType = key.replace(/Model$/, ''), axisModel = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0]; if (!axisModel) throw Error(axisType + ' "' + retrieve3(seriesModel.get(axisType + 'Index'), seriesModel.get(axisType + 'Id'), 0) + '" not found'); axisModelMap[key] = axisModel; }), axisModelMap; } var Grid = function() { function Grid(gridModel, ecModel, api) { this.type = 'grid', this._coordsMap = {}, this._coordsList = [], this._axesMap = {}, this._axesList = [], this.axisPointerEnabled = !0, this.dimensions = cartesian2DDimensions, this._initCartesian(gridModel, ecModel, api), this.model = gridModel; } return Grid.prototype.getRect = function() { return this._rect; }, Grid.prototype.update = function(ecModel, api) { var axesMap = this._axesMap; this._updateScale(ecModel, this.model), each(axesMap.x, function(xAxis) { niceScaleExtent(xAxis.scale, xAxis.model); }), each(axesMap.y, function(yAxis) { niceScaleExtent(yAxis.scale, yAxis.model); }); var onZeroRecords = {}; each(axesMap.x, function(xAxis) { fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords); }), each(axesMap.y, function(yAxis) { fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords); }), this.resize(this.model, api); }, Grid.prototype.resize = function(gridModel, api, ignoreContainLabel) { var boxLayoutParams = gridModel.getBoxLayoutParams(), isContainLabel = !ignoreContainLabel && gridModel.get('containLabel'), gridRect = getLayoutRect(boxLayoutParams, { width: api.getWidth(), height: api.getHeight() }); this._rect = gridRect; var axesList = this._axesList; function adjustAxes() { each(axesList, function(axis) { var axis1, coordBase, axisExtent, axisExtentSum, isHorizontal = axis.isHorizontal(), extent = isHorizontal ? [ 0, gridRect.width ] : [ 0, gridRect.height ], idx = axis.inverse ? 1 : 0; axis.setExtent(extent[idx], extent[1 - idx]), axis1 = axis, coordBase = isHorizontal ? gridRect.x : gridRect.y, axisExtentSum = (axisExtent = axis1.getExtent())[0] + axisExtent[1], axis1.toGlobalCoord = 'x' === axis1.dim ? function(coord) { return coord + coordBase; } : function(coord) { return axisExtentSum - coord + coordBase; }, axis1.toLocalCoord = 'x' === axis1.dim ? function(coord) { return coord - coordBase; } : function(coord) { return axisExtentSum - coord + coordBase; }; }); } adjustAxes(), isContainLabel && (each(axesList, function(axis) { if (!axis.model.get([ 'axisLabel', 'inside' ])) { var labelUnionRect = function(axis) { var realNumberScaleTicks, tickCount, rect, axisModel = axis.model, scale = axis.scale; if (!(!axisModel.get([ 'axisLabel', 'show' ]) || scale.isBlank())) { var categoryScaleExtent = scale.getExtent(); tickCount = scale instanceof OrdinalScale ? scale.count() : (realNumberScaleTicks = scale.getTicks()).length; var axisLabelModel = axis.getLabelModel(), labelFormatter = makeLabelFormatter(axis), step = 1; tickCount > 40 && (step = Math.ceil(tickCount / 40)); for(var i = 0; i < tickCount; i += step){ var label = labelFormatter(realNumberScaleTicks ? realNumberScaleTicks[i] : { value: categoryScaleExtent[0] + i }, i), singleRect = function(textRect, rotate) { var rotateRadians = rotate * Math.PI / 180, beforeWidth = textRect.width, beforeHeight = textRect.height; return new BoundingRect(textRect.x, textRect.y, beforeWidth * Math.abs(Math.cos(rotateRadians)) + Math.abs(beforeHeight * Math.sin(rotateRadians)), beforeWidth * Math.abs(Math.sin(rotateRadians)) + Math.abs(beforeHeight * Math.cos(rotateRadians))); }(axisLabelModel.getTextRect(label), axisLabelModel.get('rotate') || 0); rect ? rect.union(singleRect) : rect = singleRect; } return rect; } }(axis); if (labelUnionRect) { var dim = axis.isHorizontal() ? 'height' : 'width', margin = axis.model.get([ 'axisLabel', 'margin' ]); gridRect[dim] -= labelUnionRect[dim] + margin, 'top' === axis.position ? gridRect.y += labelUnionRect.height + margin : 'left' === axis.position && (gridRect.x += labelUnionRect.width + margin); } } }), adjustAxes()), each(this._coordsList, function(coord) { coord.calcAffineTransform(); }); }, Grid.prototype.getAxis = function(dim, axisIndex) { var axesMapOnDim = this._axesMap[dim]; if (null != axesMapOnDim) return axesMapOnDim[axisIndex || 0]; }, Grid.prototype.getAxes = function() { return this._axesList.slice(); }, Grid.prototype.getCartesian = function(xAxisIndex, yAxisIndex) { if (null != xAxisIndex && null != yAxisIndex) { var key = 'x' + xAxisIndex + 'y' + yAxisIndex; return this._coordsMap[key]; } isObject(xAxisIndex) && (yAxisIndex = xAxisIndex.yAxisIndex, xAxisIndex = xAxisIndex.xAxisIndex); for(var i = 0, coordList = this._coordsList; i < coordList.length; i++)if (coordList[i].getAxis('x').index === xAxisIndex || coordList[i].getAxis('y').index === yAxisIndex) return coordList[i]; }, Grid.prototype.getCartesians = function() { return this._coordsList.slice(); }, Grid.prototype.convertToPixel = function(ecModel, finder, value) { var target = this._findConvertTarget(finder); return target.cartesian ? target.cartesian.dataToPoint(value) : target.axis ? target.axis.toGlobalCoord(target.axis.dataToCoord(value)) : null; }, Grid.prototype.convertFromPixel = function(ecModel, finder, value) { var target = this._findConvertTarget(finder); return target.cartesian ? target.cartesian.pointToData(value) : target.axis ? target.axis.coordToData(target.axis.toLocalCoord(value)) : null; }, Grid.prototype._findConvertTarget = function(finder) { var cartesian, axis, seriesModel = finder.seriesModel, xAxisModel = finder.xAxisModel || seriesModel && seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0], yAxisModel = finder.yAxisModel || seriesModel && seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0], gridModel = finder.gridModel, coordsList = this._coordsList; return seriesModel ? 0 > indexOf(coordsList, cartesian = seriesModel.coordinateSystem) && (cartesian = null) : xAxisModel && yAxisModel ? cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex) : xAxisModel ? axis = this.getAxis('x', xAxisModel.componentIndex) : yAxisModel ? axis = this.getAxis('y', yAxisModel.componentIndex) : gridModel && gridModel.coordinateSystem === this && (cartesian = this._coordsList[0]), { cartesian: cartesian, axis: axis }; }, Grid.prototype.containPoint = function(point) { var coord = this._coordsList[0]; if (coord) return coord.containPoint(point); }, Grid.prototype._initCartesian = function(gridModel, ecModel, api) { var _this = this, grid = this, axisPositionUsed = { left: !1, right: !1, top: !1, bottom: !1 }, axesMap = { x: {}, y: {} }, axesCount = { x: 0, y: 0 }; if (ecModel.eachComponent('xAxis', createAxisCreator('x'), this), ecModel.eachComponent('yAxis', createAxisCreator('y'), this), !axesCount.x || !axesCount.y) { this._axesMap = {}, this._axesList = []; return; } function createAxisCreator(dimName) { return function(axisModel, idx) { if (isAxisUsedInTheGrid(axisModel, gridModel)) { var axisPosition = axisModel.get('position'); 'x' === dimName ? 'top' !== axisPosition && 'bottom' !== axisPosition && (axisPosition = axisPositionUsed.bottom ? 'top' : 'bottom') : 'left' !== axisPosition && 'right' !== axisPosition && (axisPosition = axisPositionUsed.left ? 'right' : 'left'), axisPositionUsed[axisPosition] = !0; var axis = new Axis2D(dimName, createScaleByModel(axisModel), [ 0, 0 ], axisModel.get('type'), axisPosition), isCategory = 'category' === axis.type; axis.onBand = isCategory && axisModel.get('boundaryGap'), axis.inverse = axisModel.get('inverse'), axisModel.axis = axis, axis.model = axisModel, axis.grid = grid, axis.index = idx, grid._axesList.push(axis), axesMap[dimName][idx] = axis, axesCount[dimName]++; } }; } this._axesMap = axesMap, each(axesMap.x, function(xAxis, xAxisIndex) { each(axesMap.y, function(yAxis, yAxisIndex) { var key = 'x' + xAxisIndex + 'y' + yAxisIndex, cartesian = new Cartesian2D(key); cartesian.master = _this, cartesian.model = gridModel, _this._coordsMap[key] = cartesian, _this._coordsList.push(cartesian), cartesian.addAxis(xAxis), cartesian.addAxis(yAxis); }); }); }, Grid.prototype._updateScale = function(ecModel, gridModel) { function unionExtent(data, axis) { each(getDataDimensionsOnAxis(data, axis.dim), function(dim) { axis.scale.unionExtentFromData(data, dim); }); } each(this._axesList, function(axis) { if (axis.scale.setExtent(1 / 0, -1 / 0), 'category' === axis.type) { var categorySortInfo = axis.model.get('categorySortInfo'); axis.scale.setSortInfo(categorySortInfo); } }), ecModel.eachSeries(function(seriesModel) { if (isCartesian2DSeries(seriesModel)) { var axesModelMap = findAxisModels(seriesModel), xAxisModel = axesModelMap.xAxisModel, yAxisModel = axesModelMap.yAxisModel; if (isAxisUsedInTheGrid(xAxisModel, gridModel) && isAxisUsedInTheGrid(yAxisModel, gridModel)) { var cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex), data = seriesModel.getData(), xAxis = cartesian.getAxis('x'), yAxis = cartesian.getAxis('y'); 'list' === data.type && (unionExtent(data, xAxis), unionExtent(data, yAxis)); } } }, this); }, Grid.prototype.getTooltipAxes = function(dim) { var baseAxes = [], otherAxes = []; return each(this.getCartesians(), function(cartesian) { var baseAxis = null != dim && 'auto' !== dim ? cartesian.getAxis(dim) : cartesian.getBaseAxis(), otherAxis = cartesian.getOtherAxis(baseAxis); 0 > indexOf(baseAxes, baseAxis) && baseAxes.push(baseAxis), 0 > indexOf(otherAxes, otherAxis) && otherAxes.push(otherAxis); }), { baseAxes: baseAxes, otherAxes: otherAxes }; }, Grid.create = function(ecModel, api) { var grids = []; return ecModel.eachComponent('grid', function(gridModel, idx) { var grid = new Grid(gridModel, ecModel, api); grid.name = 'grid_' + idx, grid.resize(gridModel, api, !0), gridModel.coordinateSystem = grid, grids.push(grid); }), ecModel.eachSeries(function(seriesModel) { if (isCartesian2DSeries(seriesModel)) { var axesModelMap = findAxisModels(seriesModel), xAxisModel = axesModelMap.xAxisModel, yAxisModel = axesModelMap.yAxisModel, gridModel = xAxisModel.getCoordSysModel(); if (!gridModel) throw Error('Grid "' + retrieve3(xAxisModel.get('gridIndex'), xAxisModel.get('gridId'), 0) + '" not found'); if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) throw Error('xAxis and yAxis must use the same grid'); var grid = gridModel.coordinateSystem; seriesModel.coordinateSystem = grid.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex); } }), grids; }, Grid.dimensions = cartesian2DDimensions, Grid; }(); function isAxisUsedInTheGrid(axisModel, gridModel) { return axisModel.getCoordSysModel() === gridModel; } function fixAxisOnZero(axesMap, otherAxisDim, axis, onZeroRecords) { axis.getAxesOnZeroOf = function() { return otherAxisOnZeroOf ? [ otherAxisOnZeroOf ] : []; }; var otherAxisOnZeroOf, otherAxes = axesMap[otherAxisDim], axisModel = axis.model, onZero = axisModel.get([ 'axisLine', 'onZero' ]), onZeroAxisIndex = axisModel.get([ 'axisLine', 'onZeroAxisIndex' ]); if (onZero) { if (null != onZeroAxisIndex) canOnZeroToAxis(otherAxes[onZeroAxisIndex]) && (otherAxisOnZeroOf = otherAxes[onZeroAxisIndex]); else for(var idx in otherAxes)if (otherAxes.hasOwnProperty(idx) && canOnZeroToAxis(otherAxes[idx]) && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]) { otherAxisOnZeroOf = otherAxes[idx]; break; } otherAxisOnZeroOf && (onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = !0); } function getOnZeroRecordKey(axis) { return axis.dim + '_' + axis.index; } } function canOnZeroToAxis(axis) { var dataExtent, min, max; return axis && 'category' !== axis.type && 'time' !== axis.type && (min = (dataExtent = axis.scale.getExtent())[0], max = dataExtent[1], !(min > 0 && max > 0 || min < 0 && max < 0)); } var PI$5 = Math.PI, AxisBuilder = function() { function AxisBuilder(axisModel, opt) { this.group = new Group(), this.opt = opt, this.axisModel = axisModel, defaults(opt, { labelOffset: 0, nameDirection: 1, tickDirection: 1, labelDirection: 1, silent: !0, handleAutoShown: function() { return !0; } }); var transformGroup = new Group({ x: opt.position[0], y: opt.position[1], rotation: opt.rotation }); transformGroup.updateTransform(), this._transformGroup = transformGroup; } return AxisBuilder.prototype.hasBuilder = function(name) { return !!builders[name]; }, AxisBuilder.prototype.add = function(name) { builders[name](this.opt, this.axisModel, this.group, this._transformGroup); }, AxisBuilder.prototype.getGroup = function() { return this.group; }, AxisBuilder.innerTextLayout = function(axisRotation, textRotation, direction) { var textAlign, textVerticalAlign, rotationDiff = remRadian(textRotation - axisRotation); return isRadianAroundZero(rotationDiff) ? (textVerticalAlign = direction > 0 ? 'top' : 'bottom', textAlign = 'center') : isRadianAroundZero(rotationDiff - PI$5) ? (textVerticalAlign = direction > 0 ? 'bottom' : 'top', textAlign = 'center') : (textVerticalAlign = 'middle', textAlign = rotationDiff > 0 && rotationDiff < PI$5 ? direction > 0 ? 'right' : 'left' : direction > 0 ? 'left' : 'right'), { rotation: rotationDiff, textAlign: textAlign, textVerticalAlign: textVerticalAlign }; }, AxisBuilder.makeAxisEventDataBase = function(axisModel) { var eventData = { componentType: axisModel.mainType, componentIndex: axisModel.componentIndex }; return eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex, eventData; }, AxisBuilder.isLabelSilent = function(axisModel) { var tooltipOpt = axisModel.get('tooltip'); return axisModel.get('silent') || !(axisModel.get('triggerEvent') || tooltipOpt && tooltipOpt.show); }, AxisBuilder; }(), builders = { axisLine: function(opt, axisModel, group, transformGroup) { var shown = axisModel.get([ 'axisLine', 'show' ]); if ('auto' === shown && opt.handleAutoShown && (shown = opt.handleAutoShown('axisLine')), shown) { var extent = axisModel.axis.getExtent(), matrix = transformGroup.transform, pt1 = [ extent[0], 0 ], pt2 = [ extent[1], 0 ]; matrix && (applyTransform(pt1, pt1, matrix), applyTransform(pt2, pt2, matrix)); var lineStyle = extend({ lineCap: 'round' }, axisModel.getModel([ 'axisLine', 'lineStyle' ]).getLineStyle()), line = new Line({ subPixelOptimize: !0, shape: { x1: pt1[0], y1: pt1[1], x2: pt2[0], y2: pt2[1] }, style: lineStyle, strokeContainThreshold: opt.strokeContainThreshold || 5, silent: !0, z2: 1 }); line.anid = 'line', group.add(line); var arrows = axisModel.get([ 'axisLine', 'symbol' ]), arrowSize = axisModel.get([ 'axisLine', 'symbolSize' ]), arrowOffset = axisModel.get([ 'axisLine', 'symbolOffset' ]) || 0; if ('number' == typeof arrowOffset && (arrowOffset = [ arrowOffset, arrowOffset ]), null != arrows) { 'string' == typeof arrows && (arrows = [ arrows, arrows ]), ('string' == typeof arrowSize || 'number' == typeof arrowSize) && (arrowSize = [ arrowSize, arrowSize ]); var symbolWidth_1 = arrowSize[0], symbolHeight_1 = arrowSize[1]; each([ { rotate: opt.rotation + Math.PI / 2, offset: arrowOffset[0], r: 0 }, { rotate: opt.rotation - Math.PI / 2, offset: arrowOffset[1], r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0]) + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1])) } ], function(point, index) { if ('none' !== arrows[index] && null != arrows[index]) { var symbol = createSymbol(arrows[index], -symbolWidth_1 / 2, -symbolHeight_1 / 2, symbolWidth_1, symbolHeight_1, lineStyle.stroke, !0), r = point.r + point.offset; symbol.attr({ rotation: point.rotate, x: pt1[0] + r * Math.cos(opt.rotation), y: pt1[1] - r * Math.sin(opt.rotation), silent: !0, z2: 11 }), group.add(symbol); } }); } } }, axisTickLabel: function(opt, axisModel, group, transformGroup) { var ticksEls = function(group, transformGroup, axisModel, opt) { var axis = axisModel.axis, tickModel = axisModel.getModel('axisTick'), shown = tickModel.get('show'); if ('auto' === shown && opt.handleAutoShown && (shown = opt.handleAutoShown('axisTick')), !(!shown || axis.scale.isBlank())) { for(var lineStyleModel = tickModel.getModel('lineStyle'), tickEndCoord = opt.tickDirection * tickModel.get('length'), ticksEls = createTicks(axis.getTicksCoords(), transformGroup.transform, tickEndCoord, defaults(lineStyleModel.getLineStyle(), { stroke: axisModel.get([ 'axisLine', 'lineStyle', 'color' ]) }), 'ticks'), i = 0; i < ticksEls.length; i++)group.add(ticksEls[i]); return ticksEls; } }(group, transformGroup, axisModel, opt), labelEls = function(group, transformGroup, axisModel, opt) { var axis = axisModel.axis; if (!(!retrieve(opt.axisLabelShow, axisModel.get([ 'axisLabel', 'show' ])) || axis.scale.isBlank())) { var labelModel = axisModel.getModel('axisLabel'), labelMargin = labelModel.get('margin'), labels = axis.getViewLabels(), labelRotation = (retrieve(opt.labelRotate, labelModel.get('rotate')) || 0) * PI$5 / 180, labelLayout = AxisBuilder.innerTextLayout(opt.rotation, labelRotation, opt.labelDirection), rawCategoryData = axisModel.getCategories && axisModel.getCategories(!0), labelEls = [], silent = AxisBuilder.isLabelSilent(axisModel), triggerEvent = axisModel.get('triggerEvent'); return each(labels, function(labelItem, index) { var tickValue = 'ordinal' === axis.scale.type ? axis.scale.getRawOrdinalNumber(labelItem.tickValue) : labelItem.tickValue, formattedLabel = labelItem.formattedLabel, rawLabel = labelItem.rawLabel, itemLabelModel = labelModel; if (rawCategoryData && rawCategoryData[tickValue]) { var rawCategoryItem = rawCategoryData[tickValue]; isObject(rawCategoryItem) && rawCategoryItem.textStyle && (itemLabelModel = new Model(rawCategoryItem.textStyle, labelModel, axisModel.ecModel)); } var textColor = itemLabelModel.getTextColor() || axisModel.get([ 'axisLine', 'lineStyle', 'color' ]), tickCoord = axis.dataToCoord(tickValue), textEl = new ZRText({ x: tickCoord, y: opt.labelOffset + opt.labelDirection * labelMargin, rotation: labelLayout.rotation, silent: silent, z2: 10, style: createTextStyle(itemLabelModel, { text: formattedLabel, align: itemLabelModel.getShallow('align', !0) || labelLayout.textAlign, verticalAlign: itemLabelModel.getShallow('verticalAlign', !0) || itemLabelModel.getShallow('baseline', !0) || labelLayout.textVerticalAlign, fill: 'function' == typeof textColor ? textColor('category' === axis.type ? rawLabel : 'value' === axis.type ? tickValue + '' : tickValue, index) : textColor }) }); if (textEl.anid = 'label_' + tickValue, triggerEvent) { var eventData = AxisBuilder.makeAxisEventDataBase(axisModel); eventData.targetType = 'axisLabel', eventData.value = rawLabel, getECData(textEl).eventData = eventData; } transformGroup.add(textEl), textEl.updateTransform(), labelEls.push(textEl), group.add(textEl), textEl.decomposeTransform(); }), labelEls; } }(group, transformGroup, axisModel, opt); (function(axisModel, labelEls, tickEls) { if (!shouldShowAllLabels(axisModel.axis)) { var showMinLabel = axisModel.get([ 'axisLabel', 'showMinLabel' ]), showMaxLabel = axisModel.get([ 'axisLabel', 'showMaxLabel' ]); tickEls = tickEls || []; var firstLabel = (labelEls = labelEls || [])[0], nextLabel = labelEls[1], lastLabel = labelEls[labelEls.length - 1], prevLabel = labelEls[labelEls.length - 2], firstTick = tickEls[0], nextTick = tickEls[1], lastTick = tickEls[tickEls.length - 1], prevTick = tickEls[tickEls.length - 2]; !1 === showMinLabel ? (ignoreEl(firstLabel), ignoreEl(firstTick)) : isTwoLabelOverlapped(firstLabel, nextLabel) && (showMinLabel ? (ignoreEl(nextLabel), ignoreEl(nextTick)) : (ignoreEl(firstLabel), ignoreEl(firstTick))), !1 === showMaxLabel ? (ignoreEl(lastLabel), ignoreEl(lastTick)) : isTwoLabelOverlapped(prevLabel, lastLabel) && (showMaxLabel ? (ignoreEl(prevLabel), ignoreEl(prevTick)) : (ignoreEl(lastLabel), ignoreEl(lastTick))); } })(axisModel, labelEls, ticksEls), function(group, transformGroup, axisModel, tickDirection) { var axis = axisModel.axis, minorTickModel = axisModel.getModel('minorTick'); if (!(!minorTickModel.get('show') || axis.scale.isBlank())) { var minorTicksCoords = axis.getMinorTicksCoords(); if (minorTicksCoords.length) for(var lineStyleModel = minorTickModel.getModel('lineStyle'), tickEndCoord = tickDirection * minorTickModel.get('length'), minorTickLineStyle = defaults(lineStyleModel.getLineStyle(), defaults(axisModel.getModel('axisTick').getLineStyle(), { stroke: axisModel.get([ 'axisLine', 'lineStyle', 'color' ]) })), i = 0; i < minorTicksCoords.length; i++)for(var minorTicksEls = createTicks(minorTicksCoords[i], transformGroup.transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i), k = 0; k < minorTicksEls.length; k++)group.add(minorTicksEls[k]); } }(group, transformGroup, axisModel, opt.tickDirection); }, axisName: function(opt, axisModel, group, transformGroup) { var labelLayout, axisNameAvailableWidth, name = retrieve(opt.axisName, axisModel.get('name')); if (name) { var rotation, textAlign, textVerticalAlign, rotationDiff, inverse, onLeft, nameLocation = axisModel.get('nameLocation'), nameDirection = opt.nameDirection, textStyleModel = axisModel.getModel('nameTextStyle'), gap = axisModel.get('nameGap') || 0, extent = axisModel.axis.getExtent(), gapSignal = extent[0] > extent[1] ? -1 : 1, pos = [ 'start' === nameLocation ? extent[0] - gapSignal * gap : 'end' === nameLocation ? extent[1] + gapSignal * gap : (extent[0] + extent[1]) / 2, isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0 ], nameRotation = axisModel.get('nameRotate'); null != nameRotation && (nameRotation = nameRotation * PI$5 / 180), isNameLocationCenter(nameLocation) ? labelLayout = AxisBuilder.innerTextLayout(opt.rotation, null != nameRotation ? nameRotation : opt.rotation, nameDirection) : (rotation = opt.rotation, rotationDiff = remRadian((nameRotation || 0) - rotation), inverse = extent[0] > extent[1], onLeft = 'start' === nameLocation && !inverse || 'start' !== nameLocation && inverse, isRadianAroundZero(rotationDiff - PI$5 / 2) ? (textVerticalAlign = onLeft ? 'bottom' : 'top', textAlign = 'center') : isRadianAroundZero(rotationDiff - 1.5 * PI$5) ? (textVerticalAlign = onLeft ? 'top' : 'bottom', textAlign = 'center') : (textVerticalAlign = 'middle', textAlign = rotationDiff < 1.5 * PI$5 && rotationDiff > PI$5 / 2 ? onLeft ? 'left' : 'right' : onLeft ? 'right' : 'left'), labelLayout = { rotation: rotationDiff, textAlign: textAlign, textVerticalAlign: textVerticalAlign }, null != (axisNameAvailableWidth = opt.axisNameAvailableWidth) && (isFinite(axisNameAvailableWidth = Math.abs(axisNameAvailableWidth / Math.sin(labelLayout.rotation))) || (axisNameAvailableWidth = null))); var textFont = textStyleModel.getFont(), truncateOpt = axisModel.get('nameTruncate', !0) || {}, ellipsis = truncateOpt.ellipsis, maxWidth = retrieve(opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth), textEl = new ZRText({ x: pos[0], y: pos[1], rotation: labelLayout.rotation, silent: AxisBuilder.isLabelSilent(axisModel), style: createTextStyle(textStyleModel, { text: name, font: textFont, overflow: 'truncate', width: maxWidth, ellipsis: ellipsis, fill: textStyleModel.getTextColor() || axisModel.get([ 'axisLine', 'lineStyle', 'color' ]), align: textStyleModel.get('align') || labelLayout.textAlign, verticalAlign: textStyleModel.get('verticalAlign') || labelLayout.textVerticalAlign }), z2: 1 }); if (setTooltipConfig({ el: textEl, componentModel: axisModel, itemName: name }), textEl.__fullText = name, textEl.anid = 'name', axisModel.get('triggerEvent')) { var eventData = AxisBuilder.makeAxisEventDataBase(axisModel); eventData.targetType = 'axisName', eventData.name = name, getECData(textEl).eventData = eventData; } transformGroup.add(textEl), textEl.updateTransform(), group.add(textEl), textEl.decomposeTransform(); } } }; function ignoreEl(el) { el && (el.ignore = !0); } function isTwoLabelOverlapped(current, next) { var firstRect = current && current.getBoundingRect().clone(), nextRect = next && next.getBoundingRect().clone(); if (firstRect && nextRect) { var mRotationBack = identity([]); return rotate(mRotationBack, mRotationBack, -current.rotation), firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform())), nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform())), firstRect.intersect(nextRect); } } function isNameLocationCenter(nameLocation) { return 'middle' === nameLocation || 'center' === nameLocation; } function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, anidPrefix) { for(var tickEls = [], pt1 = [], pt2 = [], i = 0; i < ticksCoords.length; i++){ var tickCoord = ticksCoords[i].coord; pt1[0] = tickCoord, pt1[1] = 0, pt2[0] = tickCoord, pt2[1] = tickEndCoord, tickTransform && (applyTransform(pt1, pt1, tickTransform), applyTransform(pt2, pt2, tickTransform)); var tickEl = new Line({ subPixelOptimize: !0, shape: { x1: pt1[0], y1: pt1[1], x2: pt2[0], y2: pt2[1] }, style: tickLineStyle, z2: 2, autoBatch: !0, silent: !0 }); tickEl.anid = anidPrefix + '_' + ticksCoords[i].tickValue, tickEls.push(tickEl); } return tickEls; } function checkPropInLink(linkPropValue, axisPropValue) { return 'all' === linkPropValue || isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0 || linkPropValue === axisPropValue; } function getAxisInfo(axisModel) { var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo; return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)]; } function isHandleTrigger(axisPointerModel) { return !!axisPointerModel.get([ 'handle', 'show' ]); } function makeKey(model) { return model.type + '||' + model.id; } var axisPointerClazz = {}, AxisView = function(_super) { function AxisView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = AxisView.type, _this; } return __extends(AxisView, _super), AxisView.prototype.render = function(axisModel, ecModel, api, payload) { this.axisPointerClass && function(axisModel) { var axisInfo = getAxisInfo(axisModel); if (axisInfo) { var axisPointerModel = axisInfo.axisPointerModel, scale = axisInfo.axis.scale, option = axisPointerModel.option, status = axisPointerModel.get('status'), value = axisPointerModel.get('value'); null != value && (value = scale.parse(value)); var useHandle = isHandleTrigger(axisPointerModel); null == status && (option.status = useHandle ? 'show' : 'hide'); var extent = scale.getExtent().slice(); extent[0] > extent[1] && extent.reverse(), (null == value || value > extent[1]) && (value = extent[1]), value < extent[0] && (value = extent[0]), option.value = value, useHandle && (option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show'); } }(axisModel), _super.prototype.render.apply(this, arguments), this._doUpdateAxisPointerClass(axisModel, api, !0); }, AxisView.prototype.updateAxisPointer = function(axisModel, ecModel, api, payload) { this._doUpdateAxisPointerClass(axisModel, api, !1); }, AxisView.prototype.remove = function(ecModel, api) { var axisPointer = this._axisPointer; axisPointer && axisPointer.remove(api); }, AxisView.prototype.dispose = function(ecModel, api) { this._disposeAxisPointer(api), _super.prototype.dispose.apply(this, arguments); }, AxisView.prototype._doUpdateAxisPointerClass = function(axisModel, api, forceRender) { var axisInfo, Clazz = AxisView.getAxisPointerClass(this.axisPointerClass); if (Clazz) { var axisPointerModel = (axisInfo = getAxisInfo(axisModel)) && axisInfo.axisPointerModel; axisPointerModel ? (this._axisPointer || (this._axisPointer = new Clazz())).render(axisModel, axisPointerModel, api, forceRender) : this._disposeAxisPointer(api); } }, AxisView.prototype._disposeAxisPointer = function(api) { this._axisPointer && this._axisPointer.dispose(api), this._axisPointer = null; }, AxisView.registerAxisPointerClass = function(type, clazz) { if (axisPointerClazz[type]) throw Error('axisPointer ' + type + ' exists'); axisPointerClazz[type] = clazz; }, AxisView.getAxisPointerClass = function(type) { return type && axisPointerClazz[type]; }, AxisView.type = 'axis', AxisView; }(ComponentView), inner$5 = makeInner(); function rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel) { var axis = axisModel.axis; if (!axis.scale.isBlank()) { var splitAreaModel = axisModel.getModel('splitArea'), areaStyleModel = splitAreaModel.getModel('areaStyle'), areaColors = areaStyleModel.get('color'), gridRect = gridModel.coordinateSystem.getRect(), ticksCoords = axis.getTicksCoords({ tickModel: splitAreaModel, clamp: !0 }); if (ticksCoords.length) { var areaColorsLen = areaColors.length, lastSplitAreaColors = inner$5(axisView).splitAreaColors, newSplitAreaColors = createHashMap(), colorIndex = 0; if (lastSplitAreaColors) for(var i = 0; i < ticksCoords.length; i++){ var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue); if (null != cIndex) { colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen; break; } } var prev = axis.toGlobalCoord(ticksCoords[0].coord), areaStyle = areaStyleModel.getAreaStyle(); areaColors = isArray(areaColors) ? areaColors : [ areaColors ]; for(var i = 1; i < ticksCoords.length; i++){ var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord), x = void 0, y = void 0, width = void 0, height = void 0; axis.isHorizontal() ? (x = prev, y = gridRect.y, width = tickCoord - x, height = gridRect.height, prev = x + width) : (x = gridRect.x, y = prev, width = gridRect.width, height = tickCoord - y, prev = y + height); var tickValue = ticksCoords[i - 1].tickValue; null != tickValue && newSplitAreaColors.set(tickValue, colorIndex), axisGroup.add(new Rect({ anid: null != tickValue ? 'area_' + tickValue : null, shape: { x: x, y: y, width: width, height: height }, style: defaults({ fill: areaColors[colorIndex] }, areaStyle), autoBatch: !0, silent: !0 })), colorIndex = (colorIndex + 1) % areaColorsLen; } inner$5(axisView).splitAreaColors = newSplitAreaColors; } } } function rectCoordAxisHandleRemove(axisView) { inner$5(axisView).splitAreaColors = null; } var axisBuilderAttrs = [ 'axisLine', 'axisTickLabel', 'axisName' ], selfBuilderAttrs = [ 'splitArea', 'splitLine', 'minorSplitLine' ], CartesianAxisView = function(_super) { function CartesianAxisView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = CartesianAxisView.type, _this.axisPointerClass = 'CartesianAxisPointer', _this; } return __extends(CartesianAxisView, _super), CartesianAxisView.prototype.render = function(axisModel, ecModel, api, payload) { this.group.removeAll(); var oldAxisGroup = this._axisGroup; if (this._axisGroup = new Group(), this.group.add(this._axisGroup), axisModel.get('show')) { var gridModel = axisModel.getCoordSysModel(), layout = layout$1(gridModel, axisModel), axisBuilder = new AxisBuilder(axisModel, extend({ handleAutoShown: function(elementType) { for(var cartesians = gridModel.coordinateSystem.getCartesians(), i = 0; i < cartesians.length; i++){ var otherAxisType = cartesians[i].getOtherAxis(axisModel.axis).type; if ('value' === otherAxisType || 'log' === otherAxisType) return !0; } return !1; } }, layout)); each(axisBuilderAttrs, axisBuilder.add, axisBuilder), this._axisGroup.add(axisBuilder.getGroup()), each(selfBuilderAttrs, function(name) { axisModel.get([ name, 'show' ]) && axisElementBuilders[name](this, this._axisGroup, axisModel, gridModel); }, this), groupTransition(oldAxisGroup, this._axisGroup, axisModel), _super.prototype.render.call(this, axisModel, ecModel, api, payload); } }, CartesianAxisView.prototype.remove = function() { rectCoordAxisHandleRemove(this); }, CartesianAxisView.type = 'cartesianAxis', CartesianAxisView; }(AxisView), axisElementBuilders = { splitLine: function(axisView, axisGroup, axisModel, gridModel) { var axis = axisModel.axis; if (!axis.scale.isBlank()) { var splitLineModel = axisModel.getModel('splitLine'), lineStyleModel = splitLineModel.getModel('lineStyle'), lineColors = lineStyleModel.get('color'); lineColors = isArray(lineColors) ? lineColors : [ lineColors ]; for(var gridRect = gridModel.coordinateSystem.getRect(), isHorizontal = axis.isHorizontal(), lineCount = 0, ticksCoords = axis.getTicksCoords({ tickModel: splitLineModel }), p1 = [], p2 = [], lineStyle = lineStyleModel.getLineStyle(), i = 0; i < ticksCoords.length; i++){ var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord); isHorizontal ? (p1[0] = tickCoord, p1[1] = gridRect.y, p2[0] = tickCoord, p2[1] = gridRect.y + gridRect.height) : (p1[0] = gridRect.x, p1[1] = tickCoord, p2[0] = gridRect.x + gridRect.width, p2[1] = tickCoord); var colorIndex = lineCount++ % lineColors.length, tickValue = ticksCoords[i].tickValue; axisGroup.add(new Line({ anid: null != tickValue ? 'line_' + ticksCoords[i].tickValue : null, subPixelOptimize: !0, autoBatch: !0, shape: { x1: p1[0], y1: p1[1], x2: p2[0], y2: p2[1] }, style: defaults({ stroke: lineColors[colorIndex] }, lineStyle), silent: !0 })); } } }, minorSplitLine: function(axisView, axisGroup, axisModel, gridModel) { var axis = axisModel.axis, lineStyleModel = axisModel.getModel('minorSplitLine').getModel('lineStyle'), gridRect = gridModel.coordinateSystem.getRect(), isHorizontal = axis.isHorizontal(), minorTicksCoords = axis.getMinorTicksCoords(); if (minorTicksCoords.length) for(var p1 = [], p2 = [], lineStyle = lineStyleModel.getLineStyle(), i = 0; i < minorTicksCoords.length; i++)for(var k = 0; k < minorTicksCoords[i].length; k++){ var tickCoord = axis.toGlobalCoord(minorTicksCoords[i][k].coord); isHorizontal ? (p1[0] = tickCoord, p1[1] = gridRect.y, p2[0] = tickCoord, p2[1] = gridRect.y + gridRect.height) : (p1[0] = gridRect.x, p1[1] = tickCoord, p2[0] = gridRect.x + gridRect.width, p2[1] = tickCoord), axisGroup.add(new Line({ anid: 'minor_line_' + minorTicksCoords[i][k].tickValue, subPixelOptimize: !0, autoBatch: !0, shape: { x1: p1[0], y1: p1[1], x2: p2[0], y2: p2[1] }, style: lineStyle, silent: !0 })); } }, splitArea: function(axisView, axisGroup, axisModel, gridModel) { rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel); } }, CartesianXAxisView = function(_super) { function CartesianXAxisView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = CartesianXAxisView.type, _this; } return __extends(CartesianXAxisView, _super), CartesianXAxisView.type = 'xAxis', CartesianXAxisView; }(CartesianAxisView), CartesianYAxisView = function(_super) { function CartesianYAxisView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = CartesianXAxisView.type, _this; } return __extends(CartesianYAxisView, _super), CartesianYAxisView.type = 'yAxis', CartesianYAxisView; }(CartesianAxisView), GridView = function(_super) { function GridView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = 'grid', _this; } return __extends(GridView, _super), GridView.prototype.render = function(gridModel, ecModel) { this.group.removeAll(), gridModel.get('show') && this.group.add(new Rect({ shape: gridModel.coordinateSystem.getRect(), style: defaults({ fill: gridModel.get('backgroundColor') }, gridModel.getItemStyle()), silent: !0, z2: -1 })); }, GridView.type = 'grid', GridView; }(ComponentView), extraOption = { offset: 0 }; function install$5(registers) { registers.registerComponentView(GridView), registers.registerComponentModel(GridModel), registers.registerCoordinateSystem('cartesian2d', Grid), axisModelCreator(registers, 'x', CartesianAxisModel, extraOption), axisModelCreator(registers, 'y', CartesianAxisModel, extraOption), registers.registerComponentView(CartesianXAxisView), registers.registerComponentView(CartesianYAxisView), registers.registerPreprocessor(function(option) { option.xAxis && option.yAxis && !option.grid && (option.grid = {}); }); } function radarLayout(ecModel) { ecModel.eachSeriesByType('radar', function(seriesModel) { var data = seriesModel.getData(), points = [], coordSys = seriesModel.coordinateSystem; if (coordSys) { var axes = coordSys.getIndicatorAxes(); each(axes, function(axis, axisIndex) { data.each(data.mapDimension(axes[axisIndex].dim), function(val, dataIndex) { points[dataIndex] = points[dataIndex] || []; var point = coordSys.dataToPoint(val, axisIndex); points[dataIndex][axisIndex] = isValidPoint(point) ? point : [ coordSys.cx, coordSys.cy ]; }); }), data.each(function(idx) { var firstPoint = find(points[idx], function(point) { return isValidPoint(point); }) || [ coordSys.cx, coordSys.cy ]; points[idx].push(firstPoint.slice()), data.setItemLayout(idx, points[idx]); }); } }); } function isValidPoint(point) { return !isNaN(point[0]) && !isNaN(point[1]); } function radarBackwardCompat(option) { var polarOptArr = option.polar; if (polarOptArr) { isArray(polarOptArr) || (polarOptArr = [ polarOptArr ]); var polarNotRadar_1 = []; each(polarOptArr, function(polarOpt, idx) { polarOpt.indicator ? (polarOpt.type && !polarOpt.shape && (polarOpt.shape = polarOpt.type), option.radar = option.radar || [], isArray(option.radar) || (option.radar = [ option.radar ]), option.radar.push(polarOpt)) : polarNotRadar_1.push(polarOpt); }), option.polar = polarNotRadar_1; } each(option.series, function(seriesOpt) { seriesOpt && 'radar' === seriesOpt.type && seriesOpt.polarIndex && (seriesOpt.radarIndex = seriesOpt.polarIndex); }); } var RadarView = function(_super) { function RadarView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = RadarView.type, _this; } return __extends(RadarView, _super), RadarView.prototype.render = function(seriesModel, ecModel, api) { var polar = seriesModel.coordinateSystem, group = this.group, data = seriesModel.getData(), oldData = this._data; function updateSymbols(oldPoints, newPoints, symbolGroup, data, idx, isInit) { symbolGroup.removeAll(); for(var i = 0; i < newPoints.length - 1; i++){ var symbolPath = function(data, idx) { var symbolSize, symbolType = data.getItemVisual(idx, 'symbol') || 'circle'; if ('none' !== symbolType) { var symbolSize1 = (isArray(symbolSize = data.getItemVisual(idx, 'symbolSize')) || (symbolSize = [ +symbolSize, +symbolSize ]), symbolSize), symbolPath = createSymbol(symbolType, -1, -1, 2, 2), symbolRotate = data.getItemVisual(idx, 'symbolRotate') || 0; return symbolPath.attr({ style: { strokeNoScale: !0 }, z2: 100, scaleX: symbolSize1[0] / 2, scaleY: symbolSize1[1] / 2, rotation: symbolRotate * Math.PI / 180 || 0 }), symbolPath; } }(data, idx); symbolPath && (symbolPath.__dimIdx = i, oldPoints[i] ? (symbolPath.setPosition(oldPoints[i]), graphic[isInit ? 'initProps' : 'updateProps'](symbolPath, { x: newPoints[i][0], y: newPoints[i][1] }, seriesModel, idx)) : symbolPath.setPosition(newPoints[i]), symbolGroup.add(symbolPath)); } } function getInitialPoints(points) { return map(points, function(pt) { return [ polar.cx, polar.cy ]; }); } data.diff(oldData).add(function(idx) { var points = data.getItemLayout(idx); if (points) { var polygon = new Polygon(), polyline = new Polyline(), target = { shape: { points: points } }; polygon.shape.points = getInitialPoints(points), polyline.shape.points = getInitialPoints(points), initProps(polygon, target, seriesModel, idx), initProps(polyline, target, seriesModel, idx); var itemGroup = new Group(), symbolGroup = new Group(); itemGroup.add(polyline), itemGroup.add(polygon), itemGroup.add(symbolGroup), updateSymbols(polyline.shape.points, points, symbolGroup, data, idx, !0), data.setItemGraphicEl(idx, itemGroup); } }).update(function(newIdx, oldIdx) { var itemGroup = oldData.getItemGraphicEl(oldIdx), polyline = itemGroup.childAt(0), polygon = itemGroup.childAt(1), symbolGroup = itemGroup.childAt(2), target = { shape: { points: data.getItemLayout(newIdx) } }; target.shape.points && (updateSymbols(polyline.shape.points, target.shape.points, symbolGroup, data, newIdx, !1), updateProps(polyline, target, seriesModel), updateProps(polygon, target, seriesModel), data.setItemGraphicEl(newIdx, itemGroup)); }).remove(function(idx) { group.remove(oldData.getItemGraphicEl(idx)); }).execute(), data.eachItemGraphicEl(function(itemGroup, idx) { var itemModel = data.getItemModel(idx), polyline = itemGroup.childAt(0), polygon = itemGroup.childAt(1), symbolGroup = itemGroup.childAt(2), itemStyle = data.getItemVisual(idx, 'style'), color = itemStyle.fill; group.add(itemGroup), polyline.useStyle(defaults(itemModel.getModel('lineStyle').getLineStyle(), { fill: 'none', stroke: color })), setStatesStylesFromModel(polyline, itemModel, 'lineStyle'), setStatesStylesFromModel(polygon, itemModel, 'areaStyle'); var areaStyleModel = itemModel.getModel('areaStyle'), polygonIgnore = areaStyleModel.isEmpty() && areaStyleModel.parentModel.isEmpty(); polygon.ignore = polygonIgnore, each([ 'emphasis', 'select', 'blur' ], function(stateName) { var stateModel = itemModel.getModel([ stateName, 'areaStyle' ]), stateIgnore = stateModel.isEmpty() && stateModel.parentModel.isEmpty(); polygon.ensureState(stateName).ignore = stateIgnore && polygonIgnore; }), polygon.useStyle(defaults(areaStyleModel.getAreaStyle(), { fill: color, opacity: 0.7, decal: itemStyle.decal })); var emphasisModel = itemModel.getModel('emphasis'), itemHoverStyle = emphasisModel.getModel('itemStyle').getItemStyle(); symbolGroup.eachChild(function(symbolPath) { if (symbolPath instanceof ZRImage) { var pathStyle = symbolPath.style; symbolPath.useStyle(extend({ image: pathStyle.image, x: pathStyle.x, y: pathStyle.y, width: pathStyle.width, height: pathStyle.height }, itemStyle)); } else symbolPath.useStyle(itemStyle), symbolPath.setColor(color); symbolPath.ensureState('emphasis').style = clone(itemHoverStyle); var defaultText = data.get(data.dimensions[symbolPath.__dimIdx], idx); (null == defaultText || isNaN(defaultText)) && (defaultText = ''), setLabelStyle(symbolPath, getLabelStatesModels(itemModel), { labelFetcher: data.hostModel, labelDataIndex: idx, labelDimIndex: symbolPath.__dimIdx, defaultText: defaultText, inheritColor: color, defaultOpacity: itemStyle.opacity }); }), enableHoverEmphasis(itemGroup, emphasisModel.get('focus'), emphasisModel.get('blurScope')); }), this._data = data; }, RadarView.prototype.remove = function() { this.group.removeAll(), this._data = null; }, RadarView.type = 'radar', RadarView; }(ChartView), RadarSeriesModel = function(_super) { function RadarSeriesModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = RadarSeriesModel.type, _this.useColorPaletteOnData = !0, _this.hasSymbolVisual = !0, _this; } return __extends(RadarSeriesModel, _super), RadarSeriesModel.prototype.init = function(option) { _super.prototype.init.apply(this, arguments), this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this)); }, RadarSeriesModel.prototype.getInitialData = function(option, ecModel) { return createListSimply(this, { generateCoord: 'indicator_', generateCoordCount: 1 / 0 }); }, RadarSeriesModel.prototype.formatTooltip = function(dataIndex, multipleSeries, dataType) { var data = this.getData(), indicatorAxes = this.coordinateSystem.getIndicatorAxes(), name = this.getData().getName(dataIndex), nameToDisplay = '' === name ? this.name : name, markerColor = retrieveVisualColorForTooltipMarker(this, dataIndex); return createTooltipMarkup('section', { header: nameToDisplay, sortBlocks: !0, blocks: map(indicatorAxes, function(axis) { var val = data.get(data.mapDimension(axis.dim), dataIndex); return createTooltipMarkup('nameValue', { markerType: 'subItem', markerColor: markerColor, name: axis.name, value: val, sortParam: val }); }) }); }, RadarSeriesModel.prototype.getTooltipPosition = function(dataIndex) { if (null != dataIndex) { for(var data_1 = this.getData(), coordSys = this.coordinateSystem, values = data_1.getValues(map(coordSys.dimensions, function(dim) { return data_1.mapDimension(dim); }), dataIndex), i = 0, len = values.length; i < len; i++)if (!isNaN(values[i])) { var indicatorAxes = coordSys.getIndicatorAxes(); return coordSys.coordToPoint(indicatorAxes[i].dataToCoord(values[i]), i); } } }, RadarSeriesModel.type = 'series.radar', RadarSeriesModel.dependencies = [ 'radar' ], RadarSeriesModel.defaultOption = { zlevel: 0, z: 2, coordinateSystem: 'radar', legendHoverLink: !0, radarIndex: 0, lineStyle: { width: 2, type: 'solid' }, label: { position: 'top' }, symbolSize: 8 }, RadarSeriesModel; }(SeriesModel), valueAxisDefault = axisDefault.value; function defaultsShow(opt, show) { return defaults({ show: show }, opt); } var RadarModel = function(_super) { function RadarModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = RadarModel.type, _this; } return __extends(RadarModel, _super), RadarModel.prototype.optionUpdated = function() { var boundaryGap = this.get('boundaryGap'), splitNumber = this.get('splitNumber'), scale = this.get('scale'), axisLine = this.get('axisLine'), axisTick = this.get('axisTick'), axisLabel = this.get('axisLabel'), nameTextStyle = this.get('axisName'), showName = this.get([ 'axisName', 'show' ]), nameFormatter = this.get([ 'axisName', 'formatter' ]), nameGap = this.get('axisNameGap'), triggerEvent = this.get('triggerEvent'), indicatorModels = map(this.get('indicator') || [], function(indicatorOpt) { null != indicatorOpt.max && indicatorOpt.max > 0 && !indicatorOpt.min ? indicatorOpt.min = 0 : null != indicatorOpt.min && indicatorOpt.min < 0 && !indicatorOpt.max && (indicatorOpt.max = 0); var iNameTextStyle = nameTextStyle; null != indicatorOpt.color && (iNameTextStyle = defaults({ color: indicatorOpt.color }, nameTextStyle)); var innerIndicatorOpt = merge(clone(indicatorOpt), { boundaryGap: boundaryGap, splitNumber: splitNumber, scale: scale, axisLine: axisLine, axisTick: axisTick, axisLabel: axisLabel, name: indicatorOpt.text, nameLocation: 'end', nameGap: nameGap, nameTextStyle: iNameTextStyle, triggerEvent: triggerEvent }, !1); if (showName || (innerIndicatorOpt.name = ''), 'string' == typeof nameFormatter) { var indName = innerIndicatorOpt.name; innerIndicatorOpt.name = nameFormatter.replace('{value}', null != indName ? indName : ''); } else 'function' == typeof nameFormatter && (innerIndicatorOpt.name = nameFormatter(innerIndicatorOpt.name, innerIndicatorOpt)); var model = new Model(innerIndicatorOpt, null, this.ecModel); return mixin(model, AxisModelCommonMixin.prototype), model.mainType = 'radar', model.componentIndex = this.componentIndex, model; }, this); this._indicatorModels = indicatorModels; }, RadarModel.prototype.getIndicatorModels = function() { return this._indicatorModels; }, RadarModel.type = 'radar', RadarModel.defaultOption = { zlevel: 0, z: 0, center: [ '50%', '50%' ], radius: '75%', startAngle: 90, axisName: { show: !0 }, boundaryGap: [ 0, 0 ], splitNumber: 5, axisNameGap: 15, scale: !1, shape: 'polygon', axisLine: merge({ lineStyle: { color: '#bbb' } }, valueAxisDefault.axisLine), axisLabel: defaultsShow(valueAxisDefault.axisLabel, !1), axisTick: defaultsShow(valueAxisDefault.axisTick, !1), splitLine: defaultsShow(valueAxisDefault.splitLine, !0), splitArea: defaultsShow(valueAxisDefault.splitArea, !0), indicator: [] }, RadarModel; }(ComponentModel), axisBuilderAttrs$1 = [ 'axisLine', 'axisTickLabel', 'axisName' ], RadarView$1 = function(_super) { function RadarView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = RadarView.type, _this; } return __extends(RadarView, _super), RadarView.prototype.render = function(radarModel, ecModel, api) { this.group.removeAll(), this._buildAxes(radarModel), this._buildSplitLineAndArea(radarModel); }, RadarView.prototype._buildAxes = function(radarModel) { var radar = radarModel.coordinateSystem; each(map(radar.getIndicatorAxes(), function(indicatorAxis) { return new AxisBuilder(indicatorAxis.model, { position: [ radar.cx, radar.cy ], rotation: indicatorAxis.angle, labelDirection: -1, tickDirection: -1, nameDirection: 1 }); }), function(axisBuilder) { each(axisBuilderAttrs$1, axisBuilder.add, axisBuilder), this.group.add(axisBuilder.getGroup()); }, this); }, RadarView.prototype._buildSplitLineAndArea = function(radarModel) { var radar = radarModel.coordinateSystem, indicatorAxes = radar.getIndicatorAxes(); if (indicatorAxes.length) { var shape = radarModel.get('shape'), splitLineModel = radarModel.getModel('splitLine'), splitAreaModel = radarModel.getModel('splitArea'), lineStyleModel = splitLineModel.getModel('lineStyle'), areaStyleModel = splitAreaModel.getModel('areaStyle'), showSplitLine = splitLineModel.get('show'), showSplitArea = splitAreaModel.get('show'), splitLineColors = lineStyleModel.get('color'), splitAreaColors = areaStyleModel.get('color'), splitLineColorsArr = isArray(splitLineColors) ? splitLineColors : [ splitLineColors ], splitAreaColorsArr = isArray(splitAreaColors) ? splitAreaColors : [ splitAreaColors ], splitLines = [], splitAreas = []; if ('circle' === shape) for(var ticksRadius = indicatorAxes[0].getTicksCoords(), cx = radar.cx, cy = radar.cy, i = 0; i < ticksRadius.length; i++){ if (showSplitLine) { var colorIndex = getColorIndex(splitLines, splitLineColorsArr, i); splitLines[colorIndex].push(new Circle({ shape: { cx: cx, cy: cy, r: ticksRadius[i].coord } })); } if (showSplitArea && i < ticksRadius.length - 1) { var colorIndex = getColorIndex(splitAreas, splitAreaColorsArr, i); splitAreas[colorIndex].push(new Ring({ shape: { cx: cx, cy: cy, r0: ticksRadius[i].coord, r: ticksRadius[i + 1].coord } })); } } else for(var realSplitNumber_1, axesTicksPoints = map(indicatorAxes, function(indicatorAxis, idx) { var ticksCoords = indicatorAxis.getTicksCoords(); return realSplitNumber_1 = null == realSplitNumber_1 ? ticksCoords.length - 1 : Math.min(ticksCoords.length - 1, realSplitNumber_1), map(ticksCoords, function(tickCoord) { return radar.coordToPoint(tickCoord.coord, idx); }); }), prevPoints = [], i = 0; i <= realSplitNumber_1; i++){ for(var points = [], j = 0; j < indicatorAxes.length; j++)points.push(axesTicksPoints[j][i]); if (points[0] ? points.push(points[0].slice()) : console.error('Can\'t draw value axis ' + i), showSplitLine) { var colorIndex = getColorIndex(splitLines, splitLineColorsArr, i); splitLines[colorIndex].push(new Polyline({ shape: { points: points } })); } if (showSplitArea && prevPoints) { var colorIndex = getColorIndex(splitAreas, splitAreaColorsArr, i - 1); splitAreas[colorIndex].push(new Polygon({ shape: { points: points.concat(prevPoints) } })); } prevPoints = points.slice().reverse(); } var lineStyle = lineStyleModel.getLineStyle(), areaStyle = areaStyleModel.getAreaStyle(); each(splitAreas, function(splitAreas, idx) { this.group.add(mergePath$1(splitAreas, { style: defaults({ stroke: 'none', fill: splitAreaColorsArr[idx % splitAreaColorsArr.length] }, areaStyle), silent: !0 })); }, this), each(splitLines, function(splitLines, idx) { this.group.add(mergePath$1(splitLines, { style: defaults({ fill: 'none', stroke: splitLineColorsArr[idx % splitLineColorsArr.length] }, lineStyle), silent: !0 })); }, this); } function getColorIndex(areaOrLine, areaOrLineColorList, idx) { var colorIndex = idx % areaOrLineColorList.length; return areaOrLine[colorIndex] = areaOrLine[colorIndex] || [], colorIndex; } }, RadarView.type = 'radar', RadarView; }(ComponentView), IndicatorAxis = function(_super) { function IndicatorAxis(dim, scale, radiusExtent) { var _this = _super.call(this, dim, scale, radiusExtent) || this; return _this.type = 'value', _this.angle = 0, _this.name = '', _this; } return __extends(IndicatorAxis, _super), IndicatorAxis; }(Axis), Radar = function() { function Radar(radarModel, ecModel, api) { this.dimensions = [], this._model = radarModel, this._indicatorAxes = map(radarModel.getIndicatorModels(), function(indicatorModel, idx) { var dim = 'indicator_' + idx, indicatorAxis = new IndicatorAxis(dim, new IntervalScale()); return indicatorAxis.name = indicatorModel.get('name'), indicatorAxis.model = indicatorModel, indicatorModel.axis = indicatorAxis, this.dimensions.push(dim), indicatorAxis; }, this), this.resize(radarModel, api); } return Radar.prototype.getIndicatorAxes = function() { return this._indicatorAxes; }, Radar.prototype.dataToPoint = function(value, indicatorIndex) { var indicatorAxis = this._indicatorAxes[indicatorIndex]; return this.coordToPoint(indicatorAxis.dataToCoord(value), indicatorIndex); }, Radar.prototype.coordToPoint = function(coord, indicatorIndex) { var angle = this._indicatorAxes[indicatorIndex].angle; return [ this.cx + coord * Math.cos(angle), this.cy - coord * Math.sin(angle) ]; }, Radar.prototype.pointToData = function(pt) { var closestAxis, dx = pt[0] - this.cx, dy = pt[1] - this.cy, radius = Math.sqrt(dx * dx + dy * dy); dx /= radius; for(var radian = Math.atan2(-(dy /= radius), dx), minRadianDiff = 1 / 0, closestAxisIdx = -1, i = 0; i < this._indicatorAxes.length; i++){ var indicatorAxis = this._indicatorAxes[i], diff = Math.abs(radian - indicatorAxis.angle); diff < minRadianDiff && (closestAxis = indicatorAxis, closestAxisIdx = i, minRadianDiff = diff); } return [ closestAxisIdx, +(closestAxis && closestAxis.coordToData(radius)) ]; }, Radar.prototype.resize = function(radarModel, api) { var center = radarModel.get('center'), viewWidth = api.getWidth(), viewHeight = api.getHeight(), viewSize = Math.min(viewWidth, viewHeight) / 2; this.cx = parsePercent$1(center[0], viewWidth), this.cy = parsePercent$1(center[1], viewHeight), this.startAngle = radarModel.get('startAngle') * Math.PI / 180; var radius = radarModel.get('radius'); ('string' == typeof radius || 'number' == typeof radius) && (radius = [ 0, radius ]), this.r0 = parsePercent$1(radius[0], viewSize), this.r = parsePercent$1(radius[1], viewSize), each(this._indicatorAxes, function(indicatorAxis, idx) { indicatorAxis.setExtent(this.r0, this.r); var angle = this.startAngle + idx * Math.PI * 2 / this._indicatorAxes.length; angle = Math.atan2(Math.sin(angle), Math.cos(angle)), indicatorAxis.angle = angle; }, this); }, Radar.prototype.update = function(ecModel, api) { var indicatorAxes = this._indicatorAxes, radarModel = this._model; each(indicatorAxes, function(indicatorAxis) { indicatorAxis.scale.setExtent(1 / 0, -1 / 0); }), ecModel.eachSeriesByType('radar', function(radarSeries, idx) { if ('radar' === radarSeries.get('coordinateSystem') && ecModel.getComponent('radar', radarSeries.get('radarIndex')) === radarModel) { var data = radarSeries.getData(); each(indicatorAxes, function(indicatorAxis) { indicatorAxis.scale.unionExtentFromData(data, data.mapDimension(indicatorAxis.dim)); }); } }, this); var splitNumber = radarModel.get('splitNumber'); function increaseInterval(interval) { var exp10 = Math.pow(10, Math.floor(Math.log(interval) / Math.LN10)), f = interval / exp10; return 2 === f ? f = 5 : f *= 2, f * exp10; } each(indicatorAxes, function(indicatorAxis, idx) { var rawExtent = getScaleExtent(indicatorAxis.scale, indicatorAxis.model).extent; niceScaleExtent(indicatorAxis.scale, indicatorAxis.model); var axisModel = indicatorAxis.model, scale = indicatorAxis.scale, fixedMin = parseAxisModelMinMax(scale, axisModel.get('min', !0)), fixedMax = parseAxisModelMinMax(scale, axisModel.get('max', !0)), interval = scale.getInterval(); if (null != fixedMin && null != fixedMax) scale.setExtent(+fixedMin, +fixedMax), scale.setInterval((fixedMax - fixedMin) / splitNumber); else if (null != fixedMin) { var max = void 0; do max = fixedMin + interval * splitNumber, scale.setExtent(+fixedMin, max), scale.setInterval(interval), interval = increaseInterval(interval); while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1])) } else if (null != fixedMax) { var min = void 0; do min = fixedMax - interval * splitNumber, scale.setExtent(min, +fixedMax), scale.setInterval(interval), interval = increaseInterval(interval); while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0])) } else { scale.getTicks().length - 1 > splitNumber && (interval = increaseInterval(interval)); var max = Math.ceil(rawExtent[1] / interval) * interval, min = round(max - interval * splitNumber); scale.setExtent(min, max), scale.setInterval(interval); } }); }, Radar.prototype.convertToPixel = function(ecModel, finder, value) { return console.warn('Not implemented.'), null; }, Radar.prototype.convertFromPixel = function(ecModel, finder, pixel) { return console.warn('Not implemented.'), null; }, Radar.prototype.containPoint = function(point) { return console.warn('Not implemented.'), !1; }, Radar.create = function(ecModel, api) { var radarList = []; return ecModel.eachComponent('radar', function(radarModel) { var radar = new Radar(radarModel, ecModel, api); radarList.push(radar), radarModel.coordinateSystem = radar; }), ecModel.eachSeriesByType('radar', function(radarSeries) { 'radar' === radarSeries.get('coordinateSystem') && (radarSeries.coordinateSystem = radarList[radarSeries.get('radarIndex') || 0]); }), radarList; }, Radar.dimensions = [], Radar; }(); function install$7(registers) { registers.registerCoordinateSystem('radar', Radar), registers.registerComponentModel(RadarModel), registers.registerComponentView(RadarView$1), registers.registerVisual({ seriesType: 'radar', reset: function(seriesModel) { var data = seriesModel.getData(); data.each(function(idx) { data.setItemVisual(idx, 'legendSymbol', 'roundRect'); }), data.setVisual('legendSymbol', 'roundRect'); } }); } var ATTR = '\0_ec_interaction_mutex'; function getStore(zr) { return zr[ATTR] || (zr[ATTR] = {}); } registerAction({ type: 'takeGlobalCursor', event: 'globalCursorTaken', update: 'update' }, function() {}); var RoamController = function(_super) { function RoamController(zr) { var _this = _super.call(this) || this; _this._zr = zr; var mousedownHandler = bind(_this._mousedownHandler, _this), mousemoveHandler = bind(_this._mousemoveHandler, _this), mouseupHandler = bind(_this._mouseupHandler, _this), mousewheelHandler = bind(_this._mousewheelHandler, _this), pinchHandler = bind(_this._pinchHandler, _this); return _this.enable = function(controlType, opt) { this.disable(), this._opt = defaults(clone(opt) || {}, { zoomOnMouseWheel: !0, moveOnMouseMove: !0, moveOnMouseWheel: !1, preventDefaultMouseMove: !0 }), null == controlType && (controlType = !0), (!0 === controlType || 'move' === controlType || 'pan' === controlType) && (zr.on('mousedown', mousedownHandler), zr.on('mousemove', mousemoveHandler), zr.on('mouseup', mouseupHandler)), (!0 === controlType || 'scale' === controlType || 'zoom' === controlType) && (zr.on('mousewheel', mousewheelHandler), zr.on('pinch', pinchHandler)); }, _this.disable = function() { zr.off('mousedown', mousedownHandler), zr.off('mousemove', mousemoveHandler), zr.off('mouseup', mouseupHandler), zr.off('mousewheel', mousewheelHandler), zr.off('pinch', pinchHandler); }, _this; } return __extends(RoamController, _super), RoamController.prototype.isDragging = function() { return this._dragging; }, RoamController.prototype.isPinching = function() { return this._pinching; }, RoamController.prototype.setPointerChecker = function(pointerChecker) { this.pointerChecker = pointerChecker; }, RoamController.prototype.dispose = function() { this.disable(); }, RoamController.prototype._mousedownHandler = function(e) { if (!isMiddleOrRightButtonOnMouseUpDown(e) && (!e.target || !e.target.draggable)) { var x = e.offsetX, y = e.offsetY; this.pointerChecker && this.pointerChecker(e, x, y) && (this._x = x, this._y = y, this._dragging = !0); } }, RoamController.prototype._mousemoveHandler = function(e) { if (this._dragging && isAvailableBehavior('moveOnMouseMove', e, this._opt) && 'pinch' !== e.gestureEvent && !getStore(this._zr).globalPan) { var x = e.offsetX, y = e.offsetY, oldX = this._x, oldY = this._y; this._x = x, this._y = y, this._opt.preventDefaultMouseMove && stop(e.event), trigger(this, 'pan', 'moveOnMouseMove', e, { dx: x - oldX, dy: y - oldY, oldX: oldX, oldY: oldY, newX: x, newY: y, isAvailableBehavior: null }); } }, RoamController.prototype._mouseupHandler = function(e) { isMiddleOrRightButtonOnMouseUpDown(e) || (this._dragging = !1); }, RoamController.prototype._mousewheelHandler = function(e) { var shouldZoom = isAvailableBehavior('zoomOnMouseWheel', e, this._opt), shouldMove = isAvailableBehavior('moveOnMouseWheel', e, this._opt), wheelDelta = e.wheelDelta, absWheelDeltaDelta = Math.abs(wheelDelta), originX = e.offsetX, originY = e.offsetY; if (0 !== wheelDelta && (shouldZoom || shouldMove)) { if (shouldZoom) { var factor = absWheelDeltaDelta > 3 ? 1.4 : absWheelDeltaDelta > 1 ? 1.2 : 1.1; checkPointerAndTrigger(this, 'zoom', 'zoomOnMouseWheel', e, { scale: wheelDelta > 0 ? factor : 1 / factor, originX: originX, originY: originY, isAvailableBehavior: null }); } if (shouldMove) { var absDelta = Math.abs(wheelDelta); checkPointerAndTrigger(this, 'scrollMove', 'moveOnMouseWheel', e, { scrollDelta: (wheelDelta > 0 ? 1 : -1) * (absDelta > 3 ? 0.4 : absDelta > 1 ? 0.15 : 0.05), originX: originX, originY: originY, isAvailableBehavior: null }); } } }, RoamController.prototype._pinchHandler = function(e) { if (!getStore(this._zr).globalPan) { var scale = e.pinchScale > 1 ? 1.1 : 1 / 1.1; checkPointerAndTrigger(this, 'zoom', null, e, { scale: scale, originX: e.pinchX, originY: e.pinchY, isAvailableBehavior: null }); } }, RoamController; }(Eventful); function checkPointerAndTrigger(controller, eventName, behaviorToCheck, e, contollerEvent) { controller.pointerChecker && controller.pointerChecker(e, contollerEvent.originX, contollerEvent.originY) && (stop(e.event), trigger(controller, eventName, behaviorToCheck, e, contollerEvent)); } function trigger(controller, eventName, behaviorToCheck, e, contollerEvent) { contollerEvent.isAvailableBehavior = bind(isAvailableBehavior, null, behaviorToCheck, e), controller.trigger(eventName, contollerEvent); } function isAvailableBehavior(behaviorToCheck, e, settings) { var setting = settings[behaviorToCheck]; return !behaviorToCheck || setting && (!isString(setting) || e.event[setting + 'Key']); } function updateViewOnPan(controllerHost, dx, dy) { var target = controllerHost.target; target.x += dx, target.y += dy, target.dirty(); } function updateViewOnZoom(controllerHost, zoomDelta, zoomX, zoomY) { var target = controllerHost.target, zoomLimit = controllerHost.zoomLimit, newZoom = controllerHost.zoom = controllerHost.zoom || 1; if (newZoom *= zoomDelta, zoomLimit) { var zoomMin = zoomLimit.min || 0; newZoom = Math.max(Math.min(zoomLimit.max || 1 / 0, newZoom), zoomMin); } var zoomScale = newZoom / controllerHost.zoom; controllerHost.zoom = newZoom, target.x -= (zoomX - target.x) * (zoomScale - 1), target.y -= (zoomY - target.y) * (zoomScale - 1), target.scaleX *= zoomScale, target.scaleY *= zoomScale, target.dirty(); } var IRRELEVANT_EXCLUDES = { axisPointer: 1, tooltip: 1, brush: 1 }; function onIrrelevantElement(e, api, targetCoordSysModel) { var model = api.getComponentByElement(e.topTarget), coordSys = model && model.coordinateSystem; return model && model !== targetCoordSysModel && !IRRELEVANT_EXCLUDES.hasOwnProperty(model.mainType) && coordSys && coordSys.model !== targetCoordSysModel; } var OPTION_STYLE_ENABLED_TAGS = [ 'rect', 'circle', 'line', 'ellipse', 'polygon', 'polyline', 'path' ], OPTION_STYLE_ENABLED_TAG_MAP = createHashMap(OPTION_STYLE_ENABLED_TAGS), STATE_TRIGGER_TAG_MAP = createHashMap(OPTION_STYLE_ENABLED_TAGS.concat([ 'g' ])), LABEL_HOST_MAP = createHashMap(OPTION_STYLE_ENABLED_TAGS.concat([ 'g' ])), mapLabelRaw = makeInner(); function getFixedItemStyle(model) { var itemStyle = model.getItemStyle(), areaColor = model.get('areaColor'); return null != areaColor && (itemStyle.fill = areaColor), itemStyle; } var MapDraw = function() { function MapDraw(api) { var group = new Group(); this.uid = getUID('ec_map_draw'), this._controller = new RoamController(api.getZr()), this._controllerHost = { target: group }, this.group = group, group.add(this._regionsGroup = new Group()), group.add(this._svgGroup = new Group()); } return MapDraw.prototype.draw = function(mapOrGeoModel, ecModel, api, fromView, payload) { var isGeo = 'geo' === mapOrGeoModel.mainType, data = mapOrGeoModel.getData && mapOrGeoModel.getData(); isGeo && ecModel.eachComponent({ mainType: 'series', subType: 'map' }, function(mapSeries) { data || mapSeries.getHostGeoModel() !== mapOrGeoModel || (data = mapSeries.getData()); }); var geo = mapOrGeoModel.coordinateSystem, regionsGroup = this._regionsGroup, group = this.group, transformInfo = geo.getTransformInfo(), transformInfoRaw = transformInfo.raw, transformInfoRoam = transformInfo.roam; !regionsGroup.childAt(0) || payload ? (group.x = transformInfoRoam.x, group.y = transformInfoRoam.y, group.scaleX = transformInfoRoam.scaleX, group.scaleY = transformInfoRoam.scaleY, group.dirty()) : updateProps(group, transformInfoRoam, mapOrGeoModel); var isVisualEncodedByVisualMap = data && data.getVisual('visualMeta') && data.getVisual('visualMeta').length > 0, viewBuildCtx = { api: api, geo: geo, mapOrGeoModel: mapOrGeoModel, data: data, isVisualEncodedByVisualMap: isVisualEncodedByVisualMap, isGeo: isGeo, transformInfoRaw: transformInfoRaw }; 'geoJSON' === geo.resourceType ? this._buildGeoJSON(viewBuildCtx) : 'geoSVG' === geo.resourceType && this._buildSVG(viewBuildCtx), this._updateController(mapOrGeoModel, ecModel, api), this._updateMapSelectHandler(mapOrGeoModel, regionsGroup, api, fromView); }, MapDraw.prototype._buildGeoJSON = function(viewBuildCtx) { var nameMap = this._regionsGroupByName = createHashMap(), regionsGroup = this._regionsGroup, transformInfoRaw = viewBuildCtx.transformInfoRaw, mapOrGeoModel = viewBuildCtx.mapOrGeoModel, data = viewBuildCtx.data, transformPoint = function(point) { return [ point[0] * transformInfoRaw.scaleX + transformInfoRaw.x, point[1] * transformInfoRaw.scaleY + transformInfoRaw.y ]; }; regionsGroup.removeAll(), each(viewBuildCtx.geo.regions, function(region) { var regionName = region.name, regionModel = mapOrGeoModel.getRegionModel(regionName), dataIdx = data ? data.indexOfName(regionName) : null, regionGroup = nameMap.get(regionName), hasRegionGroup = !!regionGroup; hasRegionGroup || (regionGroup = nameMap.set(regionName, new Group()), regionsGroup.add(regionGroup)); var compoundPath = new CompoundPath({ segmentIgnoreThreshold: 1, shape: { paths: [] } }); regionGroup.add(compoundPath), hasRegionGroup || (resetEventTriggerForRegion(viewBuildCtx, regionGroup, regionName, regionModel, mapOrGeoModel, dataIdx), resetTooltipForRegion(viewBuildCtx, regionGroup, regionName, regionModel, mapOrGeoModel), resetStateTriggerForRegion(viewBuildCtx, regionGroup, regionName, regionModel, mapOrGeoModel)), each(region.geometries, function(geometry) { if ('polygon' === geometry.type) { for(var points = [], i = 0; i < geometry.exterior.length; ++i)points.push(transformPoint(geometry.exterior[i])); compoundPath.shape.paths.push(new Polygon({ segmentIgnoreThreshold: 1, shape: { points: points } })); for(var i = 0; i < (geometry.interiors ? geometry.interiors.length : 0); ++i){ for(var interior = geometry.interiors[i], points_1 = [], j = 0; j < interior.length; ++j)points_1.push(transformPoint(interior[j])); compoundPath.shape.paths.push(new Polygon({ segmentIgnoreThreshold: 1, shape: { points: points_1 } })); } } }), applyOptionStyleForRegion(viewBuildCtx, compoundPath, dataIdx, regionModel), compoundPath instanceof Displayable && (compoundPath.culling = !0), resetLabelForRegion(viewBuildCtx, compoundPath, regionName, regionModel, mapOrGeoModel, dataIdx, transformPoint(region.getCenter())); }, this); }, MapDraw.prototype._buildSVG = function(viewBuildCtx) { var mapName = viewBuildCtx.geo.map, transformInfoRaw = viewBuildCtx.transformInfoRaw; this._svgGroup.x = transformInfoRaw.x, this._svgGroup.y = transformInfoRaw.y, this._svgGroup.scaleX = transformInfoRaw.scaleX, this._svgGroup.scaleY = transformInfoRaw.scaleY, this._svgResourceChanged(mapName) && (this._freeSVG(), this._useSVG(mapName)); var svgDispatcherMap = this._svgDispatcherMap = createHashMap(), focusSelf = !1; each(this._svgGraphicRecord.named, function(namedItem) { var regionName = namedItem.name, mapOrGeoModel = viewBuildCtx.mapOrGeoModel, data = viewBuildCtx.data, svgNodeTagLower = namedItem.svgNodeTagLower, el = namedItem.el, dataIdx = data ? data.indexOfName(regionName) : null, regionModel = mapOrGeoModel.getRegionModel(regionName); null != OPTION_STYLE_ENABLED_TAG_MAP.get(svgNodeTagLower) && el instanceof Displayable && applyOptionStyleForRegion(viewBuildCtx, el, dataIdx, regionModel), el instanceof Displayable && (el.culling = !0), el.z2EmphasisLift = 0, namedItem.namedFrom || (null != LABEL_HOST_MAP.get(svgNodeTagLower) && resetLabelForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel, dataIdx, null), resetEventTriggerForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel, dataIdx), resetTooltipForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel), null != STATE_TRIGGER_TAG_MAP.get(svgNodeTagLower) && ('self' === resetStateTriggerForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel) && (focusSelf = !0), (svgDispatcherMap.get(regionName) || svgDispatcherMap.set(regionName, [])).push(el))); }, this), this._enableBlurEntireSVG(focusSelf, viewBuildCtx); }, MapDraw.prototype._enableBlurEntireSVG = function(focusSelf, viewBuildCtx) { if (focusSelf && viewBuildCtx.isGeo) { var opacity_1 = viewBuildCtx.mapOrGeoModel.getModel([ 'blur', 'itemStyle' ]).getItemStyle().opacity; this._svgGraphicRecord.root.traverse(function(el) { if (!el.isGroup) { setDefaultStateProxy(el); var style = el.ensureState('blur').style || {}; null == style.opacity && null != opacity_1 && (style.opacity = opacity_1), el.ensureState('emphasis'); } }); } }, MapDraw.prototype.remove = function() { this._regionsGroup.removeAll(), this._regionsGroupByName = null, this._svgGroup.removeAll(), this._freeSVG(), this._controller.dispose(), this._controllerHost = null; }, MapDraw.prototype.findHighDownDispatchers = function(name, geoModel) { if (null == name) return []; var geo = geoModel.coordinateSystem; if ('geoJSON' === geo.resourceType) { var regionsGroupByName = this._regionsGroupByName; if (regionsGroupByName) { var regionGroup = regionsGroupByName.get(name); return regionGroup ? [ regionGroup ] : []; } } else if ('geoSVG' === geo.resourceType) return this._svgDispatcherMap && this._svgDispatcherMap.get(name) || []; }, MapDraw.prototype._svgResourceChanged = function(mapName) { return this._svgMapName !== mapName; }, MapDraw.prototype._useSVG = function(mapName) { var resource = geoSourceManager.getGeoResource(mapName); if (resource && 'geoSVG' === resource.type) { var svgGraphic = resource.useGraphic(this.uid); this._svgGroup.add(svgGraphic.root), this._svgGraphicRecord = svgGraphic, this._svgMapName = mapName; } }, MapDraw.prototype._freeSVG = function() { var mapName = this._svgMapName; if (null != mapName) { var resource = geoSourceManager.getGeoResource(mapName); resource && 'geoSVG' === resource.type && resource.freeGraphic(this.uid), this._svgGraphicRecord = null, this._svgDispatcherMap = null, this._svgGroup.removeAll(), this._svgMapName = null; } }, MapDraw.prototype._updateController = function(mapOrGeoModel, ecModel, api) { var geo = mapOrGeoModel.coordinateSystem, controller = this._controller, controllerHost = this._controllerHost; controllerHost.zoomLimit = mapOrGeoModel.get('scaleLimit'), controllerHost.zoom = geo.getZoom(), controller.enable(mapOrGeoModel.get('roam') || !1); var mainType = mapOrGeoModel.mainType; function makeActionBase() { var action = { type: 'geoRoam', componentType: mainType }; return action[mainType + 'Id'] = mapOrGeoModel.id, action; } controller.off('pan').on('pan', function(e) { this._mouseDownFlag = !1, updateViewOnPan(controllerHost, e.dx, e.dy), api.dispatchAction(extend(makeActionBase(), { dx: e.dx, dy: e.dy })); }, this), controller.off('zoom').on('zoom', function(e) { this._mouseDownFlag = !1, updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY), api.dispatchAction(extend(makeActionBase(), { zoom: e.scale, originX: e.originX, originY: e.originY })); }, this), controller.setPointerChecker(function(e, x, y) { return geo.containPoint([ x, y ]) && !onIrrelevantElement(e, api, mapOrGeoModel); }); }, MapDraw.prototype.resetForLabelLayout = function() { this.group.traverse(function(el) { var label = el.getTextContent(); label && (label.ignore = mapLabelRaw(label).ignore); }); }, MapDraw.prototype._updateMapSelectHandler = function(mapOrGeoModel, regionsGroup, api, fromView) { var mapDraw = this; regionsGroup.off('mousedown'), regionsGroup.off('click'), mapOrGeoModel.get('selectedMode') && (regionsGroup.on('mousedown', function() { mapDraw._mouseDownFlag = !0; }), regionsGroup.on('click', function(e) { mapDraw._mouseDownFlag && (mapDraw._mouseDownFlag = !1); })); }, MapDraw; }(); function applyOptionStyleForRegion(viewBuildCtx, el, dataIndex, regionModel) { var normalStyleModel = regionModel.getModel('itemStyle'), emphasisStyleModel = regionModel.getModel([ 'emphasis', 'itemStyle' ]), blurStyleModel = regionModel.getModel([ 'blur', 'itemStyle' ]), selectStyleModel = regionModel.getModel([ 'select', 'itemStyle' ]), normalStyle = getFixedItemStyle(normalStyleModel), emphasisStyle = getFixedItemStyle(emphasisStyleModel), selectStyle = getFixedItemStyle(selectStyleModel), blurStyle = getFixedItemStyle(blurStyleModel), data = viewBuildCtx.data; if (data) { var style = data.getItemVisual(dataIndex, 'style'), decal = data.getItemVisual(dataIndex, 'decal'); viewBuildCtx.isVisualEncodedByVisualMap && style.fill && (normalStyle.fill = style.fill), decal && (normalStyle.decal = createOrUpdatePatternFromDecal(decal, viewBuildCtx.api)); } el.setStyle(normalStyle), el.style.strokeNoScale = !0, el.ensureState('emphasis').style = emphasisStyle, el.ensureState('select').style = selectStyle, el.ensureState('blur').style = blurStyle, setDefaultStateProxy(el); } function resetLabelForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel, dataIdx, labelXY) { var data = viewBuildCtx.data, isGeo = viewBuildCtx.isGeo, isDataNaN = data && isNaN(data.get(data.mapDimension('value'), dataIdx)), itemLayout = data && data.getItemLayout(dataIdx); if (isGeo || isDataNaN || itemLayout && itemLayout.showLabel) { var labelFetcher = void 0; (!data || dataIdx >= 0) && (labelFetcher = mapOrGeoModel), setLabelStyle(el, getLabelStatesModels(regionModel), { labelFetcher: labelFetcher, labelDataIndex: isGeo ? regionName : dataIdx, defaultText: regionName }, labelXY ? { normal: { align: 'center', verticalAlign: 'middle' } } : null); var textEl = el.getTextContent(); if (textEl && (mapLabelRaw(textEl).ignore = textEl.ignore, el.textConfig && labelXY)) { var rect = el.getBoundingRect().clone(); el.textConfig.position = [ (labelXY[0] - rect.x) / rect.width * 100 + '%', (labelXY[1] - rect.y) / rect.height * 100 + '%' ]; } getECData(el).dataIndex = dataIdx, getECData(el).dataType = null, el.disableLabelAnimation = !0; } else el.removeTextContent(), el.removeTextConfig(), el.disableLabelAnimation = null; } function resetEventTriggerForRegion(viewBuildCtx, eventTrigger, regionName, regionModel, mapOrGeoModel, dataIdx) { viewBuildCtx.data ? viewBuildCtx.data.setItemGraphicEl(dataIdx, eventTrigger) : getECData(eventTrigger).eventData = { componentType: 'geo', componentIndex: mapOrGeoModel.componentIndex, geoIndex: mapOrGeoModel.componentIndex, name: regionName, region: regionModel && regionModel.option || {} }; } function resetTooltipForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel) { viewBuildCtx.data || setTooltipConfig({ el: el, componentModel: mapOrGeoModel, itemName: regionName, itemTooltipOption: regionModel.get('tooltip') }); } function resetStateTriggerForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel) { el.highDownSilentOnTouch = !!mapOrGeoModel.get('selectedMode'); var ecData, emphasisModel = regionModel.getModel('emphasis'), focus = emphasisModel.get('focus'); return enableHoverEmphasis(el, focus, emphasisModel.get('blurScope')), viewBuildCtx.isGeo && ((ecData = getECData(el)).componentMainType = mapOrGeoModel.mainType, ecData.componentIndex = mapOrGeoModel.componentIndex, ecData.componentHighDownName = regionName), focus; } var MapView = function(_super) { function MapView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = MapView.type, _this; } return __extends(MapView, _super), MapView.prototype.render = function(mapModel, ecModel, api, payload) { if (!payload || 'mapToggleSelect' !== payload.type || payload.from !== this.uid) { var group = this.group; if (group.removeAll(), !mapModel.getHostGeoModel()) { if (this._mapDraw && payload && 'geoRoam' === payload.type && this._mapDraw.resetForLabelLayout(), payload && 'geoRoam' === payload.type && 'series' === payload.componentType && payload.seriesId === mapModel.id) { var mapDraw = this._mapDraw; mapDraw && group.add(mapDraw.group); } else if (mapModel.needsDrawMap) { var mapDraw = this._mapDraw || new MapDraw(api); group.add(mapDraw.group), mapDraw.draw(mapModel, ecModel, api, this, payload), this._mapDraw = mapDraw; } else this._mapDraw && this._mapDraw.remove(), this._mapDraw = null; mapModel.get('showLegendSymbol') && ecModel.getComponent('legend') && this._renderSymbols(mapModel, ecModel, api); } } }, MapView.prototype.remove = function() { this._mapDraw && this._mapDraw.remove(), this._mapDraw = null, this.group.removeAll(); }, MapView.prototype.dispose = function() { this._mapDraw && this._mapDraw.remove(), this._mapDraw = null; }, MapView.prototype._renderSymbols = function(mapModel, ecModel, api) { var originalData = mapModel.originalData, group = this.group; originalData.each(originalData.mapDimension('value'), function(value, originalDataIndex) { if (!isNaN(value)) { var layout = originalData.getItemLayout(originalDataIndex); if (layout && layout.point) { var point = layout.point, offset = layout.offset, circle = new Circle({ style: { fill: mapModel.getData().getVisual('style').fill }, shape: { cx: point[0] + 9 * offset, cy: point[1], r: 3 }, silent: !0, z2: 8 + (offset ? 0 : 11) }); if (!offset) { var fullData = mapModel.mainSeries.getData(), name_1 = originalData.getName(originalDataIndex), fullIndex_1 = fullData.indexOfName(name_1), itemModel = originalData.getItemModel(originalDataIndex), labelModel = itemModel.getModel('label'), regionGroup = fullData.getItemGraphicEl(fullIndex_1); setLabelStyle(circle, getLabelStatesModels(itemModel), { labelFetcher: { getFormattedLabel: function(idx, state) { return mapModel.getFormattedLabel(fullIndex_1, state); } } }), circle.disableLabelAnimation = !0, labelModel.get('position') || circle.setTextConfig({ position: 'bottom' }), regionGroup.onHoverStateChange = function(toState) { setStatesFlag(circle, toState); }; } group.add(circle); } } }); }, MapView.type = 'map', MapView; }(ChartView), MapSeries = function(_super) { function MapSeries() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = MapSeries.type, _this.needsDrawMap = !1, _this.seriesGroup = [], _this.getTooltipPosition = function(dataIndex) { if (null != dataIndex) { var name_1 = this.getData().getName(dataIndex), geo = this.coordinateSystem, region = geo.getRegion(name_1); return region && geo.dataToPoint(region.getCenter()); } }, _this; } return __extends(MapSeries, _super), MapSeries.prototype.getInitialData = function(option) { for(var data = createListSimply(this, { coordDimensions: [ 'value' ], encodeDefaulter: curry(makeSeriesEncodeForNameBased, this) }), dataNameMap = createHashMap(), toAppendNames = [], i = 0, len = data.count(); i < len; i++){ var name_2 = data.getName(i); dataNameMap.set(name_2, !0); } return each(geoSourceManager.load(this.getMapType(), this.option.nameMap, this.option.nameProperty).regions, function(region) { var name = region.name; dataNameMap.get(name) || toAppendNames.push(name); }), data.appendValues([], toAppendNames), data; }, MapSeries.prototype.getHostGeoModel = function() { var geoIndex = this.option.geoIndex; return null != geoIndex ? this.ecModel.getComponent('geo', geoIndex) : null; }, MapSeries.prototype.getMapType = function() { return (this.getHostGeoModel() || this).option.map; }, MapSeries.prototype.getRawValue = function(dataIndex) { var data = this.getData(); return data.get(data.mapDimension('value'), dataIndex); }, MapSeries.prototype.getRegionModel = function(regionName) { var data = this.getData(); return data.getItemModel(data.indexOfName(regionName)); }, MapSeries.prototype.formatTooltip = function(dataIndex, multipleSeries, dataType) { for(var data = this.getData(), value = this.getRawValue(dataIndex), name = data.getName(dataIndex), seriesGroup = this.seriesGroup, seriesNames = [], i = 0; i < seriesGroup.length; i++){ var otherIndex = seriesGroup[i].originalData.indexOfName(name), valueDim = data.mapDimension('value'); isNaN(seriesGroup[i].originalData.get(valueDim, otherIndex)) || seriesNames.push(seriesGroup[i].name); } return createTooltipMarkup('section', { header: seriesNames.join(', '), noHeader: !seriesNames.length, blocks: [ createTooltipMarkup('nameValue', { name: name, value: value }) ] }); }, MapSeries.prototype.setZoom = function(zoom) { this.option.zoom = zoom; }, MapSeries.prototype.setCenter = function(center) { this.option.center = center; }, MapSeries.prototype.getLegendIcon = function(opt) { var symbolType = opt.symbolType || 'roundRect', symbol = createSymbol(symbolType, 0, 0, opt.itemWidth, opt.itemHeight, opt.itemStyle.fill, opt.symbolKeepAspect); return symbol.setStyle(opt.itemStyle), symbol.style.stroke = 'none', symbolType.indexOf('empty') > -1 && (symbol.style.stroke = symbol.style.fill, symbol.style.fill = '#fff', symbol.style.lineWidth = 2), symbol; }, MapSeries.type = 'series.map', MapSeries.dependencies = [ 'geo' ], MapSeries.layoutMode = 'box', MapSeries.defaultOption = { zlevel: 0, z: 2, coordinateSystem: 'geo', map: '', left: 'center', top: 'center', aspectScale: null, showLegendSymbol: !0, boundingCoords: null, center: null, zoom: 1, scaleLimit: null, selectedMode: !0, label: { show: !1, color: '#000' }, itemStyle: { borderWidth: 0.5, borderColor: '#444', areaColor: '#eee' }, emphasis: { label: { show: !0, color: 'rgb(100,0,0)' }, itemStyle: { areaColor: 'rgba(255,215,0,0.8)' } }, select: { label: { show: !0, color: 'rgb(100,0,0)' }, itemStyle: { color: 'rgba(255,215,0,0.8)' } }, nameProperty: 'name' }, MapSeries; }(SeriesModel); function mapDataStatistic(ecModel) { var seriesGroups = {}; ecModel.eachSeriesByType('map', function(seriesModel) { var hostGeoModel = seriesModel.getHostGeoModel(), key = hostGeoModel ? 'o' + hostGeoModel.id : 'i' + seriesModel.getMapType(); (seriesGroups[key] = seriesGroups[key] || []).push(seriesModel); }), each(seriesGroups, function(seriesList, key) { for(var datas, statisticType, dataNameMap, data = (datas = map(seriesList, function(seriesModel) { return seriesModel.getData(); }), statisticType = seriesList[0].get('mapValueCalculation'), dataNameMap = {}, each(datas, function(data) { data.each(data.mapDimension('value'), function(value, idx) { var mapKey = 'ec-' + data.getName(idx); dataNameMap[mapKey] = dataNameMap[mapKey] || [], isNaN(value) || dataNameMap[mapKey].push(value); }); }), datas[0].map(datas[0].mapDimension('value'), function(value, idx) { for(var result, mapKey = 'ec-' + datas[0].getName(idx), sum = 0, min = 1 / 0, max = -1 / 0, len = dataNameMap[mapKey].length, i = 0; i < len; i++)min = Math.min(min, dataNameMap[mapKey][i]), max = Math.max(max, dataNameMap[mapKey][i]), sum += dataNameMap[mapKey][i]; return result = 'min' === statisticType ? min : 'max' === statisticType ? max : 'average' === statisticType ? sum / len : sum, 0 === len ? NaN : result; })), i = 0; i < seriesList.length; i++)seriesList[i].originalData = seriesList[i].getData(); for(var i = 0; i < seriesList.length; i++)seriesList[i].seriesGroup = seriesList, seriesList[i].needsDrawMap = 0 === i && !seriesList[i].getHostGeoModel(), seriesList[i].setData(data.cloneShallow()), seriesList[i].mainSeries = seriesList[0]; }); } function mapSymbolLayout(ecModel) { var processedMapType = {}; ecModel.eachSeriesByType('map', function(mapSeries) { var mapType = mapSeries.getMapType(); if (!mapSeries.getHostGeoModel() && !processedMapType[mapType]) { var mapSymbolOffsets = {}; each(mapSeries.seriesGroup, function(subMapSeries) { var geo = subMapSeries.coordinateSystem, data = subMapSeries.originalData; subMapSeries.get('showLegendSymbol') && ecModel.getComponent('legend') && data.each(data.mapDimension('value'), function(value, idx) { var name = data.getName(idx), region = geo.getRegion(name); if (!(!region || isNaN(value))) { var offset = mapSymbolOffsets[name] || 0, point = geo.dataToPoint(region.getCenter()); mapSymbolOffsets[name] = offset + 1, data.setItemLayout(idx, { point: point, offset: offset }); } }); }); var data = mapSeries.getData(); data.each(function(idx) { var name = data.getName(idx), layout = data.getItemLayout(idx) || {}; layout.showLabel = !mapSymbolOffsets[name], data.setItemLayout(idx, layout); }), processedMapType[mapType] = !0; } }); } var View = function(_super) { function View(name) { var _this = _super.call(this) || this; return _this.type = 'view', _this.dimensions = [ 'x', 'y' ], _this._roamTransformable = new Transformable(), _this._rawTransformable = new Transformable(), _this.name = name, _this; } return __extends(View, _super), View.prototype.setBoundingRect = function(x, y, width, height) { return this._rect = new BoundingRect(x, y, width, height), this._rect; }, View.prototype.getBoundingRect = function() { return this._rect; }, View.prototype.setViewRect = function(x, y, width, height) { this._transformTo(x, y, width, height), this._viewRect = new BoundingRect(x, y, width, height); }, View.prototype._transformTo = function(x, y, width, height) { var rect = this.getBoundingRect(), rawTransform = this._rawTransformable; rawTransform.transform = rect.calculateTransform(new BoundingRect(x, y, width, height)); var rawParent = rawTransform.parent; rawTransform.parent = null, rawTransform.decomposeTransform(), rawTransform.parent = rawParent, this._updateTransform(); }, View.prototype.setCenter = function(centerCoord) { centerCoord && (this._center = centerCoord, this._updateCenterAndZoom()); }, View.prototype.setZoom = function(zoom) { zoom = zoom || 1; var zoomLimit = this.zoomLimit; zoomLimit && (null != zoomLimit.max && (zoom = Math.min(zoomLimit.max, zoom)), null != zoomLimit.min && (zoom = Math.max(zoomLimit.min, zoom))), this._zoom = zoom, this._updateCenterAndZoom(); }, View.prototype.getDefaultCenter = function() { var rawRect = this.getBoundingRect(); return [ rawRect.x + rawRect.width / 2, rawRect.y + rawRect.height / 2 ]; }, View.prototype.getCenter = function() { return this._center || this.getDefaultCenter(); }, View.prototype.getZoom = function() { return this._zoom || 1; }, View.prototype.getRoamTransform = function() { return this._roamTransformable.getLocalTransform(); }, View.prototype._updateCenterAndZoom = function() { var rawTransformMatrix = this._rawTransformable.getLocalTransform(), roamTransform = this._roamTransformable, defaultCenter = this.getDefaultCenter(), center = this.getCenter(), zoom = this.getZoom(); center = applyTransform([], center, rawTransformMatrix), defaultCenter = applyTransform([], defaultCenter, rawTransformMatrix), roamTransform.originX = center[0], roamTransform.originY = center[1], roamTransform.x = defaultCenter[0] - center[0], roamTransform.y = defaultCenter[1] - center[1], roamTransform.scaleX = roamTransform.scaleY = zoom, this._updateTransform(); }, View.prototype._updateTransform = function() { var roamTransformable = this._roamTransformable, rawTransformable = this._rawTransformable; rawTransformable.parent = roamTransformable, roamTransformable.updateTransform(), rawTransformable.updateTransform(), copy$1(this.transform || (this.transform = []), rawTransformable.transform || create$1()), this._rawTransform = rawTransformable.getLocalTransform(), this.invTransform = this.invTransform || [], invert(this.invTransform, this.transform), this.decomposeTransform(); }, View.prototype.getTransformInfo = function() { var rawTransformable = this._rawTransformable, roamTransformable = this._roamTransformable, dummyTransformable = new Transformable(); return dummyTransformable.transform = roamTransformable.transform, dummyTransformable.decomposeTransform(), { roam: { x: dummyTransformable.x, y: dummyTransformable.y, scaleX: dummyTransformable.scaleX, scaleY: dummyTransformable.scaleY }, raw: { x: rawTransformable.x, y: rawTransformable.y, scaleX: rawTransformable.scaleX, scaleY: rawTransformable.scaleY } }; }, View.prototype.getViewRect = function() { return this._viewRect; }, View.prototype.getViewRectAfterRoam = function() { var rect = this.getBoundingRect().clone(); return rect.applyTransform(this.transform), rect; }, View.prototype.dataToPoint = function(data, noRoam, out) { var transform = noRoam ? this._rawTransform : this.transform; return out = out || [], transform ? applyTransform(out, data, transform) : copy(out, data); }, View.prototype.pointToData = function(point) { var invTransform = this.invTransform; return invTransform ? applyTransform([], point, invTransform) : [ point[0], point[1] ]; }, View.prototype.convertToPixel = function(ecModel, finder, value) { var coordSys = getCoordSys(finder); return coordSys === this ? coordSys.dataToPoint(value) : null; }, View.prototype.convertFromPixel = function(ecModel, finder, pixel) { var coordSys = getCoordSys(finder); return coordSys === this ? coordSys.pointToData(pixel) : null; }, View.prototype.containPoint = function(point) { return this.getViewRectAfterRoam().contain(point[0], point[1]); }, View.dimensions = [ 'x', 'y' ], View; }(Transformable); function getCoordSys(finder) { var seriesModel = finder.seriesModel; return seriesModel ? seriesModel.coordinateSystem : null; } var GEO_DEFAULT_PARAMS = { geoJSON: { aspectScale: 0.75, invertLongitute: !0 }, geoSVG: { aspectScale: 1, invertLongitute: !1 } }, Geo = function(_super) { function Geo(name, map, opt) { var _this = _super.call(this, name) || this; _this.dimensions = [ 'lng', 'lat' ], _this.type = 'geo', _this._nameCoordMap = createHashMap(), _this.map = map; var source = geoSourceManager.load(map, opt.nameMap, opt.nameProperty), resource = geoSourceManager.getGeoResource(map); _this.resourceType = resource ? resource.type : null; var defaultParmas = GEO_DEFAULT_PARAMS[resource.type]; _this._regionsMap = source.regionsMap, _this._invertLongitute = defaultParmas.invertLongitute, _this.regions = source.regions, _this.aspectScale = retrieve2(opt.aspectScale, defaultParmas.aspectScale); var boundingRect = source.boundingRect; return _this.setBoundingRect(boundingRect.x, boundingRect.y, boundingRect.width, boundingRect.height), _this; } return __extends(Geo, _super), Geo.prototype._transformTo = function(x, y, width, height) { var rect = this.getBoundingRect(), invertLongitute = this._invertLongitute; rect = rect.clone(), invertLongitute && (rect.y = -rect.y - rect.height); var rawTransformable = this._rawTransformable; rawTransformable.transform = rect.calculateTransform(new BoundingRect(x, y, width, height)); var rawParent = rawTransformable.parent; rawTransformable.parent = null, rawTransformable.decomposeTransform(), rawTransformable.parent = rawParent, invertLongitute && (rawTransformable.scaleY = -rawTransformable.scaleY), this._updateTransform(); }, Geo.prototype.getRegion = function(name) { return this._regionsMap.get(name); }, Geo.prototype.getRegionByCoord = function(coord) { for(var regions = this.regions, i = 0; i < regions.length; i++){ var region = regions[i]; if ('geoJSON' === region.type && region.contain(coord)) return regions[i]; } }, Geo.prototype.addGeoCoord = function(name, geoCoord) { this._nameCoordMap.set(name, geoCoord); }, Geo.prototype.getGeoCoord = function(name) { var region = this._regionsMap.get(name); return this._nameCoordMap.get(name) || region && region.getCenter(); }, Geo.prototype.dataToPoint = function(data, noRoam, out) { if ('string' == typeof data && (data = this.getGeoCoord(data)), data) return View.prototype.dataToPoint.call(this, data, noRoam, out); }, Geo.prototype.convertToPixel = function(ecModel, finder, value) { var coordSys = getCoordSys$1(finder); return coordSys === this ? coordSys.dataToPoint(value) : null; }, Geo.prototype.convertFromPixel = function(ecModel, finder, pixel) { var coordSys = getCoordSys$1(finder); return coordSys === this ? coordSys.pointToData(pixel) : null; }, Geo; }(View); function getCoordSys$1(finder) { var geoModel = finder.geoModel, seriesModel = finder.seriesModel; return geoModel ? geoModel.coordinateSystem : seriesModel ? seriesModel.coordinateSystem || (seriesModel.getReferringComponents('geo', SINGLE_REFERRING).models[0] || {}).coordinateSystem : null; } function resizeGeo(geoModel, api) { var center, size, viewRect, boundingCoords = geoModel.get('boundingCoords'); if (null != boundingCoords) { var leftTop = boundingCoords[0], rightBottom = boundingCoords[1]; isNaN(leftTop[0]) || isNaN(leftTop[1]) || isNaN(rightBottom[0]) || isNaN(rightBottom[1]) ? console.error('Invalid boundingCoords') : this.setBoundingRect(leftTop[0], leftTop[1], rightBottom[0] - leftTop[0], rightBottom[1] - leftTop[1]); } var rect = this.getBoundingRect(), centerOption = geoModel.get('layoutCenter'), sizeOption = geoModel.get('layoutSize'), viewWidth = api.getWidth(), viewHeight = api.getHeight(), aspect = rect.width / rect.height * this.aspectScale, useCenterAndSize = !1; if (centerOption && sizeOption && (center = [ parsePercent$1(centerOption[0], viewWidth), parsePercent$1(centerOption[1], viewHeight) ], size = parsePercent$1(sizeOption, Math.min(viewWidth, viewHeight)), isNaN(center[0]) || isNaN(center[1]) || isNaN(size) ? console.warn('Given layoutCenter or layoutSize data are invalid. Use left/top/width/height instead.') : useCenterAndSize = !0), useCenterAndSize) viewRect = {}, aspect > 1 ? (viewRect.width = size, viewRect.height = size / aspect) : (viewRect.height = size, viewRect.width = size * aspect), viewRect.y = center[1] - viewRect.height / 2, viewRect.x = center[0] - viewRect.width / 2; else { var boxLayoutOption = geoModel.getBoxLayoutParams(); boxLayoutOption.aspect = aspect, viewRect = getLayoutRect(boxLayoutOption, { width: viewWidth, height: viewHeight }); } this.setViewRect(viewRect.x, viewRect.y, viewRect.width, viewRect.height), this.setCenter(geoModel.get('center')), this.setZoom(geoModel.get('zoom')); } mixin(Geo, View); var geoCreator = new (function() { function GeoCreator() { this.dimensions = Geo.prototype.dimensions; } return GeoCreator.prototype.create = function(ecModel, api) { var geoList = []; ecModel.eachComponent('geo', function(geoModel, idx) { var name = geoModel.get('map'), geo = new Geo(name + idx, name, { nameMap: geoModel.get('nameMap'), nameProperty: geoModel.get('nameProperty'), aspectScale: geoModel.get('aspectScale') }); geo.zoomLimit = geoModel.get('scaleLimit'), geoList.push(geo), geoModel.coordinateSystem = geo, geo.model = geoModel, geo.resize = resizeGeo, geo.resize(geoModel, api); }), ecModel.eachSeries(function(seriesModel) { if ('geo' === seriesModel.get('coordinateSystem')) { var geoIndex = seriesModel.get('geoIndex') || 0; seriesModel.coordinateSystem = geoList[geoIndex]; } }); var mapModelGroupBySeries = {}; return ecModel.eachSeriesByType('map', function(seriesModel) { if (!seriesModel.getHostGeoModel()) { var mapType = seriesModel.getMapType(); mapModelGroupBySeries[mapType] = mapModelGroupBySeries[mapType] || [], mapModelGroupBySeries[mapType].push(seriesModel); } }), each(mapModelGroupBySeries, function(mapSeries, mapType) { var nameMapList = map(mapSeries, function(singleMapSeries) { return singleMapSeries.get('nameMap'); }), geo = new Geo(mapType, mapType, { nameMap: mergeAll(nameMapList), nameProperty: mapSeries[0].get('nameProperty'), aspectScale: mapSeries[0].get('aspectScale') }); geo.zoomLimit = retrieve.apply(null, map(mapSeries, function(singleMapSeries) { return singleMapSeries.get('scaleLimit'); })), geoList.push(geo), geo.resize = resizeGeo, geo.resize(mapSeries[0], api), each(mapSeries, function(singleMapSeries) { singleMapSeries.coordinateSystem = geo, each(singleMapSeries.get('geoCoord'), function(geoCoord, name) { geo.addGeoCoord(name, geoCoord); }); }); }), geoList; }, GeoCreator.prototype.getFilledRegions = function(originRegionArr, mapName, nameMap, nameProperty) { for(var regionsArr = (originRegionArr || []).slice(), dataNameMap = createHashMap(), i = 0; i < regionsArr.length; i++)dataNameMap.set(regionsArr[i].name, regionsArr[i]); return each(geoSourceManager.load(mapName, nameMap, nameProperty).regions, function(region) { var name = region.name; dataNameMap.get(name) || regionsArr.push({ name: name }); }), regionsArr; }, GeoCreator; }())(), GeoModel = function(_super) { function GeoModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = GeoModel.type, _this; } return __extends(GeoModel, _super), GeoModel.prototype.init = function(option, parentModel, ecModel) { var source = geoSourceManager.getGeoResource(option.map); if (source && 'geoJSON' === source.type) { var itemStyle = option.itemStyle = option.itemStyle || {}; 'color' in itemStyle || (itemStyle.color = '#eee'); } this.mergeDefaultAndTheme(option, ecModel), defaultEmphasis(option, 'label', [ 'show' ]); }, GeoModel.prototype.optionUpdated = function() { var _this = this, option = this.option; option.regions = geoCreator.getFilledRegions(option.regions, option.map, option.nameMap, option.nameProperty); var selectedMap = {}; this._optionModelMap = reduce(option.regions || [], function(optionModelMap, regionOpt) { var regionName = regionOpt.name; return regionName && (optionModelMap.set(regionName, new Model(regionOpt, _this, _this.ecModel)), regionOpt.selected && (selectedMap[regionName] = !0)), optionModelMap; }, createHashMap()), option.selectedMap || (option.selectedMap = selectedMap); }, GeoModel.prototype.getRegionModel = function(name) { return this._optionModelMap.get(name) || new Model(null, this, this.ecModel); }, GeoModel.prototype.getFormattedLabel = function(name, status) { var regionModel = this.getRegionModel(name), formatter = 'normal' === status ? regionModel.get([ 'label', 'formatter' ]) : regionModel.get([ 'emphasis', 'label', 'formatter' ]), params = { name: name }; return 'function' == typeof formatter ? (params.status = status, formatter(params)) : 'string' == typeof formatter ? formatter.replace('{a}', null != name ? name : '') : void 0; }, GeoModel.prototype.setZoom = function(zoom) { this.option.zoom = zoom; }, GeoModel.prototype.setCenter = function(center) { this.option.center = center; }, GeoModel.prototype.select = function(name) { var option = this.option, selectedMode = option.selectedMode; selectedMode && ('multiple' !== selectedMode && (option.selectedMap = null), (option.selectedMap || (option.selectedMap = {}))[name] = !0); }, GeoModel.prototype.unSelect = function(name) { var selectedMap = this.option.selectedMap; selectedMap && (selectedMap[name] = !1); }, GeoModel.prototype.toggleSelected = function(name) { this[this.isSelected(name) ? 'unSelect' : 'select'](name); }, GeoModel.prototype.isSelected = function(name) { var selectedMap = this.option.selectedMap; return !!(selectedMap && selectedMap[name]); }, GeoModel.type = 'geo', GeoModel.layoutMode = 'box', GeoModel.defaultOption = { zlevel: 0, z: 0, show: !0, left: 'center', top: 'center', aspectScale: null, silent: !1, map: '', boundingCoords: null, center: null, zoom: 1, scaleLimit: null, label: { show: !1, color: '#000' }, itemStyle: { borderWidth: 0.5, borderColor: '#444' }, emphasis: { label: { show: !0, color: 'rgb(100,0,0)' }, itemStyle: { color: 'rgba(255,215,0,0.8)' } }, select: { label: { show: !0, color: 'rgb(100,0,0)' }, itemStyle: { color: 'rgba(255,215,0,0.8)' } }, regions: [] }, GeoModel; }(ComponentModel); function updateCenterAndZoom(view, payload, zoomLimit) { var previousZoom = view.getZoom(), center = view.getCenter(), zoom = payload.zoom, point = view.dataToPoint(center); if (null != payload.dx && null != payload.dy && (point[0] -= payload.dx, point[1] -= payload.dy, view.setCenter(view.pointToData(point))), null != zoom) { if (zoomLimit) { var zoomMin = zoomLimit.min || 0; zoom = Math.max(Math.min(previousZoom * zoom, zoomLimit.max || 1 / 0), zoomMin) / previousZoom; } view.scaleX *= zoom, view.scaleY *= zoom; var fixX = (payload.originX - view.x) * (zoom - 1), fixY = (payload.originY - view.y) * (zoom - 1); view.x -= fixX, view.y -= fixY, view.updateTransform(), view.setCenter(view.pointToData(point)), view.setZoom(zoom * previousZoom); } return { center: view.getCenter(), zoom: view.getZoom() }; } var GeoView = function(_super) { function GeoView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = GeoView.type, _this.focusBlurEnabled = !0, _this; } return __extends(GeoView, _super), GeoView.prototype.init = function(ecModel, api) { var mapDraw = new MapDraw(api); this._mapDraw = mapDraw, this.group.add(mapDraw.group), this._api = api; }, GeoView.prototype.render = function(geoModel, ecModel, api, payload) { var mapDraw = this._mapDraw; geoModel.get('show') ? mapDraw.draw(geoModel, ecModel, api, this, payload) : this._mapDraw.group.removeAll(), mapDraw.group.on('click', this._handleRegionClick, this), mapDraw.group.silent = geoModel.get('silent'), this._model = geoModel, this.updateSelectStatus(geoModel, ecModel, api); }, GeoView.prototype._handleRegionClick = function(e) { var eventData; findEventDispatcher(e.target, function(current) { return null != (eventData = getECData(current).eventData); }, !0), eventData && this._api.dispatchAction({ type: 'geoToggleSelect', geoId: this._model.id, name: eventData.name }); }, GeoView.prototype.updateSelectStatus = function(model, ecModel, api) { var _this = this; this._mapDraw.group.traverse(function(node) { var eventData = getECData(node).eventData; if (eventData) return _this._model.isSelected(eventData.name) ? api.enterSelect(node) : api.leaveSelect(node), !0; }); }, GeoView.prototype.findHighDownDispatchers = function(name) { return this._mapDraw && this._mapDraw.findHighDownDispatchers(name, this._model); }, GeoView.prototype.dispose = function() { this._mapDraw && this._mapDraw.remove(); }, GeoView.type = 'geo', GeoView; }(ComponentView); function install$9(registers) { function makeAction(method, actionInfo) { actionInfo.update = 'geo:updateSelectStatus', registers.registerAction(actionInfo, function(payload, ecModel) { var selected = {}, allSelected = []; return ecModel.eachComponent({ mainType: 'geo', query: payload }, function(geoModel) { geoModel[method](payload.name), each(geoModel.coordinateSystem.regions, function(region) { selected[region.name] = geoModel.isSelected(region.name) || !1; }); var names = []; each(selected, function(v, name) { selected[name] && names.push(name); }), allSelected.push({ geoIndex: geoModel.componentIndex, name: names }); }), { selected: selected, allSelected: allSelected, name: payload.name }; }); } registers.registerCoordinateSystem('geo', geoCreator), registers.registerComponentModel(GeoModel), registers.registerComponentView(GeoView), makeAction('toggleSelected', { type: 'geoToggleSelect', event: 'geoselectchanged' }), makeAction('select', { type: 'geoSelect', event: 'geoselected' }), makeAction('unSelect', { type: 'geoUnSelect', event: 'geounselected' }), registers.registerAction({ type: 'geoRoam', event: 'geoRoam', update: 'updateTransform' }, function(payload, ecModel) { var componentType = payload.componentType || 'series'; ecModel.eachComponent({ mainType: componentType, query: payload }, function(componentModel) { var geo = componentModel.coordinateSystem; if ('geo' === geo.type) { var res = updateCenterAndZoom(geo, payload, componentModel.get('scaleLimit')); componentModel.setCenter && componentModel.setCenter(res.center), componentModel.setZoom && componentModel.setZoom(res.zoom), 'series' === componentType && each(componentModel.seriesGroup, function(seriesModel) { seriesModel.setCenter(res.center), seriesModel.setZoom(res.zoom); }); } }); }); } function firstWalk(node, separation) { var children = node.isExpand ? node.children : [], siblings = node.parentNode.children, subtreeW = node.hierNode.i ? siblings[node.hierNode.i - 1] : null; if (children.length) { !function(node) { for(var children = node.children, n = children.length, shift = 0, change = 0; --n >= 0;){ var child = children[n]; child.hierNode.prelim += shift, child.hierNode.modifier += shift, change += child.hierNode.change, shift += child.hierNode.shift + change; } }(node); var midPoint = (children[0].hierNode.prelim + children[children.length - 1].hierNode.prelim) / 2; subtreeW ? (node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW), node.hierNode.modifier = node.hierNode.prelim - midPoint) : node.hierNode.prelim = midPoint; } else subtreeW && (node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW)); node.parentNode.hierNode.defaultAncestor = function(subtreeV, subtreeW, ancestor, separation) { if (subtreeW) { for(var nodeOutRight = subtreeV, nodeInRight = subtreeV, nodeOutLeft = nodeInRight.parentNode.children[0], nodeInLeft = subtreeW, sumOutRight = nodeOutRight.hierNode.modifier, sumInRight = nodeInRight.hierNode.modifier, sumOutLeft = nodeOutLeft.hierNode.modifier, sumInLeft = nodeInLeft.hierNode.modifier; nodeInLeft = nextRight(nodeInLeft), nodeInRight = nextLeft(nodeInRight), nodeInLeft && nodeInRight;){ nodeOutRight = nextRight(nodeOutRight), nodeOutLeft = nextLeft(nodeOutLeft), nodeOutRight.hierNode.ancestor = subtreeV; var nodeInLeft1, ancestor1, shift = nodeInLeft.hierNode.prelim + sumInLeft - nodeInRight.hierNode.prelim - sumInRight + separation(nodeInLeft, nodeInRight); shift > 0 && (function(wl, wr, shift) { var change = shift / (wr.hierNode.i - wl.hierNode.i); wr.hierNode.change -= change, wr.hierNode.shift += shift, wr.hierNode.modifier += shift, wr.hierNode.prelim += shift, wl.hierNode.change += change; }((nodeInLeft1 = nodeInLeft, ancestor1 = ancestor, nodeInLeft1.hierNode.ancestor.parentNode === subtreeV.parentNode ? nodeInLeft1.hierNode.ancestor : ancestor1), subtreeV, shift), sumInRight += shift, sumOutRight += shift), sumInLeft += nodeInLeft.hierNode.modifier, sumInRight += nodeInRight.hierNode.modifier, sumOutRight += nodeOutRight.hierNode.modifier, sumOutLeft += nodeOutLeft.hierNode.modifier; } nodeInLeft && !nextRight(nodeOutRight) && (nodeOutRight.hierNode.thread = nodeInLeft, nodeOutRight.hierNode.modifier += sumInLeft - sumOutRight), nodeInRight && !nextLeft(nodeOutLeft) && (nodeOutLeft.hierNode.thread = nodeInRight, nodeOutLeft.hierNode.modifier += sumInRight - sumOutLeft, ancestor = subtreeV); } return ancestor; }(node, subtreeW, node.parentNode.hierNode.defaultAncestor || siblings[0], separation); } function secondWalk(node) { var nodeX = node.hierNode.prelim + node.parentNode.hierNode.modifier; node.setLayout({ x: nodeX }, !0), node.hierNode.modifier += node.parentNode.hierNode.modifier; } function separation(cb) { return arguments.length ? cb : defaultSeparation; } function radialCoordinate(rad, r) { return { x: r * Math.cos(rad -= Math.PI / 2), y: r * Math.sin(rad) }; } function nextRight(node) { var children = node.children; return children.length && node.isExpand ? children[children.length - 1] : node.hierNode.thread; } function nextLeft(node) { var children = node.children; return children.length && node.isExpand ? children[0] : node.hierNode.thread; } function defaultSeparation(node1, node2) { return node1.parentNode === node2.parentNode ? 1 : 2; } var TreeEdgeShape = function() { this.parentPoint = [], this.childPoints = []; }, TreePath = function(_super) { function TreePath(opts) { return _super.call(this, opts) || this; } return __extends(TreePath, _super), TreePath.prototype.getDefaultStyle = function() { return { stroke: '#000', fill: null }; }, TreePath.prototype.getDefaultShape = function() { return new TreeEdgeShape(); }, TreePath.prototype.buildPath = function(ctx, shape) { var childPoints = shape.childPoints, childLen = childPoints.length, parentPoint = shape.parentPoint, firstChildPos = childPoints[0], lastChildPos = childPoints[childLen - 1]; if (1 === childLen) { ctx.moveTo(parentPoint[0], parentPoint[1]), ctx.lineTo(firstChildPos[0], firstChildPos[1]); return; } var orient = shape.orient, forkDim = 'TB' === orient || 'BT' === orient ? 0 : 1, otherDim = 1 - forkDim, forkPosition = parsePercent$1(shape.forkPosition, 1), tmpPoint = []; tmpPoint[forkDim] = parentPoint[forkDim], tmpPoint[otherDim] = parentPoint[otherDim] + (lastChildPos[otherDim] - parentPoint[otherDim]) * forkPosition, ctx.moveTo(parentPoint[0], parentPoint[1]), ctx.lineTo(tmpPoint[0], tmpPoint[1]), ctx.moveTo(firstChildPos[0], firstChildPos[1]), tmpPoint[forkDim] = firstChildPos[forkDim], ctx.lineTo(tmpPoint[0], tmpPoint[1]), tmpPoint[forkDim] = lastChildPos[forkDim], ctx.lineTo(tmpPoint[0], tmpPoint[1]), ctx.lineTo(lastChildPos[0], lastChildPos[1]); for(var i = 1; i < childLen - 1; i++){ var point = childPoints[i]; ctx.moveTo(point[0], point[1]), tmpPoint[forkDim] = point[forkDim], ctx.lineTo(tmpPoint[0], tmpPoint[1]); } }, TreePath; }(Path), TreeView = function(_super) { function TreeView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = TreeView.type, _this._mainGroup = new Group(), _this; } return __extends(TreeView, _super), TreeView.prototype.init = function(ecModel, api) { this._controller = new RoamController(api.getZr()), this._controllerHost = { target: this.group }, this.group.add(this._mainGroup); }, TreeView.prototype.render = function(seriesModel, ecModel, api) { var data = seriesModel.getData(), layoutInfo = seriesModel.layoutInfo, group = this._mainGroup; 'radial' === seriesModel.get('layout') ? (group.x = layoutInfo.x + layoutInfo.width / 2, group.y = layoutInfo.y + layoutInfo.height / 2) : (group.x = layoutInfo.x, group.y = layoutInfo.y), this._updateViewCoordSys(seriesModel), this._updateController(seriesModel, ecModel, api); var oldData = this._data; data.diff(oldData).add(function(newIdx) { symbolNeedsDraw$1(data, newIdx) && updateNode(data, newIdx, null, group, seriesModel); }).update(function(newIdx, oldIdx) { var symbolEl = oldData.getItemGraphicEl(oldIdx); if (!symbolNeedsDraw$1(data, newIdx)) { symbolEl && removeNode(oldData, oldIdx, symbolEl, group, seriesModel); return; } updateNode(data, newIdx, symbolEl, group, seriesModel); }).remove(function(oldIdx) { var symbolEl = oldData.getItemGraphicEl(oldIdx); symbolEl && removeNode(oldData, oldIdx, symbolEl, group, seriesModel); }).execute(), this._nodeScaleRatio = seriesModel.get('nodeScaleRatio'), this._updateNodeAndLinkScale(seriesModel), !0 === seriesModel.get('expandAndCollapse') && data.eachItemGraphicEl(function(el, dataIndex) { el.off('click').on('click', function() { api.dispatchAction({ type: 'treeExpandAndCollapse', seriesId: seriesModel.id, dataIndex: dataIndex }); }); }), this._data = data; }, TreeView.prototype._updateViewCoordSys = function(seriesModel) { var data = seriesModel.getData(), points = []; data.each(function(idx) { var layout = data.getItemLayout(idx); !layout || isNaN(layout.x) || isNaN(layout.y) || points.push([ +layout.x, +layout.y ]); }); var min = [], max = []; fromPoints(points, min, max); var oldMin = this._min, oldMax = this._max; max[0] - min[0] == 0 && (min[0] = oldMin ? oldMin[0] : min[0] - 1, max[0] = oldMax ? oldMax[0] : max[0] + 1), max[1] - min[1] == 0 && (min[1] = oldMin ? oldMin[1] : min[1] - 1, max[1] = oldMax ? oldMax[1] : max[1] + 1); var viewCoordSys = seriesModel.coordinateSystem = new View(); viewCoordSys.zoomLimit = seriesModel.get('scaleLimit'), viewCoordSys.setBoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]), viewCoordSys.setCenter(seriesModel.get('center')), viewCoordSys.setZoom(seriesModel.get('zoom')), this.group.attr({ x: viewCoordSys.x, y: viewCoordSys.y, scaleX: viewCoordSys.scaleX, scaleY: viewCoordSys.scaleY }), this._min = min, this._max = max; }, TreeView.prototype._updateController = function(seriesModel, ecModel, api) { var _this = this, controller = this._controller, controllerHost = this._controllerHost, group = this.group; controller.setPointerChecker(function(e, x, y) { var rect = group.getBoundingRect(); return rect.applyTransform(group.transform), rect.contain(x, y) && !onIrrelevantElement(e, api, seriesModel); }), controller.enable(seriesModel.get('roam')), controllerHost.zoomLimit = seriesModel.get('scaleLimit'), controllerHost.zoom = seriesModel.coordinateSystem.getZoom(), controller.off('pan').off('zoom').on('pan', function(e) { updateViewOnPan(controllerHost, e.dx, e.dy), api.dispatchAction({ seriesId: seriesModel.id, type: 'treeRoam', dx: e.dx, dy: e.dy }); }).on('zoom', function(e) { updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY), api.dispatchAction({ seriesId: seriesModel.id, type: 'treeRoam', zoom: e.scale, originX: e.originX, originY: e.originY }), _this._updateNodeAndLinkScale(seriesModel), api.updateLabelLayout(); }); }, TreeView.prototype._updateNodeAndLinkScale = function(seriesModel) { var data = seriesModel.getData(), nodeScale = this._getNodeGlobalScale(seriesModel); data.eachItemGraphicEl(function(el, idx) { el.setSymbolScale(nodeScale); }); }, TreeView.prototype._getNodeGlobalScale = function(seriesModel) { var coordSys = seriesModel.coordinateSystem; if ('view' !== coordSys.type) return 1; var nodeScaleRatio = this._nodeScaleRatio, groupZoom = coordSys.scaleX || 1; return ((coordSys.getZoom() - 1) * nodeScaleRatio + 1) / groupZoom; }, TreeView.prototype.dispose = function() { this._controller && this._controller.dispose(), this._controllerHost = null; }, TreeView.prototype.remove = function() { this._mainGroup.removeAll(), this._data = null; }, TreeView.type = 'tree', TreeView; }(ChartView); function symbolNeedsDraw$1(data, dataIndex) { var layout = data.getItemLayout(dataIndex); return layout && !isNaN(layout.x) && !isNaN(layout.y); } function updateNode(data, dataIndex, symbolEl, group, seriesModel) { var isInit = !symbolEl, node = data.tree.getNodeByDataIndex(dataIndex), itemModel = node.getModel(), visualColor = node.getVisual('style').fill, symbolInnerColor = !1 === node.isExpand && 0 !== node.children.length ? visualColor : '#fff', virtualRoot = data.tree.root, source = node.parentNode === virtualRoot ? node : node.parentNode || node, sourceSymbolEl = data.getItemGraphicEl(source.dataIndex), sourceLayout = source.getLayout(), sourceOldLayout = sourceSymbolEl ? { x: sourceSymbolEl.__oldX, y: sourceSymbolEl.__oldY, rawX: sourceSymbolEl.__radialOldRawX, rawY: sourceSymbolEl.__radialOldRawY } : sourceLayout, targetLayout = node.getLayout(); isInit ? ((symbolEl = new Symbol(data, dataIndex, null, { symbolInnerColor: symbolInnerColor, useNameLabel: !0 })).x = sourceOldLayout.x, symbolEl.y = sourceOldLayout.y) : symbolEl.updateData(data, dataIndex, null, { symbolInnerColor: symbolInnerColor, useNameLabel: !0 }), symbolEl.__radialOldRawX = symbolEl.__radialRawX, symbolEl.__radialOldRawY = symbolEl.__radialRawY, symbolEl.__radialRawX = targetLayout.rawX, symbolEl.__radialRawY = targetLayout.rawY, group.add(symbolEl), data.setItemGraphicEl(dataIndex, symbolEl), symbolEl.__oldX = symbolEl.x, symbolEl.__oldY = symbolEl.y, updateProps(symbolEl, { x: targetLayout.x, y: targetLayout.y }, seriesModel); var symbolPath = symbolEl.getSymbolPath(); if ('radial' === seriesModel.get('layout')) { var realRoot = virtualRoot.children[0], rootLayout = realRoot.getLayout(), length_1 = realRoot.children.length, rad = void 0, isLeft = void 0; if (targetLayout.x === rootLayout.x && !0 === node.isExpand) { var center = { x: (realRoot.children[0].getLayout().x + realRoot.children[length_1 - 1].getLayout().x) / 2, y: (realRoot.children[0].getLayout().y + realRoot.children[length_1 - 1].getLayout().y) / 2 }; (rad = Math.atan2(center.y - rootLayout.y, center.x - rootLayout.x)) < 0 && (rad = 2 * Math.PI + rad), (isLeft = center.x < rootLayout.x) && (rad -= Math.PI); } else (rad = Math.atan2(targetLayout.y - rootLayout.y, targetLayout.x - rootLayout.x)) < 0 && (rad = 2 * Math.PI + rad), 0 === node.children.length || 0 !== node.children.length && !1 === node.isExpand ? (isLeft = targetLayout.x < rootLayout.x) && (rad -= Math.PI) : (isLeft = targetLayout.x > rootLayout.x) || (rad -= Math.PI); var textPosition = isLeft ? 'left' : 'right', normalLabelModel = itemModel.getModel('label'), rotate = normalLabelModel.get('rotate'), textContent = symbolPath.getTextContent(); textContent && (symbolPath.setTextConfig({ position: normalLabelModel.get('position') || textPosition, rotation: null == rotate ? -rad : rotate * (Math.PI / 180), origin: 'center' }), textContent.setStyle('verticalAlign', 'middle')); } var focus = itemModel.get([ 'emphasis', 'focus' ]), focusDataIndices = 'ancestor' === focus ? node.getAncestorsIndices() : 'descendant' === focus ? node.getDescendantIndices() : null; focusDataIndices && (getECData(symbolEl).focus = focusDataIndices), function(seriesModel, node, virtualRoot, symbolEl, sourceOldLayout, sourceLayout, targetLayout, group) { var itemModel = node.getModel(), edgeShape = seriesModel.get('edgeShape'), layout = seriesModel.get('layout'), orient = seriesModel.getOrient(), curvature = seriesModel.get([ 'lineStyle', 'curveness' ]), edgeForkPosition = seriesModel.get('edgeForkPosition'), lineStyle = itemModel.getModel('lineStyle').getLineStyle(), edge = symbolEl.__edge; if ('curve' === edgeShape) node.parentNode && node.parentNode !== virtualRoot && (edge || (edge = symbolEl.__edge = new BezierCurve({ shape: getEdgeShape(layout, orient, curvature, sourceOldLayout, sourceOldLayout) })), updateProps(edge, { shape: getEdgeShape(layout, orient, curvature, sourceLayout, targetLayout) }, seriesModel)); else if ('polyline' === edgeShape) { if ('orthogonal' === layout) { if (node !== virtualRoot && node.children && 0 !== node.children.length && !0 === node.isExpand) { for(var children = node.children, childPoints = [], i = 0; i < children.length; i++){ var childLayout = children[i].getLayout(); childPoints.push([ childLayout.x, childLayout.y ]); } edge || (edge = symbolEl.__edge = new TreePath({ shape: { parentPoint: [ targetLayout.x, targetLayout.y ], childPoints: [ [ targetLayout.x, targetLayout.y ] ], orient: orient, forkPosition: edgeForkPosition } })), updateProps(edge, { shape: { parentPoint: [ targetLayout.x, targetLayout.y ], childPoints: childPoints } }, seriesModel); } } else throw Error('The polyline edgeShape can only be used in orthogonal layout'); } edge && (edge.useStyle(defaults({ strokeNoScale: !0, fill: null }, lineStyle)), setStatesStylesFromModel(edge, itemModel, 'lineStyle'), setDefaultStateProxy(edge), group.add(edge)); }(seriesModel, node, virtualRoot, symbolEl, sourceOldLayout, sourceLayout, targetLayout, group), symbolEl.__edge && (symbolEl.onHoverStateChange = function(toState) { if ('blur' !== toState) { var parentEl = node.parentNode && data.getItemGraphicEl(node.parentNode.dataIndex); parentEl && 1 === parentEl.hoverState || setStatesFlag(symbolEl.__edge, toState); } }); } function removeNode(data, dataIndex, symbolEl, group, seriesModel) { for(var sourceLayout, node = data.tree.getNodeByDataIndex(dataIndex), virtualRoot = data.tree.root, source = node.parentNode === virtualRoot ? node : node.parentNode || node; null == (sourceLayout = source.getLayout());)source = source.parentNode === virtualRoot ? source : source.parentNode || source; var removeAnimationOpt = { duration: seriesModel.get('animationDurationUpdate'), easing: seriesModel.get('animationEasingUpdate') }; removeElement(symbolEl, { x: sourceLayout.x + 1, y: sourceLayout.y + 1 }, seriesModel, { cb: function() { group.remove(symbolEl), data.setItemGraphicEl(dataIndex, null); }, removeOpt: removeAnimationOpt }), symbolEl.fadeOut(null, { fadeLabel: !0, animation: removeAnimationOpt }); var sourceEdge = data.getItemGraphicEl(source.dataIndex).__edge, edge = symbolEl.__edge || (!1 === source.isExpand || 1 === source.children.length ? sourceEdge : void 0), edgeShape = seriesModel.get('edgeShape'), layoutOpt = seriesModel.get('layout'), orient = seriesModel.get('orient'), curvature = seriesModel.get([ 'lineStyle', 'curveness' ]); edge && ('curve' === edgeShape ? removeElement(edge, { shape: getEdgeShape(layoutOpt, orient, curvature, sourceLayout, sourceLayout), style: { opacity: 0 } }, seriesModel, { cb: function() { group.remove(edge); }, removeOpt: removeAnimationOpt }) : 'polyline' === edgeShape && 'orthogonal' === seriesModel.get('layout') && removeElement(edge, { shape: { parentPoint: [ sourceLayout.x, sourceLayout.y ], childPoints: [ [ sourceLayout.x, sourceLayout.y ] ] }, style: { opacity: 0 } }, seriesModel, { cb: function() { group.remove(edge); }, removeOpt: removeAnimationOpt })); } function getEdgeShape(layoutOpt, orient, curvature, sourceLayout, targetLayout) { if ('radial' === layoutOpt) { x1 = sourceLayout.rawX, y1 = sourceLayout.rawY, x2 = targetLayout.rawX, y2 = targetLayout.rawY; var cpx1, cpy1, cpx2, cpy2, x1, x2, y1, y2, radialCoor1 = radialCoordinate(x1, y1), radialCoor2 = radialCoordinate(x1, y1 + (y2 - y1) * curvature), radialCoor3 = radialCoordinate(x2, y2 + (y1 - y2) * curvature), radialCoor4 = radialCoordinate(x2, y2); return { x1: radialCoor1.x || 0, y1: radialCoor1.y || 0, x2: radialCoor4.x || 0, y2: radialCoor4.y || 0, cpx1: radialCoor2.x || 0, cpy1: radialCoor2.y || 0, cpx2: radialCoor3.x || 0, cpy2: radialCoor3.y || 0 }; } return x1 = sourceLayout.x, y1 = sourceLayout.y, x2 = targetLayout.x, y2 = targetLayout.y, ('LR' === orient || 'RL' === orient) && (cpx1 = x1 + (x2 - x1) * curvature, cpy1 = y1, cpx2 = x2 + (x1 - x2) * curvature, cpy2 = y2), ('TB' === orient || 'BT' === orient) && (cpx1 = x1, cpy1 = y1 + (y2 - y1) * curvature, cpx2 = x2, cpy2 = y2 + (y1 - y2) * curvature), { x1: x1, y1: y1, x2: x2, y2: y2, cpx1: cpx1, cpy1: cpy1, cpx2: cpx2, cpy2: cpy2 }; } var inner$6 = makeInner(); function linkList(opt) { var mainData = opt.mainData, datas = opt.datas; datas || (datas = { main: mainData }, opt.datasAttr = { main: 'data' }), opt.datas = opt.mainData = null, linkAll(mainData, datas, opt), each(datas, function(data) { each(mainData.TRANSFERABLE_METHODS, function(methodName) { data.wrapMethod(methodName, curry(transferInjection, opt)); }); }), mainData.wrapMethod('cloneShallow', curry(cloneShallowInjection, opt)), each(mainData.CHANGABLE_METHODS, function(methodName) { mainData.wrapMethod(methodName, curry(changeInjection, opt)); }), assert(datas[mainData.dataType] === mainData); } function transferInjection(opt, res) { if (inner$6(this).mainData === this) { var datas = extend({}, inner$6(this).datas); datas[this.dataType] = res, linkAll(res, datas, opt); } else linkSingle(res, this.dataType, inner$6(this).mainData, opt); return res; } function changeInjection(opt, res) { return opt.struct && opt.struct.update(), res; } function cloneShallowInjection(opt, res) { return each(inner$6(res).datas, function(data, dataType) { data !== res && linkSingle(data.cloneShallow(), dataType, res, opt); }), res; } function getLinkedData(dataType) { var mainData = inner$6(this).mainData; return null == dataType || null == mainData ? mainData : inner$6(mainData).datas[dataType]; } function getLinkedDataAll() { var mainData = inner$6(this).mainData; return null == mainData ? [ { data: mainData } ] : map(keys(inner$6(mainData).datas), function(type) { return { type: type, data: inner$6(mainData).datas[type] }; }); } function linkAll(mainData, datas, opt) { inner$6(mainData).datas = {}, each(datas, function(data, dataType) { linkSingle(data, dataType, mainData, opt); }); } function linkSingle(data, dataType, mainData, opt) { inner$6(mainData).datas[dataType] = data, inner$6(data).mainData = mainData, data.dataType = dataType, opt.struct && (data[opt.structAttr] = opt.struct, opt.struct[opt.datasAttr[dataType]] = data), data.getLinkedData = getLinkedData, data.getLinkedDataAll = getLinkedDataAll; } var TreeNode = function() { function TreeNode(name, hostTree) { this.depth = 0, this.height = 0, this.dataIndex = -1, this.children = [], this.viewChildren = [], this.isExpand = !1, this.name = name || '', this.hostTree = hostTree; } return TreeNode.prototype.isRemoved = function() { return this.dataIndex < 0; }, TreeNode.prototype.eachNode = function(options, cb, context) { 'function' == typeof options && (context = cb, cb = options, options = null), isString(options = options || {}) && (options = { order: options }); var suppressVisitSub, order = options.order || 'preorder', children = this[options.attr || 'children']; 'preorder' === order && (suppressVisitSub = cb.call(context, this)); for(var i = 0; !suppressVisitSub && i < children.length; i++)children[i].eachNode(options, cb, context); 'postorder' === order && cb.call(context, this); }, TreeNode.prototype.updateDepthAndHeight = function(depth) { var height = 0; this.depth = depth; for(var i = 0; i < this.children.length; i++){ var child = this.children[i]; child.updateDepthAndHeight(depth + 1), child.height > height && (height = child.height); } this.height = height + 1; }, TreeNode.prototype.getNodeById = function(id) { if (this.getId() === id) return this; for(var i = 0, children = this.children, len = children.length; i < len; i++){ var res = children[i].getNodeById(id); if (res) return res; } }, TreeNode.prototype.contains = function(node) { if (node === this) return !0; for(var i = 0, children = this.children, len = children.length; i < len; i++){ var res = children[i].contains(node); if (res) return res; } }, TreeNode.prototype.getAncestors = function(includeSelf) { for(var ancestors = [], node = includeSelf ? this : this.parentNode; node;)ancestors.push(node), node = node.parentNode; return ancestors.reverse(), ancestors; }, TreeNode.prototype.getAncestorsIndices = function() { for(var indices = [], currNode = this; currNode;)indices.push(currNode.dataIndex), currNode = currNode.parentNode; return indices.reverse(), indices; }, TreeNode.prototype.getDescendantIndices = function() { var indices = []; return this.eachNode(function(childNode) { indices.push(childNode.dataIndex); }), indices; }, TreeNode.prototype.getValue = function(dimension) { var data = this.hostTree.data; return data.get(data.getDimension(dimension || 'value'), this.dataIndex); }, TreeNode.prototype.setLayout = function(layout, merge) { this.dataIndex >= 0 && this.hostTree.data.setItemLayout(this.dataIndex, layout, merge); }, TreeNode.prototype.getLayout = function() { return this.hostTree.data.getItemLayout(this.dataIndex); }, TreeNode.prototype.getModel = function(path) { if (!(this.dataIndex < 0)) return this.hostTree.data.getItemModel(this.dataIndex).getModel(path); }, TreeNode.prototype.getLevelModel = function() { return (this.hostTree.levelModels || [])[this.depth]; }, TreeNode.prototype.setVisual = function(key, value) { this.dataIndex >= 0 && this.hostTree.data.setItemVisual(this.dataIndex, key, value); }, TreeNode.prototype.getVisual = function(key) { return this.hostTree.data.getItemVisual(this.dataIndex, key); }, TreeNode.prototype.getRawIndex = function() { return this.hostTree.data.getRawIndex(this.dataIndex); }, TreeNode.prototype.getId = function() { return this.hostTree.data.getId(this.dataIndex); }, TreeNode.prototype.isAncestorOf = function(node) { for(var parent = node.parentNode; parent;){ if (parent === this) return !0; parent = parent.parentNode; } return !1; }, TreeNode.prototype.isDescendantOf = function(node) { return node !== this && node.isAncestorOf(this); }, TreeNode; }(), Tree = function() { function Tree(hostModel) { this.type = 'tree', this._nodes = [], this.hostModel = hostModel; } return Tree.prototype.eachNode = function(options, cb, context) { this.root.eachNode(options, cb, context); }, Tree.prototype.getNodeByDataIndex = function(dataIndex) { var rawIndex = this.data.getRawIndex(dataIndex); return this._nodes[rawIndex]; }, Tree.prototype.getNodeById = function(name) { return this.root.getNodeById(name); }, Tree.prototype.update = function() { for(var data = this.data, nodes = this._nodes, i = 0, len = nodes.length; i < len; i++)nodes[i].dataIndex = -1; for(var i = 0, len = data.count(); i < len; i++)nodes[data.getRawIndex(i)].dataIndex = i; }, Tree.prototype.clearLayouts = function() { this.data.clearItemLayouts(); }, Tree.createTree = function(dataRoot, hostModel, beforeLink) { var tree = new Tree(hostModel), listData = [], dimMax = 1; (function buildHierarchy(dataNode, parentNode) { var child, children, value = dataNode.value; dimMax = Math.max(dimMax, isArray(value) ? value.length : 1), listData.push(dataNode); var node = new TreeNode(convertOptionIdName(dataNode.name, ''), tree); parentNode ? (child = node, children = parentNode.children, child.parentNode !== parentNode && (children.push(child), child.parentNode = parentNode)) : tree.root = node, tree._nodes.push(node); var children1 = dataNode.children; if (children1) for(var i = 0; i < children1.length; i++)buildHierarchy(children1[i], node); })(dataRoot), tree.root.updateDepthAndHeight(0); var dimensionsInfo = createDimensions(listData, { coordDimensions: [ 'value' ], dimensionsCount: dimMax }), list = new List(dimensionsInfo, hostModel); return list.initData(listData), beforeLink && beforeLink(list), linkList({ mainData: list, struct: tree, structAttr: 'tree' }), tree.update(), tree; }, Tree; }(), TreeSeriesModel = function(_super) { function TreeSeriesModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.hasSymbolVisual = !0, _this.ignoreStyleOnData = !0, _this; } return __extends(TreeSeriesModel, _super), TreeSeriesModel.prototype.getInitialData = function(option) { var root = { name: option.name, children: option.data }, leaves = option.leaves || {}, leavesModel = new Model(leaves, this, this.ecModel), tree = Tree.createTree(root, this, function(nodeData) { nodeData.wrapMethod('getItemModel', function(model, idx) { var node = tree.getNodeByDataIndex(idx); return node.children.length && node.isExpand || (model.parentModel = leavesModel), model; }); }), treeDepth = 0; tree.eachNode('preorder', function(node) { node.depth > treeDepth && (treeDepth = node.depth); }); var expandTreeDepth = option.expandAndCollapse && option.initialTreeDepth >= 0 ? option.initialTreeDepth : treeDepth; return tree.root.eachNode('preorder', function(node) { var item = node.hostTree.data.getRawDataItem(node.dataIndex); node.isExpand = item && null != item.collapsed ? !item.collapsed : node.depth <= expandTreeDepth; }), tree.data; }, TreeSeriesModel.prototype.getOrient = function() { var orient = this.get('orient'); return 'horizontal' === orient ? orient = 'LR' : 'vertical' === orient && (orient = 'TB'), orient; }, TreeSeriesModel.prototype.setZoom = function(zoom) { this.option.zoom = zoom; }, TreeSeriesModel.prototype.setCenter = function(center) { this.option.center = center; }, TreeSeriesModel.prototype.formatTooltip = function(dataIndex, multipleSeries, dataType) { for(var tree = this.getData().tree, realRoot = tree.root.children[0], node = tree.getNodeByDataIndex(dataIndex), value = node.getValue(), name = node.name; node && node !== realRoot;)name = node.parentNode.name + '.' + name, node = node.parentNode; return createTooltipMarkup('nameValue', { name: name, value: value, noValue: isNaN(value) || null == value }); }, TreeSeriesModel.type = 'series.tree', TreeSeriesModel.layoutMode = 'box', TreeSeriesModel.defaultOption = { zlevel: 0, z: 2, coordinateSystem: 'view', left: '12%', top: '12%', right: '12%', bottom: '12%', layout: 'orthogonal', edgeShape: 'curve', edgeForkPosition: '50%', roam: !1, nodeScaleRatio: 0.4, center: null, zoom: 1, orient: 'LR', symbol: 'emptyCircle', symbolSize: 7, expandAndCollapse: !0, initialTreeDepth: 2, lineStyle: { color: '#ccc', width: 1.5, curveness: 0.5 }, itemStyle: { color: 'lightsteelblue', borderWidth: 1.5 }, label: { show: !0 }, animationEasing: 'linear', animationDuration: 700, animationDurationUpdate: 500 }, TreeSeriesModel; }(SeriesModel); function eachBefore(root, callback) { for(var node, nodes = [ root ]; node = nodes.pop();)if (callback(node), node.isExpand) { var children = node.children; if (children.length) for(var i = children.length - 1; i >= 0; i--)nodes.push(children[i]); } } function treeLayout(ecModel, api) { ecModel.eachSeriesByType('tree', function(seriesModel) { !function(seriesModel, api) { var layoutInfo = getLayoutRect(seriesModel.getBoxLayoutParams(), { width: api.getWidth(), height: api.getHeight() }); seriesModel.layoutInfo = layoutInfo; var layout = seriesModel.get('layout'), width = 0, height = 0, separation$1 = null; 'radial' === layout ? (width = 2 * Math.PI, height = Math.min(layoutInfo.height, layoutInfo.width) / 2, separation$1 = separation(function(node1, node2) { return (node1.parentNode === node2.parentNode ? 1 : 2) / node1.depth; })) : (width = layoutInfo.width, height = layoutInfo.height, separation$1 = separation()); var virtualRoot = seriesModel.getData().tree.root, realRoot = virtualRoot.children[0]; if (realRoot) { !function(inRoot) { var node, children, root = inRoot; root.hierNode = { defaultAncestor: null, ancestor: root, prelim: 0, modifier: 0, change: 0, shift: 0, i: 0, thread: null }; for(var nodes = [ root ]; node = nodes.pop();)if (children = node.children, node.isExpand && children.length) for(var n = children.length, i = n - 1; i >= 0; i--){ var child = children[i]; child.hierNode = { defaultAncestor: null, ancestor: child, prelim: 0, modifier: 0, change: 0, shift: 0, i: i, thread: null }, nodes.push(child); } }(virtualRoot), function(root, callback, separation) { for(var node, nodes = [ root ], next = []; node = nodes.pop();)if (next.push(node), node.isExpand) { var children = node.children; if (children.length) for(var i = 0; i < children.length; i++)nodes.push(children[i]); } for(; node = next.pop();)callback(node, separation); }(realRoot, firstWalk, separation$1), virtualRoot.hierNode.modifier = -realRoot.hierNode.prelim, eachBefore(realRoot, secondWalk); var left_1 = realRoot, right_1 = realRoot, bottom_1 = realRoot; eachBefore(realRoot, function(node) { var x = node.getLayout().x; x < left_1.getLayout().x && (left_1 = node), x > right_1.getLayout().x && (right_1 = node), node.depth > bottom_1.depth && (bottom_1 = node); }); var delta = left_1 === right_1 ? 1 : separation$1(left_1, right_1) / 2, tx_1 = delta - left_1.getLayout().x, kx_1 = 0, ky_1 = 0, coorX_1 = 0, coorY_1 = 0; if ('radial' === layout) kx_1 = width / (right_1.getLayout().x + delta + tx_1), ky_1 = height / (bottom_1.depth - 1 || 1), eachBefore(realRoot, function(node) { var finalCoor = radialCoordinate(coorX_1 = (node.getLayout().x + tx_1) * kx_1, coorY_1 = (node.depth - 1) * ky_1); node.setLayout({ x: finalCoor.x, y: finalCoor.y, rawX: coorX_1, rawY: coorY_1 }, !0); }); else { var orient_1 = seriesModel.getOrient(); 'RL' === orient_1 || 'LR' === orient_1 ? (ky_1 = height / (right_1.getLayout().x + delta + tx_1), kx_1 = width / (bottom_1.depth - 1 || 1), eachBefore(realRoot, function(node) { coorY_1 = (node.getLayout().x + tx_1) * ky_1, coorX_1 = 'LR' === orient_1 ? (node.depth - 1) * kx_1 : width - (node.depth - 1) * kx_1, node.setLayout({ x: coorX_1, y: coorY_1 }, !0); })) : ('TB' === orient_1 || 'BT' === orient_1) && (kx_1 = width / (right_1.getLayout().x + delta + tx_1), ky_1 = height / (bottom_1.depth - 1 || 1), eachBefore(realRoot, function(node) { coorX_1 = (node.getLayout().x + tx_1) * kx_1, coorY_1 = 'TB' === orient_1 ? (node.depth - 1) * ky_1 : height - (node.depth - 1) * ky_1, node.setLayout({ x: coorX_1, y: coorY_1 }, !0); })); } } }(seriesModel, api); }); } function treeVisual(ecModel) { ecModel.eachSeriesByType('tree', function(seriesModel) { var data = seriesModel.getData(); data.tree.eachNode(function(node) { var style = node.getModel().getModel('itemStyle').getItemStyle(); extend(data.ensureUniqueItemVisual(node.dataIndex, 'style'), style); }); }); } function retrieveTargetInfo(payload, validPayloadTypes, seriesModel) { if (payload && indexOf(validPayloadTypes, payload.type) >= 0) { var root = seriesModel.getData().tree.root, targetNode = payload.targetNode; if ('string' == typeof targetNode && (targetNode = root.getNodeById(targetNode)), targetNode && root.contains(targetNode)) return { node: targetNode }; var targetNodeId = payload.targetNodeId; if (null != targetNodeId && (targetNode = root.getNodeById(targetNodeId))) return { node: targetNode }; } } function getPathToRoot(node) { for(var path = []; node;)(node = node.parentNode) && path.push(node); return path.reverse(); } function aboveViewRoot(viewRoot, node) { return indexOf(getPathToRoot(viewRoot), node) >= 0; } function wrapTreePathInfo(node, seriesModel) { for(var treePathInfo = []; node;){ var nodeDataIndex = node.dataIndex; treePathInfo.push({ name: node.name, dataIndex: nodeDataIndex, value: seriesModel.getRawValue(nodeDataIndex) }), node = node.parentNode; } return treePathInfo.reverse(), treePathInfo; } var noop$1 = function() {}, actionTypes = [ 'treemapZoomToNode', 'treemapRender', 'treemapMove' ]; function enableAriaDecalForTree(seriesModel) { var tree = seriesModel.getData().tree, decalPaletteScope = {}; tree.eachNode(function(node) { for(var current = node; current && current.depth > 1;)current = current.parentNode; var decal = getDecalFromPalette(seriesModel.ecModel, current.name || current.dataIndex + '', decalPaletteScope); node.setVisual('decal', decal); }); } var TreemapSeriesModel = function(_super) { function TreemapSeriesModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = TreemapSeriesModel.type, _this.preventUsingHoverLayer = !0, _this; } return __extends(TreemapSeriesModel, _super), TreemapSeriesModel.prototype.getInitialData = function(option, ecModel) { var root = { name: option.name, children: option.data }; (function completeTreeValue(dataNode) { var sum = 0; each(dataNode.children, function(child) { completeTreeValue(child); var childValue = child.value; isArray(childValue) && (childValue = childValue[0]), sum += childValue; }); var thisValue = dataNode.value; isArray(thisValue) && (thisValue = thisValue[0]), (null == thisValue || isNaN(thisValue)) && (thisValue = sum), thisValue < 0 && (thisValue = 0), isArray(dataNode.value) ? dataNode.value[0] = thisValue : dataNode.value = thisValue; })(root); var levels = option.levels || [], designatedVisualItemStyle = this.designatedVisualItemStyle = {}, designatedVisualModel = new Model({ itemStyle: designatedVisualItemStyle }, this, ecModel), levelModels = map((levels = option.levels = function(levels, ecModel) { var hasColorDefine, hasDecalDefine, globalColorList = normalizeToArray(ecModel.get('color')), globalDecalList = normalizeToArray(ecModel.get([ 'aria', 'decal', 'decals' ])); if (globalColorList) { each(levels = levels || [], function(levelDefine) { var model = new Model(levelDefine), modelColor = model.get('color'), modelDecal = model.get('decal'); (model.get([ 'itemStyle', 'color' ]) || modelColor && 'none' !== modelColor) && (hasColorDefine = !0), (model.get([ 'itemStyle', 'decal' ]) || modelDecal && 'none' !== modelDecal) && (hasDecalDefine = !0); }); var level0 = levels[0] || (levels[0] = {}); return hasColorDefine || (level0.color = globalColorList.slice()), !hasDecalDefine && globalDecalList && (level0.decal = globalDecalList.slice()), levels; } }(levels, ecModel)) || [], function(levelDefine) { return new Model(levelDefine, designatedVisualModel, ecModel); }, this), tree = Tree.createTree(root, this, function(nodeData) { nodeData.wrapMethod('getItemModel', function(model, idx) { var levelModel = levelModels[tree.getNodeByDataIndex(idx).depth]; return model.parentModel = levelModel || designatedVisualModel, model; }); }); return tree.data; }, TreemapSeriesModel.prototype.optionUpdated = function() { this.resetViewRoot(); }, TreemapSeriesModel.prototype.formatTooltip = function(dataIndex, multipleSeries, dataType) { var data = this.getData(), value = this.getRawValue(dataIndex); return createTooltipMarkup('nameValue', { name: data.getName(dataIndex), value: value }); }, TreemapSeriesModel.prototype.getDataParams = function(dataIndex) { var params = _super.prototype.getDataParams.apply(this, arguments), node = this.getData().tree.getNodeByDataIndex(dataIndex); return params.treePathInfo = wrapTreePathInfo(node, this), params; }, TreemapSeriesModel.prototype.setLayoutInfo = function(layoutInfo) { this.layoutInfo = this.layoutInfo || {}, extend(this.layoutInfo, layoutInfo); }, TreemapSeriesModel.prototype.mapIdToIndex = function(id) { var idIndexMap = this._idIndexMap; idIndexMap || (idIndexMap = this._idIndexMap = createHashMap(), this._idIndexMapCount = 0); var index = idIndexMap.get(id); return null == index && idIndexMap.set(id, index = this._idIndexMapCount++), index; }, TreemapSeriesModel.prototype.getViewRoot = function() { return this._viewRoot; }, TreemapSeriesModel.prototype.resetViewRoot = function(viewRoot) { viewRoot ? this._viewRoot = viewRoot : viewRoot = this._viewRoot; var root = this.getRawData().tree.root; viewRoot && (viewRoot === root || root.contains(viewRoot)) || (this._viewRoot = root); }, TreemapSeriesModel.prototype.enableAriaDecal = function() { enableAriaDecalForTree(this); }, TreemapSeriesModel.type = 'series.treemap', TreemapSeriesModel.layoutMode = 'box', TreemapSeriesModel.defaultOption = { progressive: 0, left: 'center', top: 'middle', width: '80%', height: '80%', sort: !0, clipWindow: 'origin', squareRatio: 0.5 * (1 + Math.sqrt(5)), leafDepth: null, drillDownIcon: '▶', zoomToNodeRatio: 0.1024, roam: !0, nodeClick: 'zoomToNode', animation: !0, animationDurationUpdate: 900, animationEasing: 'quinticInOut', breadcrumb: { show: !0, height: 22, left: 'center', top: 'bottom', emptyItemWidth: 25, itemStyle: { color: 'rgba(0,0,0,0.7)', textStyle: { color: '#fff' } } }, label: { show: !0, distance: 0, padding: 5, position: 'inside', color: '#fff', overflow: 'truncate' }, upperLabel: { show: !1, position: [ 0, '50%' ], height: 20, overflow: 'truncate', verticalAlign: 'middle' }, itemStyle: { color: null, colorAlpha: null, colorSaturation: null, borderWidth: 0, gapWidth: 0, borderColor: '#fff', borderColorSaturation: null }, emphasis: { upperLabel: { show: !0, position: [ 0, '50%' ], ellipsis: !0, verticalAlign: 'middle' } }, visualDimension: 0, visualMin: null, visualMax: null, color: [], colorAlpha: null, colorSaturation: null, colorMappingBy: 'index', visibleMin: 10, childrenVisibleMin: null, levels: [] }, TreemapSeriesModel; }(SeriesModel), Breadcrumb = function() { function Breadcrumb(containerGroup) { this.group = new Group(), containerGroup.add(this.group); } return Breadcrumb.prototype.render = function(seriesModel, api, targetNode, onSelect) { var model = seriesModel.getModel('breadcrumb'), thisGroup = this.group; if (thisGroup.removeAll(), model.get('show') && targetNode) { var normalStyleModel = model.getModel('itemStyle'), textStyleModel = normalStyleModel.getModel('textStyle'), layoutParam = { pos: { left: model.get('left'), right: model.get('right'), top: model.get('top'), bottom: model.get('bottom') }, box: { width: api.getWidth(), height: api.getHeight() }, emptyItemWidth: model.get('emptyItemWidth'), totalWidth: 0, renderList: [] }; this._prepare(targetNode, layoutParam, textStyleModel), this._renderContent(seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect), positionElement(thisGroup, layoutParam.pos, layoutParam.box); } }, Breadcrumb.prototype._prepare = function(targetNode, layoutParam, textStyleModel) { for(var node = targetNode; node; node = node.parentNode){ var text = convertOptionIdName(node.getModel().get('name'), ''), itemWidth = Math.max(textStyleModel.getTextRect(text).width + 16, layoutParam.emptyItemWidth); layoutParam.totalWidth += itemWidth + 8, layoutParam.renderList.push({ node: node, text: text, width: itemWidth }); } }, Breadcrumb.prototype._renderContent = function(seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect) { for(var positionInfo, containerRect, margin, containerWidth, containerHeight, x, y, x2, y2, lastX = 0, emptyItemWidth = layoutParam.emptyItemWidth, height = seriesModel.get([ 'breadcrumb', 'height' ]), availableSize = (positionInfo = layoutParam.pos, containerWidth = (containerRect = layoutParam.box).width, containerHeight = containerRect.height, x = parsePercent$1(positionInfo.left, containerWidth), y = parsePercent$1(positionInfo.top, containerHeight), x2 = parsePercent$1(positionInfo.right, containerWidth), y2 = parsePercent$1(positionInfo.bottom, containerHeight), (isNaN(x) || isNaN(parseFloat(positionInfo.left))) && (x = 0), (isNaN(x2) || isNaN(parseFloat(positionInfo.right))) && (x2 = containerWidth), (isNaN(y) || isNaN(parseFloat(positionInfo.top))) && (y = 0), (isNaN(y2) || isNaN(parseFloat(positionInfo.bottom))) && (y2 = containerHeight), { width: Math.max(x2 - x - (margin = normalizeCssArray(margin || 0))[1] - margin[3], 0), height: Math.max(y2 - y - margin[0] - margin[2], 0) }), totalWidth = layoutParam.totalWidth, renderList = layoutParam.renderList, i = renderList.length - 1; i >= 0; i--){ var item = renderList[i], itemNode = item.node, itemWidth = item.width, text = item.text; totalWidth > availableSize.width && (totalWidth -= itemWidth - emptyItemWidth, itemWidth = emptyItemWidth, text = null); var el = new Polygon({ shape: { points: function(x, y, itemWidth, itemHeight, head, tail) { var points = [ [ head ? x : x - 5, y ], [ x + itemWidth, y ], [ x + itemWidth, y + itemHeight ], [ head ? x : x - 5, y + itemHeight ] ]; return tail || points.splice(2, 0, [ x + itemWidth + 5, y + itemHeight / 2 ]), head || points.push([ x, y + itemHeight / 2 ]), points; }(lastX, 0, itemWidth, height, i === renderList.length - 1, 0 === i) }, style: defaults(normalStyleModel.getItemStyle(), { lineJoin: 'bevel' }), textContent: new ZRText({ style: { text: text, fill: textStyleModel.getTextColor(), font: textStyleModel.getFont() } }), textConfig: { position: 'inside' }, z2: 100000, onclick: curry(onSelect, itemNode) }); el.disableLabelAnimation = !0, this.group.add(el), getECData(el).eventData = { componentType: 'series', componentSubType: 'treemap', componentIndex: seriesModel.componentIndex, seriesIndex: seriesModel.componentIndex, seriesName: seriesModel.name, seriesType: 'treemap', selfType: 'breadcrumb', nodeData: { dataIndex: itemNode && itemNode.dataIndex, name: itemNode && itemNode.name }, treePathInfo: itemNode && wrapTreePathInfo(itemNode, seriesModel) }, lastX += itemWidth + 8; } }, Breadcrumb.prototype.remove = function() { this.group.removeAll(); }, Breadcrumb; }(), AnimationWrap = function() { function AnimationWrap() { this._storage = [], this._elExistsMap = {}; } return AnimationWrap.prototype.add = function(el, target, duration, delay, easing) { return !this._elExistsMap[el.id] && (this._elExistsMap[el.id] = !0, this._storage.push({ el: el, target: target, duration: duration, delay: delay, easing: easing }), !0); }, AnimationWrap.prototype.finished = function(callback) { return this._finishedCallback = callback, this; }, AnimationWrap.prototype.start = function() { for(var _this = this, count = this._storage.length, checkTerminate = function() { --count <= 0 && (_this._storage.length = 0, _this._elExistsMap = {}, _this._finishedCallback && _this._finishedCallback()); }, i = 0, len = this._storage.length; i < len; i++){ var item = this._storage[i]; item.el.animateTo(item.target, { duration: item.duration, delay: item.delay, easing: item.easing, setToFinal: !0, done: checkTerminate, aborted: checkTerminate }); } return this; }, AnimationWrap; }(), PATH_LABEL_NOAMAL = 'label', PATH_UPPERLABEL_NORMAL = 'upperLabel', getStateItemStyle = makeStyleMapper([ [ 'fill', 'color' ], [ 'stroke', 'strokeColor' ], [ 'lineWidth', 'strokeWidth' ], [ 'shadowBlur' ], [ 'shadowOffsetX' ], [ 'shadowOffsetY' ], [ 'shadowColor' ] ]), getItemStyleNormal = function(model) { var itemStyle = getStateItemStyle(model); return itemStyle.stroke = itemStyle.fill = itemStyle.lineWidth = null, itemStyle; }, inner$7 = makeInner(), TreemapView = function(_super) { function TreemapView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = TreemapView.type, _this._state = 'ready', _this._storage = createStorage(), _this; } return __extends(TreemapView, _super), TreemapView.prototype.render = function(seriesModel, ecModel, api, payload) { if (!(0 > indexOf(ecModel.findComponents({ mainType: 'series', subType: 'treemap', query: payload }), seriesModel))) { this.seriesModel = seriesModel, this.api = api, this.ecModel = ecModel; var targetInfo = retrieveTargetInfo(payload, [ 'treemapZoomToNode', 'treemapRootToNode' ], seriesModel), payloadType = payload && payload.type, layoutInfo = seriesModel.layoutInfo, isInit = !this._oldTree, thisStorage = this._storage, reRoot = 'treemapRootToNode' === payloadType && targetInfo && thisStorage ? { rootNodeGroup: thisStorage.nodeGroup[targetInfo.node.getRawIndex()], direction: payload.direction } : null, containerGroup = this._giveContainerGroup(layoutInfo), renderResult = this._doRender(containerGroup, seriesModel, reRoot); isInit || payloadType && 'treemapZoomToNode' !== payloadType && 'treemapRootToNode' !== payloadType ? renderResult.renderFinally() : this._doAnimation(containerGroup, renderResult, seriesModel, reRoot), this._resetController(api), this._renderBreadcrumb(seriesModel, api, targetInfo); } }, TreemapView.prototype._giveContainerGroup = function(layoutInfo) { var containerGroup = this._containerGroup; return containerGroup || (containerGroup = this._containerGroup = new Group(), this._initEvents(containerGroup), this.group.add(containerGroup)), containerGroup.x = layoutInfo.x, containerGroup.y = layoutInfo.y, containerGroup; }, TreemapView.prototype._doRender = function(containerGroup, seriesModel, reRoot) { var willDeleteEls, thisTree = seriesModel.getData().tree, oldTree = this._oldTree, lastsForAnimation = createStorage(), thisStorage = createStorage(), oldStorage = this._storage, willInvisibleEls = []; (function dualTravel(thisViewChildren, oldViewChildren, parentGroup, sameTree, depth) { function getKey(node) { return node.getId(); } function processNode(newIndex, oldIndex) { var thisNode = null != newIndex ? thisViewChildren[newIndex] : null, oldNode = null != oldIndex ? oldViewChildren[oldIndex] : null, group = function(seriesModel, thisStorage, oldStorage, reRoot, lastsForAnimation, willInvisibleEls, thisNode, oldNode, parentGroup, depth) { if (thisNode) { var thisLayout = thisNode.getLayout(), data = seriesModel.getData(), nodeModel = thisNode.getModel(); if (data.setItemGraphicEl(thisNode.dataIndex, null), thisLayout && thisLayout.isInView) { var thisWidth = thisLayout.width, thisHeight = thisLayout.height, borderWidth = thisLayout.borderWidth, thisInvisible = thisLayout.invisible, thisRawIndex = thisNode.getRawIndex(), oldRawIndex = oldNode && oldNode.getRawIndex(), thisViewChildren = thisNode.viewChildren, upperHeight = thisLayout.upperHeight, isParent = thisViewChildren && thisViewChildren.length, itemStyleNormalModel = nodeModel.getModel('itemStyle'), itemStyleEmphasisModel = nodeModel.getModel([ 'emphasis', 'itemStyle' ]), itemStyleBlurModel = nodeModel.getModel([ 'blur', 'itemStyle' ]), itemStyleSelectModel = nodeModel.getModel([ 'select', 'itemStyle' ]), borderRadius = itemStyleNormalModel.get('borderRadius') || 0, group = giveGraphic('nodeGroup', Group); if (group) { if (parentGroup.add(group), group.x = thisLayout.x || 0, group.y = thisLayout.y || 0, group.markRedraw(), inner$7(group).nodeWidth = thisWidth, inner$7(group).nodeHeight = thisHeight, thisLayout.isAboveViewRoot) return group; var bg = giveGraphic('background', Rect, depth, 20); bg && function(group, bg, useUpperLabel) { var ecData = getECData(bg); if (ecData.dataIndex = thisNode.dataIndex, ecData.seriesIndex = seriesModel.seriesIndex, bg.setShape({ x: 0, y: 0, width: thisWidth, height: thisHeight, r: borderRadius }), thisInvisible) processInvisible(bg); else { bg.invisible = !1; var style = thisNode.getVisual('style'), visualBorderColor = style.stroke, normalStyle = getItemStyleNormal(itemStyleNormalModel); normalStyle.fill = visualBorderColor; var emphasisStyle = getStateItemStyle(itemStyleEmphasisModel); emphasisStyle.fill = itemStyleEmphasisModel.get('borderColor'); var blurStyle = getStateItemStyle(itemStyleBlurModel); blurStyle.fill = itemStyleBlurModel.get('borderColor'); var selectStyle = getStateItemStyle(itemStyleSelectModel); selectStyle.fill = itemStyleSelectModel.get('borderColor'), useUpperLabel ? prepareText(bg, visualBorderColor, style.opacity, { x: borderWidth, y: 0, width: thisWidth - 2 * borderWidth, height: upperHeight }) : bg.removeTextContent(), bg.setStyle(normalStyle), bg.ensureState('emphasis').style = emphasisStyle, bg.ensureState('blur').style = blurStyle, bg.ensureState('select').style = selectStyle, setDefaultStateProxy(bg); } group.add(bg); }(group, bg, isParent && thisLayout.upperLabelHeight); var focus = nodeModel.get([ 'emphasis', 'focus' ]), blurScope = nodeModel.get([ 'emphasis', 'blurScope' ]), focusOrIndices = 'ancestor' === focus ? thisNode.getAncestorsIndices() : 'descendant' === focus ? thisNode.getDescendantIndices() : focus; if (isParent) isHighDownDispatcher(group) && setAsHighDownDispatcher(group, !1), bg && (setAsHighDownDispatcher(bg, !0), data.setItemGraphicEl(thisNode.dataIndex, bg), enableHoverFocus(bg, focusOrIndices, blurScope)); else { var content = giveGraphic('content', Rect, depth, 30); content && function(group, content) { var ecData = getECData(content); if (ecData.dataIndex = thisNode.dataIndex, ecData.seriesIndex = seriesModel.seriesIndex, content.culling = !0, content.setShape({ x: borderWidth, y: borderWidth, width: Math.max(thisWidth - 2 * borderWidth, 0), height: Math.max(thisHeight - 2 * borderWidth, 0), r: borderRadius }), thisInvisible) processInvisible(content); else { content.invisible = !1; var nodeStyle = thisNode.getVisual('style'), visualColor = nodeStyle.fill, normalStyle = getItemStyleNormal(itemStyleNormalModel); normalStyle.fill = visualColor, normalStyle.decal = nodeStyle.decal; var emphasisStyle = getStateItemStyle(itemStyleEmphasisModel), blurStyle = getStateItemStyle(itemStyleBlurModel), selectStyle = getStateItemStyle(itemStyleSelectModel); prepareText(content, visualColor, nodeStyle.opacity, null), content.setStyle(normalStyle), content.ensureState('emphasis').style = emphasisStyle, content.ensureState('blur').style = blurStyle, content.ensureState('select').style = selectStyle, setDefaultStateProxy(content); } group.add(content); }(group, content), bg && isHighDownDispatcher(bg) && setAsHighDownDispatcher(bg, !1), setAsHighDownDispatcher(group, !0), data.setItemGraphicEl(thisNode.dataIndex, group), enableHoverFocus(group, focusOrIndices, blurScope); } return group; } } } function processInvisible(element) { element.invisible || willInvisibleEls.push(element); } function prepareText(rectEl, visualColor, visualOpacity, upperLabelRect) { var normalLabelModel = nodeModel.getModel(upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL), defaultText = convertOptionIdName(nodeModel.get('name'), null), isShow = normalLabelModel.getShallow('show'); setLabelStyle(rectEl, getLabelStatesModels(nodeModel, upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL), { defaultText: isShow ? defaultText : null, inheritColor: visualColor, defaultOpacity: visualOpacity, labelFetcher: seriesModel, labelDataIndex: thisNode.dataIndex }); var textEl = rectEl.getTextContent(), textStyle = textEl.style, textPadding = normalizeCssArray(textStyle.padding || 0); upperLabelRect && (rectEl.setTextConfig({ layoutRect: upperLabelRect }), textEl.disableLabelLayout = !0), textEl.beforeUpdate = function() { var width = Math.max((upperLabelRect ? upperLabelRect.width : rectEl.shape.width) - textPadding[1] - textPadding[3], 0), height = Math.max((upperLabelRect ? upperLabelRect.height : rectEl.shape.height) - textPadding[0] - textPadding[2], 0); (textStyle.width !== width || textStyle.height !== height) && textEl.setStyle({ width: width, height: height }); }, textStyle.truncateMinChar = 2, textStyle.lineOverflow = 'truncate', addDrillDownIcon(textStyle, upperLabelRect, thisLayout); var textEmphasisState = textEl.getState('emphasis'); addDrillDownIcon(textEmphasisState ? textEmphasisState.style : null, upperLabelRect, thisLayout); } function addDrillDownIcon(style, upperLabelRect, thisLayout) { var text = style ? style.text : null; if (!upperLabelRect && thisLayout.isLeafRoot && null != text) { var iconChar = seriesModel.get('drillDownIcon', !0); style.text = iconChar ? iconChar + ' ' + text : text; } } function giveGraphic(storageName, Ctor, depth, z) { var lasts, element, lastCfg, element1 = null != oldRawIndex && oldStorage[storageName][oldRawIndex], lasts1 = lastsForAnimation[storageName]; return element1 ? (oldStorage[storageName][oldRawIndex] = null, lasts = lasts1, element = element1, lastCfg = lasts[thisRawIndex] = {}, element instanceof Group ? (lastCfg.oldX = element.x, lastCfg.oldY = element.y) : lastCfg.oldShape = extend({}, element.shape)) : thisInvisible || ((element1 = new Ctor()) instanceof Displayable && (element1.z2 = 100 * depth + z), function(lasts, element) { var lastCfg = lasts[thisRawIndex] = {}, parentNode = thisNode.parentNode, isGroup = element instanceof Group; if (parentNode && (!reRoot || 'drillDown' === reRoot.direction)) { var parentOldX = 0, parentOldY = 0, parentOldBg = lastsForAnimation.background[parentNode.getRawIndex()]; !reRoot && parentOldBg && parentOldBg.oldShape && (parentOldX = parentOldBg.oldShape.width, parentOldY = parentOldBg.oldShape.height), isGroup ? (lastCfg.oldX = 0, lastCfg.oldY = parentOldY) : lastCfg.oldShape = { x: parentOldX, y: parentOldY, width: 0, height: 0 }; } lastCfg.fadein = !isGroup; }(lasts1, element1)), thisStorage[storageName][thisRawIndex] = element1; } }(seriesModel, thisStorage, oldStorage, reRoot, lastsForAnimation, willInvisibleEls, thisNode, oldNode, parentGroup, depth); group && dualTravel(thisNode && thisNode.viewChildren || [], oldNode && oldNode.viewChildren || [], group, sameTree, depth + 1); } sameTree ? (oldViewChildren = thisViewChildren, each(thisViewChildren, function(child, index) { child.isRemoved() || processNode(index, index); })) : new DataDiffer(oldViewChildren, thisViewChildren, getKey, getKey).add(processNode).update(processNode).remove(curry(processNode, null)).execute(); })(thisTree.root ? [ thisTree.root ] : [], oldTree && oldTree.root ? [ oldTree.root ] : [], containerGroup, thisTree === oldTree || !oldTree, 0); var willDeleteEls1 = (willDeleteEls = createStorage(), oldStorage && each(oldStorage, function(store, storageName) { var delEls = willDeleteEls[storageName]; each(store, function(el) { el && (delEls.push(el), inner$7(el).willDelete = !0); }); }), willDeleteEls); return this._oldTree = thisTree, this._storage = thisStorage, { lastsForAnimation: lastsForAnimation, willDeleteEls: willDeleteEls1, renderFinally: function() { each(willDeleteEls1, function(els) { each(els, function(el) { el.parent && el.parent.remove(el); }); }), each(willInvisibleEls, function(el) { el.invisible = !0, el.dirty(); }); } }; }, TreemapView.prototype._doAnimation = function(containerGroup, renderResult, seriesModel, reRoot) { if (seriesModel.get('animation')) { var durationOption = seriesModel.get('animationDurationUpdate'), easingOption = seriesModel.get('animationEasing'), duration = (isFunction(durationOption) ? 0 : durationOption) || 0, easing = (isFunction(easingOption) ? null : easingOption) || 'cubicOut', animationWrap = new AnimationWrap(); each(renderResult.willDeleteEls, function(store, storageName) { each(store, function(el, rawIndex) { if (!el.invisible) { var target, parent = el.parent, innerStore = inner$7(parent); if (reRoot && 'drillDown' === reRoot.direction) target = parent === reRoot.rootNodeGroup ? { shape: { x: 0, y: 0, width: innerStore.nodeWidth, height: innerStore.nodeHeight }, style: { opacity: 0 } } : { style: { opacity: 0 } }; else { var targetX = 0, targetY = 0; innerStore.willDelete || (targetX = innerStore.nodeWidth / 2, targetY = innerStore.nodeHeight / 2), target = 'nodeGroup' === storageName ? { x: targetX, y: targetY, style: { opacity: 0 } } : { shape: { x: targetX, y: targetY, width: 0, height: 0 }, style: { opacity: 0 } }; } target && animationWrap.add(el, target, duration, 0, easing); } }); }), each(this._storage, function(store, storageName) { each(store, function(el, rawIndex) { var last = renderResult.lastsForAnimation[storageName][rawIndex], target = {}; last && (el instanceof Group ? null != last.oldX && (target.x = el.x, target.y = el.y, el.x = last.oldX, el.y = last.oldY) : (last.oldShape && (target.shape = extend({}, el.shape), el.setShape(last.oldShape)), last.fadein ? (el.setStyle('opacity', 0), target.style = { opacity: 1 }) : 1 !== el.style.opacity && (target.style = { opacity: 1 })), animationWrap.add(el, target, duration, 0, easing)); }); }, this), this._state = 'animating', animationWrap.finished(bind(function() { this._state = 'ready', renderResult.renderFinally(); }, this)).start(); } }, TreemapView.prototype._resetController = function(api) { var controller = this._controller; controller || ((controller = this._controller = new RoamController(api.getZr())).enable(this.seriesModel.get('roam')), controller.on('pan', bind(this._onPan, this)), controller.on('zoom', bind(this._onZoom, this))); var rect = new BoundingRect(0, 0, api.getWidth(), api.getHeight()); controller.setPointerChecker(function(e, x, y) { return rect.contain(x, y); }); }, TreemapView.prototype._clearController = function() { var controller = this._controller; controller && (controller.dispose(), controller = null); }, TreemapView.prototype._onPan = function(e) { if ('animating' !== this._state && (Math.abs(e.dx) > 3 || Math.abs(e.dy) > 3)) { var root = this.seriesModel.getData().tree.root; if (root) { var rootLayout = root.getLayout(); rootLayout && this.api.dispatchAction({ type: 'treemapMove', from: this.uid, seriesId: this.seriesModel.id, rootRect: { x: rootLayout.x + e.dx, y: rootLayout.y + e.dy, width: rootLayout.width, height: rootLayout.height } }); } } }, TreemapView.prototype._onZoom = function(e) { var mouseX = e.originX, mouseY = e.originY; if ('animating' !== this._state) { var root = this.seriesModel.getData().tree.root; if (!root) return; var rootLayout = root.getLayout(); if (!rootLayout) return; var rect = new BoundingRect(rootLayout.x, rootLayout.y, rootLayout.width, rootLayout.height), layoutInfo = this.seriesModel.layoutInfo; mouseX -= layoutInfo.x, mouseY -= layoutInfo.y; var m = create$1(); translate(m, m, [ -mouseX, -mouseY ]), scale$1(m, m, [ e.scale, e.scale ]), translate(m, m, [ mouseX, mouseY ]), rect.applyTransform(m), this.api.dispatchAction({ type: 'treemapRender', from: this.uid, seriesId: this.seriesModel.id, rootRect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height } }); } }, TreemapView.prototype._initEvents = function(containerGroup) { var _this = this; containerGroup.on('click', function(e) { if ('ready' === _this._state) { var nodeClick = _this.seriesModel.get('nodeClick', !0); if (nodeClick) { var targetInfo = _this.findTarget(e.offsetX, e.offsetY); if (targetInfo) { var node = targetInfo.node; if (node.getLayout().isLeafRoot) _this._rootToNode(targetInfo); else if ('zoomToNode' === nodeClick) _this._zoomToNode(targetInfo); else if ('link' === nodeClick) { var itemModel = node.hostTree.data.getItemModel(node.dataIndex), link = itemModel.get('link', !0), linkTarget = itemModel.get('target', !0) || 'blank'; link && windowOpen(link, linkTarget); } } } } }, this); }, TreemapView.prototype._renderBreadcrumb = function(seriesModel, api, targetInfo) { var _this = this; targetInfo || (targetInfo = null != seriesModel.get('leafDepth', !0) ? { node: seriesModel.getViewRoot() } : this.findTarget(api.getWidth() / 2, api.getHeight() / 2)) || (targetInfo = { node: seriesModel.getData().tree.root }), (this._breadcrumb || (this._breadcrumb = new Breadcrumb(this.group))).render(seriesModel, api, targetInfo.node, function(node) { 'animating' !== _this._state && (aboveViewRoot(seriesModel.getViewRoot(), node) ? _this._rootToNode({ node: node }) : _this._zoomToNode({ node: node })); }); }, TreemapView.prototype.remove = function() { this._clearController(), this._containerGroup && this._containerGroup.removeAll(), this._storage = createStorage(), this._state = 'ready', this._breadcrumb && this._breadcrumb.remove(); }, TreemapView.prototype.dispose = function() { this._clearController(); }, TreemapView.prototype._zoomToNode = function(targetInfo) { this.api.dispatchAction({ type: 'treemapZoomToNode', from: this.uid, seriesId: this.seriesModel.id, targetNode: targetInfo.node }); }, TreemapView.prototype._rootToNode = function(targetInfo) { this.api.dispatchAction({ type: 'treemapRootToNode', from: this.uid, seriesId: this.seriesModel.id, targetNode: targetInfo.node }); }, TreemapView.prototype.findTarget = function(x, y) { var targetInfo; return this.seriesModel.getViewRoot().eachNode({ attr: 'viewChildren', order: 'preorder' }, function(node) { var bgEl = this._storage.background[node.getRawIndex()]; if (bgEl) { var point = bgEl.transformCoordToLocal(x, y), shape = bgEl.shape; if (!(shape.x <= point[0]) || !(point[0] <= shape.x + shape.width) || !(shape.y <= point[1]) || !(point[1] <= shape.y + shape.height)) return !1; targetInfo = { node: node, offsetX: point[0], offsetY: point[1] }; } }, this), targetInfo; }, TreemapView.type = 'treemap', TreemapView; }(ChartView); function createStorage() { return { nodeGroup: [], background: [], content: [] }; } var VisualMapping = function() { function VisualMapping(option) { var thisOption, pieceList, mappingMethod = option.mappingMethod, visualType = option.type, thisOption1 = this.option = clone(option); this.type = visualType, this.mappingMethod = mappingMethod, this._normalizeData = normalizers[mappingMethod]; var visualHandler = VisualMapping.visualHandlers[visualType]; this.applyVisual = visualHandler.applyVisual, this.getColorMapper = visualHandler.getColorMapper, this._normalizedToVisual = visualHandler._normalizedToVisual[mappingMethod], 'piecewise' === mappingMethod ? (normalizeVisualRange(thisOption1), pieceList = (thisOption = thisOption1).pieceList, thisOption.hasSpecialVisual = !1, each(pieceList, function(piece, index) { piece.originIndex = index, null != piece.visual && (thisOption.hasSpecialVisual = !0); })) : 'category' === mappingMethod ? thisOption1.categories ? function(thisOption) { var categories = thisOption.categories, categoryMap = thisOption.categoryMap = {}, visual = thisOption.visual; if (each(categories, function(cate, index) { categoryMap[cate] = index; }), !isArray(visual)) { var visualArr_1 = []; isObject(visual) ? each(visual, function(v, cate) { var index = categoryMap[cate]; visualArr_1[null != index ? index : -1] = v; }) : visualArr_1[-1] = visual, visual = setVisualToOption(thisOption, visualArr_1); } for(var i = categories.length - 1; i >= 0; i--)null == visual[i] && (delete categoryMap[categories[i]], categories.pop()); }(thisOption1) : normalizeVisualRange(thisOption1, !0) : (assert('linear' !== mappingMethod || thisOption1.dataExtent), normalizeVisualRange(thisOption1)); } return VisualMapping.prototype.mapValueToVisual = function(value) { var normalized = this._normalizeData(value); return this._normalizedToVisual(normalized, value); }, VisualMapping.prototype.getNormalizer = function() { return bind(this._normalizeData, this); }, VisualMapping.listVisualTypes = function() { return keys(VisualMapping.visualHandlers); }, VisualMapping.isValidType = function(visualType) { return VisualMapping.visualHandlers.hasOwnProperty(visualType); }, VisualMapping.eachVisual = function(visual, callback, context) { isObject(visual) ? each(visual, callback, context) : callback.call(context, visual); }, VisualMapping.mapVisual = function(visual, callback, context) { var isPrimary, newVisual = isArray(visual) ? [] : isObject(visual) ? {} : (isPrimary = !0, null); return VisualMapping.eachVisual(visual, function(v, key) { var newVal = callback.call(context, v, key); isPrimary ? newVisual = newVal : newVisual[key] = newVal; }), newVisual; }, VisualMapping.retrieveVisuals = function(obj) { var hasVisual, ret = {}; return obj && each(VisualMapping.visualHandlers, function(h, visualType) { obj.hasOwnProperty(visualType) && (ret[visualType] = obj[visualType], hasVisual = !0); }), hasVisual ? ret : null; }, VisualMapping.prepareVisualTypes = function(visualTypes) { if (isArray(visualTypes)) visualTypes = visualTypes.slice(); else { if (!isObject(visualTypes)) return []; var types_1 = []; each(visualTypes, function(item, type) { types_1.push(type); }), visualTypes = types_1; } return visualTypes.sort(function(type1, type2) { return 'color' === type2 && 'color' !== type1 && 0 === type1.indexOf('color') ? 1 : -1; }), visualTypes; }, VisualMapping.dependsOn = function(visualType1, visualType2) { return 'color' === visualType2 ? !!(visualType1 && 0 === visualType1.indexOf(visualType2)) : visualType1 === visualType2; }, VisualMapping.findPieceIndex = function(value, pieceList, findClosestWhenOutside) { for(var possibleI, abs = 1 / 0, i = 0, len = pieceList.length; i < len; i++){ var pieceValue = pieceList[i].value; if (null != pieceValue) { if (pieceValue === value || 'string' == typeof pieceValue && pieceValue === value + '') return i; findClosestWhenOutside && updatePossible(pieceValue, i); } } for(var i = 0, len = pieceList.length; i < len; i++){ var close, b, close1, a, close2, a1, close3, b1, piece = pieceList[i], interval = piece.interval, close_1 = piece.close; if (interval) { if (interval[0] === -1 / 0) { if (close = close_1[1], b = interval[1], close ? value <= b : value < b) return i; } else if (interval[1] === 1 / 0) { if (close1 = close_1[0], a = interval[0], close1 ? a <= value : a < value) return i; } else if (close2 = close_1[0], a1 = interval[0], (close2 ? a1 <= value : a1 < value) && (close3 = close_1[1], b1 = interval[1], close3 ? value <= b1 : value < b1)) return i; findClosestWhenOutside && updatePossible(interval[0], i), findClosestWhenOutside && updatePossible(interval[1], i); } } if (findClosestWhenOutside) return value === 1 / 0 ? pieceList.length - 1 : value === -1 / 0 ? 0 : possibleI; function updatePossible(val, index) { var newAbs = Math.abs(val - value); newAbs < abs && (abs = newAbs, possibleI = index); } }, VisualMapping.visualHandlers = { color: { applyVisual: makeApplyVisual('color'), getColorMapper: function() { var thisOption = this.option; return bind('category' === thisOption.mappingMethod ? function(value, isNormalized) { return isNormalized || (value = this._normalizeData(value)), doMapCategory.call(this, value); } : function(value, isNormalized, out) { var returnRGBArray = !!out; return isNormalized || (value = this._normalizeData(value)), out = fastLerp(value, thisOption.parsedVisual, out), returnRGBArray ? out : stringify(out, 'rgba'); }, this); }, _normalizedToVisual: { linear: function(normalized) { return stringify(fastLerp(normalized, this.option.parsedVisual), 'rgba'); }, category: doMapCategory, piecewise: function(normalized, value) { var result = getSpecifiedVisual.call(this, value); return null == result && (result = stringify(fastLerp(normalized, this.option.parsedVisual), 'rgba')), result; }, fixed: doMapFixed } }, colorHue: makePartialColorVisualHandler(function(color$1, value) { return modifyHSL(color$1, value); }), colorSaturation: makePartialColorVisualHandler(function(color$1, value) { return modifyHSL(color$1, null, value); }), colorLightness: makePartialColorVisualHandler(function(color$1, value) { return modifyHSL(color$1, null, null, value); }), colorAlpha: makePartialColorVisualHandler(function(color$1, value) { return modifyAlpha(color$1, value); }), decal: { applyVisual: makeApplyVisual('decal'), _normalizedToVisual: { linear: null, category: doMapCategory, piecewise: null, fixed: null } }, opacity: { applyVisual: makeApplyVisual('opacity'), _normalizedToVisual: createNormalizedToNumericVisual([ 0, 1 ]) }, liftZ: { applyVisual: makeApplyVisual('liftZ'), _normalizedToVisual: { linear: doMapFixed, category: doMapFixed, piecewise: doMapFixed, fixed: doMapFixed } }, symbol: { applyVisual: function(value, getter, setter) { setter('symbol', this.mapValueToVisual(value)); }, _normalizedToVisual: { linear: doMapToArray, category: doMapCategory, piecewise: function(normalized, value) { var result = getSpecifiedVisual.call(this, value); return null == result && (result = doMapToArray.call(this, normalized)), result; }, fixed: doMapFixed } }, symbolSize: { applyVisual: makeApplyVisual('symbolSize'), _normalizedToVisual: createNormalizedToNumericVisual([ 0, 1 ]) } }, VisualMapping; }(); function normalizeVisualRange(thisOption, isCategory) { var visual = thisOption.visual, visualArr = []; isObject(visual) ? each(visual, function(v) { visualArr.push(v); }) : null != visual && visualArr.push(visual), isCategory || 1 !== visualArr.length || ({ color: 1, symbol: 1 }).hasOwnProperty(thisOption.type) || (visualArr[1] = visualArr[0]), setVisualToOption(thisOption, visualArr); } function makePartialColorVisualHandler(applyValue) { return { applyVisual: function(value, getter, setter) { var colorChannel = this.mapValueToVisual(value); setter('color', applyValue(getter('color'), colorChannel)); }, _normalizedToVisual: createNormalizedToNumericVisual([ 0, 1 ]) }; } function doMapToArray(normalized) { var visual = this.option.visual; return visual[Math.round(linearMap(normalized, [ 0, 1 ], [ 0, visual.length - 1 ], !0))] || {}; } function makeApplyVisual(visualType) { return function(value, getter, setter) { setter(visualType, this.mapValueToVisual(value)); }; } function doMapCategory(normalized) { var visual = this.option.visual; return visual[this.option.loop && -1 !== normalized ? normalized % visual.length : normalized]; } function doMapFixed() { return this.option.visual[0]; } function createNormalizedToNumericVisual(sourceExtent) { return { linear: function(normalized) { return linearMap(normalized, sourceExtent, this.option.visual, !0); }, category: doMapCategory, piecewise: function(normalized, value) { var result = getSpecifiedVisual.call(this, value); return null == result && (result = linearMap(normalized, sourceExtent, this.option.visual, !0)), result; }, fixed: doMapFixed }; } function getSpecifiedVisual(value) { var thisOption = this.option, pieceList = thisOption.pieceList; if (thisOption.hasSpecialVisual) { var piece = pieceList[VisualMapping.findPieceIndex(value, pieceList)]; if (piece && piece.visual) return piece.visual[this.type]; } } function setVisualToOption(thisOption, visualArr) { return thisOption.visual = visualArr, 'color' === thisOption.type && (thisOption.parsedVisual = map(visualArr, function(item) { return parse(item); })), visualArr; } var normalizers = { linear: function(value) { return linearMap(value, this.option.dataExtent, [ 0, 1 ], !0); }, piecewise: function(value) { var pieceList = this.option.pieceList, pieceIndex = VisualMapping.findPieceIndex(value, pieceList, !0); if (null != pieceIndex) return linearMap(pieceIndex, [ 0, pieceList.length - 1 ], [ 0, 1 ], !0); }, category: function(value) { var index = this.option.categories ? this.option.categoryMap[value] : value; return null == index ? -1 : index; }, fixed: noop }, inner$8 = makeInner(), treemapVisual = { seriesType: 'treemap', reset: function(seriesModel) { var root = seriesModel.getData().tree.root; root.isRemoved() || function travelTree(node, designatedVisual, viewRootAncestors, seriesModel) { var thisNodeColor, nodeModel = node.getModel(), nodeLayout = node.getLayout(), data = node.hostTree.data; if (nodeLayout && !nodeLayout.invisible && nodeLayout.isInView) { var visuals, designatedVisualItemStyle, thisNodeColor1, nodeItemStyleModel = nodeModel.getModel('itemStyle'), visuals1 = (visuals = extend({}, designatedVisual), designatedVisualItemStyle = seriesModel.designatedVisualItemStyle, each([ 'color', 'colorAlpha', 'colorSaturation' ], function(visualName) { designatedVisualItemStyle[visualName] = designatedVisual[visualName]; var val = nodeItemStyleModel.get(visualName); designatedVisualItemStyle[visualName] = null, null != val && (visuals[visualName] = val); }), visuals), existsStyle = data.ensureUniqueItemVisual(node.dataIndex, 'style'), borderColor = nodeItemStyleModel.get('borderColor'), borderColorSaturation = nodeItemStyleModel.get('borderColorSaturation'); null != borderColorSaturation && (borderColor = null != (thisNodeColor1 = thisNodeColor = calculateColor(visuals1)) ? modifyHSL(thisNodeColor1, null, null, borderColorSaturation) : null), existsStyle.stroke = borderColor; var viewChildren = node.viewChildren; if (viewChildren && viewChildren.length) { var mapping_1 = function(node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren) { if (viewChildren && viewChildren.length) { var rangeVisual = getRangeVisual(nodeModel, 'color') || null != visuals.color && 'none' !== visuals.color && (getRangeVisual(nodeModel, 'colorAlpha') || getRangeVisual(nodeModel, 'colorSaturation')); if (rangeVisual) { var visualMin = nodeModel.get('visualMin'), visualMax = nodeModel.get('visualMax'), dataExtent = nodeLayout.dataExtent.slice(); null != visualMin && visualMin < dataExtent[0] && (dataExtent[0] = visualMin), null != visualMax && visualMax > dataExtent[1] && (dataExtent[1] = visualMax); var colorMappingBy = nodeModel.get('colorMappingBy'), opt = { type: rangeVisual.name, dataExtent: dataExtent, visual: rangeVisual.range }; 'color' === opt.type && ('index' === colorMappingBy || 'id' === colorMappingBy) ? (opt.mappingMethod = 'category', opt.loop = !0) : opt.mappingMethod = 'linear'; var mapping = new VisualMapping(opt); return inner$8(mapping).drColorMappingBy = colorMappingBy, mapping; } } }(0, nodeModel, nodeLayout, 0, visuals1, viewChildren); each(viewChildren, function(child, index) { if (child.depth >= viewRootAncestors.length || child === viewRootAncestors[child.depth]) { var childVisual = function(nodeModel, visuals, child, index, mapping, seriesModel) { var childVisuals = extend({}, visuals); if (mapping) { var mappingType = mapping.type, colorMappingBy = 'color' === mappingType && inner$8(mapping).drColorMappingBy, value = 'index' === colorMappingBy ? index : 'id' === colorMappingBy ? seriesModel.mapIdToIndex(child.getId()) : child.getValue(nodeModel.get('visualDimension')); childVisuals[mappingType] = mapping.mapValueToVisual(value); } return childVisuals; }(nodeModel, visuals1, child, index, mapping_1, seriesModel); travelTree(child, childVisual, viewRootAncestors, seriesModel); } }); } else thisNodeColor = calculateColor(visuals1), existsStyle.fill = thisNodeColor; } }(root, {}, seriesModel.getViewRoot().getAncestors(), seriesModel); } }; function calculateColor(visuals) { var color = getValueVisualDefine(visuals, 'color'); if (color) { var colorAlpha = getValueVisualDefine(visuals, 'colorAlpha'), colorSaturation = getValueVisualDefine(visuals, 'colorSaturation'); return colorSaturation && (color = modifyHSL(color, null, null, colorSaturation)), colorAlpha && (color = modifyAlpha(color, colorAlpha)), color; } } function getValueVisualDefine(visuals, name) { var value = visuals[name]; if (null != value && 'none' !== value) return value; } function getRangeVisual(nodeModel, name) { var range = nodeModel.get(name); return isArray(range) && range.length ? { name: name, range: range } : null; } var mathMax$7 = Math.max, mathMin$7 = Math.min, PATH_BORDER_WIDTH = [ 'itemStyle', 'borderWidth' ], PATH_GAP_WIDTH = [ 'itemStyle', 'gapWidth' ], PATH_UPPER_LABEL_SHOW = [ 'upperLabel', 'show' ], PATH_UPPER_LABEL_HEIGHT = [ 'upperLabel', 'height' ], treemapLayout = { seriesType: 'treemap', reset: function(seriesModel, ecModel, api, payload) { var ecWidth = api.getWidth(), ecHeight = api.getHeight(), seriesOption = seriesModel.option, layoutInfo = getLayoutRect(seriesModel.getBoxLayoutParams(), { width: api.getWidth(), height: api.getHeight() }), size = seriesOption.size || [], containerWidth = parsePercent$1(retrieve(layoutInfo.width, size[0]), ecWidth), containerHeight = parsePercent$1(retrieve(layoutInfo.height, size[1]), ecHeight), payloadType = payload && payload.type, targetInfo = retrieveTargetInfo(payload, [ 'treemapZoomToNode', 'treemapRootToNode' ], seriesModel), rootRect = 'treemapRender' === payloadType || 'treemapMove' === payloadType ? payload.rootRect : null, viewRoot = seriesModel.getViewRoot(), viewAbovePath = getPathToRoot(viewRoot); if ('treemapMove' !== payloadType) { var rootSize = 'treemapZoomToNode' === payloadType ? function(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) { var parent, currNode = (targetInfo || {}).node, defaultSize = [ containerWidth, containerHeight ]; if (!currNode || currNode === viewRoot) return defaultSize; for(var viewArea = containerWidth * containerHeight, area = viewArea * seriesModel.option.zoomToNodeRatio; parent = currNode.parentNode;){ for(var sum = 0, siblings = parent.children, i = 0, len = siblings.length; i < len; i++)sum += siblings[i].getValue(); var currNodeValue = currNode.getValue(); if (0 === currNodeValue) return defaultSize; area *= sum / currNodeValue; var parentModel = parent.getModel(), borderWidth = parentModel.get(PATH_BORDER_WIDTH), upperHeight = Math.max(borderWidth, getUpperLabelHeight(parentModel)); (area += 4 * borderWidth * borderWidth + (3 * borderWidth + upperHeight) * Math.pow(area, 0.5)) > 9007199254740991 && (area = 9007199254740991), currNode = parent; } area < viewArea && (area = viewArea); var scale = Math.pow(area / viewArea, 0.5); return [ containerWidth * scale, containerHeight * scale ]; }(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) : rootRect ? [ rootRect.width, rootRect.height ] : [ containerWidth, containerHeight ], sort_1 = seriesOption.sort; sort_1 && 'asc' !== sort_1 && 'desc' !== sort_1 && (sort_1 = 'desc'); var options = { squareRatio: seriesOption.squareRatio, sort: sort_1, leafDepth: seriesOption.leafDepth }; viewRoot.hostTree.clearLayouts(); var viewRootLayout_1 = { x: 0, y: 0, width: rootSize[0], height: rootSize[1], area: rootSize[0] * rootSize[1] }; viewRoot.setLayout(viewRootLayout_1), function squarify(node, options, hideChildren, depth) { if (!node.isRemoved()) { var width, height, thisLayout = node.getLayout(); width = thisLayout.width, height = thisLayout.height; var nodeModel = node.getModel(), borderWidth = nodeModel.get(PATH_BORDER_WIDTH), halfGapWidth = nodeModel.get(PATH_GAP_WIDTH) / 2, upperLabelHeight = getUpperLabelHeight(nodeModel), upperHeight = Math.max(borderWidth, upperLabelHeight), layoutOffset = borderWidth - halfGapWidth, layoutOffsetUpper = upperHeight - halfGapWidth; node.setLayout({ borderWidth: borderWidth, upperHeight: upperHeight, upperLabelHeight: upperLabelHeight }, !0); var totalArea = (width = mathMax$7(width - 2 * layoutOffset, 0)) * (height = mathMax$7(height - layoutOffset - layoutOffsetUpper, 0)), viewChildren = function(node, nodeModel, totalArea, options, hideChildren, depth) { var viewChildren, orderBy, viewChildren1 = node.children || [], orderBy1 = options.sort; 'asc' !== orderBy1 && 'desc' !== orderBy1 && (orderBy1 = null); var overLeafDepth = null != options.leafDepth && options.leafDepth <= depth; if (hideChildren && !overLeafDepth) return node.viewChildren = []; viewChildren = viewChildren1 = filter(viewChildren1, function(child) { return !child.isRemoved(); }), (orderBy = orderBy1) && viewChildren.sort(function(a, b) { var diff = 'asc' === orderBy ? a.getValue() - b.getValue() : b.getValue() - a.getValue(); return 0 === diff ? 'asc' === orderBy ? a.dataIndex - b.dataIndex : b.dataIndex - a.dataIndex : diff; }); var info = function(nodeModel, children, orderBy) { for(var dataExtent, sum = 0, i = 0, len = children.length; i < len; i++)sum += children[i].getValue(); var dimension = nodeModel.get('visualDimension'); return children && children.length ? 'value' === dimension && orderBy ? (dataExtent = [ children[children.length - 1].getValue(), children[0].getValue() ], 'asc' === orderBy && dataExtent.reverse()) : (dataExtent = [ 1 / 0, -1 / 0 ], each(children, function(child) { var value = child.getValue(dimension); value < dataExtent[0] && (dataExtent[0] = value), value > dataExtent[1] && (dataExtent[1] = value); })) : dataExtent = [ NaN, NaN ], { sum: sum, dataExtent: dataExtent }; }(nodeModel, viewChildren1, orderBy1); if (0 === info.sum || (info.sum = function(nodeModel, totalArea, sum, orderBy, orderedChildren) { if (!orderBy) return sum; for(var visibleMin = nodeModel.get('visibleMin'), len = orderedChildren.length, deletePoint = len, i = len - 1; i >= 0; i--){ var value = orderedChildren['asc' === orderBy ? len - i - 1 : i].getValue(); value / sum * totalArea < visibleMin && (deletePoint = i, sum -= value); } return 'asc' === orderBy ? orderedChildren.splice(0, len - deletePoint) : orderedChildren.splice(deletePoint, len - deletePoint), sum; }(nodeModel, totalArea, info.sum, orderBy1, viewChildren1), 0 === info.sum)) return node.viewChildren = []; for(var i = 0, len = viewChildren1.length; i < len; i++){ var area = viewChildren1[i].getValue() / info.sum * totalArea; viewChildren1[i].setLayout({ area: area }); } return overLeafDepth && (viewChildren1.length && node.setLayout({ isLeafRoot: !0 }, !0), viewChildren1.length = 0), node.viewChildren = viewChildren1, node.setLayout({ dataExtent: info.dataExtent }, !0), viewChildren1; }(node, nodeModel, totalArea, options, hideChildren, depth); if (viewChildren.length) { var rect = { x: layoutOffset, y: layoutOffsetUpper, width: width, height: height }, rowFixedLength = mathMin$7(width, height), best = 1 / 0, row = []; row.area = 0; for(var i = 0, len = viewChildren.length; i < len;){ var child = viewChildren[i]; row.push(child), row.area += child.getLayout().area; var score = function(row, rowFixedLength, ratio) { for(var areaMax = 0, areaMin = 1 / 0, i = 0, area = void 0, len = row.length; i < len; i++)(area = row[i].getLayout().area) && (area < areaMin && (areaMin = area), area > areaMax && (areaMax = area)); var squareArea = row.area * row.area, f = rowFixedLength * rowFixedLength * ratio; return squareArea ? mathMax$7(f * areaMax / squareArea, squareArea / (f * areaMin)) : 1 / 0; }(row, rowFixedLength, options.squareRatio); score <= best ? (i++, best = score) : (row.area -= row.pop().getLayout().area, position(row, rowFixedLength, rect, halfGapWidth, !1), rowFixedLength = mathMin$7(rect.width, rect.height), row.length = row.area = 0, best = 1 / 0); } if (row.length && position(row, rowFixedLength, rect, halfGapWidth, !0), !hideChildren) { var childrenVisibleMin = nodeModel.get('childrenVisibleMin'); null != childrenVisibleMin && totalArea < childrenVisibleMin && (hideChildren = !0); } for(var i = 0, len = viewChildren.length; i < len; i++)squarify(viewChildren[i], options, hideChildren, depth + 1); } } }(viewRoot, options, !1, 0), viewRootLayout_1 = viewRoot.getLayout(), each(viewAbovePath, function(node, index) { var childValue = (viewAbovePath[index + 1] || viewRoot).getValue(); node.setLayout(extend({ dataExtent: [ childValue, childValue ], borderWidth: 0, upperHeight: 0 }, viewRootLayout_1)); }); } var treeRoot = seriesModel.getData().tree.root; treeRoot.setLayout(function(layoutInfo, rootRect, targetInfo) { if (rootRect) return { x: rootRect.x, y: rootRect.y }; var defaultPosition = { x: 0, y: 0 }; if (!targetInfo) return defaultPosition; var targetNode = targetInfo.node, layout = targetNode.getLayout(); if (!layout) return defaultPosition; for(var targetCenter = [ layout.width / 2, layout.height / 2 ], node = targetNode; node;){ var nodeLayout = node.getLayout(); targetCenter[0] += nodeLayout.x, targetCenter[1] += nodeLayout.y, node = node.parentNode; } return { x: layoutInfo.width / 2 - targetCenter[0], y: layoutInfo.height / 2 - targetCenter[1] }; }(layoutInfo, rootRect, targetInfo), !0), seriesModel.setLayoutInfo(layoutInfo), function prunning(node, clipRect, viewAbovePath, viewRoot, depth) { var nodeLayout = node.getLayout(), nodeInViewAbovePath = viewAbovePath[depth], isAboveViewRoot = nodeInViewAbovePath && nodeInViewAbovePath === node; if ((!nodeInViewAbovePath || isAboveViewRoot) && (depth !== viewAbovePath.length || node === viewRoot)) { node.setLayout({ isInView: !0, invisible: !isAboveViewRoot && !clipRect.intersect(nodeLayout), isAboveViewRoot: isAboveViewRoot }, !0); var childClipRect = new BoundingRect(clipRect.x - nodeLayout.x, clipRect.y - nodeLayout.y, clipRect.width, clipRect.height); each(node.viewChildren || [], function(child) { prunning(child, childClipRect, viewAbovePath, viewRoot, depth + 1); }); } }(treeRoot, new BoundingRect(-layoutInfo.x, -layoutInfo.y, ecWidth, ecHeight), viewAbovePath, viewRoot, 0); } }; function position(row, rowFixedLength, rect, halfGapWidth, flush) { var idx0WhenH = rowFixedLength === rect.width ? 0 : 1, idx1WhenH = 1 - idx0WhenH, xy = [ 'x', 'y' ], wh = [ 'width', 'height' ], last = rect[xy[idx0WhenH]], rowOtherLength = rowFixedLength ? row.area / rowFixedLength : 0; (flush || rowOtherLength > rect[wh[idx1WhenH]]) && (rowOtherLength = rect[wh[idx1WhenH]]); for(var i = 0, rowLen = row.length; i < rowLen; i++){ var node = row[i], nodeLayout = {}, step = rowOtherLength ? node.getLayout().area / rowOtherLength : 0, wh1 = nodeLayout[wh[idx1WhenH]] = mathMax$7(rowOtherLength - 2 * halfGapWidth, 0), remain = rect[xy[idx0WhenH]] + rect[wh[idx0WhenH]] - last, modWH = i === rowLen - 1 || remain < step ? remain : step, wh0 = nodeLayout[wh[idx0WhenH]] = mathMax$7(modWH - 2 * halfGapWidth, 0); nodeLayout[xy[idx1WhenH]] = rect[xy[idx1WhenH]] + mathMin$7(halfGapWidth, wh1 / 2), nodeLayout[xy[idx0WhenH]] = last + mathMin$7(halfGapWidth, wh0 / 2), last += modWH, node.setLayout(nodeLayout, !0); } rect[xy[idx1WhenH]] += rowOtherLength, rect[wh[idx1WhenH]] -= rowOtherLength; } function getUpperLabelHeight(model) { return model.get(PATH_UPPER_LABEL_SHOW) ? model.get(PATH_UPPER_LABEL_HEIGHT) : 0; } function categoryFilter(ecModel) { var legendModels = ecModel.findComponents({ mainType: 'legend' }); legendModels && legendModels.length && ecModel.eachSeriesByType('graph', function(graphSeries) { var categoriesData = graphSeries.getCategoriesData(), data = graphSeries.getGraph().data, categoryNames = categoriesData.mapArray(categoriesData.getName); data.filterSelf(function(idx) { var category = data.getItemModel(idx).getShallow('category'); if (null != category) { 'number' == typeof category && (category = categoryNames[category]); for(var i = 0; i < legendModels.length; i++)if (!legendModels[i].isSelected(category)) return !1; } return !0; }); }); } function categoryVisual(ecModel) { var paletteScope = {}; ecModel.eachSeriesByType('graph', function(seriesModel) { var categoriesData = seriesModel.getCategoriesData(), data = seriesModel.getData(), categoryNameIdxMap = {}; categoriesData.each(function(idx) { var name = categoriesData.getName(idx); categoryNameIdxMap['ec-' + name] = idx; var itemModel = categoriesData.getItemModel(idx), style = itemModel.getModel('itemStyle').getItemStyle(); style.fill || (style.fill = seriesModel.getColorFromPalette(name, paletteScope)), categoriesData.setItemVisual(idx, 'style', style); for(var symbolVisualList = [ 'symbol', 'symbolSize', 'symbolKeepAspect' ], i = 0; i < symbolVisualList.length; i++){ var symbolVisual = itemModel.getShallow(symbolVisualList[i], !0); null != symbolVisual && categoriesData.setItemVisual(idx, symbolVisualList[i], symbolVisual); } }), categoriesData.count() && data.each(function(idx) { var categoryIdx = data.getItemModel(idx).getShallow('category'); if (null != categoryIdx) { 'string' == typeof categoryIdx && (categoryIdx = categoryNameIdxMap['ec-' + categoryIdx]); var categoryStyle = categoriesData.getItemVisual(categoryIdx, 'style'); extend(data.ensureUniqueItemVisual(idx, 'style'), categoryStyle); for(var visualList = [ 'symbol', 'symbolSize', 'symbolKeepAspect' ], i = 0; i < visualList.length; i++)data.setItemVisual(idx, visualList[i], categoriesData.getItemVisual(categoryIdx, visualList[i])); } }); }); } function normalize$2(a) { return a instanceof Array || (a = [ a, a ]), a; } function graphEdgeVisual(ecModel) { ecModel.eachSeriesByType('graph', function(seriesModel) { var graph = seriesModel.getGraph(), edgeData = seriesModel.getEdgeData(), symbolType = normalize$2(seriesModel.get('edgeSymbol')), symbolSize = normalize$2(seriesModel.get('edgeSymbolSize')); edgeData.setVisual('fromSymbol', symbolType && symbolType[0]), edgeData.setVisual('toSymbol', symbolType && symbolType[1]), edgeData.setVisual('fromSymbolSize', symbolSize && symbolSize[0]), edgeData.setVisual('toSymbolSize', symbolSize && symbolSize[1]), edgeData.setVisual('style', seriesModel.getModel('lineStyle').getLineStyle()), edgeData.each(function(idx) { var itemModel = edgeData.getItemModel(idx), edge = graph.getEdgeByIndex(idx), symbolType = normalize$2(itemModel.getShallow('symbol', !0)), symbolSize = normalize$2(itemModel.getShallow('symbolSize', !0)), style = itemModel.getModel('lineStyle').getLineStyle(), existsStyle = edgeData.ensureUniqueItemVisual(idx, 'style'); switch(extend(existsStyle, style), existsStyle.stroke){ case 'source': var nodeStyle = edge.node1.getVisual('style'); existsStyle.stroke = nodeStyle && nodeStyle.fill; break; case 'target': var nodeStyle = edge.node2.getVisual('style'); existsStyle.stroke = nodeStyle && nodeStyle.fill; } symbolType[0] && edge.setVisual('fromSymbol', symbolType[0]), symbolType[1] && edge.setVisual('toSymbol', symbolType[1]), symbolSize[0] && edge.setVisual('fromSymbolSize', symbolSize[0]), symbolSize[1] && edge.setVisual('toSymbolSize', symbolSize[1]); }); }); } var getAutoCurvenessParams = function(seriesModel) { return seriesModel.get('autoCurveness') || null; }, createCurveness = function(seriesModel, appendLength) { var autoCurvenessParmas = getAutoCurvenessParams(seriesModel), length = 20, curvenessList = []; if ('number' == typeof autoCurvenessParmas) length = autoCurvenessParmas; else if (isArray(autoCurvenessParmas)) { seriesModel.__curvenessList = autoCurvenessParmas; return; } appendLength > length && (length = appendLength); var len = length % 2 ? length + 2 : length + 3; curvenessList = []; for(var i = 0; i < len; i++)curvenessList.push((i % 2 ? i + 1 : i) / 10 * (i % 2 ? -1 : 1)); seriesModel.__curvenessList = curvenessList; }, getKeyOfEdges = function(n1, n2, seriesModel) { var source = [ n1.id, n1.dataIndex ].join('.'), target = [ n2.id, n2.dataIndex ].join('.'); return [ seriesModel.uid, source, target ].join('-->'); }, getOppositeKey = function(key) { var keys = key.split('-->'); return [ keys[0], keys[2], keys[1] ].join('-->'); }, getEdgeFromMap = function(edge, seriesModel) { var key = getKeyOfEdges(edge.node1, edge.node2, seriesModel); return seriesModel.__edgeMap[key]; }, getEdgeMapLengthWithKey = function(key, seriesModel) { var edgeMap = seriesModel.__edgeMap; return edgeMap[key] ? edgeMap[key].length : 0; }; function getCurvenessForEdge(edge, seriesModel, index, needReverse) { var autoCurvenessParams = getAutoCurvenessParams(seriesModel), isArrayParam = isArray(autoCurvenessParams); if (!autoCurvenessParams) return null; var edgeArray = getEdgeFromMap(edge, seriesModel); if (!edgeArray) return null; for(var edgeIndex = -1, i = 0; i < edgeArray.length; i++)if (edgeArray[i] === index) { edgeIndex = i; break; } var totalLen = getEdgeMapLengthWithKey(getKeyOfEdges(edge.node1, edge.node2, seriesModel), seriesModel) + getEdgeMapLengthWithKey(getKeyOfEdges(edge.node2, edge.node1, seriesModel), seriesModel); createCurveness(seriesModel, totalLen), edge.lineStyle = edge.lineStyle || {}; var curKey = getKeyOfEdges(edge.node1, edge.node2, seriesModel), curvenessList = seriesModel.__curvenessList, parityCorrection = isArrayParam ? 0 : totalLen % 2 ? 0 : 1; if (edgeArray.isForward) return curvenessList[parityCorrection + edgeIndex]; var len = getEdgeMapLengthWithKey(getOppositeKey(curKey), seriesModel), resValue = curvenessList[edgeIndex + len + parityCorrection]; return needReverse ? isArrayParam ? autoCurvenessParams && 0 === autoCurvenessParams[0] ? (len + parityCorrection) % 2 ? resValue : -resValue : ((len % 2 ? 0 : 1) + parityCorrection) % 2 ? resValue : -resValue : (len + parityCorrection) % 2 ? resValue : -resValue : curvenessList[edgeIndex + len + parityCorrection]; } function simpleLayout(seriesModel) { var coordSys = seriesModel.coordinateSystem; if (!coordSys || 'view' === coordSys.type) { var graph = seriesModel.getGraph(); graph.eachNode(function(node) { var model = node.getModel(); node.setLayout([ +model.get('x'), +model.get('y') ]); }), simpleLayoutEdge(graph, seriesModel); } } function simpleLayoutEdge(graph, seriesModel) { graph.eachEdge(function(edge, index) { var curveness = retrieve3(edge.getModel().get([ 'lineStyle', 'curveness' ]), -getCurvenessForEdge(edge, seriesModel, index, !0), 0), p1 = clone$1(edge.node1.getLayout()), p2 = clone$1(edge.node2.getLayout()), points = [ p1, p2 ]; +curveness && points.push([ (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * curveness, (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * curveness ]), edge.setLayout(points); }); } function graphSimpleLayout(ecModel, api) { ecModel.eachSeriesByType('graph', function(seriesModel) { var layout = seriesModel.get('layout'), coordSys = seriesModel.coordinateSystem; if (coordSys && 'view' !== coordSys.type) { var data_1 = seriesModel.getData(), dimensions_1 = []; each(coordSys.dimensions, function(coordDim) { dimensions_1 = dimensions_1.concat(data_1.mapDimensionsAll(coordDim)); }); for(var dataIndex = 0; dataIndex < data_1.count(); dataIndex++){ for(var value = [], hasValue = !1, i = 0; i < dimensions_1.length; i++){ var val = data_1.get(dimensions_1[i], dataIndex); isNaN(val) || (hasValue = !0), value.push(val); } hasValue ? data_1.setItemLayout(dataIndex, coordSys.dataToPoint(value)) : data_1.setItemLayout(dataIndex, [ NaN, NaN ]); } simpleLayoutEdge(data_1.graph, seriesModel); } else layout && 'none' !== layout || simpleLayout(seriesModel); }); } function getNodeGlobalScale(seriesModel) { var coordSys = seriesModel.coordinateSystem; if ('view' !== coordSys.type) return 1; var nodeScaleRatio = seriesModel.option.nodeScaleRatio, groupZoom = coordSys.scaleX; return ((coordSys.getZoom() - 1) * nodeScaleRatio + 1) / groupZoom; } function getSymbolSize(node) { var symbolSize = node.getVisual('symbolSize'); return symbolSize instanceof Array && (symbolSize = (symbolSize[0] + symbolSize[1]) / 2), +symbolSize; } var PI$6 = Math.PI, _symbolRadiansHalf = []; function circularLayout(seriesModel, basedOn) { var coordSys = seriesModel.coordinateSystem; if (!coordSys || 'view' === coordSys.type) { var rect = coordSys.getBoundingRect(), nodeData = seriesModel.getData(), graph = nodeData.graph, cx = rect.width / 2 + rect.x, cy = rect.height / 2 + rect.y, r = Math.min(rect.width, rect.height) / 2, count = nodeData.count(); nodeData.setLayout({ cx: cx, cy: cy }), count && (_layoutNodesBasedOn[basedOn](seriesModel, graph, nodeData, r, cx, cy, count), graph.eachEdge(function(edge, index) { var cp1, curveness = retrieve3(edge.getModel().get([ 'lineStyle', 'curveness' ]), getCurvenessForEdge(edge, seriesModel, index), 0), p1 = clone$1(edge.node1.getLayout()), p2 = clone$1(edge.node2.getLayout()), x12 = (p1[0] + p2[0]) / 2, y12 = (p1[1] + p2[1]) / 2; +curveness && (curveness *= 3, cp1 = [ cx * curveness + x12 * (1 - curveness), cy * curveness + y12 * (1 - curveness) ]), edge.setLayout([ p1, p2, cp1 ]); })); } } var _layoutNodesBasedOn = { value: function(seriesModel, graph, nodeData, r, cx, cy, count) { var angle = 0, sum = nodeData.getSum('value'), unitAngle = 2 * Math.PI / (sum || count); graph.eachNode(function(node) { var value = node.getValue('value'), radianHalf = unitAngle * (sum ? value : 1) / 2; angle += radianHalf, node.setLayout([ r * Math.cos(angle) + cx, r * Math.sin(angle) + cy ]), angle += radianHalf; }); }, symbolSize: function(seriesModel, graph, nodeData, r, cx, cy, count) { var sumRadian = 0; _symbolRadiansHalf.length = count; var nodeScale = getNodeGlobalScale(seriesModel); graph.eachNode(function(node) { var symbolSize = getSymbolSize(node); isNaN(symbolSize) && (symbolSize = 2), symbolSize < 0 && (symbolSize = 0); var symbolRadianHalf = Math.asin((symbolSize *= nodeScale) / 2 / r); isNaN(symbolRadianHalf) && (symbolRadianHalf = PI$6 / 2), _symbolRadiansHalf[node.dataIndex] = symbolRadianHalf, sumRadian += 2 * symbolRadianHalf; }); var halfRemainRadian = (2 * PI$6 - sumRadian) / count / 2, angle = 0; graph.eachNode(function(node) { var radianHalf = halfRemainRadian + _symbolRadiansHalf[node.dataIndex]; angle += radianHalf, node.setLayout([ r * Math.cos(angle) + cx, r * Math.sin(angle) + cy ]), angle += radianHalf; }); } }; function graphCircularLayout(ecModel) { ecModel.eachSeriesByType('graph', function(seriesModel) { 'circular' === seriesModel.get('layout') && circularLayout(seriesModel, 'symbolSize'); }); } function graphForceLayout(ecModel) { ecModel.eachSeriesByType('graph', function(graphSeries) { var coordSys = graphSeries.coordinateSystem; if (!coordSys || 'view' === coordSys.type) { if ('force' === graphSeries.get('layout')) { var preservedPoints_1 = graphSeries.preservedPoints || {}, graph_1 = graphSeries.getGraph(), nodeData_1 = graph_1.data, edgeData = graph_1.edgeData, forceModel = graphSeries.getModel('force'), initLayout = forceModel.get('initLayout'); graphSeries.preservedPoints ? nodeData_1.each(function(idx) { var id = nodeData_1.getId(idx); nodeData_1.setItemLayout(idx, preservedPoints_1[id] || [ NaN, NaN ]); }) : initLayout && 'none' !== initLayout ? 'circular' === initLayout && circularLayout(graphSeries, 'value') : simpleLayout(graphSeries); var nodeDataExtent_1 = nodeData_1.getDataExtent('value'), edgeDataExtent_1 = edgeData.getDataExtent('value'), repulsion = forceModel.get('repulsion'), edgeLength = forceModel.get('edgeLength'), repulsionArr_1 = isArray(repulsion) ? repulsion : [ repulsion, repulsion ], edgeLengthArr_1 = isArray(edgeLength) ? edgeLength : [ edgeLength, edgeLength ]; edgeLengthArr_1 = [ edgeLengthArr_1[1], edgeLengthArr_1[0] ]; var nodes_1 = nodeData_1.mapArray('value', function(value, idx) { var point = nodeData_1.getItemLayout(idx), rep = linearMap(value, nodeDataExtent_1, repulsionArr_1); return isNaN(rep) && (rep = (repulsionArr_1[0] + repulsionArr_1[1]) / 2), { w: rep, rep: rep, fixed: nodeData_1.getItemModel(idx).get('fixed'), p: !point || isNaN(point[0]) || isNaN(point[1]) ? null : point }; }), edges = edgeData.mapArray('value', function(value, idx) { var edge = graph_1.getEdgeByIndex(idx), d = linearMap(value, edgeDataExtent_1, edgeLengthArr_1); isNaN(d) && (d = (edgeLengthArr_1[0] + edgeLengthArr_1[1]) / 2); var edgeModel = edge.getModel(), curveness = retrieve3(edge.getModel().get([ 'lineStyle', 'curveness' ]), -getCurvenessForEdge(edge, graphSeries, idx, !0), 0); return { n1: nodes_1[edge.node1.dataIndex], n2: nodes_1[edge.node2.dataIndex], d: d, curveness: curveness, ignoreForceLayout: edgeModel.get('ignoreForceLayout') }; }), forceInstance = function(inNodes, inEdges, opts) { for(var beforeStepCallback, afterStepCallback, nodes = inNodes, rect = opts.rect, width = rect.width, height = rect.height, center = [ rect.x + width / 2, rect.y + height / 2 ], gravity = null == opts.gravity ? 0.1 : opts.gravity, i = 0; i < nodes.length; i++){ var n = nodes[i]; n.p || (n.p = create(width * (Math.random() - 0.5) + center[0], height * (Math.random() - 0.5) + center[1])), n.pp = clone$1(n.p), n.edges = null; } var initialFriction = null == opts.friction ? 0.6 : opts.friction, friction = initialFriction; return { warmUp: function() { friction = 0.8 * initialFriction; }, setFixed: function(idx) { nodes[idx].fixed = !0; }, setUnfixed: function(idx) { nodes[idx].fixed = !1; }, beforeStep: function(cb) { beforeStepCallback = cb; }, afterStep: function(cb) { afterStepCallback = cb; }, step: function(cb) { beforeStepCallback && beforeStepCallback(nodes, inEdges); for(var v12 = [], nLen = nodes.length, i = 0; i < inEdges.length; i++){ var e = inEdges[i]; if (!e.ignoreForceLayout) { var n1 = e.n1, n2 = e.n2; sub(v12, n2.p, n1.p); var d = len(v12) - e.d, w = n2.w / (n1.w + n2.w); isNaN(w) && (w = 0), normalize(v12, v12), n1.fixed || scaleAndAdd(n1.p, n1.p, v12, w * d * friction), n2.fixed || scaleAndAdd(n2.p, n2.p, v12, -(1 - w) * d * friction); } } for(var i = 0; i < nLen; i++){ var n = nodes[i]; n.fixed || (sub(v12, center, n.p), scaleAndAdd(n.p, n.p, v12, gravity * friction)); } for(var i = 0; i < nLen; i++)for(var n1 = nodes[i], j = i + 1; j < nLen; j++){ var n2 = nodes[j]; sub(v12, n2.p, n1.p); var d = len(v12); 0 === d && (set(v12, Math.random() - 0.5, Math.random() - 0.5), d = 1); var repFact = (n1.rep + n2.rep) / d / d; n1.fixed || scaleAndAdd(n1.pp, n1.pp, v12, repFact), n2.fixed || scaleAndAdd(n2.pp, n2.pp, v12, -repFact); } for(var v = [], i = 0; i < nLen; i++){ var n = nodes[i]; n.fixed || (sub(v, n.p, n.pp), scaleAndAdd(n.p, n.p, v, friction), copy(n.pp, n.p)); } var finished = (friction *= 0.992) < 0.01; afterStepCallback && afterStepCallback(nodes, inEdges, finished), cb && cb(finished); } }; }(nodes_1, edges, { rect: coordSys.getBoundingRect(), gravity: forceModel.get('gravity'), friction: forceModel.get('friction') }); forceInstance.beforeStep(function(nodes, edges) { for(var i = 0, l = nodes.length; i < l; i++)nodes[i].fixed && copy(nodes[i].p, graph_1.getNodeByIndex(i).getLayout()); }), forceInstance.afterStep(function(nodes, edges, stopped) { for(var i = 0, l = nodes.length; i < l; i++)nodes[i].fixed || graph_1.getNodeByIndex(i).setLayout(nodes[i].p), preservedPoints_1[nodeData_1.getId(i)] = nodes[i].p; for(var i = 0, l = edges.length; i < l; i++){ var e = edges[i], edge = graph_1.getEdgeByIndex(i), p1 = e.n1.p, p2 = e.n2.p, points = edge.getLayout(); (points = points ? points.slice() : [])[0] = points[0] || [], points[1] = points[1] || [], copy(points[0], p1), copy(points[1], p2), +e.curveness && (points[2] = [ (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * e.curveness, (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * e.curveness ]), edge.setLayout(points); } }), graphSeries.forceLayout = forceInstance, graphSeries.preservedPoints = preservedPoints_1, forceInstance.step(); } else graphSeries.forceLayout = null; } }); } function createViewCoordSys(ecModel, api) { var viewList = []; return ecModel.eachSeriesByType('graph', function(seriesModel) { var coordSysType = seriesModel.get('coordinateSystem'); if (!coordSysType || 'view' === coordSysType) { var data_1 = seriesModel.getData(), positions = data_1.mapArray(function(idx) { var itemModel = data_1.getItemModel(idx); return [ +itemModel.get('x'), +itemModel.get('y') ]; }), min = [], max = []; fromPoints(positions, min, max), max[0] - min[0] == 0 && (max[0] += 1, min[0] -= 1), max[1] - min[1] == 0 && (max[1] += 1, min[1] -= 1); var aspect = (max[0] - min[0]) / (max[1] - min[1]), viewRect = getLayoutRect(extend(seriesModel.getBoxLayoutParams(), { aspect: aspect }), { width: api.getWidth(), height: api.getHeight() }); isNaN(aspect) && (min = [ viewRect.x, viewRect.y ], max = [ viewRect.x + viewRect.width, viewRect.y + viewRect.height ]); var bbWidth = max[0] - min[0], bbHeight = max[1] - min[1], viewWidth = viewRect.width, viewHeight = viewRect.height, viewCoordSys = seriesModel.coordinateSystem = new View(); viewCoordSys.zoomLimit = seriesModel.get('scaleLimit'), viewCoordSys.setBoundingRect(min[0], min[1], bbWidth, bbHeight), viewCoordSys.setViewRect(viewRect.x, viewRect.y, viewWidth, viewHeight), viewCoordSys.setCenter(seriesModel.get('center')), viewCoordSys.setZoom(seriesModel.get('zoom')), viewList.push(viewCoordSys); } }), viewList; } var straightLineProto = Line.prototype, bezierCurveProto = BezierCurve.prototype, StraightLineShape = function() { this.x1 = 0, this.y1 = 0, this.x2 = 0, this.y2 = 0, this.percent = 1; }; function isStraightLine(shape) { return isNaN(+shape.cpx1) || isNaN(+shape.cpy1); } __extends(function() { return null !== _super && _super.apply(this, arguments) || this; }, _super = StraightLineShape); var ECLinePath = function(_super) { function ECLinePath(opts) { var _this = _super.call(this, opts) || this; return _this.type = 'ec-line', _this; } return __extends(ECLinePath, _super), ECLinePath.prototype.getDefaultStyle = function() { return { stroke: '#000', fill: null }; }, ECLinePath.prototype.getDefaultShape = function() { return new StraightLineShape(); }, ECLinePath.prototype.buildPath = function(ctx, shape) { isStraightLine(shape) ? straightLineProto.buildPath.call(this, ctx, shape) : bezierCurveProto.buildPath.call(this, ctx, shape); }, ECLinePath.prototype.pointAt = function(t) { return isStraightLine(this.shape) ? straightLineProto.pointAt.call(this, t) : bezierCurveProto.pointAt.call(this, t); }, ECLinePath.prototype.tangentAt = function(t) { var shape = this.shape, p = isStraightLine(shape) ? [ shape.x2 - shape.x1, shape.y2 - shape.y1 ] : bezierCurveProto.tangentAt.call(this, t); return normalize(p, p); }, ECLinePath; }(Path), SYMBOL_CATEGORIES = [ 'fromSymbol', 'toSymbol' ]; function makeSymbolTypeKey(symbolCategory) { return '_' + symbolCategory + 'Type'; } function createSymbol$1(name, lineData, idx) { var symbolType = lineData.getItemVisual(idx, name); if (symbolType && 'none' !== symbolType) { var symbolSize = lineData.getItemVisual(idx, name + 'Size'), symbolRotate = lineData.getItemVisual(idx, name + 'Rotate'), symbolOffset = lineData.getItemVisual(idx, name + 'Offset') || 0, symbolKeepAspect = lineData.getItemVisual(idx, name + 'KeepAspect'), symbolSizeArr = isArray(symbolSize) ? symbolSize : [ symbolSize, symbolSize ], symbolOffsetArr = isArray(symbolOffset) ? symbolOffset : [ symbolOffset, symbolOffset ]; symbolOffsetArr[0] = parsePercent$1(symbolOffsetArr[0], symbolSizeArr[0]), symbolOffsetArr[1] = parsePercent$1(retrieve2(symbolOffsetArr[1], symbolOffsetArr[0]), symbolSizeArr[1]); var symbolPath = createSymbol(symbolType, -symbolSizeArr[0] / 2 + symbolOffsetArr[0], -symbolSizeArr[1] / 2 + symbolOffsetArr[1], symbolSizeArr[0], symbolSizeArr[1], null, symbolKeepAspect); return symbolPath.__specifiedRotation = null == symbolRotate || isNaN(symbolRotate) ? void 0 : +symbolRotate * Math.PI / 180 || 0, symbolPath.name = name, symbolPath; } } function setLinePoints(targetShape, points) { targetShape.x1 = points[0][0], targetShape.y1 = points[0][1], targetShape.x2 = points[1][0], targetShape.y2 = points[1][1], targetShape.percent = 1; var cp1 = points[2]; cp1 ? (targetShape.cpx1 = cp1[0], targetShape.cpy1 = cp1[1]) : (targetShape.cpx1 = NaN, targetShape.cpy1 = NaN); } var Line$1 = function(_super) { function Line(lineData, idx, seriesScope) { var _this = _super.call(this) || this; return _this._createLine(lineData, idx, seriesScope), _this; } return __extends(Line, _super), Line.prototype._createLine = function(lineData, idx, seriesScope) { var points, line, seriesModel = lineData.hostModel, line1 = (points = lineData.getItemLayout(idx), setLinePoints((line = new ECLinePath({ name: 'line', subPixelOptimize: !0 })).shape, points), line); line1.shape.percent = 0, initProps(line1, { shape: { percent: 1 } }, seriesModel, idx), this.add(line1), each(SYMBOL_CATEGORIES, function(symbolCategory) { var symbol = createSymbol$1(symbolCategory, lineData, idx); this.add(symbol), this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory); }, this), this._updateCommonStl(lineData, idx, seriesScope); }, Line.prototype.updateData = function(lineData, idx, seriesScope) { var seriesModel = lineData.hostModel, line = this.childOfName('line'), linePoints = lineData.getItemLayout(idx), target = { shape: {} }; setLinePoints(target.shape, linePoints), updateProps(line, target, seriesModel, idx), each(SYMBOL_CATEGORIES, function(symbolCategory) { var symbolType = lineData.getItemVisual(idx, symbolCategory), key = makeSymbolTypeKey(symbolCategory); if (this[key] !== symbolType) { this.remove(this.childOfName(symbolCategory)); var symbol = createSymbol$1(symbolCategory, lineData, idx); this.add(symbol); } this[key] = symbolType; }, this), this._updateCommonStl(lineData, idx, seriesScope); }, Line.prototype.getLinePath = function() { return this.childAt(0); }, Line.prototype._updateCommonStl = function(lineData, idx, seriesScope) { var seriesModel = lineData.hostModel, line = this.childOfName('line'), emphasisLineStyle = seriesScope && seriesScope.emphasisLineStyle, blurLineStyle = seriesScope && seriesScope.blurLineStyle, selectLineStyle = seriesScope && seriesScope.selectLineStyle, labelStatesModels = seriesScope && seriesScope.labelStatesModels; if (!seriesScope || lineData.hasItemOption) { var itemModel = lineData.getItemModel(idx); emphasisLineStyle = itemModel.getModel([ 'emphasis', 'lineStyle' ]).getLineStyle(), blurLineStyle = itemModel.getModel([ 'blur', 'lineStyle' ]).getLineStyle(), selectLineStyle = itemModel.getModel([ 'select', 'lineStyle' ]).getLineStyle(), labelStatesModels = getLabelStatesModels(itemModel); } var lineStyle = lineData.getItemVisual(idx, 'style'), visualColor = lineStyle.stroke; line.useStyle(lineStyle), line.style.fill = null, line.style.strokeNoScale = !0, line.ensureState('emphasis').style = emphasisLineStyle, line.ensureState('blur').style = blurLineStyle, line.ensureState('select').style = selectLineStyle, each(SYMBOL_CATEGORIES, function(symbolCategory) { var symbol = this.childOfName(symbolCategory); if (symbol) { symbol.setColor(visualColor), symbol.style.opacity = lineStyle.opacity; for(var i = 0; i < SPECIAL_STATES.length; i++){ var stateName = SPECIAL_STATES[i], lineState = line.getState(stateName); if (lineState) { var lineStateStyle = lineState.style || {}, state = symbol.ensureState(stateName), stateStyle = state.style || (state.style = {}); null != lineStateStyle.stroke && (stateStyle[symbol.__isEmptyBrush ? 'stroke' : 'fill'] = lineStateStyle.stroke), null != lineStateStyle.opacity && (stateStyle.opacity = lineStateStyle.opacity); } } symbol.markRedraw(); } }, this); var rawVal = seriesModel.getRawValue(idx); setLabelStyle(this, labelStatesModels, { labelDataIndex: idx, labelFetcher: { getFormattedLabel: function(dataIndex, stateName) { return seriesModel.getFormattedLabel(dataIndex, stateName, lineData.dataType); } }, inheritColor: visualColor || '#000', defaultOpacity: lineStyle.opacity, defaultText: (null == rawVal ? lineData.getName(idx) : isFinite(rawVal) ? round(rawVal) : rawVal) + '' }); var label = this.getTextContent(); if (label) { var labelNormalModel = labelStatesModels.normal; label.__align = label.style.align, label.__verticalAlign = label.style.verticalAlign, label.__position = labelNormalModel.get('position') || 'middle'; var distance = labelNormalModel.get('distance'); isArray(distance) || (distance = [ distance, distance ]), label.__labelDistance = distance; } this.setTextConfig({ position: null, local: !0, inside: !1 }), enableHoverEmphasis(this); }, Line.prototype.highlight = function() { enterEmphasis(this); }, Line.prototype.downplay = function() { leaveEmphasis(this); }, Line.prototype.updateLayout = function(lineData, idx) { this.setLinePoints(lineData.getItemLayout(idx)); }, Line.prototype.setLinePoints = function(points) { var linePath = this.childOfName('line'); setLinePoints(linePath.shape, points), linePath.dirty(); }, Line.prototype.beforeUpdate = function() { var symbolFrom = this.childOfName('fromSymbol'), symbolTo = this.childOfName('toSymbol'), label = this.getTextContent(); if (symbolFrom || symbolTo || label && !label.ignore) { for(var invScale = 1, parentNode = this.parent; parentNode;)parentNode.scaleX && (invScale /= parentNode.scaleX), parentNode = parentNode.parent; var line = this.childOfName('line'); if (this.__dirty || line.__dirty) { var percent = line.shape.percent, fromPos = line.pointAt(0), toPos = line.pointAt(percent), d = sub([], toPos, fromPos); if (normalize(d, d), symbolFrom && (symbolFrom.setPosition(fromPos), setSymbolRotation(symbolFrom, 0), symbolFrom.scaleX = symbolFrom.scaleY = invScale * percent, symbolFrom.markRedraw()), symbolTo && (symbolTo.setPosition(toPos), setSymbolRotation(symbolTo, 1), symbolTo.scaleX = symbolTo.scaleY = invScale * percent, symbolTo.markRedraw()), label && !label.ignore) { label.x = label.y = 0, label.originX = label.originY = 0; var textAlign = void 0, textVerticalAlign = void 0, distance = label.__labelDistance, distanceX = distance[0] * invScale, distanceY = distance[1] * invScale, halfPercent = percent / 2, tangent = line.tangentAt(halfPercent), n = [ tangent[1], -tangent[0] ], cp = line.pointAt(halfPercent); n[1] > 0 && (n[0] = -n[0], n[1] = -n[1]); var dir = tangent[0] < 0 ? -1 : 1; if ('start' !== label.__position && 'end' !== label.__position) { var rotation = -Math.atan2(tangent[1], tangent[0]); toPos[0] < fromPos[0] && (rotation = Math.PI + rotation), label.rotation = rotation; } var dy = void 0; switch(label.__position){ case 'insideStartTop': case 'insideMiddleTop': case 'insideEndTop': case 'middle': dy = -distanceY, textVerticalAlign = 'bottom'; break; case 'insideStartBottom': case 'insideMiddleBottom': case 'insideEndBottom': dy = distanceY, textVerticalAlign = 'top'; break; default: dy = 0, textVerticalAlign = 'middle'; } switch(label.__position){ case 'end': label.x = d[0] * distanceX + toPos[0], label.y = d[1] * distanceY + toPos[1], textAlign = d[0] > 0.8 ? 'left' : d[0] < -0.8 ? 'right' : 'center', textVerticalAlign = d[1] > 0.8 ? 'top' : d[1] < -0.8 ? 'bottom' : 'middle'; break; case 'start': label.x = -d[0] * distanceX + fromPos[0], label.y = -d[1] * distanceY + fromPos[1], textAlign = d[0] > 0.8 ? 'right' : d[0] < -0.8 ? 'left' : 'center', textVerticalAlign = d[1] > 0.8 ? 'bottom' : d[1] < -0.8 ? 'top' : 'middle'; break; case 'insideStartTop': case 'insideStart': case 'insideStartBottom': label.x = distanceX * dir + fromPos[0], label.y = fromPos[1] + dy, textAlign = tangent[0] < 0 ? 'right' : 'left', label.originX = -distanceX * dir, label.originY = -dy; break; case 'insideMiddleTop': case 'insideMiddle': case 'insideMiddleBottom': case 'middle': label.x = cp[0], label.y = cp[1] + dy, textAlign = 'center', label.originY = -dy; break; case 'insideEndTop': case 'insideEnd': case 'insideEndBottom': label.x = -distanceX * dir + toPos[0], label.y = toPos[1] + dy, textAlign = tangent[0] >= 0 ? 'right' : 'left', label.originX = distanceX * dir, label.originY = -dy; } label.scaleX = label.scaleY = invScale, label.setStyle({ verticalAlign: label.__verticalAlign || textVerticalAlign, align: label.__align || textAlign }); } } } function setSymbolRotation(symbol, percent) { var specifiedRotation = symbol.__specifiedRotation; if (null == specifiedRotation) { var tangent = line.tangentAt(percent); symbol.attr('rotation', (1 === percent ? -1 : 1) * Math.PI / 2 - Math.atan2(tangent[1], tangent[0])); } else symbol.attr('rotation', specifiedRotation); } }, Line; }(Group), LineDraw = function() { function LineDraw(LineCtor) { this.group = new Group(), this._LineCtor = LineCtor || Line$1; } return LineDraw.prototype.isPersistent = function() { return !0; }, LineDraw.prototype.updateData = function(lineData) { var _this = this, lineDraw = this, group = lineDraw.group, oldLineData = lineDraw._lineData; lineDraw._lineData = lineData, oldLineData || group.removeAll(); var seriesScope = makeSeriesScope$1(lineData); lineData.diff(oldLineData).add(function(idx) { _this._doAdd(lineData, idx, seriesScope); }).update(function(newIdx, oldIdx) { _this._doUpdate(oldLineData, lineData, oldIdx, newIdx, seriesScope); }).remove(function(idx) { group.remove(oldLineData.getItemGraphicEl(idx)); }).execute(); }, LineDraw.prototype.updateLayout = function() { var lineData = this._lineData; lineData && lineData.eachItemGraphicEl(function(el, idx) { el.updateLayout(lineData, idx); }, this); }, LineDraw.prototype.incrementalPrepareUpdate = function(lineData) { this._seriesScope = makeSeriesScope$1(lineData), this._lineData = null, this.group.removeAll(); }, LineDraw.prototype.incrementalUpdate = function(taskParams, lineData) { function updateIncrementalAndHover(el) { el.isGroup || el.animators && el.animators.length > 0 || (el.incremental = !0, el.ensureState('emphasis').hoverLayer = !0); } for(var idx = taskParams.start; idx < taskParams.end; idx++)if (lineNeedsDraw(lineData.getItemLayout(idx))) { var el = new this._LineCtor(lineData, idx, this._seriesScope); el.traverse(updateIncrementalAndHover), this.group.add(el), lineData.setItemGraphicEl(idx, el); } }, LineDraw.prototype.remove = function() { this.group.removeAll(); }, LineDraw.prototype._doAdd = function(lineData, idx, seriesScope) { if (lineNeedsDraw(lineData.getItemLayout(idx))) { var el = new this._LineCtor(lineData, idx, seriesScope); lineData.setItemGraphicEl(idx, el), this.group.add(el); } }, LineDraw.prototype._doUpdate = function(oldLineData, newLineData, oldIdx, newIdx, seriesScope) { var itemEl = oldLineData.getItemGraphicEl(oldIdx); if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) { this.group.remove(itemEl); return; } itemEl ? itemEl.updateData(newLineData, newIdx, seriesScope) : itemEl = new this._LineCtor(newLineData, newIdx, seriesScope), newLineData.setItemGraphicEl(newIdx, itemEl), this.group.add(itemEl); }, LineDraw; }(); function makeSeriesScope$1(lineData) { var hostModel = lineData.hostModel; return { lineStyle: hostModel.getModel('lineStyle').getLineStyle(), emphasisLineStyle: hostModel.getModel([ 'emphasis', 'lineStyle' ]).getLineStyle(), blurLineStyle: hostModel.getModel([ 'blur', 'lineStyle' ]).getLineStyle(), selectLineStyle: hostModel.getModel([ 'select', 'lineStyle' ]).getLineStyle(), labelStatesModels: getLabelStatesModels(hostModel) }; } function isPointNaN(pt) { return isNaN(pt[0]) || isNaN(pt[1]); } function lineNeedsDraw(pts) { return !isPointNaN(pts[0]) && !isPointNaN(pts[1]); } var v1 = [], v2 = [], v3 = [], mathAbs$2 = Math.abs; function intersectCurveCircle(curvePoints, center, radius) { for(var t, p0 = curvePoints[0], p1 = curvePoints[1], p2 = curvePoints[2], d = 1 / 0, radiusSquare = radius * radius, interval = 0.1, _t = 0.1; _t <= 0.9; _t += 0.1){ v1[0] = quadraticAt(p0[0], p1[0], p2[0], _t), v1[1] = quadraticAt(p0[1], p1[1], p2[1], _t); var diff = mathAbs$2(distanceSquare(v1, center) - radiusSquare); diff < d && (d = diff, t = _t); } for(var i = 0; i < 32; i++){ var next = t + interval; v2[0] = quadraticAt(p0[0], p1[0], p2[0], t), v2[1] = quadraticAt(p0[1], p1[1], p2[1], t), v3[0] = quadraticAt(p0[0], p1[0], p2[0], next), v3[1] = quadraticAt(p0[1], p1[1], p2[1], next); var diff = distanceSquare(v2, center) - radiusSquare; if (1e-2 > mathAbs$2(diff)) break; var nextDiff = distanceSquare(v3, center) - radiusSquare; interval /= 2, diff < 0 ? nextDiff >= 0 ? t += interval : t -= interval : nextDiff >= 0 ? t -= interval : t += interval; } return t; } function adjustEdge(graph, scale) { var tmp0 = [], pts = [ [], [], [] ], pts2 = [ [], [] ], v = []; scale /= 2, graph.eachEdge(function(edge, idx) { var linePoints = edge.getLayout(), fromSymbol = edge.getVisual('fromSymbol'), toSymbol = edge.getVisual('toSymbol'); !linePoints.__original && (linePoints.__original = [ clone$1(linePoints[0]), clone$1(linePoints[1]) ], linePoints[2] && linePoints.__original.push(clone$1(linePoints[2]))); var originalPoints = linePoints.__original; if (null != linePoints[2]) { if (copy(pts[0], originalPoints[0]), copy(pts[1], originalPoints[2]), copy(pts[2], originalPoints[1]), fromSymbol && 'none' !== fromSymbol) { var symbolSize = getSymbolSize(edge.node1), t = intersectCurveCircle(pts, originalPoints[0], symbolSize * scale); quadraticSubdivide(pts[0][0], pts[1][0], pts[2][0], t, tmp0), pts[0][0] = tmp0[3], pts[1][0] = tmp0[4], quadraticSubdivide(pts[0][1], pts[1][1], pts[2][1], t, tmp0), pts[0][1] = tmp0[3], pts[1][1] = tmp0[4]; } if (toSymbol && 'none' !== toSymbol) { var symbolSize = getSymbolSize(edge.node2), t = intersectCurveCircle(pts, originalPoints[1], symbolSize * scale); quadraticSubdivide(pts[0][0], pts[1][0], pts[2][0], t, tmp0), pts[1][0] = tmp0[1], pts[2][0] = tmp0[2], quadraticSubdivide(pts[0][1], pts[1][1], pts[2][1], t, tmp0), pts[1][1] = tmp0[1], pts[2][1] = tmp0[2]; } copy(linePoints[0], pts[0]), copy(linePoints[1], pts[2]), copy(linePoints[2], pts[1]); } else { if (copy(pts2[0], originalPoints[0]), copy(pts2[1], originalPoints[1]), sub(v, pts2[1], pts2[0]), normalize(v, v), fromSymbol && 'none' !== fromSymbol) { var symbolSize = getSymbolSize(edge.node1); scaleAndAdd(pts2[0], pts2[0], v, symbolSize * scale); } if (toSymbol && 'none' !== toSymbol) { var symbolSize = getSymbolSize(edge.node2); scaleAndAdd(pts2[1], pts2[1], v, -symbolSize * scale); } copy(linePoints[0], pts2[0]), copy(linePoints[1], pts2[1]); } }); } function isViewCoordSys(coordSys) { return 'view' === coordSys.type; } var GraphView = function(_super) { function GraphView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = GraphView.type, _this; } return __extends(GraphView, _super), GraphView.prototype.init = function(ecModel, api) { var symbolDraw = new SymbolDraw(), lineDraw = new LineDraw(), group = this.group; this._controller = new RoamController(api.getZr()), this._controllerHost = { target: group }, group.add(symbolDraw.group), group.add(lineDraw.group), this._symbolDraw = symbolDraw, this._lineDraw = lineDraw, this._firstRender = !0; }, GraphView.prototype.render = function(seriesModel, ecModel, api) { var _this = this, coordSys = seriesModel.coordinateSystem; this._model = seriesModel; var symbolDraw = this._symbolDraw, lineDraw = this._lineDraw, group = this.group; if (isViewCoordSys(coordSys)) { var groupNewProp = { x: coordSys.x, y: coordSys.y, scaleX: coordSys.scaleX, scaleY: coordSys.scaleY }; this._firstRender ? group.attr(groupNewProp) : updateProps(group, groupNewProp, seriesModel); } adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel)); var data = seriesModel.getData(); symbolDraw.updateData(data); var edgeData = seriesModel.getEdgeData(); lineDraw.updateData(edgeData), this._updateNodeAndLinkScale(), this._updateController(seriesModel, ecModel, api), clearTimeout(this._layoutTimeout); var forceLayout = seriesModel.forceLayout, layoutAnimation = seriesModel.get([ 'force', 'layoutAnimation' ]); forceLayout && this._startForceLayoutIteration(forceLayout, layoutAnimation), data.graph.eachNode(function(node) { var idx = node.dataIndex, el = node.getGraphicEl(), itemModel = node.getModel(); el.off('drag').off('dragend'); var draggable = itemModel.get('draggable'); draggable && el.on('drag', function() { forceLayout && (forceLayout.warmUp(), _this._layouting || _this._startForceLayoutIteration(forceLayout, layoutAnimation), forceLayout.setFixed(idx), data.setItemLayout(idx, [ el.x, el.y ])); }).on('dragend', function() { forceLayout && forceLayout.setUnfixed(idx); }), el.setDraggable(draggable && !!forceLayout), 'adjacency' === itemModel.get([ 'emphasis', 'focus' ]) && (getECData(el).focus = node.getAdjacentDataIndices()); }), data.graph.eachEdge(function(edge) { var el = edge.getGraphicEl(); 'adjacency' === edge.getModel().get([ 'emphasis', 'focus' ]) && (getECData(el).focus = { edge: [ edge.dataIndex ], node: [ edge.node1.dataIndex, edge.node2.dataIndex ] }); }); var circularRotateLabel = 'circular' === seriesModel.get('layout') && seriesModel.get([ 'circular', 'rotateLabel' ]), cx = data.getLayout('cx'), cy = data.getLayout('cy'); data.eachItemGraphicEl(function(el, idx) { var labelRotate = data.getItemModel(idx).get([ 'label', 'rotate' ]) || 0, symbolPath = el.getSymbolPath(); if (circularRotateLabel) { var pos = data.getItemLayout(idx), rad = Math.atan2(pos[1] - cy, pos[0] - cx); rad < 0 && (rad = 2 * Math.PI + rad); var isLeft = pos[0] < cx; isLeft && (rad -= Math.PI); var textPosition = isLeft ? 'left' : 'right'; symbolPath.setTextConfig({ rotation: -rad, position: textPosition, origin: 'center' }); var emphasisState = symbolPath.ensureState('emphasis'); extend(emphasisState.textConfig || (emphasisState.textConfig = {}), { position: textPosition }); } else symbolPath.setTextConfig({ rotation: labelRotate *= Math.PI / 180 }); }), this._firstRender = !1; }, GraphView.prototype.dispose = function() { this._controller && this._controller.dispose(), this._controllerHost = null; }, GraphView.prototype._startForceLayoutIteration = function(forceLayout, layoutAnimation) { var self1 = this; !function step() { forceLayout.step(function(stopped) { self1.updateLayout(self1._model), (self1._layouting = !stopped) && (layoutAnimation ? self1._layoutTimeout = setTimeout(step, 16) : step()); }); }(); }, GraphView.prototype._updateController = function(seriesModel, ecModel, api) { var _this = this, controller = this._controller, controllerHost = this._controllerHost, group = this.group; if (controller.setPointerChecker(function(e, x, y) { var rect = group.getBoundingRect(); return rect.applyTransform(group.transform), rect.contain(x, y) && !onIrrelevantElement(e, api, seriesModel); }), !isViewCoordSys(seriesModel.coordinateSystem)) { controller.disable(); return; } controller.enable(seriesModel.get('roam')), controllerHost.zoomLimit = seriesModel.get('scaleLimit'), controllerHost.zoom = seriesModel.coordinateSystem.getZoom(), controller.off('pan').off('zoom').on('pan', function(e) { updateViewOnPan(controllerHost, e.dx, e.dy), api.dispatchAction({ seriesId: seriesModel.id, type: 'graphRoam', dx: e.dx, dy: e.dy }); }).on('zoom', function(e) { updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY), api.dispatchAction({ seriesId: seriesModel.id, type: 'graphRoam', zoom: e.scale, originX: e.originX, originY: e.originY }), _this._updateNodeAndLinkScale(), adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel)), _this._lineDraw.updateLayout(), api.updateLabelLayout(); }); }, GraphView.prototype._updateNodeAndLinkScale = function() { var seriesModel = this._model, data = seriesModel.getData(), nodeScale = getNodeGlobalScale(seriesModel); data.eachItemGraphicEl(function(el, idx) { el.setSymbolScale(nodeScale); }); }, GraphView.prototype.updateLayout = function(seriesModel) { adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel)), this._symbolDraw.updateLayout(), this._lineDraw.updateLayout(); }, GraphView.prototype.remove = function(ecModel, api) { this._symbolDraw && this._symbolDraw.remove(), this._lineDraw && this._lineDraw.remove(); }, GraphView.type = 'graph', GraphView; }(ChartView); function generateNodeKey(id) { return '_EC_' + id; } var Graph = function() { function Graph(directed) { this.type = 'graph', this.nodes = [], this.edges = [], this._nodesMap = {}, this._edgesMap = {}, this._directed = directed || !1; } return Graph.prototype.isDirected = function() { return this._directed; }, Graph.prototype.addNode = function(id, dataIndex) { id = null == id ? '' + dataIndex : '' + id; var nodesMap = this._nodesMap; if (nodesMap[generateNodeKey(id)]) { console.error('Graph nodes have duplicate name or id'); return; } var node = new GraphNode(id, dataIndex); return node.hostGraph = this, this.nodes.push(node), nodesMap[generateNodeKey(id)] = node, node; }, Graph.prototype.getNodeByIndex = function(dataIndex) { var rawIdx = this.data.getRawIndex(dataIndex); return this.nodes[rawIdx]; }, Graph.prototype.getNodeById = function(id) { return this._nodesMap[generateNodeKey(id)]; }, Graph.prototype.addEdge = function(n1, n2, dataIndex) { var nodesMap = this._nodesMap, edgesMap = this._edgesMap; if ('number' == typeof n1 && (n1 = this.nodes[n1]), 'number' == typeof n2 && (n2 = this.nodes[n2]), n1 instanceof GraphNode || (n1 = nodesMap[generateNodeKey(n1)]), n2 instanceof GraphNode || (n2 = nodesMap[generateNodeKey(n2)]), n1 && n2) { var key = n1.id + '-' + n2.id, edge = new GraphEdge(n1, n2, dataIndex); return edge.hostGraph = this, this._directed && (n1.outEdges.push(edge), n2.inEdges.push(edge)), n1.edges.push(edge), n1 !== n2 && n2.edges.push(edge), this.edges.push(edge), edgesMap[key] = edge, edge; } }, Graph.prototype.getEdgeByIndex = function(dataIndex) { var rawIdx = this.edgeData.getRawIndex(dataIndex); return this.edges[rawIdx]; }, Graph.prototype.getEdge = function(n1, n2) { n1 instanceof GraphNode && (n1 = n1.id), n2 instanceof GraphNode && (n2 = n2.id); var edgesMap = this._edgesMap; return this._directed ? edgesMap[n1 + '-' + n2] : edgesMap[n1 + '-' + n2] || edgesMap[n2 + '-' + n1]; }, Graph.prototype.eachNode = function(cb, context) { for(var nodes = this.nodes, len = nodes.length, i = 0; i < len; i++)nodes[i].dataIndex >= 0 && cb.call(context, nodes[i], i); }, Graph.prototype.eachEdge = function(cb, context) { for(var edges = this.edges, len = edges.length, i = 0; i < len; i++)edges[i].dataIndex >= 0 && edges[i].node1.dataIndex >= 0 && edges[i].node2.dataIndex >= 0 && cb.call(context, edges[i], i); }, Graph.prototype.breadthFirstTraverse = function(cb, startNode, direction, context) { if (startNode instanceof GraphNode || (startNode = this._nodesMap[generateNodeKey(startNode)]), startNode) { for(var edgeType = 'out' === direction ? 'outEdges' : 'in' === direction ? 'inEdges' : 'edges', i = 0; i < this.nodes.length; i++)this.nodes[i].__visited = !1; if (!cb.call(context, startNode, null)) for(var queue = [ startNode ]; queue.length;)for(var currentNode = queue.shift(), edges = currentNode[edgeType], i = 0; i < edges.length; i++){ var e = edges[i], otherNode = e.node1 === currentNode ? e.node2 : e.node1; if (!otherNode.__visited) { if (cb.call(context, otherNode, currentNode)) return; queue.push(otherNode), otherNode.__visited = !0; } } } }, Graph.prototype.update = function() { for(var data = this.data, edgeData = this.edgeData, nodes = this.nodes, edges = this.edges, i = 0, len = nodes.length; i < len; i++)nodes[i].dataIndex = -1; for(var i = 0, len = data.count(); i < len; i++)nodes[data.getRawIndex(i)].dataIndex = i; edgeData.filterSelf(function(idx) { var edge = edges[edgeData.getRawIndex(idx)]; return edge.node1.dataIndex >= 0 && edge.node2.dataIndex >= 0; }); for(var i = 0, len = edges.length; i < len; i++)edges[i].dataIndex = -1; for(var i = 0, len = edgeData.count(); i < len; i++)edges[edgeData.getRawIndex(i)].dataIndex = i; }, Graph.prototype.clone = function() { for(var graph = new Graph(this._directed), nodes = this.nodes, edges = this.edges, i = 0; i < nodes.length; i++)graph.addNode(nodes[i].id, nodes[i].dataIndex); for(var i = 0; i < edges.length; i++){ var e = edges[i]; graph.addEdge(e.node1.id, e.node2.id, e.dataIndex); } return graph; }, Graph; }(), GraphNode = function() { function GraphNode(id, dataIndex) { this.inEdges = [], this.outEdges = [], this.edges = [], this.dataIndex = -1, this.id = null == id ? '' : id, this.dataIndex = null == dataIndex ? -1 : dataIndex; } return GraphNode.prototype.degree = function() { return this.edges.length; }, GraphNode.prototype.inDegree = function() { return this.inEdges.length; }, GraphNode.prototype.outDegree = function() { return this.outEdges.length; }, GraphNode.prototype.getModel = function(path) { if (!(this.dataIndex < 0)) return this.hostGraph.data.getItemModel(this.dataIndex).getModel(path); }, GraphNode.prototype.getAdjacentDataIndices = function() { for(var dataIndices = { edge: [], node: [] }, i = 0; i < this.edges.length; i++){ var adjacentEdge = this.edges[i]; adjacentEdge.dataIndex < 0 || (dataIndices.edge.push(adjacentEdge.dataIndex), dataIndices.node.push(adjacentEdge.node1.dataIndex, adjacentEdge.node2.dataIndex)); } return dataIndices; }, GraphNode; }(), GraphEdge = function() { function GraphEdge(n1, n2, dataIndex) { this.dataIndex = -1, this.node1 = n1, this.node2 = n2, this.dataIndex = null == dataIndex ? -1 : dataIndex; } return GraphEdge.prototype.getModel = function(path) { if (!(this.dataIndex < 0)) return this.hostGraph.edgeData.getItemModel(this.dataIndex).getModel(path); }, GraphEdge.prototype.getAdjacentDataIndices = function() { return { edge: [ this.dataIndex ], node: [ this.node1.dataIndex, this.node2.dataIndex ] }; }, GraphEdge; }(); function createGraphDataProxyMixin(hostName, dataName) { return { getValue: function(dimension) { var data = this[hostName][dataName]; return data.get(data.getDimension(dimension || 'value'), this.dataIndex); }, setVisual: function(key, value) { this.dataIndex >= 0 && this[hostName][dataName].setItemVisual(this.dataIndex, key, value); }, getVisual: function(key) { return this[hostName][dataName].getItemVisual(this.dataIndex, key); }, setLayout: function(layout, merge) { this.dataIndex >= 0 && this[hostName][dataName].setItemLayout(this.dataIndex, layout, merge); }, getLayout: function() { return this[hostName][dataName].getItemLayout(this.dataIndex); }, getGraphicEl: function() { return this[hostName][dataName].getItemGraphicEl(this.dataIndex); }, getRawIndex: function() { return this[hostName][dataName].getRawIndex(this.dataIndex); } }; } function createGraphFromNodeEdge(nodes, edges, seriesModel, directed, beforeLink) { for(var nodeData, graph = new Graph(directed), i = 0; i < nodes.length; i++)graph.addNode(retrieve(nodes[i].id, nodes[i].name, i), i); for(var linkNameList = [], validEdges = [], linkCount = 0, i = 0; i < edges.length; i++){ var link = edges[i], source = link.source, target = link.target; graph.addEdge(source, target, linkCount) && (validEdges.push(link), linkNameList.push(retrieve(convertOptionIdName(link.id, null), source + ' > ' + target)), linkCount++); } var coordSys = seriesModel.get('coordinateSystem'); if ('cartesian2d' === coordSys || 'polar' === coordSys) nodeData = createListFromArray(nodes, seriesModel); else { var coordSysCtor = CoordinateSystemManager.get(coordSys), coordDimensions = coordSysCtor && coordSysCtor.dimensions || []; 0 > indexOf(coordDimensions, 'value') && coordDimensions.concat([ 'value' ]); var dimensionNames = createDimensions(nodes, { coordDimensions: coordDimensions }); (nodeData = new List(dimensionNames, seriesModel)).initData(nodes); } var edgeData = new List([ 'value' ], seriesModel); return edgeData.initData(validEdges, linkNameList), beforeLink && beforeLink(nodeData, edgeData), linkList({ mainData: nodeData, struct: graph, structAttr: 'graph', datas: { node: nodeData, edge: edgeData }, datasAttr: { node: 'data', edge: 'edgeData' } }), graph.update(), graph; } mixin(GraphNode, createGraphDataProxyMixin('hostGraph', 'data')), mixin(GraphEdge, createGraphDataProxyMixin('hostGraph', 'edgeData')); var GraphSeriesModel = function(_super) { function GraphSeriesModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = GraphSeriesModel.type, _this.hasSymbolVisual = !0, _this; } return __extends(GraphSeriesModel, _super), GraphSeriesModel.prototype.init = function(option) { _super.prototype.init.apply(this, arguments); var self1 = this; function getCategoriesData() { return self1._categoriesData; } this.legendVisualProvider = new LegendVisualProvider(getCategoriesData, getCategoriesData), this.fillDataTextStyle(option.edges || option.links), this._updateCategoriesData(); }, GraphSeriesModel.prototype.mergeOption = function(option) { _super.prototype.mergeOption.apply(this, arguments), this.fillDataTextStyle(option.edges || option.links), this._updateCategoriesData(); }, GraphSeriesModel.prototype.mergeDefaultAndTheme = function(option) { _super.prototype.mergeDefaultAndTheme.apply(this, arguments), defaultEmphasis(option, 'edgeLabel', [ 'show' ]); }, GraphSeriesModel.prototype.getInitialData = function(option, ecModel) { var edges = option.edges || option.links || [], nodes = option.data || option.nodes || [], self1 = this; if (nodes && edges) { seriesModel = this, getAutoCurvenessParams(seriesModel) && (seriesModel.__curvenessList = [], seriesModel.__edgeMap = {}, createCurveness(seriesModel)); var seriesModel, graph = createGraphFromNodeEdge(nodes, edges, this, !0, function(nodeData, edgeData) { nodeData.wrapMethod('getItemModel', function(model) { var categoryModel = self1._categoriesModels[model.getShallow('category')]; return categoryModel && (categoryModel.parentModel = model.parentModel, model.parentModel = categoryModel), model; }); var oldGetModel = Model.prototype.getModel; function newGetModel(path, parentModel) { var model = oldGetModel.call(this, path, parentModel); return model.resolveParentPath = resolveParentPath, model; } function resolveParentPath(pathArr) { if (pathArr && ('label' === pathArr[0] || 'label' === pathArr[1])) { var newPathArr = pathArr.slice(); return 'label' === pathArr[0] ? newPathArr[0] = 'edgeLabel' : 'label' === pathArr[1] && (newPathArr[1] = 'edgeLabel'), newPathArr; } return pathArr; } edgeData.wrapMethod('getItemModel', function(model) { return model.resolveParentPath = resolveParentPath, model.getModel = newGetModel, model; }); }); return each(graph.edges, function(edge) { !function(n1, n2, seriesModel, index) { if (getAutoCurvenessParams(seriesModel)) { var key = getKeyOfEdges(n1, n2, seriesModel), edgeMap = seriesModel.__edgeMap, oppositeEdges = edgeMap[getOppositeKey(key)]; edgeMap[key] && !oppositeEdges ? edgeMap[key].isForward = !0 : oppositeEdges && edgeMap[key] && (oppositeEdges.isForward = !0, edgeMap[key].isForward = !1), edgeMap[key] = edgeMap[key] || [], edgeMap[key].push(index); } }(edge.node1, edge.node2, this, edge.dataIndex); }, this), graph.data; } }, GraphSeriesModel.prototype.getGraph = function() { return this.getData().graph; }, GraphSeriesModel.prototype.getEdgeData = function() { return this.getGraph().edgeData; }, GraphSeriesModel.prototype.getCategoriesData = function() { return this._categoriesData; }, GraphSeriesModel.prototype.formatTooltip = function(dataIndex, multipleSeries, dataType) { if ('edge' === dataType) { var nodeData = this.getData(), params = this.getDataParams(dataIndex, dataType), edge = nodeData.graph.getEdgeByIndex(dataIndex), sourceName = nodeData.getName(edge.node1.dataIndex), targetName = nodeData.getName(edge.node2.dataIndex), nameArr = []; return null != sourceName && nameArr.push(sourceName), null != targetName && nameArr.push(targetName), createTooltipMarkup('nameValue', { name: nameArr.join(' > '), value: params.value, noValue: null == params.value }); } return defaultSeriesFormatTooltip({ series: this, dataIndex: dataIndex, multipleSeries: multipleSeries }); }, GraphSeriesModel.prototype._updateCategoriesData = function() { var categories = map(this.option.categories || [], function(category) { return null != category.value ? category : extend({ value: 0 }, category); }), categoriesData = new List([ 'value' ], this); categoriesData.initData(categories), this._categoriesData = categoriesData, this._categoriesModels = categoriesData.mapArray(function(idx) { return categoriesData.getItemModel(idx); }); }, GraphSeriesModel.prototype.setZoom = function(zoom) { this.option.zoom = zoom; }, GraphSeriesModel.prototype.setCenter = function(center) { this.option.center = center; }, GraphSeriesModel.prototype.isAnimationEnabled = function() { return _super.prototype.isAnimationEnabled.call(this) && !('force' === this.get('layout') && this.get([ 'force', 'layoutAnimation' ])); }, GraphSeriesModel.type = 'series.graph', GraphSeriesModel.dependencies = [ 'grid', 'polar', 'geo', 'singleAxis', 'calendar' ], GraphSeriesModel.defaultOption = { zlevel: 0, z: 2, coordinateSystem: 'view', legendHoverLink: !0, layout: null, circular: { rotateLabel: !1 }, force: { initLayout: null, repulsion: [ 0, 50 ], gravity: 0.1, friction: 0.6, edgeLength: 30, layoutAnimation: !0 }, left: 'center', top: 'center', symbol: 'circle', symbolSize: 10, edgeSymbol: [ 'none', 'none' ], edgeSymbolSize: 10, edgeLabel: { position: 'middle', distance: 5 }, draggable: !1, roam: !1, center: null, zoom: 1, nodeScaleRatio: 0.6, label: { show: !1, formatter: '{b}' }, itemStyle: {}, lineStyle: { color: '#aaa', width: 1, opacity: 0.5 }, emphasis: { scale: !0, label: { show: !0 } }, select: { itemStyle: { borderColor: '#212121' } } }, GraphSeriesModel; }(SeriesModel), actionInfo = { type: 'graphRoam', event: 'graphRoam', update: 'none' }, PointerShape = function() { this.angle = 0, this.width = 10, this.r = 10, this.x = 0, this.y = 0; }, PointerPath = function(_super) { function PointerPath(opts) { var _this = _super.call(this, opts) || this; return _this.type = 'pointer', _this; } return __extends(PointerPath, _super), PointerPath.prototype.getDefaultShape = function() { return new PointerShape(); }, PointerPath.prototype.buildPath = function(ctx, shape) { var mathCos = Math.cos, mathSin = Math.sin, r = shape.r, width = shape.width, angle = shape.angle, x = shape.x - mathCos(angle) * width * (width >= r / 3 ? 1 : 2), y = shape.y - mathSin(angle) * width * (width >= r / 3 ? 1 : 2); angle = shape.angle - Math.PI / 2, ctx.moveTo(x, y), ctx.lineTo(shape.x + mathCos(angle) * width, shape.y + mathSin(angle) * width), ctx.lineTo(shape.x + mathCos(shape.angle) * r, shape.y + mathSin(shape.angle) * r), ctx.lineTo(shape.x - mathCos(angle) * width, shape.y - mathSin(angle) * width), ctx.lineTo(x, y); }, PointerPath; }(Path); function formatLabel(value, labelFormatter) { var label = null == value ? '' : value + ''; return labelFormatter && ('string' == typeof labelFormatter ? label = labelFormatter.replace('{value}', label) : 'function' == typeof labelFormatter && (label = labelFormatter(value))), label; } var PI2$9 = 2 * Math.PI, GaugeView = function(_super) { function GaugeView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = GaugeView.type, _this; } return __extends(GaugeView, _super), GaugeView.prototype.render = function(seriesModel, ecModel, api) { this.group.removeAll(); var center, width, height, colorList = seriesModel.get([ 'axisLine', 'lineStyle', 'color' ]), posInfo = (center = seriesModel.get('center'), width = api.getWidth(), height = api.getHeight(), { cx: parsePercent$1(center[0], api.getWidth()), cy: parsePercent$1(center[1], api.getHeight()), r: parsePercent$1(seriesModel.get('radius'), Math.min(width, height) / 2) }); this._renderMain(seriesModel, ecModel, api, colorList, posInfo), this._data = seriesModel.getData(); }, GaugeView.prototype.dispose = function() {}, GaugeView.prototype._renderMain = function(seriesModel, ecModel, api, colorList, posInfo) { for(var group = this.group, clockwise = seriesModel.get('clockwise'), startAngle = -seriesModel.get('startAngle') / 180 * Math.PI, endAngle = -seriesModel.get('endAngle') / 180 * Math.PI, axisLineModel = seriesModel.getModel('axisLine'), MainPath = axisLineModel.get('roundCap') ? SausagePath : Sector, showAxis = axisLineModel.get('show'), lineStyleModel = axisLineModel.getModel('lineStyle'), axisLineWidth = lineStyleModel.get('width'), angleRangeSpan = (endAngle - startAngle) % PI2$9 || endAngle === startAngle ? (endAngle - startAngle) % PI2$9 : PI2$9, prevEndAngle = startAngle, i = 0; showAxis && i < colorList.length; i++){ endAngle = startAngle + angleRangeSpan * Math.min(Math.max(colorList[i][0], 0), 1); var sector = new MainPath({ shape: { startAngle: prevEndAngle, endAngle: endAngle, cx: posInfo.cx, cy: posInfo.cy, clockwise: clockwise, r0: posInfo.r - axisLineWidth, r: posInfo.r }, silent: !0 }); sector.setStyle({ fill: colorList[i][1] }), sector.setStyle(lineStyleModel.getLineStyle([ 'color', 'width' ])), group.add(sector), prevEndAngle = endAngle; } var getColor = function(percent) { var i; if (percent <= 0) return colorList[0][1]; for(i = 0; i < colorList.length; i++)if (colorList[i][0] >= percent && (0 === i ? 0 : colorList[i - 1][0]) < percent) return colorList[i][1]; return colorList[i - 1][1]; }; if (!clockwise) { var tmp = startAngle; startAngle = endAngle, endAngle = tmp; } this._renderTicks(seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise, axisLineWidth), this._renderTitleAndDetail(seriesModel, ecModel, api, getColor, posInfo), this._renderAnchor(seriesModel, posInfo), this._renderPointer(seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise, axisLineWidth); }, GaugeView.prototype._renderTicks = function(seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise, axisLineWidth) { for(var unitX, unitY, group = this.group, cx = posInfo.cx, cy = posInfo.cy, r = posInfo.r, minVal = +seriesModel.get('min'), maxVal = +seriesModel.get('max'), splitLineModel = seriesModel.getModel('splitLine'), tickModel = seriesModel.getModel('axisTick'), labelModel = seriesModel.getModel('axisLabel'), splitNumber = seriesModel.get('splitNumber'), subSplitNumber = tickModel.get('splitNumber'), splitLineLen = parsePercent$1(splitLineModel.get('length'), r), tickLen = parsePercent$1(tickModel.get('length'), r), angle = startAngle, step = (endAngle - startAngle) / splitNumber, subStep = step / subSplitNumber, splitLineStyle = splitLineModel.getModel('lineStyle').getLineStyle(), tickLineStyle = tickModel.getModel('lineStyle').getLineStyle(), splitLineDistance = splitLineModel.get('distance'), i = 0; i <= splitNumber; i++){ if (unitX = Math.cos(angle), unitY = Math.sin(angle), splitLineModel.get('show')) { var distance = splitLineDistance ? splitLineDistance + axisLineWidth : axisLineWidth, splitLine = new Line({ shape: { x1: unitX * (r - distance) + cx, y1: unitY * (r - distance) + cy, x2: unitX * (r - splitLineLen - distance) + cx, y2: unitY * (r - splitLineLen - distance) + cy }, style: splitLineStyle, silent: !0 }); 'auto' === splitLineStyle.stroke && splitLine.setStyle({ stroke: getColor(i / splitNumber) }), group.add(splitLine); } if (labelModel.get('show')) { var distance = labelModel.get('distance') + splitLineDistance, label = formatLabel(round(i / splitNumber * (maxVal - minVal) + minVal), labelModel.get('formatter')), autoColor = getColor(i / splitNumber); group.add(new ZRText({ style: createTextStyle(labelModel, { text: label, x: unitX * (r - splitLineLen - distance) + cx, y: unitY * (r - splitLineLen - distance) + cy, verticalAlign: unitY < -0.8 ? 'top' : unitY > 0.8 ? 'bottom' : 'middle', align: unitX < -0.4 ? 'left' : unitX > 0.4 ? 'right' : 'center' }, { inheritColor: autoColor }), silent: !0 })); } if (tickModel.get('show') && i !== splitNumber) { var distance = tickModel.get('distance'); distance = distance ? distance + axisLineWidth : axisLineWidth; for(var j = 0; j <= subSplitNumber; j++){ unitX = Math.cos(angle), unitY = Math.sin(angle); var tickLine = new Line({ shape: { x1: unitX * (r - distance) + cx, y1: unitY * (r - distance) + cy, x2: unitX * (r - tickLen - distance) + cx, y2: unitY * (r - tickLen - distance) + cy }, silent: !0, style: tickLineStyle }); 'auto' === tickLineStyle.stroke && tickLine.setStyle({ stroke: getColor((i + j / subSplitNumber) / splitNumber) }), group.add(tickLine), angle += subStep; } angle -= subStep; } else angle += step; } }, GaugeView.prototype._renderPointer = function(seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise, axisLineWidth) { var group = this.group, oldData = this._data, oldProgressData = this._progressEls, progressList = [], showPointer = seriesModel.get([ 'pointer', 'show' ]), progressModel = seriesModel.getModel('progress'), showProgress = progressModel.get('show'), data = seriesModel.getData(), valueDim = data.mapDimension('value'), minVal = +seriesModel.get('min'), maxVal = +seriesModel.get('max'), valueExtent = [ minVal, maxVal ], angleExtent = [ startAngle, endAngle ]; function createPointer(idx, angle) { var pointer, pointerModel = data.getItemModel(idx).getModel('pointer'), pointerWidth = parsePercent$1(pointerModel.get('width'), posInfo.r), pointerLength = parsePercent$1(pointerModel.get('length'), posInfo.r), pointerStr = seriesModel.get([ 'pointer', 'icon' ]), pointerOffset = pointerModel.get('offsetCenter'), pointerOffsetX = parsePercent$1(pointerOffset[0], posInfo.r), pointerOffsetY = parsePercent$1(pointerOffset[1], posInfo.r), pointerKeepAspect = pointerModel.get('keepAspect'); return (pointer = pointerStr ? createSymbol(pointerStr, pointerOffsetX - pointerWidth / 2, pointerOffsetY - pointerLength, pointerWidth, pointerLength, null, pointerKeepAspect) : new PointerPath({ shape: { angle: -Math.PI / 2, width: pointerWidth, r: pointerLength, x: pointerOffsetX, y: pointerOffsetY } })).rotation = -(angle + Math.PI / 2), pointer.x = posInfo.cx, pointer.y = posInfo.cy, pointer; } function createProgress(idx, endAngle) { var ProgressPath = progressModel.get('roundCap') ? SausagePath : Sector, isOverlap = progressModel.get('overlap'), progressWidth = isOverlap ? progressModel.get('width') : axisLineWidth / data.count(), r0 = isOverlap ? posInfo.r - progressWidth : posInfo.r - (idx + 1) * progressWidth, r = isOverlap ? posInfo.r : posInfo.r - idx * progressWidth, progress = new ProgressPath({ shape: { startAngle: startAngle, endAngle: endAngle, cx: posInfo.cx, cy: posInfo.cy, clockwise: clockwise, r0: r0, r: r } }); return isOverlap && (progress.z2 = maxVal - data.get(valueDim, idx) % maxVal), progress; } (showProgress || showPointer) && (data.diff(oldData).add(function(idx) { if (showPointer) { var pointer = createPointer(idx, startAngle); initProps(pointer, { rotation: -(linearMap(data.get(valueDim, idx), valueExtent, angleExtent, !0) + Math.PI / 2) }, seriesModel), group.add(pointer), data.setItemGraphicEl(idx, pointer); } if (showProgress) { var progress = createProgress(idx, startAngle), isClip = progressModel.get('clip'); initProps(progress, { shape: { endAngle: linearMap(data.get(valueDim, idx), valueExtent, angleExtent, isClip) } }, seriesModel), group.add(progress), progressList[idx] = progress; } }).update(function(newIdx, oldIdx) { if (showPointer) { var previousPointer = oldData.getItemGraphicEl(oldIdx), previousRotate = previousPointer ? previousPointer.rotation : startAngle, pointer = createPointer(newIdx, previousRotate); pointer.rotation = previousRotate, updateProps(pointer, { rotation: -(linearMap(data.get(valueDim, newIdx), valueExtent, angleExtent, !0) + Math.PI / 2) }, seriesModel), group.add(pointer), data.setItemGraphicEl(newIdx, pointer); } if (showProgress) { var previousProgress = oldProgressData[oldIdx], progress = createProgress(newIdx, previousProgress ? previousProgress.shape.endAngle : startAngle), isClip = progressModel.get('clip'); updateProps(progress, { shape: { endAngle: linearMap(data.get(valueDim, newIdx), valueExtent, angleExtent, isClip) } }, seriesModel), group.add(progress), progressList[newIdx] = progress; } }).execute(), data.each(function(idx) { var itemModel = data.getItemModel(idx), emphasisModel = itemModel.getModel('emphasis'); if (showPointer) { var pointer = data.getItemGraphicEl(idx), symbolStyle = data.getItemVisual(idx, 'style'), visualColor = symbolStyle.fill; if (pointer instanceof ZRImage) { var pathStyle = pointer.style; pointer.useStyle(extend({ image: pathStyle.image, x: pathStyle.x, y: pathStyle.y, width: pathStyle.width, height: pathStyle.height }, symbolStyle)); } else pointer.useStyle(symbolStyle), 'pointer' !== pointer.type && pointer.setColor(visualColor); pointer.setStyle(itemModel.getModel([ 'pointer', 'itemStyle' ]).getItemStyle()), 'auto' === pointer.style.fill && pointer.setStyle('fill', getColor(linearMap(data.get(valueDim, idx), valueExtent, [ 0, 1 ], !0))), pointer.z2EmphasisLift = 0, setStatesStylesFromModel(pointer, itemModel), enableHoverEmphasis(pointer, emphasisModel.get('focus'), emphasisModel.get('blurScope')); } if (showProgress) { var progress = progressList[idx]; progress.useStyle(data.getItemVisual(idx, 'style')), progress.setStyle(itemModel.getModel([ 'progress', 'itemStyle' ]).getItemStyle()), progress.z2EmphasisLift = 0, setStatesStylesFromModel(progress, itemModel), enableHoverEmphasis(progress, emphasisModel.get('focus'), emphasisModel.get('blurScope')); } }), this._progressEls = progressList); }, GaugeView.prototype._renderAnchor = function(seriesModel, posInfo) { var anchorModel = seriesModel.getModel('anchor'); if (anchorModel.get('show')) { var anchorSize = anchorModel.get('size'), anchorType = anchorModel.get('icon'), offsetCenter = anchorModel.get('offsetCenter'), anchorKeepAspect = anchorModel.get('keepAspect'), anchor = createSymbol(anchorType, posInfo.cx - anchorSize / 2 + parsePercent$1(offsetCenter[0], posInfo.r), posInfo.cy - anchorSize / 2 + parsePercent$1(offsetCenter[1], posInfo.r), anchorSize, anchorSize, null, anchorKeepAspect); anchor.z2 = anchorModel.get('showAbove') ? 1 : 0, anchor.setStyle(anchorModel.getModel('itemStyle').getItemStyle()), this.group.add(anchor); } }, GaugeView.prototype._renderTitleAndDetail = function(seriesModel, ecModel, api, getColor, posInfo) { var _this = this, data = seriesModel.getData(), valueDim = data.mapDimension('value'), minVal = +seriesModel.get('min'), maxVal = +seriesModel.get('max'), contentGroup = new Group(), newTitleEls = [], newDetailEls = [], hasAnimation = seriesModel.isAnimationEnabled(); data.diff(this._data).add(function(idx) { newTitleEls[idx] = new ZRText({ silent: !0 }), newDetailEls[idx] = new ZRText({ silent: !0 }); }).update(function(idx, oldIdx) { newTitleEls[idx] = _this._titleEls[oldIdx], newDetailEls[idx] = _this._detailEls[oldIdx]; }).execute(), data.each(function(idx) { var itemModel = data.getItemModel(idx), value = data.get(valueDim, idx), itemGroup = new Group(), autoColor = getColor(linearMap(value, [ minVal, maxVal ], [ 0, 1 ], !0)), itemTitleModel = itemModel.getModel('title'); if (itemTitleModel.get('show')) { var titleOffsetCenter = itemTitleModel.get('offsetCenter'), titleX = posInfo.cx + parsePercent$1(titleOffsetCenter[0], posInfo.r), titleY = posInfo.cy + parsePercent$1(titleOffsetCenter[1], posInfo.r), labelEl = newTitleEls[idx]; labelEl.attr({ style: createTextStyle(itemTitleModel, { x: titleX, y: titleY, text: data.getName(idx), align: 'center', verticalAlign: 'middle' }, { inheritColor: autoColor }) }), itemGroup.add(labelEl); } var itemDetailModel = itemModel.getModel('detail'); if (itemDetailModel.get('show')) { var detailOffsetCenter = itemDetailModel.get('offsetCenter'), detailX = posInfo.cx + parsePercent$1(detailOffsetCenter[0], posInfo.r), detailY = posInfo.cy + parsePercent$1(detailOffsetCenter[1], posInfo.r), width = parsePercent$1(itemDetailModel.get('width'), posInfo.r), height = parsePercent$1(itemDetailModel.get('height'), posInfo.r), detailColor = seriesModel.get([ 'progress', 'show' ]) ? data.getItemVisual(idx, 'style').fill : autoColor, labelEl = newDetailEls[idx], formatter_1 = itemDetailModel.get('formatter'); labelEl.attr({ style: createTextStyle(itemDetailModel, { x: detailX, y: detailY, text: formatLabel(value, formatter_1), width: isNaN(width) ? null : width, height: isNaN(height) ? null : height, align: 'center', verticalAlign: 'middle' }, { inheritColor: detailColor }) }), setLabelValueAnimation(labelEl, { normal: itemDetailModel }, value, function(value) { return formatLabel(value, formatter_1); }), hasAnimation && animateLabelValue(labelEl, idx, data, seriesModel, { getFormattedLabel: function(labelDataIndex, status, dataType, labelDimIndex, fmt, extendParams) { return formatLabel(extendParams ? extendParams.interpolatedValue : value, formatter_1); } }), itemGroup.add(labelEl); } contentGroup.add(itemGroup); }), this.group.add(contentGroup), this._titleEls = newTitleEls, this._detailEls = newDetailEls; }, GaugeView.type = 'gauge', GaugeView; }(ChartView), GaugeSeriesModel = function(_super) { function GaugeSeriesModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = GaugeSeriesModel.type, _this.visualStyleAccessPath = 'itemStyle', _this.useColorPaletteOnData = !0, _this; } return __extends(GaugeSeriesModel, _super), GaugeSeriesModel.prototype.getInitialData = function(option, ecModel) { return createListSimply(this, [ 'value' ]); }, GaugeSeriesModel.type = 'series.gauge', GaugeSeriesModel.defaultOption = { zlevel: 0, z: 2, center: [ '50%', '50%' ], legendHoverLink: !0, radius: '75%', startAngle: 225, endAngle: -45, clockwise: !0, min: 0, max: 100, splitNumber: 10, axisLine: { show: !0, roundCap: !1, lineStyle: { color: [ [ 1, '#E6EBF8' ] ], width: 10 } }, progress: { show: !1, overlap: !0, width: 10, roundCap: !1, clip: !0 }, splitLine: { show: !0, length: 10, distance: 10, lineStyle: { color: '#63677A', width: 3, type: 'solid' } }, axisTick: { show: !0, splitNumber: 5, length: 6, distance: 10, lineStyle: { color: '#63677A', width: 1, type: 'solid' } }, axisLabel: { show: !0, distance: 15, color: '#464646', fontSize: 12 }, pointer: { icon: null, offsetCenter: [ 0, 0 ], show: !0, length: '60%', width: 6, keepAspect: !1 }, anchor: { show: !1, showAbove: !1, size: 6, icon: 'circle', offsetCenter: [ 0, 0 ], keepAspect: !1, itemStyle: { color: '#fff', borderWidth: 0, borderColor: '#5470c6' } }, title: { show: !0, offsetCenter: [ 0, '20%' ], color: '#464646', fontSize: 16, valueAnimation: !1 }, detail: { show: !0, backgroundColor: 'rgba(0,0,0,0)', borderWidth: 0, borderColor: '#ccc', width: 100, height: null, padding: [ 5, 10 ], offsetCenter: [ 0, '40%' ], color: '#464646', fontSize: 30, fontWeight: 'bold', lineHeight: 30, valueAnimation: !1 } }, GaugeSeriesModel; }(SeriesModel), opacityAccessPath = [ 'itemStyle', 'opacity' ], FunnelPiece = function(_super) { function FunnelPiece(data, idx) { var _this = _super.call(this) || this, labelLine = new Polyline(), text = new ZRText(); return _this.setTextContent(text), _this.setTextGuideLine(labelLine), _this.updateData(data, idx, !0), _this; } return __extends(FunnelPiece, _super), FunnelPiece.prototype.updateData = function(data, idx, firstCreate) { var polygon = this, seriesModel = data.hostModel, itemModel = data.getItemModel(idx), layout = data.getItemLayout(idx), emphasisModel = itemModel.getModel('emphasis'), opacity = itemModel.get(opacityAccessPath); opacity = null == opacity ? 1 : opacity, polygon.useStyle(data.getItemVisual(idx, 'style')), polygon.style.lineJoin = 'round', firstCreate ? (polygon.setShape({ points: layout.points }), polygon.style.opacity = 0, initProps(polygon, { style: { opacity: opacity } }, seriesModel, idx)) : updateProps(polygon, { style: { opacity: opacity }, shape: { points: layout.points } }, seriesModel, idx), setStatesStylesFromModel(polygon, itemModel), this._updateLabel(data, idx), enableHoverEmphasis(this, emphasisModel.get('focus'), emphasisModel.get('blurScope')); }, FunnelPiece.prototype._updateLabel = function(data, idx) { var polygon = this, labelLine = this.getTextGuideLine(), labelText = polygon.getTextContent(), seriesModel = data.hostModel, itemModel = data.getItemModel(idx), labelLayout = data.getItemLayout(idx).label, style = data.getItemVisual(idx, 'style'), visualColor = style.fill; setLabelStyle(labelText, getLabelStatesModels(itemModel), { labelFetcher: data.hostModel, labelDataIndex: idx, defaultOpacity: style.opacity, defaultText: data.getName(idx) }, { normal: { align: labelLayout.textAlign, verticalAlign: labelLayout.verticalAlign } }), polygon.setTextConfig({ local: !0, inside: !!labelLayout.inside, insideStroke: visualColor, outsideFill: visualColor }); var linePoints = labelLayout.linePoints; labelLine.setShape({ points: linePoints }), polygon.textGuideLineConfig = { anchor: linePoints ? new Point(linePoints[0][0], linePoints[0][1]) : null }, updateProps(labelText, { style: { x: labelLayout.x, y: labelLayout.y } }, seriesModel, idx), labelText.attr({ rotation: labelLayout.rotation, originX: labelLayout.x, originY: labelLayout.y, z2: 10 }), setLabelLineStyle(polygon, getLabelLineStatesModels(itemModel), { stroke: visualColor }); }, FunnelPiece; }(Polygon), FunnelView = function(_super) { function FunnelView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = FunnelView.type, _this.ignoreLabelLineUpdate = !0, _this; } return __extends(FunnelView, _super), FunnelView.prototype.render = function(seriesModel, ecModel, api) { var data = seriesModel.getData(), oldData = this._data, group = this.group; data.diff(oldData).add(function(idx) { var funnelPiece = new FunnelPiece(data, idx); data.setItemGraphicEl(idx, funnelPiece), group.add(funnelPiece); }).update(function(newIdx, oldIdx) { var piece = oldData.getItemGraphicEl(oldIdx); piece.updateData(data, newIdx), group.add(piece), data.setItemGraphicEl(newIdx, piece); }).remove(function(idx) { removeElementWithFadeOut(oldData.getItemGraphicEl(idx), seriesModel, idx); }).execute(), this._data = data; }, FunnelView.prototype.remove = function() { this.group.removeAll(), this._data = null; }, FunnelView.prototype.dispose = function() {}, FunnelView.type = 'funnel', FunnelView; }(ChartView), FunnelSeriesModel = function(_super) { function FunnelSeriesModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = FunnelSeriesModel.type, _this.useColorPaletteOnData = !0, _this; } return __extends(FunnelSeriesModel, _super), FunnelSeriesModel.prototype.init = function(option) { _super.prototype.init.apply(this, arguments), this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this)), this._defaultLabelLine(option); }, FunnelSeriesModel.prototype.getInitialData = function(option, ecModel) { return createListSimply(this, { coordDimensions: [ 'value' ], encodeDefaulter: curry(makeSeriesEncodeForNameBased, this) }); }, FunnelSeriesModel.prototype._defaultLabelLine = function(option) { defaultEmphasis(option, 'labelLine', [ 'show' ]); var labelLineNormalOpt = option.labelLine, labelLineEmphasisOpt = option.emphasis.labelLine; labelLineNormalOpt.show = labelLineNormalOpt.show && option.label.show, labelLineEmphasisOpt.show = labelLineEmphasisOpt.show && option.emphasis.label.show; }, FunnelSeriesModel.prototype.getDataParams = function(dataIndex) { var data = this.getData(), params = _super.prototype.getDataParams.call(this, dataIndex), valueDim = data.mapDimension('value'), sum = data.getSum(valueDim); return params.percent = sum ? +(data.get(valueDim, dataIndex) / sum * 100).toFixed(2) : 0, params.$vars.push('percent'), params; }, FunnelSeriesModel.type = 'series.funnel', FunnelSeriesModel.defaultOption = { zlevel: 0, z: 2, legendHoverLink: !0, left: 80, top: 60, right: 80, bottom: 60, minSize: '0%', maxSize: '100%', sort: 'descending', orient: 'vertical', gap: 0, funnelAlign: 'center', label: { show: !0, position: 'outer' }, labelLine: { show: !0, length: 20, lineStyle: { width: 1 } }, itemStyle: { borderColor: '#fff', borderWidth: 1 }, emphasis: { label: { show: !0 } }, select: { itemStyle: { borderColor: '#212121' } } }, FunnelSeriesModel; }(SeriesModel); function funnelLayout(ecModel, api) { ecModel.eachSeriesByType('funnel', function(seriesModel) { var data = seriesModel.getData(), valueDim = data.mapDimension('value'), sort = seriesModel.get('sort'), viewRect = getLayoutRect(seriesModel.getBoxLayoutParams(), { width: api.getWidth(), height: api.getHeight() }), orient = seriesModel.get('orient'), viewWidth = viewRect.width, viewHeight = viewRect.height, indices = function(data, sort) { for(var valueDim = data.mapDimension('value'), valueArr = data.mapArray(valueDim, function(val) { return val; }), indices = [], isAscending = 'ascending' === sort, i = 0, len = data.count(); i < len; i++)indices[i] = i; return 'function' == typeof sort ? indices.sort(sort) : 'none' !== sort && indices.sort(function(a, b) { return isAscending ? valueArr[a] - valueArr[b] : valueArr[b] - valueArr[a]; }), indices; }(data, sort), x = viewRect.x, y = viewRect.y, sizeExtent = 'horizontal' === orient ? [ parsePercent$1(seriesModel.get('minSize'), viewHeight), parsePercent$1(seriesModel.get('maxSize'), viewHeight) ] : [ parsePercent$1(seriesModel.get('minSize'), viewWidth), parsePercent$1(seriesModel.get('maxSize'), viewWidth) ], dataExtent = data.getDataExtent(valueDim), min = seriesModel.get('min'), max = seriesModel.get('max'); null == min && (min = Math.min(dataExtent[0], 0)), null == max && (max = dataExtent[1]); var funnelAlign = seriesModel.get('funnelAlign'), gap = seriesModel.get('gap'), itemSize = (('horizontal' === orient ? viewWidth : viewHeight) - gap * (data.count() - 1)) / data.count(), getLinePoints = function(idx, offset) { if ('horizontal' === orient) { var x0, itemHeight = linearMap(data.get(valueDim, idx) || 0, [ min, max ], sizeExtent, !0), y0 = void 0; switch(funnelAlign){ case 'top': y0 = y; break; case 'center': y0 = y + (viewHeight - itemHeight) / 2; break; case 'bottom': y0 = y + (viewHeight - itemHeight); } return [ [ offset, y0 ], [ offset, y0 + itemHeight ] ]; } var itemWidth = linearMap(data.get(valueDim, idx) || 0, [ min, max ], sizeExtent, !0); switch(funnelAlign){ case 'left': x0 = x; break; case 'center': x0 = x + (viewWidth - itemWidth) / 2; break; case 'right': x0 = x + viewWidth - itemWidth; } return [ [ x0, offset ], [ x0 + itemWidth, offset ] ]; }; 'ascending' === sort && (itemSize = -itemSize, gap = -gap, 'horizontal' === orient ? x += viewWidth : y += viewHeight, indices = indices.reverse()); for(var i = 0; i < indices.length; i++){ var idx = indices[i], nextIdx = indices[i + 1], itemModel = data.getItemModel(idx); if ('horizontal' === orient) { var width = itemModel.get([ 'itemStyle', 'width' ]); null == width ? width = itemSize : (width = parsePercent$1(width, viewWidth), 'ascending' === sort && (width = -width)); var start = getLinePoints(idx, x), end = getLinePoints(nextIdx, x + width); x += width + gap, data.setItemLayout(idx, { points: start.concat(end.slice().reverse()) }); } else { var height = itemModel.get([ 'itemStyle', 'height' ]); null == height ? height = itemSize : (height = parsePercent$1(height, viewHeight), 'ascending' === sort && (height = -height)); var start = getLinePoints(idx, y), end = getLinePoints(nextIdx, y + height); y += height + gap, data.setItemLayout(idx, { points: start.concat(end.slice().reverse()) }); } } !function(data) { var orient = data.hostModel.get('orient'); data.each(function(idx) { var textAlign, textX, textY, linePoints, itemModel = data.getItemModel(idx), labelPosition = itemModel.getModel('label').get('position'), labelLineModel = itemModel.getModel('labelLine'), layout = data.getItemLayout(idx), points = layout.points, isLabelInside = 'inner' === labelPosition || 'inside' === labelPosition || 'center' === labelPosition || 'insideLeft' === labelPosition || 'insideRight' === labelPosition; if (isLabelInside) 'insideLeft' === labelPosition ? (textX = (points[0][0] + points[3][0]) / 2 + 5, textY = (points[0][1] + points[3][1]) / 2, textAlign = 'left') : 'insideRight' === labelPosition ? (textX = (points[1][0] + points[2][0]) / 2 - 5, textY = (points[1][1] + points[2][1]) / 2, textAlign = 'right') : (textX = (points[0][0] + points[1][0] + points[2][0] + points[3][0]) / 4, textY = (points[0][1] + points[1][1] + points[2][1] + points[3][1]) / 4, textAlign = 'center'), linePoints = [ [ textX, textY ], [ textX, textY ] ]; else { var x1 = void 0, y1 = void 0, x2 = void 0, y2 = void 0, labelLineLen = labelLineModel.get('length'); 'vertical' === orient && [ 'top', 'bottom' ].indexOf(labelPosition) > -1 && (labelPosition = 'left', console.warn('Position error: Funnel chart on vertical orient dose not support top and bottom.')), 'horizontal' === orient && [ 'left', 'right' ].indexOf(labelPosition) > -1 && (labelPosition = 'bottom', console.warn('Position error: Funnel chart on horizontal orient dose not support left and right.')), 'left' === labelPosition ? (x1 = (points[3][0] + points[0][0]) / 2, y1 = (points[3][1] + points[0][1]) / 2, textX = (x2 = x1 - labelLineLen) - 5, textAlign = 'right') : 'right' === labelPosition ? (x1 = (points[1][0] + points[2][0]) / 2, y1 = (points[1][1] + points[2][1]) / 2, textX = (x2 = x1 + labelLineLen) + 5, textAlign = 'left') : 'top' === labelPosition ? (x1 = (points[3][0] + points[0][0]) / 2, textY = (y2 = (y1 = (points[3][1] + points[0][1]) / 2) - labelLineLen) - 5, textAlign = 'center') : 'bottom' === labelPosition ? (x1 = (points[1][0] + points[2][0]) / 2, textY = (y2 = (y1 = (points[1][1] + points[2][1]) / 2) + labelLineLen) + 5, textAlign = 'center') : 'rightTop' === labelPosition ? (x1 = 'horizontal' === orient ? points[3][0] : points[1][0], y1 = 'horizontal' === orient ? points[3][1] : points[1][1], 'horizontal' === orient ? (textY = (y2 = y1 - labelLineLen) - 5, textAlign = 'center') : (textX = (x2 = x1 + labelLineLen) + 5, textAlign = 'top')) : 'rightBottom' === labelPosition ? (x1 = points[2][0], y1 = points[2][1], 'horizontal' === orient ? (textY = (y2 = y1 + labelLineLen) + 5, textAlign = 'center') : (textX = (x2 = x1 + labelLineLen) + 5, textAlign = 'bottom')) : 'leftTop' === labelPosition ? (x1 = points[0][0], y1 = 'horizontal' === orient ? points[0][1] : points[1][1], 'horizontal' === orient ? (textY = (y2 = y1 - labelLineLen) - 5, textAlign = 'center') : (textX = (x2 = x1 - labelLineLen) - 5, textAlign = 'right')) : 'leftBottom' === labelPosition ? (x1 = 'horizontal' === orient ? points[1][0] : points[3][0], y1 = 'horizontal' === orient ? points[1][1] : points[2][1], 'horizontal' === orient ? (textY = (y2 = y1 + labelLineLen) + 5, textAlign = 'center') : (textX = (x2 = x1 - labelLineLen) - 5, textAlign = 'right')) : (x1 = (points[1][0] + points[2][0]) / 2, y1 = (points[1][1] + points[2][1]) / 2, 'horizontal' === orient ? (textY = (y2 = y1 + labelLineLen) + 5, textAlign = 'center') : (textX = (x2 = x1 + labelLineLen) + 5, textAlign = 'left')), 'horizontal' === orient ? textX = x2 = x1 : textY = y2 = y1, linePoints = [ [ x1, y1 ], [ x2, y2 ] ]; } layout.label = { linePoints: linePoints, x: textX, y: textY, verticalAlign: 'middle', textAlign: textAlign, inside: isLabelInside }; }); }(data); }); } var ParallelView = function(_super) { function ParallelView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = ParallelView.type, _this._dataGroup = new Group(), _this._initialized = !1, _this; } return __extends(ParallelView, _super), ParallelView.prototype.init = function() { this.group.add(this._dataGroup); }, ParallelView.prototype.render = function(seriesModel, ecModel, api, payload) { var dataGroup = this._dataGroup, data = seriesModel.getData(), oldData = this._data, coordSys = seriesModel.coordinateSystem, dimensions = coordSys.dimensions, seriesScope = makeSeriesScope$2(seriesModel); if (data.diff(oldData).add(function(newDataIndex) { updateElCommon(addEl(data, dataGroup, newDataIndex, dimensions, coordSys), data, newDataIndex, seriesScope); }).update(function(newDataIndex, oldDataIndex) { var line = oldData.getItemGraphicEl(oldDataIndex), points = createLinePoints(data, newDataIndex, dimensions, coordSys); data.setItemGraphicEl(newDataIndex, line), updateProps(line, { shape: { points: points } }, seriesModel, newDataIndex), updateElCommon(line, data, newDataIndex, seriesScope); }).remove(function(oldDataIndex) { var line = oldData.getItemGraphicEl(oldDataIndex); dataGroup.remove(line); }).execute(), !this._initialized) { this._initialized = !0; var cb, parallelModel, rect, rectEl, dim, clipPath = (cb = function() { setTimeout(function() { dataGroup.removeClipPath(); }); }, parallelModel = coordSys.model, rect = coordSys.getRect(), rectEl = new Rect({ shape: { x: rect.x, y: rect.y, width: rect.width, height: rect.height } }), dim = 'horizontal' === parallelModel.get('layout') ? 'width' : 'height', rectEl.setShape(dim, 0), initProps(rectEl, { shape: { width: rect.width, height: rect.height } }, seriesModel, cb), rectEl); dataGroup.setClipPath(clipPath); } this._data = data; }, ParallelView.prototype.incrementalPrepareRender = function(seriesModel, ecModel, api) { this._initialized = !0, this._data = null, this._dataGroup.removeAll(); }, ParallelView.prototype.incrementalRender = function(taskParams, seriesModel, ecModel) { for(var data = seriesModel.getData(), coordSys = seriesModel.coordinateSystem, dimensions = coordSys.dimensions, seriesScope = makeSeriesScope$2(seriesModel), dataIndex = taskParams.start; dataIndex < taskParams.end; dataIndex++){ var line = addEl(data, this._dataGroup, dataIndex, dimensions, coordSys); line.incremental = !0, updateElCommon(line, data, dataIndex, seriesScope); } }, ParallelView.prototype.remove = function() { this._dataGroup && this._dataGroup.removeAll(), this._data = null; }, ParallelView.type = 'parallel', ParallelView; }(ChartView); function createLinePoints(data, dataIndex, dimensions, coordSys) { for(var points = [], i = 0; i < dimensions.length; i++){ var dimName = dimensions[i], value = data.get(data.mapDimension(dimName), dataIndex); ('category' === coordSys.getAxis(dimName).type ? null == value : null == value || isNaN(value)) || points.push(coordSys.dataToPoint(value, dimName)); } return points; } function addEl(data, dataGroup, dataIndex, dimensions, coordSys) { var points = createLinePoints(data, dataIndex, dimensions, coordSys), line = new Polyline({ shape: { points: points }, z2: 10 }); return dataGroup.add(line), data.setItemGraphicEl(dataIndex, line), line; } function makeSeriesScope$2(seriesModel) { var value, smooth = seriesModel.get('smooth', !0); return !0 === smooth && (smooth = 0.3), (value = smooth = numericToNumber(smooth)) != value && (smooth = 0), { smooth: smooth }; } function updateElCommon(el, data, dataIndex, seriesScope) { el.useStyle(data.getItemVisual(dataIndex, 'style')), el.style.fill = null, el.setShape('smooth', seriesScope.smooth); var itemModel = data.getItemModel(dataIndex), emphasisModel = itemModel.getModel('emphasis'); setStatesStylesFromModel(el, itemModel, 'lineStyle'), enableHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope')); } var ParallelSeriesModel = function(_super) { function ParallelSeriesModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = ParallelSeriesModel.type, _this.visualStyleAccessPath = 'lineStyle', _this.visualDrawType = 'stroke', _this; } return __extends(ParallelSeriesModel, _super), ParallelSeriesModel.prototype.getInitialData = function(option, ecModel) { return createListFromArray(this.getSource(), this, { useEncodeDefaulter: bind(makeDefaultEncode, null, this) }); }, ParallelSeriesModel.prototype.getRawIndicesByActiveState = function(activeState) { var coordSys = this.coordinateSystem, data = this.getData(), indices = []; return coordSys.eachActiveState(data, function(theActiveState, dataIndex) { activeState === theActiveState && indices.push(data.getRawIndex(dataIndex)); }), indices; }, ParallelSeriesModel.type = 'series.parallel', ParallelSeriesModel.dependencies = [ 'parallel' ], ParallelSeriesModel.defaultOption = { zlevel: 0, z: 2, coordinateSystem: 'parallel', parallelIndex: 0, label: { show: !1 }, inactiveOpacity: 0.05, activeOpacity: 1, lineStyle: { width: 1, opacity: 0.45, type: 'solid' }, emphasis: { label: { show: !1 } }, progressive: 500, smooth: !1, animationEasing: 'linear' }, ParallelSeriesModel; }(SeriesModel); function makeDefaultEncode(seriesModel) { var parallelModel = seriesModel.ecModel.getComponent('parallel', seriesModel.get('parallelIndex')); if (parallelModel) { var encodeDefine = {}; return each(parallelModel.dimensions, function(axisDim) { var dataDimIndex = +axisDim.replace('dim', ''); encodeDefine[axisDim] = dataDimIndex; }), encodeDefine; } } var opacityAccessPath$1 = [ 'lineStyle', 'opacity' ], parallelVisual = { seriesType: 'parallel', reset: function(seriesModel, ecModel) { var coordSys = seriesModel.coordinateSystem, opacityMap = { normal: seriesModel.get([ 'lineStyle', 'opacity' ]), active: seriesModel.get('activeOpacity'), inactive: seriesModel.get('inactiveOpacity') }; return { progress: function(params, data) { coordSys.eachActiveState(data, function(activeState, dataIndex) { var opacity = opacityMap[activeState]; if ('normal' === activeState && data.hasItemOption) { var itemOpacity = data.getItemModel(dataIndex).get(opacityAccessPath$1, !0); null != itemOpacity && (opacity = itemOpacity); } data.ensureUniqueItemVisual(dataIndex, 'style').opacity = opacity; }, params.start, params.end); } }; } }; function parallelPreprocessor(option) { (function(option) { if (!option.parallel) { var hasParallelSeries = !1; each(option.series, function(seriesOpt) { seriesOpt && 'parallel' === seriesOpt.type && (hasParallelSeries = !0); }), hasParallelSeries && (option.parallel = [ {} ]); } })(option), each(normalizeToArray(option.parallelAxis), function(axisOption) { if (isObject(axisOption)) { var parallelIndex = axisOption.parallelIndex || 0, parallelOption = normalizeToArray(option.parallel)[parallelIndex]; parallelOption && parallelOption.parallelAxisDefault && merge(axisOption, parallelOption.parallelAxisDefault, !1); } }); } var ParallelView$1 = function(_super) { function ParallelView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = ParallelView.type, _this; } return __extends(ParallelView, _super), ParallelView.prototype.render = function(parallelModel, ecModel, api) { this._model = parallelModel, this._api = api, this._handlers || (this._handlers = {}, each(handlers, function(handler, eventName) { api.getZr().on(eventName, this._handlers[eventName] = bind(handler, this)); }, this)), createOrUpdate(this, '_throttledDispatchExpand', parallelModel.get('axisExpandRate'), 'fixRate'); }, ParallelView.prototype.dispose = function(ecModel, api) { each(this._handlers, function(handler, eventName) { api.getZr().off(eventName, handler); }), this._handlers = null; }, ParallelView.prototype._throttledDispatchExpand = function(opt) { this._dispatchExpand(opt); }, ParallelView.prototype._dispatchExpand = function(opt) { opt && this._api.dispatchAction(extend({ type: 'parallelAxisExpand' }, opt)); }, ParallelView.type = 'parallel', ParallelView; }(ComponentView), handlers = { mousedown: function(e) { checkTrigger(this, 'click') && (this._mouseDownPoint = [ e.offsetX, e.offsetY ]); }, mouseup: function(e) { var mouseDownPoint = this._mouseDownPoint; if (checkTrigger(this, 'click') && mouseDownPoint) { var point = [ e.offsetX, e.offsetY ]; if (Math.pow(mouseDownPoint[0] - point[0], 2) + Math.pow(mouseDownPoint[1] - point[1], 2) > 5) return; var result = this._model.coordinateSystem.getSlidedAxisExpandWindow([ e.offsetX, e.offsetY ]); 'none' !== result.behavior && this._dispatchExpand({ axisExpandWindow: result.axisExpandWindow }); } this._mouseDownPoint = null; }, mousemove: function(e) { if (!this._mouseDownPoint && checkTrigger(this, 'mousemove')) { var model = this._model, result = model.coordinateSystem.getSlidedAxisExpandWindow([ e.offsetX, e.offsetY ]), behavior = result.behavior; 'jump' === behavior && this._throttledDispatchExpand.debounceNextCall(model.get('axisExpandDebounce')), this._throttledDispatchExpand('none' === behavior ? null : { axisExpandWindow: result.axisExpandWindow, animation: 'jump' === behavior ? null : { duration: 0 } }); } } }; function checkTrigger(view, triggerOn) { var model = view._model; return model.get('axisExpandable') && model.get('axisExpandTriggerOn') === triggerOn; } var ParallelModel = function(_super) { function ParallelModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = ParallelModel.type, _this; } return __extends(ParallelModel, _super), ParallelModel.prototype.init = function() { _super.prototype.init.apply(this, arguments), this.mergeOption({}); }, ParallelModel.prototype.mergeOption = function(newOption) { var thisOption = this.option; newOption && merge(thisOption, newOption, !0), this._initDimensions(); }, ParallelModel.prototype.contains = function(model, ecModel) { var parallelIndex = model.get('parallelIndex'); return null != parallelIndex && ecModel.getComponent('parallel', parallelIndex) === this; }, ParallelModel.prototype.setAxisExpand = function(opt) { each([ 'axisExpandable', 'axisExpandCenter', 'axisExpandCount', 'axisExpandWidth', 'axisExpandWindow' ], function(name) { opt.hasOwnProperty(name) && (this.option[name] = opt[name]); }, this); }, ParallelModel.prototype._initDimensions = function() { var dimensions = this.dimensions = [], parallelAxisIndex = this.parallelAxisIndex = []; each(filter(this.ecModel.queryComponents({ mainType: 'parallelAxis' }), function(axisModel) { return (axisModel.get('parallelIndex') || 0) === this.componentIndex; }, this), function(axisModel) { dimensions.push('dim' + axisModel.get('dim')), parallelAxisIndex.push(axisModel.componentIndex); }); }, ParallelModel.type = 'parallel', ParallelModel.dependencies = [ 'parallelAxis' ], ParallelModel.layoutMode = 'box', ParallelModel.defaultOption = { zlevel: 0, z: 0, left: 80, top: 60, right: 80, bottom: 60, layout: 'horizontal', axisExpandable: !1, axisExpandCenter: null, axisExpandCount: 0, axisExpandWidth: 50, axisExpandRate: 17, axisExpandDebounce: 50, axisExpandSlideTriggerArea: [ -0.15, 0.05, 0.4 ], axisExpandTriggerOn: 'click', parallelAxisDefault: null }, ParallelModel; }(ComponentModel), ParallelAxis = function(_super) { function ParallelAxis(dim, scale, coordExtent, axisType, axisIndex) { var _this = _super.call(this, dim, scale, coordExtent) || this; return _this.type = axisType || 'value', _this.axisIndex = axisIndex, _this; } return __extends(ParallelAxis, _super), ParallelAxis.prototype.isHorizontal = function() { return 'horizontal' !== this.coordinateSystem.getModel().get('layout'); }, ParallelAxis; }(Axis); function sliderMove(delta, handleEnds, extent, handleIndex, minSpan, maxSpan) { delta = delta || 0; var currDistSign, extentSpan = extent[1] - extent[0]; if (null != minSpan && (minSpan = restrict(minSpan, [ 0, extentSpan ])), null != maxSpan && (maxSpan = Math.max(maxSpan, null != minSpan ? minSpan : 0)), 'all' === handleIndex) { var handleSpan = Math.abs(handleEnds[1] - handleEnds[0]); handleSpan = restrict(handleSpan, [ 0, extentSpan ]), minSpan = maxSpan = restrict(handleSpan, [ minSpan, maxSpan ]), handleIndex = 0; } handleEnds[0] = restrict(handleEnds[0], extent), handleEnds[1] = restrict(handleEnds[1], extent); var originalDistSign = getSpanSign(handleEnds, handleIndex); handleEnds[handleIndex] += delta; var extentMinSpan = minSpan || 0, realExtent = extent.slice(); return originalDistSign.sign < 0 ? realExtent[0] += extentMinSpan : realExtent[1] -= extentMinSpan, handleEnds[handleIndex] = restrict(handleEnds[handleIndex], realExtent), currDistSign = getSpanSign(handleEnds, handleIndex), null != minSpan && (currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan) && (handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan), currDistSign = getSpanSign(handleEnds, handleIndex), null != maxSpan && currDistSign.span > maxSpan && (handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan), handleEnds; } function getSpanSign(handleEnds, handleIndex) { var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex]; return { span: Math.abs(dist), sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1 }; } function restrict(value, extend) { return Math.min(null != extend[1] ? extend[1] : 1 / 0, Math.max(null != extend[0] ? extend[0] : -1 / 0, value)); } var mathMin$8 = Math.min, mathMax$8 = Math.max, mathFloor$2 = Math.floor, mathCeil$1 = Math.ceil, PI$7 = Math.PI, Parallel = function() { function Parallel(parallelModel, ecModel, api) { this.type = 'parallel', this._axesMap = createHashMap(), this._axesLayout = {}, this.dimensions = parallelModel.dimensions, this._model = parallelModel, this._init(parallelModel, ecModel, api); } return Parallel.prototype._init = function(parallelModel, ecModel, api) { var dimensions = parallelModel.dimensions, parallelAxisIndex = parallelModel.parallelAxisIndex; each(dimensions, function(dim, idx) { var axisIndex = parallelAxisIndex[idx], axisModel = ecModel.getComponent('parallelAxis', axisIndex), axis = this._axesMap.set(dim, new ParallelAxis(dim, createScaleByModel(axisModel), [ 0, 0 ], axisModel.get('type'), axisIndex)), isCategory = 'category' === axis.type; axis.onBand = isCategory && axisModel.get('boundaryGap'), axis.inverse = axisModel.get('inverse'), axisModel.axis = axis, axis.model = axisModel, axis.coordinateSystem = axisModel.coordinateSystem = this; }, this); }, Parallel.prototype.update = function(ecModel, api) { this._updateAxesFromSeries(this._model, ecModel); }, Parallel.prototype.containPoint = function(point) { var layoutInfo = this._makeLayoutInfo(), axisBase = layoutInfo.axisBase, layoutBase = layoutInfo.layoutBase, pixelDimIndex = layoutInfo.pixelDimIndex, pAxis = point[1 - pixelDimIndex], pLayout = point[pixelDimIndex]; return pAxis >= axisBase && pAxis <= axisBase + layoutInfo.axisLength && pLayout >= layoutBase && pLayout <= layoutBase + layoutInfo.layoutLength; }, Parallel.prototype.getModel = function() { return this._model; }, Parallel.prototype._updateAxesFromSeries = function(parallelModel, ecModel) { ecModel.eachSeries(function(seriesModel) { if (parallelModel.contains(seriesModel, ecModel)) { var data = seriesModel.getData(); each(this.dimensions, function(dim) { var axis = this._axesMap.get(dim); axis.scale.unionExtentFromData(data, data.mapDimension(dim)), niceScaleExtent(axis.scale, axis.model); }, this); } }, this); }, Parallel.prototype.resize = function(parallelModel, api) { this._rect = getLayoutRect(parallelModel.getBoxLayoutParams(), { width: api.getWidth(), height: api.getHeight() }), this._layoutAxes(); }, Parallel.prototype.getRect = function() { return this._rect; }, Parallel.prototype._makeLayoutInfo = function() { var winSize, parallelModel = this._model, rect = this._rect, xy = [ 'x', 'y' ], wh = [ 'width', 'height' ], layout = parallelModel.get('layout'), pixelDimIndex = 'horizontal' === layout ? 0 : 1, layoutLength = rect[wh[pixelDimIndex]], layoutExtent = [ 0, layoutLength ], axisCount = this.dimensions.length, axisExpandWidth = restrict$1(parallelModel.get('axisExpandWidth'), layoutExtent), axisExpandCount = restrict$1(parallelModel.get('axisExpandCount') || 0, [ 0, axisCount ]), axisExpandable = parallelModel.get('axisExpandable') && axisCount > 3 && axisCount > axisExpandCount && axisExpandCount > 1 && axisExpandWidth > 0 && layoutLength > 0, axisExpandWindow = parallelModel.get('axisExpandWindow'); axisExpandWindow ? (winSize = restrict$1(axisExpandWindow[1] - axisExpandWindow[0], layoutExtent), axisExpandWindow[1] = axisExpandWindow[0] + winSize) : (winSize = restrict$1(axisExpandWidth * (axisExpandCount - 1), layoutExtent), (axisExpandWindow = [ axisExpandWidth * (parallelModel.get('axisExpandCenter') || mathFloor$2(axisCount / 2)) - winSize / 2 ])[1] = axisExpandWindow[0] + winSize); var axisCollapseWidth = (layoutLength - winSize) / (axisCount - axisExpandCount); axisCollapseWidth < 3 && (axisCollapseWidth = 0); var winInnerIndices = [ mathFloor$2(round(axisExpandWindow[0] / axisExpandWidth, 1)) + 1, mathCeil$1(round(axisExpandWindow[1] / axisExpandWidth, 1)) - 1 ], axisExpandWindow0Pos = axisCollapseWidth / axisExpandWidth * axisExpandWindow[0]; return { layout: layout, pixelDimIndex: pixelDimIndex, layoutBase: rect[xy[pixelDimIndex]], layoutLength: layoutLength, axisBase: rect[xy[1 - pixelDimIndex]], axisLength: rect[wh[1 - pixelDimIndex]], axisExpandable: axisExpandable, axisExpandWidth: axisExpandWidth, axisCollapseWidth: axisCollapseWidth, axisExpandWindow: axisExpandWindow, axisCount: axisCount, winInnerIndices: winInnerIndices, axisExpandWindow0Pos: axisExpandWindow0Pos }; }, Parallel.prototype._layoutAxes = function() { var rect = this._rect, axes = this._axesMap, dimensions = this.dimensions, layoutInfo = this._makeLayoutInfo(), layout = layoutInfo.layout; axes.each(function(axis) { var axisExtent = [ 0, layoutInfo.axisLength ], idx = axis.inverse ? 1 : 0; axis.setExtent(axisExtent[idx], axisExtent[1 - idx]); }), each(dimensions, function(dim, idx) { var posInfo = (layoutInfo.axisExpandable ? layoutAxisWithExpand : layoutAxisWithoutExpand)(idx, layoutInfo), positionTable = { horizontal: { x: posInfo.position, y: layoutInfo.axisLength }, vertical: { x: 0, y: posInfo.position } }, position = [ positionTable[layout].x + rect.x, positionTable[layout].y + rect.y ], rotation = { horizontal: PI$7 / 2, vertical: 0 }[layout], transform = create$1(); rotate(transform, transform, rotation), translate(transform, transform, position), this._axesLayout[dim] = { position: position, rotation: rotation, transform: transform, axisNameAvailableWidth: posInfo.axisNameAvailableWidth, axisLabelShow: posInfo.axisLabelShow, nameTruncateMaxWidth: posInfo.nameTruncateMaxWidth, tickDirection: 1, labelDirection: 1 }; }, this); }, Parallel.prototype.getAxis = function(dim) { return this._axesMap.get(dim); }, Parallel.prototype.dataToPoint = function(value, dim) { return this.axisCoordToPoint(this._axesMap.get(dim).dataToCoord(value), dim); }, Parallel.prototype.eachActiveState = function(data, callback, start, end) { null == start && (start = 0), null == end && (end = data.count()); var axesMap = this._axesMap, dimensions = this.dimensions, dataDimensions = [], axisModels = []; each(dimensions, function(axisDim) { dataDimensions.push(data.mapDimension(axisDim)), axisModels.push(axesMap.get(axisDim).model); }); for(var hasActiveSet = this.hasAxisBrushed(), dataIndex = start; dataIndex < end; dataIndex++){ var activeState = void 0; if (hasActiveSet) { activeState = 'active'; for(var values = data.getValues(dataDimensions, dataIndex), j = 0, lenj = dimensions.length; j < lenj; j++)if ('inactive' === axisModels[j].getActiveState(values[j])) { activeState = 'inactive'; break; } } else activeState = 'normal'; callback(activeState, dataIndex); } }, Parallel.prototype.hasAxisBrushed = function() { for(var dimensions = this.dimensions, axesMap = this._axesMap, hasActiveSet = !1, j = 0, lenj = dimensions.length; j < lenj; j++)'normal' !== axesMap.get(dimensions[j]).model.getActiveState() && (hasActiveSet = !0); return hasActiveSet; }, Parallel.prototype.axisCoordToPoint = function(coord, dim) { return applyTransform$1([ coord, 0 ], this._axesLayout[dim].transform); }, Parallel.prototype.getAxisLayout = function(dim) { return clone(this._axesLayout[dim]); }, Parallel.prototype.getSlidedAxisExpandWindow = function(point) { var delta, layoutInfo = this._makeLayoutInfo(), pixelDimIndex = layoutInfo.pixelDimIndex, axisExpandWindow = layoutInfo.axisExpandWindow.slice(), winSize = axisExpandWindow[1] - axisExpandWindow[0], extent = [ 0, layoutInfo.axisExpandWidth * (layoutInfo.axisCount - 1) ]; if (!this.containPoint(point)) return { behavior: 'none', axisExpandWindow: axisExpandWindow }; var pointCoord = point[pixelDimIndex] - layoutInfo.layoutBase - layoutInfo.axisExpandWindow0Pos, behavior = 'slide', axisCollapseWidth = layoutInfo.axisCollapseWidth, triggerArea = this._model.get('axisExpandSlideTriggerArea'), useJump = null != triggerArea[0]; if (axisCollapseWidth) useJump && axisCollapseWidth && pointCoord < winSize * triggerArea[0] ? (behavior = 'jump', delta = pointCoord - winSize * triggerArea[2]) : useJump && axisCollapseWidth && pointCoord > winSize * (1 - triggerArea[0]) ? (behavior = 'jump', delta = pointCoord - winSize * (1 - triggerArea[2])) : (delta = pointCoord - winSize * triggerArea[1]) >= 0 && (delta = pointCoord - winSize * (1 - triggerArea[1])) <= 0 && (delta = 0), (delta *= layoutInfo.axisExpandWidth / axisCollapseWidth) ? sliderMove(delta, axisExpandWindow, extent, 'all') : behavior = 'none'; else { var winSize2 = axisExpandWindow[1] - axisExpandWindow[0]; (axisExpandWindow = [ mathMax$8(0, extent[1] * pointCoord / winSize2 - winSize2 / 2) ])[1] = mathMin$8(extent[1], axisExpandWindow[0] + winSize2), axisExpandWindow[0] = axisExpandWindow[1] - winSize2; } return { axisExpandWindow: axisExpandWindow, behavior: behavior }; }, Parallel; }(); function restrict$1(len, extent) { return mathMin$8(mathMax$8(len, extent[0]), extent[1]); } function layoutAxisWithoutExpand(axisIndex, layoutInfo) { var step = layoutInfo.layoutLength / (layoutInfo.axisCount - 1); return { position: step * axisIndex, axisNameAvailableWidth: step, axisLabelShow: !0 }; } function layoutAxisWithExpand(axisIndex, layoutInfo) { var position, nameTruncateMaxWidth, layoutLength = layoutInfo.layoutLength, axisExpandWidth = layoutInfo.axisExpandWidth, axisCount = layoutInfo.axisCount, axisCollapseWidth = layoutInfo.axisCollapseWidth, winInnerIndices = layoutInfo.winInnerIndices, axisNameAvailableWidth = axisCollapseWidth, axisLabelShow = !1; return axisIndex < winInnerIndices[0] ? (position = axisIndex * axisCollapseWidth, nameTruncateMaxWidth = axisCollapseWidth) : axisIndex <= winInnerIndices[1] ? (position = layoutInfo.axisExpandWindow0Pos + axisIndex * axisExpandWidth - layoutInfo.axisExpandWindow[0], axisNameAvailableWidth = axisExpandWidth, axisLabelShow = !0) : (position = layoutLength - (axisCount - 1 - axisIndex) * axisCollapseWidth, nameTruncateMaxWidth = axisCollapseWidth), { position: position, axisNameAvailableWidth: axisNameAvailableWidth, axisLabelShow: axisLabelShow, nameTruncateMaxWidth: nameTruncateMaxWidth }; } var parallelCoordSysCreator = { create: function(ecModel, api) { var coordSysList = []; return ecModel.eachComponent('parallel', function(parallelModel, idx) { var coordSys = new Parallel(parallelModel, ecModel, api); coordSys.name = 'parallel_' + idx, coordSys.resize(parallelModel, api), parallelModel.coordinateSystem = coordSys, coordSys.model = parallelModel, coordSysList.push(coordSys); }), ecModel.eachSeries(function(seriesModel) { if ('parallel' === seriesModel.get('coordinateSystem')) { var parallelModel = seriesModel.getReferringComponents('parallel', SINGLE_REFERRING).models[0]; seriesModel.coordinateSystem = parallelModel.coordinateSystem; } }), coordSysList; } }, ParallelAxisModel = function(_super) { function ParallelAxisModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = ParallelAxisModel.type, _this.activeIntervals = [], _this; } return __extends(ParallelAxisModel, _super), ParallelAxisModel.prototype.getAreaSelectStyle = function() { return makeStyleMapper([ [ 'fill', 'color' ], [ 'lineWidth', 'borderWidth' ], [ 'stroke', 'borderColor' ], [ 'width', 'width' ], [ 'opacity', 'opacity' ] ])(this.getModel('areaSelectStyle')); }, ParallelAxisModel.prototype.setActiveIntervals = function(intervals) { var activeIntervals = this.activeIntervals = clone(intervals); if (activeIntervals) for(var i = activeIntervals.length - 1; i >= 0; i--)asc(activeIntervals[i]); }, ParallelAxisModel.prototype.getActiveState = function(value) { var activeIntervals = this.activeIntervals; if (!activeIntervals.length) return 'normal'; if (null == value || isNaN(+value)) return 'inactive'; if (1 === activeIntervals.length) { var interval = activeIntervals[0]; if (interval[0] <= value && value <= interval[1]) return 'active'; } else for(var i = 0, len = activeIntervals.length; i < len; i++)if (activeIntervals[i][0] <= value && value <= activeIntervals[i][1]) return 'active'; return 'inactive'; }, ParallelAxisModel; }(ComponentModel); mixin(ParallelAxisModel, AxisModelCommonMixin); var mathMin$9 = Math.min, mathMax$9 = Math.max, mathPow$2 = Math.pow, MUTEX_RESOURCE_KEY = 'globalPan', DIRECTION_MAP = { w: [ 0, 0 ], e: [ 0, 1 ], n: [ 1, 0 ], s: [ 1, 1 ] }, CURSOR_MAP = { w: 'ew', e: 'ew', n: 'ns', s: 'ns', ne: 'nesw', sw: 'nesw', nw: 'nwse', se: 'nwse' }, DEFAULT_BRUSH_OPT = { brushStyle: { lineWidth: 2, stroke: 'rgba(210,219,238,0.3)', fill: '#D2DBEE' }, transformable: !0, brushMode: 'single', removeOnClick: !1 }, baseUID = 0, BrushController = function(_super) { function BrushController(zr) { var _this = _super.call(this) || this; return _this._track = [], _this._covers = [], _this._handlers = {}, assert(zr), _this._zr = zr, _this.group = new Group(), _this._uid = 'brushController_' + baseUID++, each(pointerHandlers, function(handler, eventName) { this._handlers[eventName] = bind(handler, this); }, _this), _this; } return __extends(BrushController, _super), BrushController.prototype.enableBrush = function(brushOption) { return assert(this._mounted), this._brushType && this._doDisableBrush(), brushOption.brushType && this._doEnableBrush(brushOption), this; }, BrushController.prototype._doEnableBrush = function(brushOption) { var userKey, zr = this._zr; this._enableGlobalPan || (userKey = this._uid, getStore(zr)[MUTEX_RESOURCE_KEY] = userKey), each(this._handlers, function(handler, eventName) { zr.on(eventName, handler); }), this._brushType = brushOption.brushType, this._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, !0); }, BrushController.prototype._doDisableBrush = function() { var userKey, store, zr = this._zr; userKey = this._uid, (store = getStore(zr))[MUTEX_RESOURCE_KEY] === userKey && (store[MUTEX_RESOURCE_KEY] = null), each(this._handlers, function(handler, eventName) { zr.off(eventName, handler); }), this._brushType = this._brushOption = null; }, BrushController.prototype.setPanels = function(panelOpts) { if (panelOpts && panelOpts.length) { var panels_1 = this._panels = {}; each(panelOpts, function(panelOpts) { panels_1[panelOpts.panelId] = clone(panelOpts); }); } else this._panels = null; return this; }, BrushController.prototype.mount = function(opt) { opt = opt || {}, this._mounted = !0, this._enableGlobalPan = opt.enableGlobalPan; var thisGroup = this.group; return this._zr.add(thisGroup), thisGroup.attr({ x: opt.x || 0, y: opt.y || 0, rotation: opt.rotation || 0, scaleX: opt.scaleX || 1, scaleY: opt.scaleY || 1 }), this._transform = thisGroup.getLocalTransform(), this; }, BrushController.prototype.updateCovers = function(coverConfigList) { assert(this._mounted), coverConfigList = map(coverConfigList, function(coverConfig) { return merge(clone(DEFAULT_BRUSH_OPT), coverConfig, !0); }); var oldCovers = this._covers, newCovers = this._covers = [], controller = this, creatingCover = this._creatingCover; return new DataDiffer(oldCovers, coverConfigList, function(cover, index) { return getKey(cover.__brushOption, index); }, getKey).add(addOrUpdate).update(addOrUpdate).remove(function(oldIndex) { oldCovers[oldIndex] !== creatingCover && controller.group.remove(oldCovers[oldIndex]); }).execute(), this; function getKey(brushOption, index) { return (null != brushOption.id ? brushOption.id : '\0-brush-index-' + index) + '-' + brushOption.brushType; } function addOrUpdate(newIndex, oldIndex) { var newBrushInternal = coverConfigList[newIndex]; if (null != oldIndex && oldCovers[oldIndex] === creatingCover) newCovers[newIndex] = oldCovers[oldIndex]; else { var cover = newCovers[newIndex] = null != oldIndex ? (oldCovers[oldIndex].__brushOption = newBrushInternal, oldCovers[oldIndex]) : endCreating(controller, createCover(controller, newBrushInternal)); updateCoverAfterCreation(controller, cover); } } }, BrushController.prototype.unmount = function() { return this._mounted ? (this.enableBrush(!1), clearCovers(this), this._zr.remove(this.group), this._mounted = !1, this) : void 0; }, BrushController.prototype.dispose = function() { this.unmount(), this.off(); }, BrushController; }(Eventful); function createCover(controller, brushOption) { var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption); return cover.__brushOption = brushOption, updateZ(cover, brushOption), controller.group.add(cover), cover; } function endCreating(controller, creatingCover) { var coverRenderer = getCoverRenderer(creatingCover); return coverRenderer.endCreating && (coverRenderer.endCreating(controller, creatingCover), updateZ(creatingCover, creatingCover.__brushOption)), creatingCover; } function updateCoverShape(controller, cover) { var brushOption = cover.__brushOption; getCoverRenderer(cover).updateCoverShape(controller, cover, brushOption.range, brushOption); } function updateZ(cover, brushOption) { var z = brushOption.z; null == z && (z = 10000), cover.traverse(function(el) { el.z = z, el.z2 = z; }); } function updateCoverAfterCreation(controller, cover) { getCoverRenderer(cover).updateCommon(controller, cover), updateCoverShape(controller, cover); } function getCoverRenderer(cover) { return coverRenderers[cover.__brushOption.brushType]; } function getPanelByPoint(controller, e, localCursorPoint) { var panel, panels = controller._panels; if (!panels) return !0; var transform = controller._transform; return each(panels, function(pn) { pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn); }), panel; } function getPanelByCover(controller, cover) { var panels = controller._panels; if (!panels) return !0; var panelId = cover.__brushOption.panelId; return null == panelId || panels[panelId]; } function clearCovers(controller) { var covers = controller._covers, originalLength = covers.length; return each(covers, function(cover) { controller.group.remove(cover); }, controller), covers.length = 0, !!originalLength; } function trigger$1(controller, opt) { var areas = map(controller._covers, function(cover) { var brushOption = cover.__brushOption, range = clone(brushOption.range); return { brushType: brushOption.brushType, panelId: brushOption.panelId, range: range }; }); controller.trigger('brush', { areas: areas, isEnd: !!opt.isEnd, removeOnClick: !!opt.removeOnClick }); } function getTrackEnds(track) { var tail = track.length - 1; return tail < 0 && (tail = 0), [ track[0], track[tail] ]; } function createBaseRectCover(rectRangeConverter, controller, brushOption, edgeNameSequences) { var cover = new Group(); return cover.add(new Rect({ name: 'main', style: makeStyle(brushOption), silent: !0, draggable: !0, cursor: 'move', drift: curry(driftRect, rectRangeConverter, controller, cover, [ 'n', 's', 'w', 'e' ]), ondragend: curry(trigger$1, controller, { isEnd: !0 }) })), each(edgeNameSequences, function(nameSequence) { cover.add(new Rect({ name: nameSequence.join(''), style: { opacity: 0 }, draggable: !0, silent: !0, invisible: !0, drift: curry(driftRect, rectRangeConverter, controller, cover, nameSequence), ondragend: curry(trigger$1, controller, { isEnd: !0 }) })); }), cover; } function updateBaseRect(controller, cover, localRange, brushOption) { var lineWidth = brushOption.brushStyle.lineWidth || 0, handleSize = mathMax$9(lineWidth, 6), x = localRange[0][0], y = localRange[1][0], xa = x - lineWidth / 2, ya = y - lineWidth / 2, x2 = localRange[0][1], y2 = localRange[1][1], x2a = x2 - handleSize + lineWidth / 2, y2a = y2 - handleSize + lineWidth / 2, width = x2 - x, height = y2 - y, widtha = width + lineWidth, heighta = height + lineWidth; updateRectShape(controller, cover, 'main', x, y, width, height), brushOption.transformable && (updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta), updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta), updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize), updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize), updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize), updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize), updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize), updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize)); } function updateCommon(controller, cover) { var brushOption = cover.__brushOption, transformable = brushOption.transformable, mainEl = cover.childAt(0); mainEl.useStyle(makeStyle(brushOption)), mainEl.attr({ silent: !transformable, cursor: transformable ? 'move' : 'default' }), each([ [ 'w' ], [ 'e' ], [ 'n' ], [ 's' ], [ 's', 'e' ], [ 's', 'w' ], [ 'n', 'e' ], [ 'n', 'w' ] ], function(nameSequence) { var globalDir, el = cover.childOfName(nameSequence.join('')), globalDir1 = 1 === nameSequence.length ? getGlobalDirection1(controller, nameSequence[0]) : (('e' === (globalDir = [ getGlobalDirection1(controller, nameSequence[0]), getGlobalDirection1(controller, nameSequence[1]) ])[0] || 'w' === globalDir[0]) && globalDir.reverse(), globalDir.join('')); el && el.attr({ silent: !transformable, invisible: !transformable, cursor: transformable ? CURSOR_MAP[globalDir1] + '-resize' : null }); }); } function updateRectShape(controller, cover, name, x, y, w, h) { var points, xmin, ymin, el = cover.childOfName(name); el && el.setShape({ x: xmin = mathMin$9((points = clipByPanel(controller, cover, [ [ x, y ], [ x + w, y + h ] ]))[0][0], points[1][0]), y: ymin = mathMin$9(points[0][1], points[1][1]), width: mathMax$9(points[0][0], points[1][0]) - xmin, height: mathMax$9(points[0][1], points[1][1]) - ymin }); } function makeStyle(brushOption) { return defaults({ strokeNoScale: !0 }, brushOption.brushStyle); } function formatRectRange(x, y, x2, y2) { var min = [ mathMin$9(x, x2), mathMin$9(y, y2) ], max = [ mathMax$9(x, x2), mathMax$9(y, y2) ]; return [ [ min[0], max[0] ], [ min[1], max[1] ] ]; } function getGlobalDirection1(controller, localDirName) { return ({ left: 'w', right: 'e', top: 'n', bottom: 's' })[transformDirection({ w: 'left', e: 'right', n: 'top', s: 'bottom' }[localDirName], getTransform(controller.group))]; } function driftRect(rectRangeConverter, controller, cover, dirNameSequence, dx, dy) { var brushOption = cover.__brushOption, rectRange = rectRangeConverter.toRectRange(brushOption.range), localDelta = toLocalDelta(controller, dx, dy); each(dirNameSequence, function(dirName) { var ind = DIRECTION_MAP[dirName]; rectRange[ind[0]][ind[1]] += localDelta[ind[0]]; }), brushOption.range = rectRangeConverter.fromRectRange(formatRectRange(rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1])), updateCoverAfterCreation(controller, cover), trigger$1(controller, { isEnd: !1 }); } function driftPolygon(controller, cover, dx, dy) { var range = cover.__brushOption.range, localDelta = toLocalDelta(controller, dx, dy); each(range, function(point) { point[0] += localDelta[0], point[1] += localDelta[1]; }), updateCoverAfterCreation(controller, cover), trigger$1(controller, { isEnd: !1 }); } function toLocalDelta(controller, dx, dy) { var thisGroup = controller.group, localD = thisGroup.transformCoordToLocal(dx, dy), localZero = thisGroup.transformCoordToLocal(0, 0); return [ localD[0] - localZero[0], localD[1] - localZero[1] ]; } function clipByPanel(controller, cover, data) { var panel = getPanelByCover(controller, cover); return panel && !0 !== panel ? panel.clipPath(data, controller._transform) : clone(data); } function preventDefault(e) { var rawE = e.event; rawE.preventDefault && rawE.preventDefault(); } function mainShapeContain(cover, x, y) { return cover.childOfName('main').contain(x, y); } function updateCoverByMouse(controller, e, localCursorPoint, isEnd) { var eventParams, creatingCover = controller._creatingCover, panel = controller._creatingPanel, thisBrushOption = controller._brushOption; if (controller._track.push(localCursorPoint.slice()), function(controller) { var track = controller._track; if (!track.length) return !1; var p2 = track[track.length - 1], p1 = track[0], dx = p2[0] - p1[0], dy = p2[1] - p1[1]; return mathPow$2(dx * dx + dy * dy, 0.5) > 6; }(controller) || creatingCover) { if (panel && !creatingCover) { 'single' === thisBrushOption.brushMode && clearCovers(controller); var brushOption = clone(thisBrushOption); brushOption.brushType = determineBrushType(brushOption.brushType, panel), brushOption.panelId = !0 === panel ? null : panel.panelId, creatingCover = controller._creatingCover = createCover(controller, brushOption), controller._covers.push(creatingCover); } if (creatingCover) { var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)]; creatingCover.__brushOption.range = coverRenderer.getCreatingRange(clipByPanel(controller, creatingCover, controller._track)), isEnd && (endCreating(controller, creatingCover), coverRenderer.updateCommon(controller, creatingCover)), updateCoverShape(controller, creatingCover), eventParams = { isEnd: isEnd }; } } else isEnd && 'single' === thisBrushOption.brushMode && thisBrushOption.removeOnClick && getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller) && (eventParams = { isEnd: isEnd, removeOnClick: !0 }); return eventParams; } function determineBrushType(brushType, panel) { return 'auto' === brushType ? (assert(panel && panel.defaultBrushType, 'MUST have defaultBrushType when brushType is "atuo"'), panel.defaultBrushType) : brushType; } var pointerHandlers = { mousedown: function(e) { if (this._dragging) handleDragEnd(this, e); else if (!e.target || !e.target.draggable) { preventDefault(e); var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY); this._creatingCover = null, (this._creatingPanel = getPanelByPoint(this, e, localCursorPoint)) && (this._dragging = !0, this._track = [ localCursorPoint.slice() ]); } }, mousemove: function(e) { var x = e.offsetX, y = e.offsetY, localCursorPoint = this.group.transformCoordToLocal(x, y); if (!function(controller, e, localCursorPoint) { if (!(!controller._brushType || (controller1 = controller, x = e.offsetX, y = e.offsetY, zr = controller1._zr, x < 0 || x > zr.getWidth() || y < 0 || y > zr.getHeight()))) { var controller1, x, y, zr, zr1 = controller._zr, covers = controller._covers, currPanel = getPanelByPoint(controller, e, localCursorPoint); if (!controller._dragging) for(var i = 0; i < covers.length; i++){ var brushOption = covers[i].__brushOption; if (currPanel && (!0 === currPanel || brushOption.panelId === currPanel.panelId) && coverRenderers[brushOption.brushType].contain(covers[i], localCursorPoint[0], localCursorPoint[1])) return; } currPanel && zr1.setCursorStyle('crosshair'); } }(this, e, localCursorPoint), this._dragging) { preventDefault(e); var eventParams = updateCoverByMouse(this, e, localCursorPoint, !1); eventParams && trigger$1(this, eventParams); } }, mouseup: function(e) { handleDragEnd(this, e); } }; function handleDragEnd(controller, e) { if (controller._dragging) { preventDefault(e); var x = e.offsetX, y = e.offsetY, localCursorPoint = controller.group.transformCoordToLocal(x, y), eventParams = updateCoverByMouse(controller, e, localCursorPoint, !0); controller._dragging = !1, controller._track = [], controller._creatingCover = null, eventParams && trigger$1(controller, eventParams); } } var coverRenderers = { lineX: getLineRenderer(0), lineY: getLineRenderer(1), rect: { createCover: function(controller, brushOption) { function returnInput(range) { return range; } return createBaseRectCover({ toRectRange: returnInput, fromRectRange: returnInput }, controller, brushOption, [ [ 'w' ], [ 'e' ], [ 'n' ], [ 's' ], [ 's', 'e' ], [ 's', 'w' ], [ 'n', 'e' ], [ 'n', 'w' ] ]); }, getCreatingRange: function(localTrack) { var ends = getTrackEnds(localTrack); return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]); }, updateCoverShape: function(controller, cover, localRange, brushOption) { updateBaseRect(controller, cover, localRange, brushOption); }, updateCommon: updateCommon, contain: mainShapeContain }, polygon: { createCover: function(controller, brushOption) { var cover = new Group(); return cover.add(new Polyline({ name: 'main', style: makeStyle(brushOption), silent: !0 })), cover; }, getCreatingRange: function(localTrack) { return localTrack; }, endCreating: function(controller, cover) { cover.remove(cover.childAt(0)), cover.add(new Polygon({ name: 'main', draggable: !0, drift: curry(driftPolygon, controller, cover), ondragend: curry(trigger$1, controller, { isEnd: !0 }) })); }, updateCoverShape: function(controller, cover, localRange, brushOption) { cover.childAt(0).setShape({ points: clipByPanel(controller, cover, localRange) }); }, updateCommon: updateCommon, contain: mainShapeContain } }; function getLineRenderer(xyIndex) { return { createCover: function(controller, brushOption) { return createBaseRectCover({ toRectRange: function(range) { var rectRange = [ range, [ 0, 100 ] ]; return xyIndex && rectRange.reverse(), rectRange; }, fromRectRange: function(rectRange) { return rectRange[xyIndex]; } }, controller, brushOption, [ [ [ 'w' ], [ 'e' ] ], [ [ 'n' ], [ 's' ] ] ][xyIndex]); }, getCreatingRange: function(localTrack) { var ends = getTrackEnds(localTrack); return [ mathMin$9(ends[0][xyIndex], ends[1][xyIndex]), mathMax$9(ends[0][xyIndex], ends[1][xyIndex]) ]; }, updateCoverShape: function(controller, cover, localRange, brushOption) { var otherExtent, panel = getPanelByCover(controller, cover); if (!0 !== panel && panel.getLinearBrushOtherExtent) otherExtent = panel.getLinearBrushOtherExtent(xyIndex); else { var zr = controller._zr; otherExtent = [ 0, [ zr.getWidth(), zr.getHeight() ][1 - xyIndex] ]; } var rectRange = [ localRange, otherExtent ]; xyIndex && rectRange.reverse(), updateBaseRect(controller, cover, rectRange, brushOption); }, updateCommon: updateCommon, contain: mainShapeContain }; } function makeRectPanelClipPath(rect) { return rect = normalizeRect(rect), function(localPoints) { return clipPointsByRect(localPoints, rect); }; } function makeLinearBrushOtherExtent(rect, specifiedXYIndex) { return rect = normalizeRect(rect), function(xyIndex) { var idx = null != specifiedXYIndex ? specifiedXYIndex : xyIndex, brushWidth = idx ? rect.width : rect.height, base = idx ? rect.x : rect.y; return [ base, base + (brushWidth || 0) ]; }; } function makeRectIsTargetByCursor(rect, api, targetModel) { var boundingRect = normalizeRect(rect); return function(e, localCursorPoint) { return boundingRect.contain(localCursorPoint[0], localCursorPoint[1]) && !onIrrelevantElement(e, api, targetModel); }; } function normalizeRect(rect) { return BoundingRect.create(rect); } var elementList = [ 'axisLine', 'axisTickLabel', 'axisName' ], ParallelAxisView = function(_super) { function ParallelAxisView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = ParallelAxisView.type, _this; } return __extends(ParallelAxisView, _super), ParallelAxisView.prototype.init = function(ecModel, api) { _super.prototype.init.apply(this, arguments), (this._brushController = new BrushController(api.getZr())).on('brush', bind(this._onBrush, this)); }, ParallelAxisView.prototype.render = function(axisModel, ecModel, api, payload) { if (!payload || 'axisAreaSelect' !== payload.type || ecModel.findComponents({ mainType: 'parallelAxis', query: payload })[0] !== axisModel) { this.axisModel = axisModel, this.api = api, this.group.removeAll(); var oldAxisGroup = this._axisGroup; if (this._axisGroup = new Group(), this.group.add(this._axisGroup), axisModel.get('show')) { var coordSysModel = ecModel.getComponent('parallel', axisModel.get('parallelIndex')), coordSys = coordSysModel.coordinateSystem, areaSelectStyle = axisModel.getAreaSelectStyle(), areaWidth = areaSelectStyle.width, dim = axisModel.axis.dim, builderOpt = extend({ strokeContainThreshold: areaWidth }, coordSys.getAxisLayout(dim)), axisBuilder = new AxisBuilder(axisModel, builderOpt); each(elementList, axisBuilder.add, axisBuilder), this._axisGroup.add(axisBuilder.getGroup()), this._refreshBrushController(builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api), groupTransition(oldAxisGroup, this._axisGroup, axisModel); } } }, ParallelAxisView.prototype._refreshBrushController = function(builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api) { var axis, extent = axisModel.axis.getExtent(), extentLen = extent[1] - extent[0], extra = Math.min(30, 0.1 * Math.abs(extentLen)), rect = BoundingRect.create({ x: extent[0], y: -areaWidth / 2, width: extentLen, height: areaWidth }); rect.x -= extra, rect.width += 2 * extra, this._brushController.mount({ enableGlobalPan: !0, rotation: builderOpt.rotation, x: builderOpt.position[0], y: builderOpt.position[1] }).setPanels([ { panelId: 'pl', clipPath: makeRectPanelClipPath(rect), isTargetByCursor: makeRectIsTargetByCursor(rect, api, coordSysModel), getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect, 0) } ]).enableBrush({ brushType: 'lineX', brushStyle: areaSelectStyle, removeOnClick: !0 }).updateCovers((axis = axisModel.axis, map(axisModel.activeIntervals, function(interval) { return { brushType: 'lineX', panelId: 'pl', range: [ axis.dataToCoord(interval[0], !0), axis.dataToCoord(interval[1], !0) ] }; }))); }, ParallelAxisView.prototype._onBrush = function(eventParam) { var coverInfoList = eventParam.areas, axisModel = this.axisModel, axis = axisModel.axis, intervals = map(coverInfoList, function(coverInfo) { return [ axis.coordToData(coverInfo.range[0], !0), axis.coordToData(coverInfo.range[1], !0) ]; }); (!axisModel.option.realtime === eventParam.isEnd || eventParam.removeOnClick) && this.api.dispatchAction({ type: 'axisAreaSelect', parallelAxisId: axisModel.id, intervals: intervals }); }, ParallelAxisView.prototype.dispose = function() { this._brushController.dispose(); }, ParallelAxisView.type = 'parallelAxis', ParallelAxisView; }(ComponentView), actionInfo$1 = { type: 'axisAreaSelect', event: 'axisAreaSelected' }, defaultAxisOption = { type: 'value', areaSelectStyle: { width: 20, borderWidth: 1, borderColor: 'rgba(160,197,232)', color: 'rgba(160,197,232)', opacity: 0.3 }, realtime: !0, z: 10 }; function install$g(registers) { registers.registerComponentView(ParallelView$1), registers.registerComponentModel(ParallelModel), registers.registerCoordinateSystem('parallel', parallelCoordSysCreator), registers.registerPreprocessor(parallelPreprocessor), registers.registerComponentModel(ParallelAxisModel), registers.registerComponentView(ParallelAxisView), axisModelCreator(registers, 'parallel', ParallelAxisModel, defaultAxisOption), registers.registerAction(actionInfo$1, function(payload, ecModel) { ecModel.eachComponent({ mainType: 'parallelAxis', query: payload }, function(parallelAxisModel) { parallelAxisModel.axis.model.setActiveIntervals(payload.intervals); }); }), registers.registerAction('parallelAxisExpand', function(payload, ecModel) { ecModel.eachComponent({ mainType: 'parallel', query: payload }, function(parallelModel) { parallelModel.setAxisExpand(payload); }); }); } var SankeyPathShape = function() { this.x1 = 0, this.y1 = 0, this.x2 = 0, this.y2 = 0, this.cpx1 = 0, this.cpy1 = 0, this.cpx2 = 0, this.cpy2 = 0, this.extent = 0; }, SankeyPath = function(_super) { function SankeyPath(opts) { return _super.call(this, opts) || this; } return __extends(SankeyPath, _super), SankeyPath.prototype.getDefaultShape = function() { return new SankeyPathShape(); }, SankeyPath.prototype.buildPath = function(ctx, shape) { var extent = shape.extent; ctx.moveTo(shape.x1, shape.y1), ctx.bezierCurveTo(shape.cpx1, shape.cpy1, shape.cpx2, shape.cpy2, shape.x2, shape.y2), 'vertical' === shape.orient ? (ctx.lineTo(shape.x2 + extent, shape.y2), ctx.bezierCurveTo(shape.cpx2 + extent, shape.cpy2, shape.cpx1 + extent, shape.cpy1, shape.x1 + extent, shape.y1)) : (ctx.lineTo(shape.x2, shape.y2 + extent), ctx.bezierCurveTo(shape.cpx2, shape.cpy2 + extent, shape.cpx1, shape.cpy1 + extent, shape.x1, shape.y1 + extent)), ctx.closePath(); }, SankeyPath.prototype.highlight = function() { enterEmphasis(this); }, SankeyPath.prototype.downplay = function() { leaveEmphasis(this); }, SankeyPath; }(Path), SankeyView = function(_super) { function SankeyView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = SankeyView.type, _this._focusAdjacencyDisabled = !1, _this; } return __extends(SankeyView, _super), SankeyView.prototype.render = function(seriesModel, ecModel, api) { var rect, cb, rectEl, sankeyView = this, graph = seriesModel.getGraph(), group = this.group, layoutInfo = seriesModel.layoutInfo, width = layoutInfo.width, height = layoutInfo.height, nodeData = seriesModel.getData(), edgeData = seriesModel.getData('edge'), orient = seriesModel.get('orient'); this._model = seriesModel, group.removeAll(), group.x = layoutInfo.x, group.y = layoutInfo.y, graph.eachEdge(function(edge) { var x1, y1, x2, y2, cpx1, cpy1, cpx2, cpy2, curve = new SankeyPath(), ecData = getECData(curve); ecData.dataIndex = edge.dataIndex, ecData.seriesIndex = seriesModel.seriesIndex, ecData.dataType = 'edge'; var edgeModel = edge.getModel(), lineStyleModel = edgeModel.getModel('lineStyle'), curvature = lineStyleModel.get('curveness'), n1Layout = edge.node1.getLayout(), node1Model = edge.node1.getModel(), dragX1 = node1Model.get('localX'), dragY1 = node1Model.get('localY'), n2Layout = edge.node2.getLayout(), node2Model = edge.node2.getModel(), dragX2 = node2Model.get('localX'), dragY2 = node2Model.get('localY'), edgeLayout = edge.getLayout(); switch(curve.shape.extent = Math.max(1, edgeLayout.dy), curve.shape.orient = orient, 'vertical' === orient ? (x1 = (null != dragX1 ? dragX1 * width : n1Layout.x) + edgeLayout.sy, y1 = (null != dragY1 ? dragY1 * height : n1Layout.y) + n1Layout.dy, x2 = (null != dragX2 ? dragX2 * width : n2Layout.x) + edgeLayout.ty, y2 = null != dragY2 ? dragY2 * height : n2Layout.y, cpx1 = x1, cpy1 = y1 * (1 - curvature) + y2 * curvature, cpx2 = x2, cpy2 = y1 * curvature + y2 * (1 - curvature)) : (x1 = (null != dragX1 ? dragX1 * width : n1Layout.x) + n1Layout.dx, y1 = (null != dragY1 ? dragY1 * height : n1Layout.y) + edgeLayout.sy, x2 = null != dragX2 ? dragX2 * width : n2Layout.x, y2 = (null != dragY2 ? dragY2 * height : n2Layout.y) + edgeLayout.ty, cpx1 = x1 * (1 - curvature) + x2 * curvature, cpy1 = y1, cpx2 = x1 * curvature + x2 * (1 - curvature), cpy2 = y2), curve.setShape({ x1: x1, y1: y1, x2: x2, y2: y2, cpx1: cpx1, cpy1: cpy1, cpx2: cpx2, cpy2: cpy2 }), curve.useStyle(lineStyleModel.getItemStyle()), curve.style.fill){ case 'source': curve.style.fill = edge.node1.getVisual('color'), curve.style.decal = edge.node1.getVisual('style').decal; break; case 'target': curve.style.fill = edge.node2.getVisual('color'), curve.style.decal = edge.node2.getVisual('style').decal; break; case 'gradient': var sourceColor = edge.node1.getVisual('color'), targetColor = edge.node2.getVisual('color'); 'string' == typeof sourceColor && 'string' == typeof targetColor && (curve.style.fill = new LinearGradient(0, 0, 1, 0, [ { color: sourceColor, offset: 0 }, { color: targetColor, offset: 1 } ])); } var emphasisModel = edgeModel.getModel('emphasis'); setStatesStylesFromModel(curve, edgeModel, 'lineStyle', function(model) { return model.getItemStyle(); }), group.add(curve), edgeData.setItemGraphicEl(edge.dataIndex, curve); var focus = emphasisModel.get('focus'); enableHoverEmphasis(curve, 'adjacency' === focus ? edge.getAdjacentDataIndices() : focus, emphasisModel.get('blurScope')), getECData(curve).dataType = 'edge'; }), graph.eachNode(function(node) { var layout = node.getLayout(), itemModel = node.getModel(), dragX = itemModel.get('localX'), dragY = itemModel.get('localY'), emphasisModel = itemModel.getModel('emphasis'), rect = new Rect({ shape: { x: null != dragX ? dragX * width : layout.x, y: null != dragY ? dragY * height : layout.y, width: layout.dx, height: layout.dy }, style: itemModel.getModel('itemStyle').getItemStyle(), z2: 10 }); setLabelStyle(rect, getLabelStatesModels(itemModel), { labelFetcher: seriesModel, labelDataIndex: node.dataIndex, defaultText: node.id }), rect.disableLabelAnimation = !0, rect.setStyle('fill', node.getVisual('color')), rect.setStyle('decal', node.getVisual('style').decal), setStatesStylesFromModel(rect, itemModel), group.add(rect), nodeData.setItemGraphicEl(node.dataIndex, rect), getECData(rect).dataType = 'node'; var focus = emphasisModel.get('focus'); enableHoverEmphasis(rect, 'adjacency' === focus ? node.getAdjacentDataIndices() : focus, emphasisModel.get('blurScope')); }), nodeData.eachItemGraphicEl(function(el, dataIndex) { nodeData.getItemModel(dataIndex).get('draggable') && (el.drift = function(dx, dy) { sankeyView._focusAdjacencyDisabled = !0, this.shape.x += dx, this.shape.y += dy, this.dirty(), api.dispatchAction({ type: 'dragNode', seriesId: seriesModel.id, dataIndex: nodeData.getRawIndex(dataIndex), localX: this.shape.x / width, localY: this.shape.y / height }); }, el.ondragend = function() { sankeyView._focusAdjacencyDisabled = !1; }, el.draggable = !0, el.cursor = 'move'); }), !this._data && seriesModel.isAnimationEnabled() && group.setClipPath((rect = group.getBoundingRect(), cb = function() { group.removeClipPath(); }, initProps(rectEl = new Rect({ shape: { x: rect.x - 10, y: rect.y - 10, width: 0, height: rect.height + 20 } }), { shape: { width: rect.width + 20 } }, seriesModel, cb), rectEl)), this._data = seriesModel.getData(); }, SankeyView.prototype.dispose = function() {}, SankeyView.type = 'sankey', SankeyView; }(ChartView), SankeySeriesModel = function(_super) { function SankeySeriesModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = SankeySeriesModel.type, _this; } return __extends(SankeySeriesModel, _super), SankeySeriesModel.prototype.getInitialData = function(option, ecModel) { var links = option.edges || option.links, nodes = option.data || option.nodes, levels = option.levels; this.levelModels = []; for(var levelModels = this.levelModels, i = 0; i < levels.length; i++)if (null != levels[i].depth && levels[i].depth >= 0) levelModels[levels[i].depth] = new Model(levels[i], this, ecModel); else throw Error('levels[i].depth is mandatory and should be natural number'); if (nodes && links) return createGraphFromNodeEdge(nodes, links, this, !0, function(nodeData, edgeData) { nodeData.wrapMethod('getItemModel', function(model, idx) { var seriesModel = model.parentModel, layout = seriesModel.getData().getItemLayout(idx); if (layout) { var nodeDepth = layout.depth, levelModel = seriesModel.levelModels[nodeDepth]; levelModel && (model.parentModel = levelModel); } return model; }), edgeData.wrapMethod('getItemModel', function(model, idx) { var seriesModel = model.parentModel, layout = seriesModel.getGraph().getEdgeByIndex(idx).node1.getLayout(); if (layout) { var depth = layout.depth, levelModel = seriesModel.levelModels[depth]; levelModel && (model.parentModel = levelModel); } return model; }); }).data; }, SankeySeriesModel.prototype.setNodePosition = function(dataIndex, localPosition) { var dataItem = this.option.data[dataIndex]; dataItem.localX = localPosition[0], dataItem.localY = localPosition[1]; }, SankeySeriesModel.prototype.getGraph = function() { return this.getData().graph; }, SankeySeriesModel.prototype.getEdgeData = function() { return this.getGraph().edgeData; }, SankeySeriesModel.prototype.formatTooltip = function(dataIndex, multipleSeries, dataType) { function noValue(val) { return isNaN(val) || null == val; } if ('edge' === dataType) { var params = this.getDataParams(dataIndex, dataType), rawDataOpt = params.data, edgeValue = params.value; return createTooltipMarkup('nameValue', { name: rawDataOpt.source + ' -- ' + rawDataOpt.target, value: edgeValue, noValue: noValue(edgeValue) }); } var value = this.getGraph().getNodeByIndex(dataIndex).getLayout().value, name_1 = this.getDataParams(dataIndex, dataType).data.name; return createTooltipMarkup('nameValue', { name: null != name_1 ? name_1 + '' : null, value: value, noValue: noValue(value) }); }, SankeySeriesModel.prototype.optionUpdated = function() { this.option; }, SankeySeriesModel.prototype.getDataParams = function(dataIndex, dataType) { var params = _super.prototype.getDataParams.call(this, dataIndex, dataType); if (null == params.value && 'node' === dataType) { var nodeValue = this.getGraph().getNodeByIndex(dataIndex).getLayout().value; params.value = nodeValue; } return params; }, SankeySeriesModel.type = 'series.sankey', SankeySeriesModel.defaultOption = { zlevel: 0, z: 2, coordinateSystem: 'view', left: '5%', top: '5%', right: '20%', bottom: '5%', orient: 'horizontal', nodeWidth: 20, nodeGap: 8, draggable: !0, layoutIterations: 32, label: { show: !0, position: 'right', fontSize: 12 }, levels: [], nodeAlign: 'justify', lineStyle: { color: '#314656', opacity: 0.2, curveness: 0.5 }, emphasis: { label: { show: !0 }, lineStyle: { opacity: 0.5 } }, select: { itemStyle: { borderColor: '#212121' } }, animationEasing: 'linear', animationDuration: 1000 }, SankeySeriesModel; }(SeriesModel); function sankeyLayout(ecModel, api) { ecModel.eachSeriesByType('sankey', function(seriesModel) { var orient, keyAttr, nodeWidth = seriesModel.get('nodeWidth'), nodeGap = seriesModel.get('nodeGap'), layoutInfo = getLayoutRect(seriesModel.getBoxLayoutParams(), { width: api.getWidth(), height: api.getHeight() }); seriesModel.layoutInfo = layoutInfo; var width = layoutInfo.width, height = layoutInfo.height, graph = seriesModel.getGraph(), nodes = graph.nodes, edges = graph.edges; each(nodes, function(node) { var value1 = sum(node.outEdges, getEdgeValue), value2 = sum(node.inEdges, getEdgeValue), nodeRawValue = node.getValue() || 0; node.setLayout({ value: Math.max(value1, value2, nodeRawValue) }, !0); }); var iterations = 0 !== filter(nodes, function(node) { return 0 === node.getLayout().value; }).length ? 0 : seriesModel.get('layoutIterations'); (function(nodes, edges, nodeWidth, width, height, orient, nodeAlign) { for(var kx, remainEdges = [], indegreeArr = [], zeroIndegrees = [], nextTargetNode = [], x = 0, i = 0; i < edges.length; i++)remainEdges[i] = 1; for(var i = 0; i < nodes.length; i++)indegreeArr[i] = nodes[i].inEdges.length, 0 === indegreeArr[i] && zeroIndegrees.push(nodes[i]); for(var maxNodeDepth = -1; zeroIndegrees.length;){ for(var idx = 0; idx < zeroIndegrees.length; idx++){ var node = zeroIndegrees[idx], item = node.hostGraph.data.getRawDataItem(node.dataIndex), isItemDepth = null != item.depth && item.depth >= 0; isItemDepth && item.depth > maxNodeDepth && (maxNodeDepth = item.depth), node.setLayout({ depth: isItemDepth ? item.depth : x }, !0), 'vertical' === orient ? node.setLayout({ dy: nodeWidth }, !0) : node.setLayout({ dx: nodeWidth }, !0); for(var edgeIdx = 0; edgeIdx < node.outEdges.length; edgeIdx++){ var edge = node.outEdges[edgeIdx]; remainEdges[edges.indexOf(edge)] = 0; var targetNode = edge.node2, nodeIndex = nodes.indexOf(targetNode); 0 == --indegreeArr[nodeIndex] && 0 > nextTargetNode.indexOf(targetNode) && nextTargetNode.push(targetNode); } } ++x, zeroIndegrees = nextTargetNode, nextTargetNode = []; } for(var i = 0; i < remainEdges.length; i++)if (1 === remainEdges[i]) throw Error('Sankey is a DAG, the original data has cycle!'); var maxDepth = maxNodeDepth > x - 1 ? maxNodeDepth : x - 1; nodeAlign && 'left' !== nodeAlign && function(nodes, nodeAlign, orient, maxDepth) { if ('right' === nodeAlign) { for(var nextSourceNode = [], remainNodes = nodes, nodeHeight = 0; remainNodes.length;){ for(var i = 0; i < remainNodes.length; i++){ var node = remainNodes[i]; node.setLayout({ skNodeHeight: nodeHeight }, !0); for(var j = 0; j < node.inEdges.length; j++){ var edge = node.inEdges[j]; 0 > nextSourceNode.indexOf(edge.node1) && nextSourceNode.push(edge.node1); } } remainNodes = nextSourceNode, nextSourceNode = [], ++nodeHeight; } each(nodes, function(node) { isNodeDepth(node) || node.setLayout({ depth: Math.max(0, maxDepth - node.getLayout().skNodeHeight) }, !0); }); } else 'justify' === nodeAlign && each(nodes, function(node) { isNodeDepth(node) || node.outEdges.length || node.setLayout({ depth: maxDepth }, !0); }); }(nodes, nodeAlign, 0, maxDepth), kx = 'vertical' === orient ? (height - nodeWidth) / maxDepth : (width - nodeWidth) / maxDepth, each(nodes, function(node) { var nodeDepth = node.getLayout().depth * kx; 'vertical' === orient ? node.setLayout({ y: nodeDepth }, !0) : node.setLayout({ x: nodeDepth }, !0); }); })(nodes, edges, nodeWidth, width, height, orient = seriesModel.get('orient'), seriesModel.get('nodeAlign')), function(nodes, edges, height, width, nodeGap, iterations, orient) { var nodesByBreadth, keyAttr, groupResult, minKy, nodesByBreadth1 = (nodesByBreadth = [], keyAttr = 'vertical' === orient ? 'y' : 'x', (groupResult = groupData(nodes, function(node) { return node.getLayout()[keyAttr]; })).keys.sort(function(a, b) { return a - b; }), each(groupResult.keys, function(key) { nodesByBreadth.push(groupResult.buckets.get(key)); }), nodesByBreadth); minKy = 1 / 0, each(nodesByBreadth1, function(nodes) { var n = nodes.length, sum = 0; each(nodes, function(node) { sum += node.getLayout().value; }); var ky = 'vertical' === orient ? (width - (n - 1) * nodeGap) / sum : (height - (n - 1) * nodeGap) / sum; ky < minKy && (minKy = ky); }), each(nodesByBreadth1, function(nodes) { each(nodes, function(node, i) { var nodeDy = node.getLayout().value * minKy; 'vertical' === orient ? (node.setLayout({ x: i }, !0), node.setLayout({ dx: nodeDy }, !0)) : (node.setLayout({ y: i }, !0), node.setLayout({ dy: nodeDy }, !0)); }); }), each(edges, function(edge) { var edgeDy = +edge.getValue() * minKy; edge.setLayout({ dy: edgeDy }, !0); }), resolveCollisions(nodesByBreadth1, nodeGap, height, width, orient); for(var alpha = 1; iterations > 0; iterations--)(function(nodesByBreadth, alpha, orient) { each(nodesByBreadth.slice().reverse(), function(nodes) { each(nodes, function(node) { if (node.outEdges.length) { var y = sum(node.outEdges, weightedTarget, orient) / sum(node.outEdges, getEdgeValue); if (isNaN(y)) { var len = node.outEdges.length; y = len ? sum(node.outEdges, centerTarget, orient) / len : 0; } if ('vertical' === orient) { var nodeX = node.getLayout().x + (y - center$1(node, orient)) * alpha; node.setLayout({ x: nodeX }, !0); } else { var nodeY = node.getLayout().y + (y - center$1(node, orient)) * alpha; node.setLayout({ y: nodeY }, !0); } } }); }); })(nodesByBreadth1, alpha *= 0.99, orient), resolveCollisions(nodesByBreadth1, nodeGap, height, width, orient), function(nodesByBreadth, alpha, orient) { each(nodesByBreadth, function(nodes) { each(nodes, function(node) { if (node.inEdges.length) { var y = sum(node.inEdges, weightedSource, orient) / sum(node.inEdges, getEdgeValue); if (isNaN(y)) { var len = node.inEdges.length; y = len ? sum(node.inEdges, centerSource, orient) / len : 0; } if ('vertical' === orient) { var nodeX = node.getLayout().x + (y - center$1(node, orient)) * alpha; node.setLayout({ x: nodeX }, !0); } else { var nodeY = node.getLayout().y + (y - center$1(node, orient)) * alpha; node.setLayout({ y: nodeY }, !0); } } }); }); }(nodesByBreadth1, alpha, orient), resolveCollisions(nodesByBreadth1, nodeGap, height, width, orient); }(nodes, edges, height, width, nodeGap, iterations, orient), keyAttr = 'vertical' === orient ? 'x' : 'y', each(nodes, function(node) { node.outEdges.sort(function(a, b) { return a.node2.getLayout()[keyAttr] - b.node2.getLayout()[keyAttr]; }), node.inEdges.sort(function(a, b) { return a.node1.getLayout()[keyAttr] - b.node1.getLayout()[keyAttr]; }); }), each(nodes, function(node) { var sy = 0, ty = 0; each(node.outEdges, function(edge) { edge.setLayout({ sy: sy }, !0), sy += edge.getLayout().dy; }), each(node.inEdges, function(edge) { edge.setLayout({ ty: ty }, !0), ty += edge.getLayout().dy; }); }); }); } function isNodeDepth(node) { var item = node.hostGraph.data.getRawDataItem(node.dataIndex); return null != item.depth && item.depth >= 0; } function resolveCollisions(nodesByBreadth, nodeGap, height, width, orient) { var keyAttr = 'vertical' === orient ? 'x' : 'y'; each(nodesByBreadth, function(nodes) { nodes.sort(function(a, b) { return a.getLayout()[keyAttr] - b.getLayout()[keyAttr]; }); for(var nodeX, node, dy, y0 = 0, n = nodes.length, nodeDyAttr = 'vertical' === orient ? 'dx' : 'dy', i = 0; i < n; i++)(dy = y0 - (node = nodes[i]).getLayout()[keyAttr]) > 0 && (nodeX = node.getLayout()[keyAttr] + dy, 'vertical' === orient ? node.setLayout({ x: nodeX }, !0) : node.setLayout({ y: nodeX }, !0)), y0 = node.getLayout()[keyAttr] + node.getLayout()[nodeDyAttr] + nodeGap; if ((dy = y0 - nodeGap - ('vertical' === orient ? width : height)) > 0) { nodeX = node.getLayout()[keyAttr] - dy, 'vertical' === orient ? node.setLayout({ x: nodeX }, !0) : node.setLayout({ y: nodeX }, !0), y0 = nodeX; for(var i = n - 2; i >= 0; --i)(dy = (node = nodes[i]).getLayout()[keyAttr] + node.getLayout()[nodeDyAttr] + nodeGap - y0) > 0 && (nodeX = node.getLayout()[keyAttr] - dy, 'vertical' === orient ? node.setLayout({ x: nodeX }, !0) : node.setLayout({ y: nodeX }, !0)), y0 = node.getLayout()[keyAttr]; } }); } function weightedTarget(edge, orient) { return center$1(edge.node2, orient) * edge.getValue(); } function centerTarget(edge, orient) { return center$1(edge.node2, orient); } function weightedSource(edge, orient) { return center$1(edge.node1, orient) * edge.getValue(); } function centerSource(edge, orient) { return center$1(edge.node1, orient); } function center$1(node, orient) { return 'vertical' === orient ? node.getLayout().x + node.getLayout().dx / 2 : node.getLayout().y + node.getLayout().dy / 2; } function getEdgeValue(edge) { return edge.getValue(); } function sum(array, cb, orient) { for(var sum = 0, len = array.length, i = -1; ++i < len;){ var value = +cb(array[i], orient); isNaN(value) || (sum += value); } return sum; } function sankeyVisual(ecModel) { ecModel.eachSeriesByType('sankey', function(seriesModel) { var nodes = seriesModel.getGraph().nodes; if (nodes.length) { var minValue_1 = 1 / 0, maxValue_1 = -1 / 0; each(nodes, function(node) { var nodeValue = node.getLayout().value; nodeValue < minValue_1 && (minValue_1 = nodeValue), nodeValue > maxValue_1 && (maxValue_1 = nodeValue); }), each(nodes, function(node) { var mapValueToColor = new VisualMapping({ type: 'color', mappingMethod: 'linear', dataExtent: [ minValue_1, maxValue_1 ], visual: seriesModel.get('color') }).mapValueToVisual(node.getLayout().value), customColor = node.getModel().get([ 'itemStyle', 'color' ]); null != customColor ? (node.setVisual('color', customColor), node.setVisual('style', { fill: customColor })) : (node.setVisual('color', mapValueToColor), node.setVisual('style', { fill: mapValueToColor })); }); } }); } var WhiskerBoxCommonMixin = function() { function WhiskerBoxCommonMixin() {} return WhiskerBoxCommonMixin.prototype.getInitialData = function(option, ecModel) { var ordinalMeta, addOrdinal, xAxisModel = ecModel.getComponent('xAxis', this.get('xAxisIndex')), yAxisModel = ecModel.getComponent('yAxis', this.get('yAxisIndex')), xAxisType = xAxisModel.get('type'), yAxisType = yAxisModel.get('type'); 'category' === xAxisType ? (option.layout = 'horizontal', ordinalMeta = xAxisModel.getOrdinalMeta(), addOrdinal = !0) : 'category' === yAxisType ? (option.layout = 'vertical', ordinalMeta = yAxisModel.getOrdinalMeta(), addOrdinal = !0) : option.layout = option.layout || 'horizontal'; var coordDims = [ 'x', 'y' ], baseAxisDimIndex = 'horizontal' === option.layout ? 0 : 1, baseAxisDim = this._baseAxisDim = coordDims[baseAxisDimIndex], otherAxisDim = coordDims[1 - baseAxisDimIndex], axisModels = [ xAxisModel, yAxisModel ], baseAxisType = axisModels[baseAxisDimIndex].get('type'), otherAxisType = axisModels[1 - baseAxisDimIndex].get('type'), data = option.data; if (data && addOrdinal) { var newOptionData_1 = []; each(data, function(item, index) { var newItem; isArray(item) ? (newItem = item.slice(), item.unshift(index)) : isArray(item.value) ? (newItem = item.value.slice(), item.value.unshift(index)) : newItem = item, newOptionData_1.push(newItem); }), option.data = newOptionData_1; } var defaultValueDimensions = this.defaultValueDimensions, coordDimensions = [ { name: baseAxisDim, type: getDimensionTypeByAxis(baseAxisType), ordinalMeta: ordinalMeta, otherDims: { tooltip: !1, itemName: 0 }, dimsDef: [ 'base' ] }, { name: otherAxisDim, type: getDimensionTypeByAxis(otherAxisType), dimsDef: defaultValueDimensions.slice() } ]; return createListSimply(this, { coordDimensions: coordDimensions, dimensionsCount: defaultValueDimensions.length + 1, encodeDefaulter: curry(makeSeriesEncodeForAxisCoordSys, coordDimensions, this) }); }, WhiskerBoxCommonMixin.prototype.getBaseAxis = function() { var dim = this._baseAxisDim; return this.ecModel.getComponent(dim + 'Axis', this.get(dim + 'AxisIndex')).axis; }, WhiskerBoxCommonMixin; }(), BoxplotSeriesModel = function(_super) { function BoxplotSeriesModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = BoxplotSeriesModel.type, _this.defaultValueDimensions = [ { name: 'min', defaultTooltip: !0 }, { name: 'Q1', defaultTooltip: !0 }, { name: 'median', defaultTooltip: !0 }, { name: 'Q3', defaultTooltip: !0 }, { name: 'max', defaultTooltip: !0 } ], _this.visualDrawType = 'stroke', _this; } return __extends(BoxplotSeriesModel, _super), BoxplotSeriesModel.type = 'series.boxplot', BoxplotSeriesModel.dependencies = [ 'xAxis', 'yAxis', 'grid' ], BoxplotSeriesModel.defaultOption = { zlevel: 0, z: 2, coordinateSystem: 'cartesian2d', legendHoverLink: !0, layout: null, boxWidth: [ 7, 50 ], itemStyle: { color: '#fff', borderWidth: 1 }, emphasis: { scale: !0, itemStyle: { borderWidth: 2, shadowBlur: 5, shadowOffsetX: 1, shadowOffsetY: 1, shadowColor: 'rgba(0,0,0,0.2)' } }, animationDuration: 800 }, BoxplotSeriesModel; }(SeriesModel); mixin(BoxplotSeriesModel, WhiskerBoxCommonMixin, !0); var BoxplotView = function(_super) { function BoxplotView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = BoxplotView.type, _this; } return __extends(BoxplotView, _super), BoxplotView.prototype.render = function(seriesModel, ecModel, api) { var data = seriesModel.getData(), group = this.group, oldData = this._data; this._data || group.removeAll(); var constDim = 'horizontal' === seriesModel.get('layout') ? 1 : 0; data.diff(oldData).add(function(newIdx) { if (data.hasValue(newIdx)) { var symbolEl = createNormalBox(data.getItemLayout(newIdx), data, newIdx, constDim, !0); data.setItemGraphicEl(newIdx, symbolEl), group.add(symbolEl); } }).update(function(newIdx, oldIdx) { var symbolEl = oldData.getItemGraphicEl(oldIdx); if (!data.hasValue(newIdx)) { group.remove(symbolEl); return; } var itemLayout = data.getItemLayout(newIdx); symbolEl ? updateNormalBoxData(itemLayout, symbolEl, data, newIdx) : symbolEl = createNormalBox(itemLayout, data, newIdx, constDim), group.add(symbolEl), data.setItemGraphicEl(newIdx, symbolEl); }).remove(function(oldIdx) { var el = oldData.getItemGraphicEl(oldIdx); el && group.remove(el); }).execute(), this._data = data; }, BoxplotView.prototype.remove = function(ecModel) { var group = this.group, data = this._data; this._data = null, data && data.eachItemGraphicEl(function(el) { el && group.remove(el); }); }, BoxplotView.type = 'boxplot', BoxplotView; }(ChartView), BoxPathShape = function() {}, BoxPath = function(_super) { function BoxPath(opts) { var _this = _super.call(this, opts) || this; return _this.type = 'boxplotBoxPath', _this; } return __extends(BoxPath, _super), BoxPath.prototype.getDefaultShape = function() { return new BoxPathShape(); }, BoxPath.prototype.buildPath = function(ctx, shape) { var ends = shape.points, i = 0; for(ctx.moveTo(ends[i][0], ends[i][1]), i++; i < 4; i++)ctx.lineTo(ends[i][0], ends[i][1]); for(ctx.closePath(); i < ends.length; i++)ctx.moveTo(ends[i][0], ends[i][1]), i++, ctx.lineTo(ends[i][0], ends[i][1]); }, BoxPath; }(Path); function createNormalBox(itemLayout, data, dataIndex, constDim, isInit) { var ends = itemLayout.ends, el = new BoxPath({ shape: { points: isInit ? map(ends, function(point) { return (point = point.slice())[constDim] = itemLayout.initBaseline, point; }) : ends } }); return updateNormalBoxData(itemLayout, el, data, dataIndex, isInit), el; } function updateNormalBoxData(itemLayout, el, data, dataIndex, isInit) { var seriesModel = data.hostModel; (0, graphic[isInit ? 'initProps' : 'updateProps'])(el, { shape: { points: itemLayout.ends } }, seriesModel, dataIndex), el.useStyle(data.getItemVisual(dataIndex, 'style')), el.style.strokeNoScale = !0, el.z2 = 100; var itemModel = data.getItemModel(dataIndex); setStatesStylesFromModel(el, itemModel), enableHoverEmphasis(el, itemModel.get([ 'emphasis', 'focus' ]), itemModel.get([ 'emphasis', 'blurScope' ])); } function boxplotVisual(ecModel, api) {} function boxplotLayout(ecModel) { var result, axisList; each((result = [], axisList = [], ecModel.eachSeriesByType('boxplot', function(seriesModel) { var baseAxis = seriesModel.getBaseAxis(), idx = indexOf(axisList, baseAxis); idx < 0 && (axisList[idx = axisList.length] = baseAxis, result[idx] = { axis: baseAxis, seriesModels: [] }), result[idx].seriesModels.push(seriesModel); }), result), function(groupItem) { var seriesModels = groupItem.seriesModels; seriesModels.length && (function(groupItem) { var extent, bandWidth, baseAxis = groupItem.axis, seriesModels = groupItem.seriesModels, seriesCount = seriesModels.length, boxWidthList = groupItem.boxWidthList = [], boxOffsetList = groupItem.boxOffsetList = [], boundList = []; if ('category' === baseAxis.type) bandWidth = baseAxis.getBandWidth(); else { var maxDataCount_1 = 0; each(seriesModels, function(seriesModel) { maxDataCount_1 = Math.max(maxDataCount_1, seriesModel.getData().count()); }), (extent = baseAxis.getExtent())[1], extent[0]; } each(seriesModels, function(seriesModel) { var boxWidthBound = seriesModel.get('boxWidth'); isArray(boxWidthBound) || (boxWidthBound = [ boxWidthBound, boxWidthBound ]), boundList.push([ parsePercent$1(boxWidthBound[0], bandWidth) || 0, parsePercent$1(boxWidthBound[1], bandWidth) || 0 ]); }); var availableWidth = 0.8 * bandWidth - 2, boxGap = availableWidth / seriesCount * 0.3, boxWidth = (availableWidth - boxGap * (seriesCount - 1)) / seriesCount, base = boxWidth / 2 - availableWidth / 2; each(seriesModels, function(seriesModel, idx) { boxOffsetList.push(base), base += boxGap + boxWidth, boxWidthList.push(Math.min(Math.max(boxWidth, boundList[idx][0]), boundList[idx][1])); }); }(groupItem), each(seriesModels, function(seriesModel, idx) { (function(seriesModel, offset, boxWidth) { var coordSys = seriesModel.coordinateSystem, data = seriesModel.getData(), halfWidth = boxWidth / 2, cDimIdx = 'horizontal' === seriesModel.get('layout') ? 0 : 1, vDimIdx = 1 - cDimIdx, coordDims = [ 'x', 'y' ], cDim = data.mapDimension(coordDims[cDimIdx]), vDims = data.mapDimensionsAll(coordDims[vDimIdx]); if (null != cDim && !(vDims.length < 5)) for(var dataIndex = 0; dataIndex < data.count(); dataIndex++){ var axisDimVal = data.get(cDim, dataIndex), median = getPoint(axisDimVal, vDims[2], dataIndex), end1 = getPoint(axisDimVal, vDims[0], dataIndex), end2 = getPoint(axisDimVal, vDims[1], dataIndex), end4 = getPoint(axisDimVal, vDims[3], dataIndex), end5 = getPoint(axisDimVal, vDims[4], dataIndex), ends = []; addBodyEnd(ends, end2, !1), addBodyEnd(ends, end4, !0), ends.push(end1, end2, end5, end4), layEndLine(ends, end1), layEndLine(ends, end5), layEndLine(ends, median), data.setItemLayout(dataIndex, { initBaseline: median[vDimIdx], ends: ends }); } function getPoint(axisDimVal, dim, dataIndex) { var point, val = data.get(dim, dataIndex), p = []; return p[cDimIdx] = axisDimVal, p[vDimIdx] = val, isNaN(axisDimVal) || isNaN(val) ? point = [ NaN, NaN ] : (point = coordSys.dataToPoint(p), point[cDimIdx] += offset), point; } function addBodyEnd(ends, point, start) { var point1 = point.slice(), point2 = point.slice(); point1[cDimIdx] += halfWidth, point2[cDimIdx] -= halfWidth, start ? ends.push(point1, point2) : ends.push(point2, point1); } function layEndLine(ends, endCenter) { var from = endCenter.slice(), to = endCenter.slice(); from[cDimIdx] -= halfWidth, to[cDimIdx] += halfWidth, ends.push(from, to); } })(seriesModel, groupItem.boxOffsetList[idx], groupItem.boxWidthList[idx]); })); }); } var boxplotTransform = { type: 'echarts:boxplot', transform: function(params) { var upstream = params.upstream; upstream.sourceFormat !== SOURCE_FORMAT_ARRAY_ROWS && throwError(makePrintable('source data is not applicable for this boxplot transform. Expect number[][].')); var result = function(rawData, opt) { for(var boxData = [], outliers = [], boundIQR = (opt = opt || {}).boundIQR, useExtreme = 'none' === boundIQR || 0 === boundIQR, i = 0; i < rawData.length; i++){ var ascList = asc(rawData[i].slice()), Q1 = quantile(ascList, 0.25), Q2 = quantile(ascList, 0.5), Q3 = quantile(ascList, 0.75), min = ascList[0], max = ascList[ascList.length - 1], bound = (null == boundIQR ? 1.5 : boundIQR) * (Q3 - Q1), low = useExtreme ? min : Math.max(min, Q1 - bound), high = useExtreme ? max : Math.min(max, Q3 + bound), itemNameFormatter = opt.itemNameFormatter, itemName = isFunction(itemNameFormatter) ? itemNameFormatter({ value: i }) : isString(itemNameFormatter) ? itemNameFormatter.replace('{value}', i + '') : i + ''; boxData.push([ itemName, low, Q1, Q2, Q3, high ]); for(var j = 0; j < ascList.length; j++){ var dataItem = ascList[j]; if (dataItem < low || dataItem > high) { var outlier = [ itemName, dataItem ]; outliers.push(outlier); } } } return { boxData: boxData, outliers: outliers }; }(upstream.getRawData(), params.config); return [ { dimensions: [ 'ItemName', 'Low', 'Q1', 'Q2', 'Q3', 'High' ], data: result.boxData }, { data: result.outliers } ]; } }, SKIP_PROPS = [ 'color', 'borderColor' ], CandlestickView = function(_super) { function CandlestickView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = CandlestickView.type, _this; } return __extends(CandlestickView, _super), CandlestickView.prototype.render = function(seriesModel, ecModel, api) { this.group.removeClipPath(), this._updateDrawMode(seriesModel), this._isLargeDraw ? this._renderLarge(seriesModel) : this._renderNormal(seriesModel); }, CandlestickView.prototype.incrementalPrepareRender = function(seriesModel, ecModel, api) { this._clear(), this._updateDrawMode(seriesModel); }, CandlestickView.prototype.incrementalRender = function(params, seriesModel, ecModel, api) { this._isLargeDraw ? this._incrementalRenderLarge(params, seriesModel) : this._incrementalRenderNormal(params, seriesModel); }, CandlestickView.prototype._updateDrawMode = function(seriesModel) { var isLargeDraw = seriesModel.pipelineContext.large; (null == this._isLargeDraw || isLargeDraw !== this._isLargeDraw) && (this._isLargeDraw = isLargeDraw, this._clear()); }, CandlestickView.prototype._renderNormal = function(seriesModel) { var data = seriesModel.getData(), oldData = this._data, group = this.group, isSimpleBox = data.getLayout('isSimpleBox'), needsClip = seriesModel.get('clip', !0), coord = seriesModel.coordinateSystem, clipArea = coord.getArea && coord.getArea(); this._data || group.removeAll(), data.diff(oldData).add(function(newIdx) { if (data.hasValue(newIdx)) { var itemLayout = data.getItemLayout(newIdx); if (!(needsClip && isNormalBoxClipped(clipArea, itemLayout))) { var el = createNormalBox$1(itemLayout, newIdx, !0); initProps(el, { shape: { points: itemLayout.ends } }, seriesModel, newIdx), setBoxCommon(el, data, newIdx, isSimpleBox), group.add(el), data.setItemGraphicEl(newIdx, el); } } }).update(function(newIdx, oldIdx) { var el = oldData.getItemGraphicEl(oldIdx); if (!data.hasValue(newIdx)) { group.remove(el); return; } var itemLayout = data.getItemLayout(newIdx); if (needsClip && isNormalBoxClipped(clipArea, itemLayout)) { group.remove(el); return; } el ? updateProps(el, { shape: { points: itemLayout.ends } }, seriesModel, newIdx) : el = createNormalBox$1(itemLayout), setBoxCommon(el, data, newIdx, isSimpleBox), group.add(el), data.setItemGraphicEl(newIdx, el); }).remove(function(oldIdx) { var el = oldData.getItemGraphicEl(oldIdx); el && group.remove(el); }).execute(), this._data = data; }, CandlestickView.prototype._renderLarge = function(seriesModel) { this._clear(), createLarge$1(seriesModel, this.group); var clipPath = seriesModel.get('clip', !0) ? createClipPath(seriesModel.coordinateSystem, !1, seriesModel) : null; clipPath ? this.group.setClipPath(clipPath) : this.group.removeClipPath(); }, CandlestickView.prototype._incrementalRenderNormal = function(params, seriesModel) { for(var dataIndex, data = seriesModel.getData(), isSimpleBox = data.getLayout('isSimpleBox'); null != (dataIndex = params.next());){ var el = createNormalBox$1(data.getItemLayout(dataIndex)); setBoxCommon(el, data, dataIndex, isSimpleBox), el.incremental = !0, this.group.add(el); } }, CandlestickView.prototype._incrementalRenderLarge = function(params, seriesModel) { createLarge$1(seriesModel, this.group, !0); }, CandlestickView.prototype.remove = function(ecModel) { this._clear(); }, CandlestickView.prototype._clear = function() { this.group.removeAll(), this._data = null; }, CandlestickView.type = 'candlestick', CandlestickView; }(ChartView), NormalBoxPathShape = function() {}, NormalBoxPath = function(_super) { function NormalBoxPath(opts) { var _this = _super.call(this, opts) || this; return _this.type = 'normalCandlestickBox', _this; } return __extends(NormalBoxPath, _super), NormalBoxPath.prototype.getDefaultShape = function() { return new NormalBoxPathShape(); }, NormalBoxPath.prototype.buildPath = function(ctx, shape) { var ends = shape.points; this.__simpleBox ? (ctx.moveTo(ends[4][0], ends[4][1]), ctx.lineTo(ends[6][0], ends[6][1])) : (ctx.moveTo(ends[0][0], ends[0][1]), ctx.lineTo(ends[1][0], ends[1][1]), ctx.lineTo(ends[2][0], ends[2][1]), ctx.lineTo(ends[3][0], ends[3][1]), ctx.closePath(), ctx.moveTo(ends[4][0], ends[4][1]), ctx.lineTo(ends[5][0], ends[5][1]), ctx.moveTo(ends[6][0], ends[6][1]), ctx.lineTo(ends[7][0], ends[7][1])); }, NormalBoxPath; }(Path); function createNormalBox$1(itemLayout, dataIndex, isInit) { var ends = itemLayout.ends; return new NormalBoxPath({ shape: { points: isInit ? map(ends, function(point) { return (point = point.slice())[1] = itemLayout.initBaseline, point; }) : ends }, z2: 100 }); } function isNormalBoxClipped(clipArea, itemLayout) { for(var clipped = !0, i = 0; i < itemLayout.ends.length; i++)if (clipArea.contain(itemLayout.ends[i][0], itemLayout.ends[i][1])) { clipped = !1; break; } return clipped; } function setBoxCommon(el, data, dataIndex, isSimpleBox) { var itemModel = data.getItemModel(dataIndex); el.useStyle(data.getItemVisual(dataIndex, 'style')), el.style.strokeNoScale = !0, el.__simpleBox = isSimpleBox, setStatesStylesFromModel(el, itemModel); } var LargeBoxPathShape = function() {}, LargeBoxPath = function(_super) { function LargeBoxPath(opts) { var _this = _super.call(this, opts) || this; return _this.type = 'largeCandlestickBox', _this; } return __extends(LargeBoxPath, _super), LargeBoxPath.prototype.getDefaultShape = function() { return new LargeBoxPathShape(); }, LargeBoxPath.prototype.buildPath = function(ctx, shape) { for(var points = shape.points, i = 0; i < points.length;)if (this.__sign === points[i++]) { var x = points[i++]; ctx.moveTo(x, points[i++]), ctx.lineTo(x, points[i++]); } else i += 3; }, LargeBoxPath; }(Path); function createLarge$1(seriesModel, group, incremental) { var largePoints = seriesModel.getData().getLayout('largePoints'), elP = new LargeBoxPath({ shape: { points: largePoints }, __sign: 1 }); group.add(elP); var elN = new LargeBoxPath({ shape: { points: largePoints }, __sign: -1 }); group.add(elN), setLargeStyle$1(1, elP, seriesModel), setLargeStyle$1(-1, elN, seriesModel), incremental && (elP.incremental = !0, elN.incremental = !0); } function setLargeStyle$1(sign, el, seriesModel, data) { var borderColor = seriesModel.get([ 'itemStyle', sign > 0 ? 'borderColor' : 'borderColor0' ]) || seriesModel.get([ 'itemStyle', sign > 0 ? 'color' : 'color0' ]), itemStyle = seriesModel.getModel('itemStyle').getItemStyle(SKIP_PROPS); el.useStyle(itemStyle), el.style.fill = null, el.style.stroke = borderColor; } var CandlestickSeriesModel = function(_super) { function CandlestickSeriesModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = CandlestickSeriesModel.type, _this.defaultValueDimensions = [ { name: 'open', defaultTooltip: !0 }, { name: 'close', defaultTooltip: !0 }, { name: 'lowest', defaultTooltip: !0 }, { name: 'highest', defaultTooltip: !0 } ], _this; } return __extends(CandlestickSeriesModel, _super), CandlestickSeriesModel.prototype.getShadowDim = function() { return 'open'; }, CandlestickSeriesModel.prototype.brushSelector = function(dataIndex, data, selectors) { var itemLayout = data.getItemLayout(dataIndex); return itemLayout && selectors.rect(itemLayout.brushRect); }, CandlestickSeriesModel.type = 'series.candlestick', CandlestickSeriesModel.dependencies = [ 'xAxis', 'yAxis', 'grid' ], CandlestickSeriesModel.defaultOption = { zlevel: 0, z: 2, coordinateSystem: 'cartesian2d', legendHoverLink: !0, layout: null, clip: !0, itemStyle: { color: '#eb5454', color0: '#47b262', borderColor: '#eb5454', borderColor0: '#47b262', borderWidth: 1 }, emphasis: { scale: !0, itemStyle: { borderWidth: 2 } }, barMaxWidth: null, barMinWidth: null, barWidth: null, large: !0, largeThreshold: 600, progressive: 3e3, progressiveThreshold: 1e4, progressiveChunkMode: 'mod', animationEasing: 'linear', animationDuration: 300 }, CandlestickSeriesModel; }(SeriesModel); function candlestickPreprocessor(option) { option && isArray(option.series) && each(option.series, function(seriesItem) { isObject(seriesItem) && 'k' === seriesItem.type && (seriesItem.type = 'candlestick'); }); } mixin(CandlestickSeriesModel, WhiskerBoxCommonMixin, !0); var positiveBorderColorQuery = [ 'itemStyle', 'borderColor' ], negativeBorderColorQuery = [ 'itemStyle', 'borderColor0' ], positiveColorQuery = [ 'itemStyle', 'color' ], negativeColorQuery = [ 'itemStyle', 'color0' ], candlestickVisual = { seriesType: 'candlestick', plan: createRenderPlanner(), performRawSeries: !0, reset: function(seriesModel, ecModel) { if (seriesModel.getData(), !ecModel.isSeriesFiltered(seriesModel)) return !seriesModel.pipelineContext.large && { progress: function(params, data) { for(var dataIndex; null != (dataIndex = params.next());){ var itemModel = data.getItemModel(dataIndex), sign = data.getItemLayout(dataIndex).sign, style = itemModel.getItemStyle(); style.fill = itemModel.get(sign > 0 ? positiveColorQuery : negativeColorQuery), style.stroke = itemModel.get(sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery) || style.fill, extend(data.ensureUniqueItemVisual(dataIndex, 'style'), style); } } }; } }, LargeArr$1 = 'undefined' != typeof Float32Array ? Float32Array : Array, candlestickLayout = { seriesType: 'candlestick', plan: createRenderPlanner(), reset: function(seriesModel) { var extent, baseAxis, bandWidth, barMaxWidth, barMinWidth, barWidth, coordSys = seriesModel.coordinateSystem, data = seriesModel.getData(), candleWidth = (bandWidth = 'category' === (baseAxis = seriesModel.getBaseAxis()).type ? baseAxis.getBandWidth() : Math.abs((extent = baseAxis.getExtent())[1] - extent[0]) / data.count(), barMaxWidth = parsePercent$1(retrieve2(seriesModel.get('barMaxWidth'), bandWidth), bandWidth), barMinWidth = parsePercent$1(retrieve2(seriesModel.get('barMinWidth'), 1), bandWidth), null != (barWidth = seriesModel.get('barWidth')) ? parsePercent$1(barWidth, bandWidth) : Math.max(Math.min(bandWidth / 2, barMaxWidth), barMinWidth)), cDim = data.mapDimension('x'), vDims = data.mapDimensionsAll('y'), openDim = vDims[0], closeDim = vDims[1], lowestDim = vDims[2], highestDim = vDims[3]; if (data.setLayout({ candleWidth: candleWidth, isSimpleBox: candleWidth <= 1.3 }), null != cDim && !(vDims.length < 4)) return { progress: seriesModel.pipelineContext.large ? function(params, data) { for(var point, dataIndex, points = new LargeArr$1(4 * params.count), offset = 0, tmpIn = [], tmpOut = []; null != (dataIndex = params.next());){ var axisDimVal = data.get(cDim, dataIndex), openVal = data.get(openDim, dataIndex), closeVal = data.get(closeDim, dataIndex), lowestVal = data.get(lowestDim, dataIndex), highestVal = data.get(highestDim, dataIndex); if (isNaN(axisDimVal) || isNaN(lowestVal) || isNaN(highestVal)) { points[offset++] = NaN, offset += 3; continue; } points[offset++] = getSign(data, dataIndex, openVal, closeVal, closeDim), tmpIn[0] = axisDimVal, tmpIn[1] = lowestVal, point = coordSys.dataToPoint(tmpIn, null, tmpOut), points[offset++] = point ? point[0] : NaN, points[offset++] = point ? point[1] : NaN, tmpIn[1] = highestVal, point = coordSys.dataToPoint(tmpIn, null, tmpOut), points[offset++] = point ? point[1] : NaN; } data.setLayout('largePoints', points); } : function(params, data) { for(var dataIndex; null != (dataIndex = params.next());){ var axisDimVal = data.get(cDim, dataIndex), openVal = data.get(openDim, dataIndex), closeVal = data.get(closeDim, dataIndex), lowestVal = data.get(lowestDim, dataIndex), highestVal = data.get(highestDim, dataIndex), ocLow = Math.min(openVal, closeVal), ocHigh = Math.max(openVal, closeVal), ocLowPoint = getPoint(ocLow, axisDimVal), ocHighPoint = getPoint(ocHigh, axisDimVal), lowestPoint = getPoint(lowestVal, axisDimVal), highestPoint = getPoint(highestVal, axisDimVal), ends = []; addBodyEnd(ends, ocHighPoint, 0), addBodyEnd(ends, ocLowPoint, 1), ends.push(subPixelOptimizePoint(highestPoint), subPixelOptimizePoint(ocHighPoint), subPixelOptimizePoint(lowestPoint), subPixelOptimizePoint(ocLowPoint)), data.setItemLayout(dataIndex, { sign: getSign(data, dataIndex, openVal, closeVal, closeDim), initBaseline: openVal > closeVal ? ocHighPoint[1] : ocLowPoint[1], ends: ends, brushRect: function(lowestVal, highestVal, axisDimVal) { var pmin = getPoint(lowestVal, axisDimVal), pmax = getPoint(highestVal, axisDimVal); return pmin[0] -= candleWidth / 2, pmax[0] -= candleWidth / 2, { x: pmin[0], y: pmin[1], width: candleWidth, height: pmax[1] - pmin[1] }; }(lowestVal, highestVal, axisDimVal) }); } function getPoint(val, axisDimVal) { var p = []; return p[0] = axisDimVal, p[1] = val, isNaN(axisDimVal) || isNaN(val) ? [ NaN, NaN ] : coordSys.dataToPoint(p); } function addBodyEnd(ends, point, start) { var point1 = point.slice(), point2 = point.slice(); point1[0] = subPixelOptimize(point1[0] + candleWidth / 2, 1, !1), point2[0] = subPixelOptimize(point2[0] - candleWidth / 2, 1, !0), start ? ends.push(point1, point2) : ends.push(point2, point1); } function subPixelOptimizePoint(point) { return point[0] = subPixelOptimize(point[0], 1), point; } } }; } }; function getSign(data, dataIndex, openVal, closeVal, closeDim) { return openVal > closeVal ? -1 : openVal < closeVal ? 1 : dataIndex > 0 ? data.get(closeDim, dataIndex - 1) <= closeVal ? 1 : -1 : 1; } function updateRipplePath(rippleGroup, effectCfg) { var color = effectCfg.rippleEffectColor || effectCfg.color; rippleGroup.eachChild(function(ripplePath) { ripplePath.attr({ z: effectCfg.z, zlevel: effectCfg.zlevel, style: { stroke: 'stroke' === effectCfg.brushType ? color : null, fill: 'fill' === effectCfg.brushType ? color : null } }); }); } var EffectSymbol = function(_super) { function EffectSymbol(data, idx) { var _this = _super.call(this) || this, symbol = new Symbol(data, idx), rippleGroup = new Group(); return _this.add(symbol), _this.add(rippleGroup), _this.updateData(data, idx), _this; } return __extends(EffectSymbol, _super), EffectSymbol.prototype.stopEffectAnimation = function() { this.childAt(1).removeAll(); }, EffectSymbol.prototype.startEffectAnimation = function(effectCfg) { for(var symbolType = effectCfg.symbolType, color = effectCfg.color, rippleGroup = this.childAt(1), i = 0; i < 3; i++){ var ripplePath = createSymbol(symbolType, -1, -1, 2, 2, color); ripplePath.attr({ style: { strokeNoScale: !0 }, z2: 99, silent: !0, scaleX: 0.5, scaleY: 0.5 }); var delay = -i / 3 * effectCfg.period + effectCfg.effectOffset; ripplePath.animate('', !0).when(effectCfg.period, { scaleX: effectCfg.rippleScale / 2, scaleY: effectCfg.rippleScale / 2 }).delay(delay).start(), ripplePath.animateStyle(!0).when(effectCfg.period, { opacity: 0 }).delay(delay).start(), rippleGroup.add(ripplePath); } updateRipplePath(rippleGroup, effectCfg); }, EffectSymbol.prototype.updateEffectAnimation = function(effectCfg) { for(var oldEffectCfg = this._effectCfg, rippleGroup = this.childAt(1), DIFFICULT_PROPS = [ 'symbolType', 'period', 'rippleScale' ], i = 0; i < DIFFICULT_PROPS.length; i++){ var propName = DIFFICULT_PROPS[i]; if (oldEffectCfg[propName] !== effectCfg[propName]) { this.stopEffectAnimation(), this.startEffectAnimation(effectCfg); return; } } updateRipplePath(rippleGroup, effectCfg); }, EffectSymbol.prototype.highlight = function() { enterEmphasis(this); }, EffectSymbol.prototype.downplay = function() { leaveEmphasis(this); }, EffectSymbol.prototype.updateData = function(data, idx) { var symbolSize, _this = this, seriesModel = data.hostModel; this.childAt(0).updateData(data, idx); var rippleGroup = this.childAt(1), itemModel = data.getItemModel(idx), symbolType = data.getItemVisual(idx, 'symbol'), symbolSize1 = (isArray(symbolSize = data.getItemVisual(idx, 'symbolSize')) || (symbolSize = [ +symbolSize, +symbolSize ]), symbolSize), symbolStyle = data.getItemVisual(idx, 'style'), color = symbolStyle && symbolStyle.fill; rippleGroup.setScale(symbolSize1), rippleGroup.traverse(function(ripplePath) { ripplePath.setStyle('fill', color); }); var symbolOffset = data.getItemVisual(idx, 'symbolOffset'); symbolOffset && (isArray(symbolOffset) || (symbolOffset = [ symbolOffset, symbolOffset ]), rippleGroup.x = parsePercent$1(symbolOffset[0], symbolSize1[0]), rippleGroup.y = parsePercent$1(retrieve2(symbolOffset[1], symbolOffset[0]) || 0, symbolSize1[1])); var symbolRotate = data.getItemVisual(idx, 'symbolRotate'); rippleGroup.rotation = (symbolRotate || 0) * Math.PI / 180 || 0; var effectCfg = {}; effectCfg.showEffectOn = seriesModel.get('showEffectOn'), effectCfg.rippleScale = itemModel.get([ 'rippleEffect', 'scale' ]), effectCfg.brushType = itemModel.get([ 'rippleEffect', 'brushType' ]), effectCfg.period = 1000 * itemModel.get([ 'rippleEffect', 'period' ]), effectCfg.effectOffset = idx / data.count(), effectCfg.z = seriesModel.getShallow('z') || 0, effectCfg.zlevel = seriesModel.getShallow('zlevel') || 0, effectCfg.symbolType = symbolType, effectCfg.color = color, effectCfg.rippleEffectColor = itemModel.get([ 'rippleEffect', 'color' ]), this.off('mouseover').off('mouseout').off('emphasis').off('normal'), 'render' === effectCfg.showEffectOn ? (this._effectCfg ? this.updateEffectAnimation(effectCfg) : this.startEffectAnimation(effectCfg), this._effectCfg = effectCfg) : (this._effectCfg = null, this.stopEffectAnimation(), this.onHoverStateChange = function(toState) { 'emphasis' === toState ? 'render' !== effectCfg.showEffectOn && _this.startEffectAnimation(effectCfg) : 'normal' === toState && 'render' !== effectCfg.showEffectOn && _this.stopEffectAnimation(); }), this._effectCfg = effectCfg, enableHoverEmphasis(this); }, EffectSymbol.prototype.fadeOut = function(cb) { this.off('mouseover').off('mouseout'), cb && cb(); }, EffectSymbol; }(Group), EffectScatterView = function(_super) { function EffectScatterView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = EffectScatterView.type, _this; } return __extends(EffectScatterView, _super), EffectScatterView.prototype.init = function() { this._symbolDraw = new SymbolDraw(EffectSymbol); }, EffectScatterView.prototype.render = function(seriesModel, ecModel, api) { var data = seriesModel.getData(), effectSymbolDraw = this._symbolDraw; effectSymbolDraw.updateData(data, { clipShape: this._getClipShape(seriesModel) }), this.group.add(effectSymbolDraw.group); }, EffectScatterView.prototype._getClipShape = function(seriesModel) { var coordSys = seriesModel.coordinateSystem, clipArea = coordSys && coordSys.getArea && coordSys.getArea(); return seriesModel.get('clip', !0) ? clipArea : null; }, EffectScatterView.prototype.updateTransform = function(seriesModel, ecModel, api) { var data = seriesModel.getData(); this.group.dirty(); var res = pointsLayout('').reset(seriesModel, ecModel, api); res.progress && res.progress({ start: 0, end: data.count(), count: data.count() }, data), this._symbolDraw.updateLayout(); }, EffectScatterView.prototype._updateGroupTransform = function(seriesModel) { var coordSys = seriesModel.coordinateSystem; coordSys && coordSys.getRoamTransform && (this.group.transform = clone$2(coordSys.getRoamTransform()), this.group.decomposeTransform()); }, EffectScatterView.prototype.remove = function(ecModel, api) { this._symbolDraw && this._symbolDraw.remove(!0); }, EffectScatterView.type = 'effectScatter', EffectScatterView; }(ChartView), EffectScatterSeriesModel = function(_super) { function EffectScatterSeriesModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = EffectScatterSeriesModel.type, _this.hasSymbolVisual = !0, _this; } return __extends(EffectScatterSeriesModel, _super), EffectScatterSeriesModel.prototype.getInitialData = function(option, ecModel) { return createListFromArray(this.getSource(), this, { useEncodeDefaulter: !0 }); }, EffectScatterSeriesModel.prototype.brushSelector = function(dataIndex, data, selectors) { return selectors.point(data.getItemLayout(dataIndex)); }, EffectScatterSeriesModel.type = 'series.effectScatter', EffectScatterSeriesModel.dependencies = [ 'grid', 'polar' ], EffectScatterSeriesModel.defaultOption = { coordinateSystem: 'cartesian2d', zlevel: 0, z: 2, legendHoverLink: !0, effectType: 'ripple', progressive: 0, showEffectOn: 'render', clip: !0, rippleEffect: { period: 4, scale: 2.5, brushType: 'fill' }, symbolSize: 10 }, EffectScatterSeriesModel; }(SeriesModel), EffectLine = function(_super) { function EffectLine(lineData, idx, seriesScope) { var _this = _super.call(this) || this; return _this.add(_this.createLine(lineData, idx, seriesScope)), _this._updateEffectSymbol(lineData, idx), _this; } return __extends(EffectLine, _super), EffectLine.prototype.createLine = function(lineData, idx, seriesScope) { return new Line$1(lineData, idx, seriesScope); }, EffectLine.prototype._updateEffectSymbol = function(lineData, idx) { var effectModel = lineData.getItemModel(idx).getModel('effect'), size = effectModel.get('symbolSize'), symbolType = effectModel.get('symbol'); isArray(size) || (size = [ size, size ]); var lineStyle = lineData.getItemVisual(idx, 'style'), color = effectModel.get('color') || lineStyle && lineStyle.stroke, symbol = this.childAt(1); this._symbolType !== symbolType && (this.remove(symbol), (symbol = createSymbol(symbolType, -0.5, -0.5, 1, 1, color)).z2 = 100, symbol.culling = !0, this.add(symbol)), symbol && (symbol.setStyle('shadowColor', color), symbol.setStyle(effectModel.getItemStyle([ 'color' ])), symbol.scaleX = size[0], symbol.scaleY = size[1], symbol.setColor(color), this._symbolType = symbolType, this._symbolScale = size, this._updateEffectAnimation(lineData, effectModel, idx)); }, EffectLine.prototype._updateEffectAnimation = function(lineData, effectModel, idx) { var symbol = this.childAt(1); if (symbol) { var self1 = this, points = lineData.getItemLayout(idx), period = 1000 * effectModel.get('period'), loop = effectModel.get('loop'), constantSpeed = effectModel.get('constantSpeed'), delayExpr = retrieve(effectModel.get('delay'), function(idx) { return idx / lineData.count() * period / 3; }); if (symbol.ignore = !0, this._updateAnimationPoints(symbol, points), constantSpeed > 0 && (period = this._getLineLength(symbol) / constantSpeed * 1000), (period !== this._period || loop !== this._loop) && (symbol.stopAnimation(), period > 0)) { var delayNum = void 0; delayNum = 'function' == typeof delayExpr ? delayExpr(idx) : delayExpr, symbol.__t > 0 && (delayNum = -period * symbol.__t), symbol.__t = 0; var animator = symbol.animate('', loop).when(period, { __t: 1 }).delay(delayNum).during(function() { self1._updateSymbolPosition(symbol); }); loop || animator.done(function() { self1.remove(symbol); }), animator.start(); } this._period = period, this._loop = loop; } }, EffectLine.prototype._getLineLength = function(symbol) { return distance(symbol.__p1, symbol.__cp1) + distance(symbol.__cp1, symbol.__p2); }, EffectLine.prototype._updateAnimationPoints = function(symbol, points) { symbol.__p1 = points[0], symbol.__p2 = points[1], symbol.__cp1 = points[2] || [ (points[0][0] + points[1][0]) / 2, (points[0][1] + points[1][1]) / 2 ]; }, EffectLine.prototype.updateData = function(lineData, idx, seriesScope) { this.childAt(0).updateData(lineData, idx, seriesScope), this._updateEffectSymbol(lineData, idx); }, EffectLine.prototype._updateSymbolPosition = function(symbol) { var p1 = symbol.__p1, p2 = symbol.__p2, cp1 = symbol.__cp1, t = symbol.__t, pos = [ symbol.x, symbol.y ], lastPos = pos.slice(); pos[0] = quadraticAt(p1[0], cp1[0], p2[0], t), pos[1] = quadraticAt(p1[1], cp1[1], p2[1], t); var tx = quadraticDerivativeAt(p1[0], cp1[0], p2[0], t), ty = quadraticDerivativeAt(p1[1], cp1[1], p2[1], t); symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2, ('line' === this._symbolType || 'rect' === this._symbolType || 'roundRect' === this._symbolType) && (void 0 !== symbol.__lastT && symbol.__lastT < symbol.__t ? (symbol.scaleY = 1.05 * distance(lastPos, pos), 1 === t && (pos[0] = lastPos[0] + (pos[0] - lastPos[0]) / 2, pos[1] = lastPos[1] + (pos[1] - lastPos[1]) / 2)) : 1 === symbol.__lastT ? symbol.scaleY = 2 * distance(p1, pos) : symbol.scaleY = this._symbolScale[1]), symbol.__lastT = symbol.__t, symbol.ignore = !1, symbol.x = pos[0], symbol.y = pos[1]; }, EffectLine.prototype.updateLayout = function(lineData, idx) { this.childAt(0).updateLayout(lineData, idx); var effectModel = lineData.getItemModel(idx).getModel('effect'); this._updateEffectAnimation(lineData, effectModel, idx); }, EffectLine; }(Group), Polyline$1 = function(_super) { function Polyline$1(lineData, idx, seriesScope) { var _this = _super.call(this) || this; return _this._createPolyline(lineData, idx, seriesScope), _this; } return __extends(Polyline$1, _super), Polyline$1.prototype._createPolyline = function(lineData, idx, seriesScope) { var points = lineData.getItemLayout(idx), line = new Polyline({ shape: { points: points } }); this.add(line), this._updateCommonStl(lineData, idx, seriesScope); }, Polyline$1.prototype.updateData = function(lineData, idx, seriesScope) { var seriesModel = lineData.hostModel; updateProps(this.childAt(0), { shape: { points: lineData.getItemLayout(idx) } }, seriesModel, idx), this._updateCommonStl(lineData, idx, seriesScope); }, Polyline$1.prototype._updateCommonStl = function(lineData, idx, seriesScope) { var line = this.childAt(0), itemModel = lineData.getItemModel(idx), hoverLineStyle = seriesScope && seriesScope.emphasisLineStyle; (!seriesScope || lineData.hasItemOption) && (hoverLineStyle = itemModel.getModel([ 'emphasis', 'lineStyle' ]).getLineStyle()), line.useStyle(lineData.getItemVisual(idx, 'style')), line.style.fill = null, line.style.strokeNoScale = !0, line.ensureState('emphasis').style = hoverLineStyle, enableHoverEmphasis(this); }, Polyline$1.prototype.updateLayout = function(lineData, idx) { this.childAt(0).setShape('points', lineData.getItemLayout(idx)); }, Polyline$1; }(Group), EffectPolyline = function(_super) { function EffectPolyline() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this._lastFrame = 0, _this._lastFramePercent = 0, _this; } return __extends(EffectPolyline, _super), EffectPolyline.prototype.createLine = function(lineData, idx, seriesScope) { return new Polyline$1(lineData, idx, seriesScope); }, EffectPolyline.prototype._updateAnimationPoints = function(symbol, points) { this._points = points; for(var accLenArr = [ 0 ], len = 0, i = 1; i < points.length; i++)len += distance(points[i - 1], points[i]), accLenArr.push(len); if (0 === len) { this._length = 0; return; } for(var i = 0; i < accLenArr.length; i++)accLenArr[i] /= len; this._offsets = accLenArr, this._length = len; }, EffectPolyline.prototype._getLineLength = function() { return this._length; }, EffectPolyline.prototype._updateSymbolPosition = function(symbol) { var frame, t = symbol.__t, points = this._points, offsets = this._offsets, len = points.length; if (offsets) { var lastFrame = this._lastFrame; if (t < this._lastFramePercent) { var start = Math.min(lastFrame + 1, len - 1); for(frame = start; frame >= 0 && !(offsets[frame] <= t); frame--); frame = Math.min(frame, len - 2); } else { for(frame = lastFrame; frame < len && !(offsets[frame] > t); frame++); frame = Math.min(frame - 1, len - 2); } var p = (t - offsets[frame]) / (offsets[frame + 1] - offsets[frame]), p0 = points[frame], p1 = points[frame + 1]; symbol.x = p0[0] * (1 - p) + p * p1[0], symbol.y = p0[1] * (1 - p) + p * p1[1]; var tx = p1[0] - p0[0], ty = p1[1] - p0[1]; symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2, this._lastFrame = frame, this._lastFramePercent = t, symbol.ignore = !1; } }, EffectPolyline; }(EffectLine), LargeLinesPathShape = function() { this.polyline = !1, this.curveness = 0, this.segs = []; }, LargeLinesPath = function(_super) { function LargeLinesPath(opts) { return _super.call(this, opts) || this; } return __extends(LargeLinesPath, _super), LargeLinesPath.prototype.getDefaultStyle = function() { return { stroke: '#000', fill: null }; }, LargeLinesPath.prototype.getDefaultShape = function() { return new LargeLinesPathShape(); }, LargeLinesPath.prototype.buildPath = function(ctx, shape) { var segs = shape.segs, curveness = shape.curveness; if (shape.polyline) for(var i = 0; i < segs.length;){ var count = segs[i++]; if (count > 0) { ctx.moveTo(segs[i++], segs[i++]); for(var k = 1; k < count; k++)ctx.lineTo(segs[i++], segs[i++]); } } else for(var i = 0; i < segs.length;){ var x0 = segs[i++], y0 = segs[i++], x1 = segs[i++], y1 = segs[i++]; if (ctx.moveTo(x0, y0), curveness > 0) { var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness, y2 = (y0 + y1) / 2 - (x1 - x0) * curveness; ctx.quadraticCurveTo(x2, y2, x1, y1); } else ctx.lineTo(x1, y1); } }, LargeLinesPath.prototype.findDataIndex = function(x, y) { var shape = this.shape, segs = shape.segs, curveness = shape.curveness, lineWidth = this.style.lineWidth; if (shape.polyline) for(var dataIndex = 0, i = 0; i < segs.length;){ var count = segs[i++]; if (count > 0) for(var x0 = segs[i++], y0 = segs[i++], k = 1; k < count; k++){ var x1 = segs[i++], y1 = segs[i++]; if (containStroke(x0, y0, x1, y1, lineWidth, x, y)) return dataIndex; } dataIndex++; } else for(var dataIndex = 0, i = 0; i < segs.length;){ var x0 = segs[i++], y0 = segs[i++], x1 = segs[i++], y1 = segs[i++]; if (curveness > 0) { var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness, y2 = (y0 + y1) / 2 - (x1 - x0) * curveness; if (containStroke$2(x0, y0, x2, y2, x1, y1, lineWidth, x, y)) return dataIndex; } else if (containStroke(x0, y0, x1, y1, lineWidth, x, y)) return dataIndex; dataIndex++; } return -1; }, LargeLinesPath; }(Path), LargeLineDraw = function() { function LargeLineDraw() { this.group = new Group(); } return LargeLineDraw.prototype.isPersistent = function() { return !this._incremental; }, LargeLineDraw.prototype.updateData = function(data) { this.group.removeAll(); var lineEl = new LargeLinesPath({ rectHover: !0, cursor: 'default' }); lineEl.setShape({ segs: data.getLayout('linesPoints') }), this._setCommon(lineEl, data), this.group.add(lineEl), this._incremental = null; }, LargeLineDraw.prototype.incrementalPrepareUpdate = function(data) { this.group.removeAll(), this._clearIncremental(), data.count() > 5e5 ? (this._incremental || (this._incremental = new IncrementalDisplayable({ silent: !0 })), this.group.add(this._incremental)) : this._incremental = null; }, LargeLineDraw.prototype.incrementalUpdate = function(taskParams, data) { var lineEl = new LargeLinesPath(); lineEl.setShape({ segs: data.getLayout('linesPoints') }), this._setCommon(lineEl, data, !!this._incremental), this._incremental ? this._incremental.addDisplayable(lineEl, !0) : (lineEl.rectHover = !0, lineEl.cursor = 'default', lineEl.__startIndex = taskParams.start, this.group.add(lineEl)); }, LargeLineDraw.prototype.remove = function() { this._clearIncremental(), this._incremental = null, this.group.removeAll(); }, LargeLineDraw.prototype._setCommon = function(lineEl, data, isIncremental) { var hostModel = data.hostModel; lineEl.setShape({ polyline: hostModel.get('polyline'), curveness: hostModel.get([ 'lineStyle', 'curveness' ]) }), lineEl.useStyle(hostModel.getModel('lineStyle').getLineStyle()), lineEl.style.strokeNoScale = !0; var style = data.getVisual('style'); if (style && style.stroke && lineEl.setStyle('stroke', style.stroke), lineEl.setStyle('fill', null), !isIncremental) { var ecData_1 = getECData(lineEl); ecData_1.seriesIndex = hostModel.seriesIndex, lineEl.on('mousemove', function(e) { ecData_1.dataIndex = null; var dataIndex = lineEl.findDataIndex(e.offsetX, e.offsetY); dataIndex > 0 && (ecData_1.dataIndex = dataIndex + lineEl.__startIndex); }); } }, LargeLineDraw.prototype._clearIncremental = function() { var incremental = this._incremental; incremental && incremental.clearDisplaybles(); }, LargeLineDraw; }(), linesLayout = { seriesType: 'lines', plan: createRenderPlanner(), reset: function(seriesModel) { var coordSys = seriesModel.coordinateSystem, isPolyline = seriesModel.get('polyline'), isLarge = seriesModel.pipelineContext.large; return { progress: function(params, lineData) { var lineCoords = []; if (isLarge) { var points = void 0, segCount = params.end - params.start; if (isPolyline) { for(var totalCoordsCount = 0, i = params.start; i < params.end; i++)totalCoordsCount += seriesModel.getLineCoordsCount(i); points = new Float32Array(segCount + 2 * totalCoordsCount); } else points = new Float32Array(4 * segCount); for(var offset = 0, pt = [], i = params.start; i < params.end; i++){ var len = seriesModel.getLineCoords(i, lineCoords); isPolyline && (points[offset++] = len); for(var k = 0; k < len; k++)pt = coordSys.dataToPoint(lineCoords[k], !1, pt), points[offset++] = pt[0], points[offset++] = pt[1]; } lineData.setLayout('linesPoints', points); } else for(var i = params.start; i < params.end; i++){ var itemModel = lineData.getItemModel(i), len = seriesModel.getLineCoords(i, lineCoords), pts = []; if (isPolyline) for(var j = 0; j < len; j++)pts.push(coordSys.dataToPoint(lineCoords[j])); else { pts[0] = coordSys.dataToPoint(lineCoords[0]), pts[1] = coordSys.dataToPoint(lineCoords[1]); var curveness = itemModel.get([ 'lineStyle', 'curveness' ]); +curveness && (pts[2] = [ (pts[0][0] + pts[1][0]) / 2 - (pts[0][1] - pts[1][1]) * curveness, (pts[0][1] + pts[1][1]) / 2 - (pts[1][0] - pts[0][0]) * curveness ]); } lineData.setItemLayout(i, pts); } } }; } }, LinesView = function(_super) { function LinesView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = LinesView.type, _this; } return __extends(LinesView, _super), LinesView.prototype.render = function(seriesModel, ecModel, api) { var data = seriesModel.getData(), lineDraw = this._updateLineDraw(data, seriesModel), zlevel = seriesModel.get('zlevel'), trailLength = seriesModel.get([ 'effect', 'trailLength' ]), zr = api.getZr(), isSvg = 'svg' === zr.painter.getType(); if (isSvg || zr.painter.getLayer(zlevel).clear(!0), null == this._lastZlevel || isSvg || zr.configLayer(this._lastZlevel, { motionBlur: !1 }), this._showEffect(seriesModel) && trailLength) { var notInIndividual_1 = !1; ecModel.eachSeries(function(otherSeriesModel) { otherSeriesModel !== seriesModel && otherSeriesModel.get('zlevel') === zlevel && (notInIndividual_1 = !0); }), notInIndividual_1 && console.warn('Lines with trail effect should have an individual zlevel'), isSvg || zr.configLayer(zlevel, { motionBlur: !0, lastFrameAlpha: Math.max(Math.min(trailLength / 10 + 0.9, 1), 0) }); } lineDraw.updateData(data); var clipPath = seriesModel.get('clip', !0) && createClipPath(seriesModel.coordinateSystem, !1, seriesModel); clipPath ? this.group.setClipPath(clipPath) : this.group.removeClipPath(), this._lastZlevel = zlevel, this._finished = !0; }, LinesView.prototype.incrementalPrepareRender = function(seriesModel, ecModel, api) { var data = seriesModel.getData(); this._updateLineDraw(data, seriesModel).incrementalPrepareUpdate(data), this._clearLayer(api), this._finished = !1; }, LinesView.prototype.incrementalRender = function(taskParams, seriesModel, ecModel) { this._lineDraw.incrementalUpdate(taskParams, seriesModel.getData()), this._finished = taskParams.end === seriesModel.getData().count(); }, LinesView.prototype.updateTransform = function(seriesModel, ecModel, api) { var data = seriesModel.getData(), pipelineContext = seriesModel.pipelineContext; if (!this._finished || pipelineContext.large || pipelineContext.progressiveRender) return { update: !0 }; var res = linesLayout.reset(seriesModel, ecModel, api); res.progress && res.progress({ start: 0, end: data.count(), count: data.count() }, data), this._lineDraw.updateLayout(), this._clearLayer(api); }, LinesView.prototype._updateLineDraw = function(data, seriesModel) { var lineDraw = this._lineDraw, hasEffect = this._showEffect(seriesModel), isPolyline = !!seriesModel.get('polyline'), isLargeDraw = seriesModel.pipelineContext.large; return hasEffect && isLargeDraw && console.warn('Large lines not support effect'), lineDraw && hasEffect === this._hasEffet && isPolyline === this._isPolyline && isLargeDraw === this._isLargeDraw || (lineDraw && lineDraw.remove(), lineDraw = this._lineDraw = isLargeDraw ? new LargeLineDraw() : new LineDraw(isPolyline ? hasEffect ? EffectPolyline : Polyline$1 : hasEffect ? EffectLine : Line$1), this._hasEffet = hasEffect, this._isPolyline = isPolyline, this._isLargeDraw = isLargeDraw, this.group.removeAll()), this.group.add(lineDraw.group), lineDraw; }, LinesView.prototype._showEffect = function(seriesModel) { return !!seriesModel.get([ 'effect', 'show' ]); }, LinesView.prototype._clearLayer = function(api) { var zr = api.getZr(); 'svg' !== zr.painter.getType() && null != this._lastZlevel && zr.painter.getLayer(this._lastZlevel).clear(!0); }, LinesView.prototype.remove = function(ecModel, api) { this._lineDraw && this._lineDraw.remove(), this._lineDraw = null, this._clearLayer(api); }, LinesView.type = 'lines', LinesView; }(ChartView), Uint32Arr = 'undefined' == typeof Uint32Array ? Array : Uint32Array, Float64Arr = 'undefined' == typeof Float64Array ? Array : Float64Array; function compatEc2(seriesOpt) { var data = seriesOpt.data; data && data[0] && data[0][0] && data[0][0].coord && (console.warn("Lines data configuration has been changed to { coords:[[1,2],[2,3]] }"), seriesOpt.data = map(data, function(itemOpt) { var target = { coords: [ itemOpt[0].coord, itemOpt[1].coord ] }; return itemOpt[0].name && (target.fromName = itemOpt[0].name), itemOpt[1].name && (target.toName = itemOpt[1].name), mergeAll([ target, itemOpt[0], itemOpt[1] ]); })); } var LinesSeriesModel = function(_super) { function LinesSeriesModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = LinesSeriesModel.type, _this.visualStyleAccessPath = 'lineStyle', _this.visualDrawType = 'stroke', _this; } return __extends(LinesSeriesModel, _super), LinesSeriesModel.prototype.init = function(option) { option.data = option.data || [], compatEc2(option); var result = this._processFlatCoordsArray(option.data); this._flatCoords = result.flatCoords, this._flatCoordsOffset = result.flatCoordsOffset, result.flatCoords && (option.data = new Float32Array(result.count)), _super.prototype.init.apply(this, arguments); }, LinesSeriesModel.prototype.mergeOption = function(option) { if (compatEc2(option), option.data) { var result = this._processFlatCoordsArray(option.data); this._flatCoords = result.flatCoords, this._flatCoordsOffset = result.flatCoordsOffset, result.flatCoords && (option.data = new Float32Array(result.count)); } _super.prototype.mergeOption.apply(this, arguments); }, LinesSeriesModel.prototype.appendData = function(params) { var result = this._processFlatCoordsArray(params.data); result.flatCoords && (this._flatCoords ? (this._flatCoords = concatArray(this._flatCoords, result.flatCoords), this._flatCoordsOffset = concatArray(this._flatCoordsOffset, result.flatCoordsOffset)) : (this._flatCoords = result.flatCoords, this._flatCoordsOffset = result.flatCoordsOffset), params.data = new Float32Array(result.count)), this.getRawData().appendData(params.data); }, LinesSeriesModel.prototype._getCoordsFromItemModel = function(idx) { var itemModel = this.getData().getItemModel(idx), coords = itemModel.option instanceof Array ? itemModel.option : itemModel.getShallow('coords'); if (!(coords instanceof Array && coords.length > 0 && coords[0] instanceof Array)) throw Error('Invalid coords ' + JSON.stringify(coords) + '. Lines must have 2d coords array in data item.'); return coords; }, LinesSeriesModel.prototype.getLineCoordsCount = function(idx) { return this._flatCoordsOffset ? this._flatCoordsOffset[2 * idx + 1] : this._getCoordsFromItemModel(idx).length; }, LinesSeriesModel.prototype.getLineCoords = function(idx, out) { if (this._flatCoordsOffset) { for(var offset = this._flatCoordsOffset[2 * idx], len = this._flatCoordsOffset[2 * idx + 1], i = 0; i < len; i++)out[i] = out[i] || [], out[i][0] = this._flatCoords[offset + 2 * i], out[i][1] = this._flatCoords[offset + 2 * i + 1]; return len; } for(var coords = this._getCoordsFromItemModel(idx), i = 0; i < coords.length; i++)out[i] = out[i] || [], out[i][0] = coords[i][0], out[i][1] = coords[i][1]; return coords.length; }, LinesSeriesModel.prototype._processFlatCoordsArray = function(data) { var startOffset = 0; if (this._flatCoords && (startOffset = this._flatCoords.length), 'number' == typeof data[0]) { for(var len = data.length, coordsOffsetAndLenStorage = new Uint32Arr(len), coordsStorage = new Float64Arr(len), coordsCursor = 0, offsetCursor = 0, dataCount = 0, i = 0; i < len;){ dataCount++; var count = data[i++]; coordsOffsetAndLenStorage[offsetCursor++] = coordsCursor + startOffset, coordsOffsetAndLenStorage[offsetCursor++] = count; for(var k = 0; k < count; k++){ var x = data[i++], y = data[i++]; if (coordsStorage[coordsCursor++] = x, coordsStorage[coordsCursor++] = y, i > len) throw Error('Invalid data format.'); } } return { flatCoordsOffset: new Uint32Array(coordsOffsetAndLenStorage.buffer, 0, offsetCursor), flatCoords: coordsStorage, count: dataCount }; } return { flatCoordsOffset: null, flatCoords: null, count: data.length }; }, LinesSeriesModel.prototype.getInitialData = function(option, ecModel) { if (!CoordinateSystemManager.get(option.coordinateSystem)) throw Error('Unkown coordinate system ' + option.coordinateSystem); var lineData = new List([ 'value' ], this); return lineData.hasItemOption = !1, lineData.initData(option.data, [], function(dataItem, dimName, dataIndex, dimIndex) { if (dataItem instanceof Array) return NaN; lineData.hasItemOption = !0; var value = dataItem.value; if (null != value) return value instanceof Array ? value[dimIndex] : value; }), lineData; }, LinesSeriesModel.prototype.formatTooltip = function(dataIndex, multipleSeries, dataType) { var itemModel = this.getData().getItemModel(dataIndex), name = itemModel.get('name'); if (name) return name; var fromName = itemModel.get('fromName'), toName = itemModel.get('toName'), nameArr = []; return null != fromName && nameArr.push(fromName), null != toName && nameArr.push(toName), createTooltipMarkup('nameValue', { name: nameArr.join(' > ') }); }, LinesSeriesModel.prototype.preventIncremental = function() { return !!this.get([ 'effect', 'show' ]); }, LinesSeriesModel.prototype.getProgressive = function() { var progressive = this.option.progressive; return null == progressive ? this.option.large ? 1e4 : this.get('progressive') : progressive; }, LinesSeriesModel.prototype.getProgressiveThreshold = function() { var progressiveThreshold = this.option.progressiveThreshold; return null == progressiveThreshold ? this.option.large ? 2e4 : this.get('progressiveThreshold') : progressiveThreshold; }, LinesSeriesModel.type = 'series.lines', LinesSeriesModel.dependencies = [ 'grid', 'polar', 'geo', 'calendar' ], LinesSeriesModel.defaultOption = { coordinateSystem: 'geo', zlevel: 0, z: 2, legendHoverLink: !0, xAxisIndex: 0, yAxisIndex: 0, symbol: [ 'none', 'none' ], symbolSize: [ 10, 10 ], geoIndex: 0, effect: { show: !1, period: 4, constantSpeed: 0, symbol: 'circle', symbolSize: 3, loop: !0, trailLength: 0.2 }, large: !1, largeThreshold: 2000, polyline: !1, clip: !0, label: { show: !1, position: 'end' }, lineStyle: { opacity: 0.5 } }, LinesSeriesModel; }(SeriesModel); function normalize$3(a) { return a instanceof Array || (a = [ a, a ]), a; } var linesVisual = { seriesType: 'lines', reset: function(seriesModel) { var symbolType = normalize$3(seriesModel.get('symbol')), symbolSize = normalize$3(seriesModel.get('symbolSize')), data = seriesModel.getData(); return data.setVisual('fromSymbol', symbolType && symbolType[0]), data.setVisual('toSymbol', symbolType && symbolType[1]), data.setVisual('fromSymbolSize', symbolSize && symbolSize[0]), data.setVisual('toSymbolSize', symbolSize && symbolSize[1]), { dataEach: data.hasItemOption ? function(data, idx) { var itemModel = data.getItemModel(idx), symbolType = normalize$3(itemModel.getShallow('symbol', !0)), symbolSize = normalize$3(itemModel.getShallow('symbolSize', !0)); symbolType[0] && data.setItemVisual(idx, 'fromSymbol', symbolType[0]), symbolType[1] && data.setItemVisual(idx, 'toSymbol', symbolType[1]), symbolSize[0] && data.setItemVisual(idx, 'fromSymbolSize', symbolSize[0]), symbolSize[1] && data.setItemVisual(idx, 'toSymbolSize', symbolSize[1]); } : null }; } }, HeatmapLayer = function() { function HeatmapLayer() { this.blurSize = 30, this.pointSize = 20, this.maxOpacity = 1, this.minOpacity = 0, this._gradientPixels = { inRange: null, outOfRange: null }; var canvas = createCanvas(); this.canvas = canvas; } return HeatmapLayer.prototype.update = function(data, width, height, normalize, colorFunc, isInRange) { var brush = this._getBrush(), gradientInRange = this._getGradient(colorFunc, 'inRange'), gradientOutOfRange = this._getGradient(colorFunc, 'outOfRange'), r = this.pointSize + this.blurSize, canvas = this.canvas, ctx = canvas.getContext('2d'), len = data.length; canvas.width = width, canvas.height = height; for(var i = 0; i < len; ++i){ var p = data[i], x = p[0], y = p[1], alpha = normalize(p[2]); ctx.globalAlpha = alpha, ctx.drawImage(brush, x - r, y - r); } if (!canvas.width || !canvas.height) return canvas; for(var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height), pixels = imageData.data, offset = 0, pixelLen = pixels.length, minOpacity = this.minOpacity, diffOpacity = this.maxOpacity - minOpacity; offset < pixelLen;){ var alpha = pixels[offset + 3] / 256, gradientOffset = 4 * Math.floor(255 * alpha); if (alpha > 0) { var gradient = isInRange(alpha) ? gradientInRange : gradientOutOfRange; alpha > 0 && (alpha = alpha * diffOpacity + minOpacity), pixels[offset++] = gradient[gradientOffset], pixels[offset++] = gradient[gradientOffset + 1], pixels[offset++] = gradient[gradientOffset + 2], pixels[offset++] = gradient[gradientOffset + 3] * alpha * 256; } else offset += 4; } return ctx.putImageData(imageData, 0, 0), canvas; }, HeatmapLayer.prototype._getBrush = function() { var brushCanvas = this._brushCanvas || (this._brushCanvas = createCanvas()), r = this.pointSize + this.blurSize, d = 2 * r; brushCanvas.width = d, brushCanvas.height = d; var ctx = brushCanvas.getContext('2d'); return ctx.clearRect(0, 0, d, d), ctx.shadowOffsetX = d, ctx.shadowBlur = this.blurSize, ctx.shadowColor = '#000', ctx.beginPath(), ctx.arc(-r, r, this.pointSize, 0, 2 * Math.PI, !0), ctx.closePath(), ctx.fill(), brushCanvas; }, HeatmapLayer.prototype._getGradient = function(colorFunc, state) { for(var gradientPixels = this._gradientPixels, pixelsSingleState = gradientPixels[state] || (gradientPixels[state] = new Uint8ClampedArray(1024)), color = [ 0, 0, 0, 0 ], off = 0, i = 0; i < 256; i++)colorFunc[state](i / 255, !0, color), pixelsSingleState[off++] = color[0], pixelsSingleState[off++] = color[1], pixelsSingleState[off++] = color[2], pixelsSingleState[off++] = color[3]; return pixelsSingleState; }, HeatmapLayer; }(); function isGeoCoordSys(coordSys) { var dimensions = coordSys.dimensions; return 'lng' === dimensions[0] && 'lat' === dimensions[1]; } var HeatmapView = function(_super) { function HeatmapView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = HeatmapView.type, _this; } return __extends(HeatmapView, _super), HeatmapView.prototype.render = function(seriesModel, ecModel, api) { if (ecModel.eachComponent('visualMap', function(visualMap) { visualMap.eachTargetSeries(function(targetSeries) { targetSeries === seriesModel && (visualMapOfThisSeries = visualMap); }); }), !visualMapOfThisSeries) throw Error('Heatmap must use with visualMap'); this.group.removeAll(), this._incrementalDisplayable = null; var visualMapOfThisSeries, coordSys = seriesModel.coordinateSystem; 'cartesian2d' === coordSys.type || 'calendar' === coordSys.type ? this._renderOnCartesianAndCalendar(seriesModel, api, 0, seriesModel.getData().count()) : isGeoCoordSys(coordSys) && this._renderOnGeo(coordSys, seriesModel, visualMapOfThisSeries, api); }, HeatmapView.prototype.incrementalPrepareRender = function(seriesModel, ecModel, api) { this.group.removeAll(); }, HeatmapView.prototype.incrementalRender = function(params, seriesModel, ecModel, api) { var coordSys = seriesModel.coordinateSystem; coordSys && (isGeoCoordSys(coordSys) ? this.render(seriesModel, ecModel, api) : this._renderOnCartesianAndCalendar(seriesModel, api, params.start, params.end, !0)); }, HeatmapView.prototype._renderOnCartesianAndCalendar = function(seriesModel, api, start, end, incremental) { var width, height, xAxisExtent, yAxisExtent, coordSys = seriesModel.coordinateSystem; if (isCoordinateSystemType(coordSys, 'cartesian2d')) { var xAxis = coordSys.getAxis('x'), yAxis = coordSys.getAxis('y'); if (!('category' === xAxis.type && 'category' === yAxis.type)) throw Error('Heatmap on cartesian must have two category axes'); if (!(xAxis.onBand && yAxis.onBand)) throw Error('Heatmap on cartesian must have two axes with boundaryGap true'); width = xAxis.getBandWidth(), height = yAxis.getBandWidth(), xAxisExtent = xAxis.scale.getExtent(), yAxisExtent = yAxis.scale.getExtent(); } for(var group = this.group, data = seriesModel.getData(), emphasisStyle = seriesModel.getModel([ 'emphasis', 'itemStyle' ]).getItemStyle(), blurStyle = seriesModel.getModel([ 'blur', 'itemStyle' ]).getItemStyle(), selectStyle = seriesModel.getModel([ 'select', 'itemStyle' ]).getItemStyle(), labelStatesModels = getLabelStatesModels(seriesModel), focus = seriesModel.get([ 'emphasis', 'focus' ]), blurScope = seriesModel.get([ 'emphasis', 'blurScope' ]), dataDims = isCoordinateSystemType(coordSys, 'cartesian2d') ? [ data.mapDimension('x'), data.mapDimension('y'), data.mapDimension('value') ] : [ data.mapDimension('time'), data.mapDimension('value') ], idx = start; idx < end; idx++){ var rect = void 0, style = data.getItemVisual(idx, 'style'); if (isCoordinateSystemType(coordSys, 'cartesian2d')) { var dataDimX = data.get(dataDims[0], idx), dataDimY = data.get(dataDims[1], idx); if (isNaN(data.get(dataDims[2], idx)) || dataDimX < xAxisExtent[0] || dataDimX > xAxisExtent[1] || dataDimY < yAxisExtent[0] || dataDimY > yAxisExtent[1]) continue; var point = coordSys.dataToPoint([ dataDimX, dataDimY ]); rect = new Rect({ shape: { x: Math.floor(Math.round(point[0]) - width / 2), y: Math.floor(Math.round(point[1]) - height / 2), width: Math.ceil(width), height: Math.ceil(height) }, style: style }); } else { if (isNaN(data.get(dataDims[1], idx))) continue; rect = new Rect({ z2: 1, shape: coordSys.dataToRect([ data.get(dataDims[0], idx) ]).contentShape, style: style }); } var itemModel = data.getItemModel(idx); if (data.hasItemOption) { var emphasisModel = itemModel.getModel('emphasis'); emphasisStyle = emphasisModel.getModel('itemStyle').getItemStyle(), blurStyle = itemModel.getModel([ 'blur', 'itemStyle' ]).getItemStyle(), selectStyle = itemModel.getModel([ 'select', 'itemStyle' ]).getItemStyle(), focus = emphasisModel.get('focus'), blurScope = emphasisModel.get('blurScope'), labelStatesModels = getLabelStatesModels(itemModel); } var rawValue = seriesModel.getRawValue(idx), defaultText = '-'; rawValue && null != rawValue[2] && (defaultText = rawValue[2] + ''), setLabelStyle(rect, labelStatesModels, { labelFetcher: seriesModel, labelDataIndex: idx, defaultOpacity: style.opacity, defaultText: defaultText }), rect.ensureState('emphasis').style = emphasisStyle, rect.ensureState('blur').style = blurStyle, rect.ensureState('select').style = selectStyle, enableHoverEmphasis(rect, focus, blurScope), rect.incremental = incremental, incremental && (rect.states.emphasis.hoverLayer = !0), group.add(rect), data.setItemGraphicEl(idx, rect); } }, HeatmapView.prototype._renderOnGeo = function(geo, seriesModel, visualMapModel, api) { var range, dataSpan, pieceList, selected, dataSpan1, len, lastIndex, inRangeVisuals = visualMapModel.targetVisuals.inRange, outOfRangeVisuals = visualMapModel.targetVisuals.outOfRange, data = seriesModel.getData(), hmLayer = this._hmLayer || this._hmLayer || new HeatmapLayer(); hmLayer.blurSize = seriesModel.get('blurSize'), hmLayer.pointSize = seriesModel.get('pointSize'), hmLayer.minOpacity = seriesModel.get('minOpacity'), hmLayer.maxOpacity = seriesModel.get('maxOpacity'); var rect = geo.getViewRect().clone(), roamTransform = geo.getRoamTransform(); rect.applyTransform(roamTransform); var x = Math.max(rect.x, 0), y = Math.max(rect.y, 0), x2 = Math.min(rect.width + rect.x, api.getWidth()), y2 = Math.min(rect.height + rect.y, api.getHeight()), width = x2 - x, height = y2 - y, dims = [ data.mapDimension('lng'), data.mapDimension('lat'), data.mapDimension('value') ], points = data.mapArray(dims, function(lng, lat, value) { var pt = geo.dataToPoint([ lng, lat ]); return pt[0] -= x, pt[1] -= y, pt.push(value), pt; }), dataExtent = visualMapModel.getExtent(), isInRange = 'visualMap.continuous' === visualMapModel.type ? (range = visualMapModel.option.range, dataSpan = dataExtent[1] - dataExtent[0], range = [ (range[0] - dataExtent[0]) / dataSpan, (range[1] - dataExtent[0]) / dataSpan ], function(val) { return val >= range[0] && val <= range[1]; }) : (pieceList = visualMapModel.getPieceList(), selected = visualMapModel.option.selected, dataSpan1 = dataExtent[1] - dataExtent[0], len = (pieceList = map(pieceList, function(piece) { return { interval: [ (piece.interval[0] - dataExtent[0]) / dataSpan1, (piece.interval[1] - dataExtent[0]) / dataSpan1 ] }; })).length, lastIndex = 0, function(val) { var i; for(i = lastIndex; i < len; i++){ var interval = pieceList[i].interval; if (interval[0] <= val && val <= interval[1]) { lastIndex = i; break; } } if (i === len) for(i = lastIndex - 1; i >= 0; i--){ var interval = pieceList[i].interval; if (interval[0] <= val && val <= interval[1]) { lastIndex = i; break; } } return i >= 0 && i < len && selected[i]; }); hmLayer.update(points, width, height, inRangeVisuals.color.getNormalizer(), { inRange: inRangeVisuals.color.getColorMapper(), outOfRange: outOfRangeVisuals.color.getColorMapper() }, isInRange); var img = new ZRImage({ style: { width: width, height: height, x: x, y: y, image: hmLayer.canvas }, silent: !0 }); this.group.add(img); }, HeatmapView.type = 'heatmap', HeatmapView; }(ChartView), HeatmapSeriesModel = function(_super) { function HeatmapSeriesModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = HeatmapSeriesModel.type, _this; } return __extends(HeatmapSeriesModel, _super), HeatmapSeriesModel.prototype.getInitialData = function(option, ecModel) { return createListFromArray(this.getSource(), this, { generateCoord: 'value' }); }, HeatmapSeriesModel.prototype.preventIncremental = function() { var coordSysCreator = CoordinateSystemManager.get(this.get('coordinateSystem')); if (coordSysCreator && coordSysCreator.dimensions) return 'lng' === coordSysCreator.dimensions[0] && 'lat' === coordSysCreator.dimensions[1]; }, HeatmapSeriesModel.type = 'series.heatmap', HeatmapSeriesModel.dependencies = [ 'grid', 'geo', 'calendar' ], HeatmapSeriesModel.defaultOption = { coordinateSystem: 'cartesian2d', zlevel: 0, z: 2, geoIndex: 0, blurSize: 30, pointSize: 20, maxOpacity: 1, minOpacity: 0, select: { itemStyle: { borderColor: '#212121' } } }, HeatmapSeriesModel; }(SeriesModel), BAR_BORDER_WIDTH_QUERY = [ 'itemStyle', 'borderWidth' ], LAYOUT_ATTRS = [ { xy: 'x', wh: 'width', index: 0, posDesc: [ 'left', 'right' ] }, { xy: 'y', wh: 'height', index: 1, posDesc: [ 'top', 'bottom' ] } ], pathForLineWidth = new Circle(), PictorialBarView = function(_super) { function PictorialBarView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = PictorialBarView.type, _this; } return __extends(PictorialBarView, _super), PictorialBarView.prototype.render = function(seriesModel, ecModel, api) { var group = this.group, data = seriesModel.getData(), oldData = this._data, cartesian = seriesModel.coordinateSystem, isHorizontal = cartesian.getBaseAxis().isHorizontal(), coordSysRect = cartesian.master.getRect(), opt = { ecSize: { width: api.getWidth(), height: api.getHeight() }, seriesModel: seriesModel, coordSys: cartesian, coordSysExtent: [ [ coordSysRect.x, coordSysRect.x + coordSysRect.width ], [ coordSysRect.y, coordSysRect.y + coordSysRect.height ] ], isHorizontal: isHorizontal, valueDim: LAYOUT_ATTRS[+isHorizontal], categoryDim: LAYOUT_ATTRS[1 - +isHorizontal] }; return data.diff(oldData).add(function(dataIndex) { if (data.hasValue(dataIndex)) { var itemModel = getItemModel(data, dataIndex), symbolMeta = getSymbolMeta(data, dataIndex, itemModel, opt), bar = createBar(data, opt, symbolMeta); data.setItemGraphicEl(dataIndex, bar), group.add(bar), updateCommon$1(bar, opt, symbolMeta); } }).update(function(newIndex, oldIndex) { var bar, animationModel, dataIndex, bar1 = oldData.getItemGraphicEl(oldIndex); if (!data.hasValue(newIndex)) { group.remove(bar1); return; } var itemModel = getItemModel(data, newIndex), symbolMeta = getSymbolMeta(data, newIndex, itemModel, opt), pictorialShapeStr = getShapeStr(data, symbolMeta); bar1 && pictorialShapeStr !== bar1.__pictorialShapeStr && (group.remove(bar1), data.setItemGraphicEl(newIndex, null), bar1 = null), bar1 ? (bar = bar1, animationModel = symbolMeta.animationModel, dataIndex = symbolMeta.dataIndex, updateProps(bar.__pictorialBundle, { x: symbolMeta.bundlePosition[0], y: symbolMeta.bundlePosition[1] }, animationModel, dataIndex), symbolMeta.symbolRepeat ? createOrUpdateRepeatSymbols(bar, opt, symbolMeta, !0) : createOrUpdateSingleSymbol(bar, opt, symbolMeta, !0), createOrUpdateBarRect(bar, symbolMeta, !0), createOrUpdateClip(bar, opt, symbolMeta, !0)) : bar1 = createBar(data, opt, symbolMeta, !0), data.setItemGraphicEl(newIndex, bar1), bar1.__pictorialSymbolMeta = symbolMeta, group.add(bar1), updateCommon$1(bar1, opt, symbolMeta); }).remove(function(dataIndex) { var bar = oldData.getItemGraphicEl(dataIndex); bar && removeBar(oldData, dataIndex, bar.__pictorialSymbolMeta.animationModel, bar); }).execute(), this._data = data, this.group; }, PictorialBarView.prototype.remove = function(ecModel, api) { var group = this.group, data = this._data; ecModel.get('animation') ? data && data.eachItemGraphicEl(function(bar) { removeBar(data, getECData(bar).dataIndex, ecModel, bar); }) : group.removeAll(); }, PictorialBarView.type = 'pictorialBar', PictorialBarView; }(ChartView); function getSymbolMeta(data, dataIndex, itemModel, opt) { var boundingLength, pxSign, outputSymbolMeta, parsedSymbolSize, valueDim, categoryDim, categorySize, symbolSize, symbolScale, symbolScale1, outputSymbolMeta1, valueLineWidth, layout = data.getItemLayout(dataIndex), symbolRepeat = itemModel.get('symbolRepeat'), symbolClip = itemModel.get('symbolClip'), symbolPosition = itemModel.get('symbolPosition') || 'start', rotation = (itemModel.get('symbolRotate') || 0) * Math.PI / 180 || 0, symbolPatternSize = itemModel.get('symbolPatternSize') || 2, isAnimationEnabled = itemModel.isAnimationEnabled(), symbolMeta = { dataIndex: dataIndex, layout: layout, itemModel: itemModel, symbolType: data.getItemVisual(dataIndex, 'symbol') || 'circle', style: data.getItemVisual(dataIndex, 'style'), symbolClip: symbolClip, symbolRepeat: symbolRepeat, symbolRepeatDirection: itemModel.get('symbolRepeatDirection'), symbolPatternSize: symbolPatternSize, rotation: rotation, animationModel: isAnimationEnabled ? itemModel : null, hoverScale: isAnimationEnabled && itemModel.get([ 'emphasis', 'scale' ]), z2: itemModel.getShallow('z', !0) || 0 }; (function(itemModel, symbolRepeat, layout, opt, outputSymbolMeta) { var boundingLength, valueDim = opt.valueDim, symbolBoundingData = itemModel.get('symbolBoundingData'), valueAxis = opt.coordSys.getOtherAxis(opt.coordSys.getBaseAxis()), zeroPx = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0)), pxSignIdx = 1 - +(layout[valueDim.wh] <= 0); if (isArray(symbolBoundingData)) { var symbolBoundingExtent = [ convertToCoordOnAxis(valueAxis, symbolBoundingData[0]) - zeroPx, convertToCoordOnAxis(valueAxis, symbolBoundingData[1]) - zeroPx ]; symbolBoundingExtent[1] < symbolBoundingExtent[0] && symbolBoundingExtent.reverse(), boundingLength = symbolBoundingExtent[pxSignIdx]; } else boundingLength = null != symbolBoundingData ? convertToCoordOnAxis(valueAxis, symbolBoundingData) - zeroPx : symbolRepeat ? opt.coordSysExtent[valueDim.index][pxSignIdx] - zeroPx : layout[valueDim.wh]; outputSymbolMeta.boundingLength = boundingLength, symbolRepeat && (outputSymbolMeta.repeatCutLength = layout[valueDim.wh]), outputSymbolMeta.pxSign = boundingLength > 0 ? 1 : boundingLength < 0 ? -1 : 0; })(itemModel, symbolRepeat, layout, opt, symbolMeta), boundingLength = symbolMeta.boundingLength, pxSign = symbolMeta.pxSign, outputSymbolMeta = symbolMeta, valueDim = opt.valueDim, categorySize = Math.abs(layout[(categoryDim = opt.categoryDim).wh]), (parsedSymbolSize = isArray(symbolSize = data.getItemVisual(dataIndex, 'symbolSize')) ? symbolSize.slice() : null == symbolSize ? [ '100%', '100%' ] : [ symbolSize, symbolSize ])[categoryDim.index] = parsePercent$1(parsedSymbolSize[categoryDim.index], categorySize), parsedSymbolSize[valueDim.index] = parsePercent$1(parsedSymbolSize[valueDim.index], symbolRepeat ? categorySize : Math.abs(boundingLength)), outputSymbolMeta.symbolSize = parsedSymbolSize, symbolScale = outputSymbolMeta.symbolScale = [ parsedSymbolSize[0] / symbolPatternSize, parsedSymbolSize[1] / symbolPatternSize ], symbolScale[valueDim.index] *= (opt.isHorizontal ? -1 : 1) * pxSign, symbolScale1 = symbolMeta.symbolScale, outputSymbolMeta1 = symbolMeta, (valueLineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0) && (pathForLineWidth.attr({ scaleX: symbolScale1[0], scaleY: symbolScale1[1], rotation: rotation }), pathForLineWidth.updateTransform(), valueLineWidth /= pathForLineWidth.getLineScale(), valueLineWidth *= symbolScale1[opt.valueDim.index]), outputSymbolMeta1.valueLineWidth = valueLineWidth; var symbolSize1 = symbolMeta.symbolSize, symbolOffset = itemModel.get('symbolOffset'); return isArray(symbolOffset) && (symbolOffset = [ parsePercent$1(symbolOffset[0], symbolSize1[0]), parsePercent$1(symbolOffset[1], symbolSize1[1]) ]), function(itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset, symbolPosition, valueLineWidth, boundingLength, repeatCutLength, opt, outputSymbolMeta) { var categoryDim = opt.categoryDim, valueDim = opt.valueDim, pxSign = outputSymbolMeta.pxSign, unitLength = Math.max(symbolSize[valueDim.index] + valueLineWidth, 0), pathLen = unitLength; if (symbolRepeat) { var absBoundingLength = Math.abs(boundingLength), symbolMargin = retrieve(itemModel.get('symbolMargin'), '15%') + '', hasEndGap = !1; symbolMargin.lastIndexOf('!') === symbolMargin.length - 1 && (hasEndGap = !0, symbolMargin = symbolMargin.slice(0, symbolMargin.length - 1)); var symbolMarginNumeric = parsePercent$1(symbolMargin, symbolSize[valueDim.index]), uLenWithMargin = Math.max(unitLength + 2 * symbolMarginNumeric, 0), endFix = hasEndGap ? 0 : 2 * symbolMarginNumeric, repeatSpecified = isNumeric(symbolRepeat), repeatTimes = repeatSpecified ? symbolRepeat : toIntTimes((absBoundingLength + endFix) / uLenWithMargin); symbolMarginNumeric = (absBoundingLength - repeatTimes * unitLength) / 2 / (hasEndGap ? repeatTimes : repeatTimes - 1), uLenWithMargin = unitLength + 2 * symbolMarginNumeric, endFix = hasEndGap ? 0 : 2 * symbolMarginNumeric, repeatSpecified || 'fixed' === symbolRepeat || (repeatTimes = repeatCutLength ? toIntTimes((Math.abs(repeatCutLength) + endFix) / uLenWithMargin) : 0), pathLen = repeatTimes * uLenWithMargin - endFix, outputSymbolMeta.repeatTimes = repeatTimes, outputSymbolMeta.symbolMargin = symbolMarginNumeric; } var sizeFix = pxSign * (pathLen / 2), pathPosition = outputSymbolMeta.pathPosition = []; pathPosition[categoryDim.index] = layout[categoryDim.wh] / 2, pathPosition[valueDim.index] = 'start' === symbolPosition ? sizeFix : 'end' === symbolPosition ? boundingLength - sizeFix : boundingLength / 2, symbolOffset && (pathPosition[0] += symbolOffset[0], pathPosition[1] += symbolOffset[1]); var bundlePosition = outputSymbolMeta.bundlePosition = []; bundlePosition[categoryDim.index] = layout[categoryDim.xy], bundlePosition[valueDim.index] = layout[valueDim.xy]; var barRectShape = outputSymbolMeta.barRectShape = extend({}, layout); barRectShape[valueDim.wh] = pxSign * Math.max(Math.abs(layout[valueDim.wh]), Math.abs(pathPosition[valueDim.index] + sizeFix)), barRectShape[categoryDim.wh] = layout[categoryDim.wh]; var clipShape = outputSymbolMeta.clipShape = {}; clipShape[categoryDim.xy] = -layout[categoryDim.xy], clipShape[categoryDim.wh] = opt.ecSize[categoryDim.wh], clipShape[valueDim.xy] = 0, clipShape[valueDim.wh] = layout[valueDim.wh]; }(itemModel, symbolSize1, layout, symbolRepeat, 0, symbolOffset, symbolPosition, symbolMeta.valueLineWidth, symbolMeta.boundingLength, symbolMeta.repeatCutLength, opt, symbolMeta), symbolMeta; } function convertToCoordOnAxis(axis, value) { return axis.toGlobalCoord(axis.dataToCoord(axis.scale.parse(value))); } function createPath(symbolMeta) { var symbolPatternSize = symbolMeta.symbolPatternSize, path = createSymbol(symbolMeta.symbolType, -symbolPatternSize / 2, -symbolPatternSize / 2, symbolPatternSize, symbolPatternSize); return path.attr({ culling: !0 }), 'image' !== path.type && path.setStyle({ strokeNoScale: !0 }), path; } function createOrUpdateRepeatSymbols(bar, opt, symbolMeta, isUpdate) { var bundle = bar.__pictorialBundle, symbolSize = symbolMeta.symbolSize, valueLineWidth = symbolMeta.valueLineWidth, pathPosition = symbolMeta.pathPosition, valueDim = opt.valueDim, repeatTimes = symbolMeta.repeatTimes || 0, index = 0, unit = symbolSize[opt.valueDim.index] + valueLineWidth + 2 * symbolMeta.symbolMargin; for(eachPath(bar, function(path) { path.__pictorialAnimationIndex = index, path.__pictorialRepeatTimes = repeatTimes, index < repeatTimes ? updateAttr(path, null, makeTarget(index), symbolMeta, isUpdate) : updateAttr(path, null, { scaleX: 0, scaleY: 0 }, symbolMeta, isUpdate, function() { bundle.remove(path); }), index++; }); index < repeatTimes; index++){ var path = createPath(symbolMeta); path.__pictorialAnimationIndex = index, path.__pictorialRepeatTimes = repeatTimes, bundle.add(path); var target = makeTarget(index); updateAttr(path, { x: target.x, y: target.y, scaleX: 0, scaleY: 0 }, { scaleX: target.scaleX, scaleY: target.scaleY, rotation: target.rotation }, symbolMeta, isUpdate); } function makeTarget(index) { var position = pathPosition.slice(), pxSign = symbolMeta.pxSign, i = index; return ('start' === symbolMeta.symbolRepeatDirection ? pxSign > 0 : pxSign < 0) && (i = repeatTimes - 1 - index), position[valueDim.index] = unit * (i - repeatTimes / 2 + 0.5) + pathPosition[valueDim.index], { x: position[0], y: position[1], scaleX: symbolMeta.symbolScale[0], scaleY: symbolMeta.symbolScale[1], rotation: symbolMeta.rotation }; } } function createOrUpdateSingleSymbol(bar, opt, symbolMeta, isUpdate) { var bundle = bar.__pictorialBundle, mainPath = bar.__pictorialMainPath; mainPath ? updateAttr(mainPath, null, { x: symbolMeta.pathPosition[0], y: symbolMeta.pathPosition[1], scaleX: symbolMeta.symbolScale[0], scaleY: symbolMeta.symbolScale[1], rotation: symbolMeta.rotation }, symbolMeta, isUpdate) : (mainPath = bar.__pictorialMainPath = createPath(symbolMeta), bundle.add(mainPath), updateAttr(mainPath, { x: symbolMeta.pathPosition[0], y: symbolMeta.pathPosition[1], scaleX: 0, scaleY: 0, rotation: symbolMeta.rotation }, { scaleX: symbolMeta.symbolScale[0], scaleY: symbolMeta.symbolScale[1] }, symbolMeta, isUpdate)); } function createOrUpdateBarRect(bar, symbolMeta, isUpdate) { var rectShape = extend({}, symbolMeta.barRectShape), barRect = bar.__pictorialBarRect; barRect ? updateAttr(barRect, null, { shape: rectShape }, symbolMeta, isUpdate) : (barRect = bar.__pictorialBarRect = new Rect({ z2: 2, shape: rectShape, silent: !0, style: { stroke: 'transparent', fill: 'transparent', lineWidth: 0 } }), bar.add(barRect)); } function createOrUpdateClip(bar, opt, symbolMeta, isUpdate) { if (symbolMeta.symbolClip) { var clipPath = bar.__pictorialClipPath, clipShape = extend({}, symbolMeta.clipShape), valueDim = opt.valueDim, animationModel = symbolMeta.animationModel, dataIndex = symbolMeta.dataIndex; if (clipPath) updateProps(clipPath, { shape: clipShape }, animationModel, dataIndex); else { clipShape[valueDim.wh] = 0, clipPath = new Rect({ shape: clipShape }), bar.__pictorialBundle.setClipPath(clipPath), bar.__pictorialClipPath = clipPath; var target = {}; target[valueDim.wh] = symbolMeta.clipShape[valueDim.wh], graphic[isUpdate ? 'updateProps' : 'initProps'](clipPath, { shape: target }, animationModel, dataIndex); } } } function getItemModel(data, dataIndex) { var itemModel = data.getItemModel(dataIndex); return itemModel.getAnimationDelayParams = getAnimationDelayParams, itemModel.isAnimationEnabled = isAnimationEnabled, itemModel; } function getAnimationDelayParams(path) { return { index: path.__pictorialAnimationIndex, count: path.__pictorialRepeatTimes }; } function isAnimationEnabled() { return this.parentModel.isAnimationEnabled() && !!this.getShallow('animation'); } function createBar(data, opt, symbolMeta, isUpdate) { var bar = new Group(), bundle = new Group(); return bar.add(bundle), bar.__pictorialBundle = bundle, bundle.x = symbolMeta.bundlePosition[0], bundle.y = symbolMeta.bundlePosition[1], symbolMeta.symbolRepeat ? createOrUpdateRepeatSymbols(bar, opt, symbolMeta) : createOrUpdateSingleSymbol(bar, opt, symbolMeta), createOrUpdateBarRect(bar, symbolMeta, isUpdate), createOrUpdateClip(bar, opt, symbolMeta, isUpdate), bar.__pictorialShapeStr = getShapeStr(data, symbolMeta), bar.__pictorialSymbolMeta = symbolMeta, bar; } function removeBar(data, dataIndex, animationModel, bar) { var labelRect = bar.__pictorialBarRect; labelRect && labelRect.removeTextContent(); var pathes = []; eachPath(bar, function(path) { pathes.push(path); }), bar.__pictorialMainPath && pathes.push(bar.__pictorialMainPath), bar.__pictorialClipPath && (animationModel = null), each(pathes, function(path) { removeElement(path, { scaleX: 0, scaleY: 0 }, animationModel, dataIndex, function() { bar.parent && bar.parent.remove(bar); }); }), data.setItemGraphicEl(dataIndex, null); } function getShapeStr(data, symbolMeta) { return [ data.getItemVisual(symbolMeta.dataIndex, 'symbol') || 'none', !!symbolMeta.symbolRepeat, !!symbolMeta.symbolClip ].join(':'); } function eachPath(bar, cb, context) { each(bar.__pictorialBundle.children(), function(el) { el !== bar.__pictorialBarRect && cb.call(context, el); }); } function updateAttr(el, immediateAttrs, animationAttrs, symbolMeta, isUpdate, cb) { immediateAttrs && el.attr(immediateAttrs), symbolMeta.symbolClip && !isUpdate ? animationAttrs && el.attr(animationAttrs) : animationAttrs && graphic[isUpdate ? 'updateProps' : 'initProps'](el, animationAttrs, symbolMeta.animationModel, symbolMeta.dataIndex, cb); } function updateCommon$1(bar, opt, symbolMeta) { var dataIndex = symbolMeta.dataIndex, itemModel = symbolMeta.itemModel, emphasisModel = itemModel.getModel('emphasis'), emphasisStyle = emphasisModel.getModel('itemStyle').getItemStyle(), blurStyle = itemModel.getModel([ 'blur', 'itemStyle' ]).getItemStyle(), selectStyle = itemModel.getModel([ 'select', 'itemStyle' ]).getItemStyle(), cursorStyle = itemModel.getShallow('cursor'), focus = emphasisModel.get('focus'), blurScope = emphasisModel.get('blurScope'), hoverScale = emphasisModel.get('scale'); eachPath(bar, function(path) { if (path instanceof ZRImage) { var pathStyle = path.style; path.useStyle(extend({ image: pathStyle.image, x: pathStyle.x, y: pathStyle.y, width: pathStyle.width, height: pathStyle.height }, symbolMeta.style)); } else path.useStyle(symbolMeta.style); var emphasisState = path.ensureState('emphasis'); emphasisState.style = emphasisStyle, hoverScale && (emphasisState.scaleX = 1.1 * path.scaleX, emphasisState.scaleY = 1.1 * path.scaleY), path.ensureState('blur').style = blurStyle, path.ensureState('select').style = selectStyle, cursorStyle && (path.cursor = cursorStyle), path.z2 = symbolMeta.z2; }); var barPositionOutside = opt.valueDim.posDesc[+(symbolMeta.boundingLength > 0)]; setLabelStyle(bar.__pictorialBarRect, getLabelStatesModels(itemModel), { labelFetcher: opt.seriesModel, labelDataIndex: dataIndex, defaultText: getDefaultLabel(opt.seriesModel.getData(), dataIndex), inheritColor: symbolMeta.style.fill, defaultOpacity: symbolMeta.style.opacity, defaultOutsidePosition: barPositionOutside }), enableHoverEmphasis(bar, focus, blurScope); } function toIntTimes(times) { var roundedTimes = Math.round(times); return 1e-4 > Math.abs(times - roundedTimes) ? roundedTimes : Math.ceil(times); } var PictorialBarSeriesModel = function(_super) { function PictorialBarSeriesModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = PictorialBarSeriesModel.type, _this.hasSymbolVisual = !0, _this.defaultSymbol = 'roundRect', _this; } return __extends(PictorialBarSeriesModel, _super), PictorialBarSeriesModel.prototype.getInitialData = function(option) { return option.stack = null, _super.prototype.getInitialData.apply(this, arguments); }, PictorialBarSeriesModel.type = 'series.pictorialBar', PictorialBarSeriesModel.dependencies = [ 'grid' ], PictorialBarSeriesModel.defaultOption = inheritDefaultOption(BaseBarSeriesModel.defaultOption, { symbol: 'circle', symbolSize: null, symbolRotate: null, symbolPosition: null, symbolOffset: null, symbolMargin: null, symbolRepeat: !1, symbolRepeatDirection: 'end', symbolClip: !1, symbolBoundingData: null, symbolPatternSize: 400, barGap: '-100%', progressive: 0, emphasis: { scale: !1 }, select: { itemStyle: { borderColor: '#212121' } } }), PictorialBarSeriesModel; }(BaseBarSeriesModel), ThemeRiverView = function(_super) { function ThemeRiverView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = ThemeRiverView.type, _this._layers = [], _this; } return __extends(ThemeRiverView, _super), ThemeRiverView.prototype.render = function(seriesModel, ecModel, api) { var data = seriesModel.getData(), self1 = this, group = this.group, layersSeries = seriesModel.getLayerSeries(), layoutInfo = data.getLayout('layoutInfo'), rect = layoutInfo.rect, boundaryGap = layoutInfo.boundaryGap; function keyGetter(item) { return item.name; } group.x = 0, group.y = rect.y + boundaryGap[0]; var dataDiffer = new DataDiffer(this._layersSeries || [], layersSeries, keyGetter, keyGetter), newLayersGroups = []; function process(status, idx, oldIdx) { var style, polygon, oldLayersGroups = self1._layers; if ('remove' === status) { group.remove(oldLayersGroups[idx]); return; } for(var points0 = [], points1 = [], indices = layersSeries[idx].indices, j = 0; j < indices.length; j++){ var layout = data.getItemLayout(indices[j]), x = layout.x, y0 = layout.y0, y = layout.y; points0.push(x, y0), points1.push(x, y0 + y), style = data.getItemVisual(indices[j], 'style'); } var textLayout = data.getItemLayout(indices[0]), margin = seriesModel.getModel('label').get('margin'), emphasisModel = seriesModel.getModel('emphasis'); if ('add' === status) { var rect, cb, rectEl, layerGroup = newLayersGroups[idx] = new Group(); polygon = new ECPolygon({ shape: { points: points0, stackedOnPoints: points1, smooth: 0.4, stackedOnSmooth: 0.4, smoothConstraint: !1 }, z2: 0 }), layerGroup.add(polygon), group.add(layerGroup), seriesModel.isAnimationEnabled() && polygon.setClipPath((rect = polygon.getBoundingRect(), cb = function() { polygon.removeClipPath(); }, initProps(rectEl = new Rect({ shape: { x: rect.x - 10, y: rect.y - 10, width: 0, height: rect.height + 20 } }), { shape: { x: rect.x - 50, width: rect.width + 100, height: rect.height + 20 } }, seriesModel, cb), rectEl)); } else { var layerGroup = oldLayersGroups[oldIdx]; polygon = layerGroup.childAt(0), group.add(layerGroup), newLayersGroups[idx] = layerGroup, updateProps(polygon, { shape: { points: points0, stackedOnPoints: points1 } }, seriesModel); } setLabelStyle(polygon, getLabelStatesModels(seriesModel), { labelDataIndex: indices[j - 1], defaultText: data.getName(indices[j - 1]), inheritColor: style.fill }, { normal: { verticalAlign: 'middle' } }), polygon.setTextConfig({ position: null, local: !0 }); var labelEl = polygon.getTextContent(); labelEl && (labelEl.x = textLayout.x - margin, labelEl.y = textLayout.y0 + textLayout.y / 2), polygon.useStyle(style), data.setItemGraphicEl(idx, polygon), setStatesStylesFromModel(polygon, seriesModel), enableHoverEmphasis(polygon, emphasisModel.get('focus'), emphasisModel.get('blurScope')); } dataDiffer.add(bind(process, this, 'add')).update(bind(process, this, 'update')).remove(bind(process, this, 'remove')).execute(), this._layersSeries = layersSeries, this._layers = newLayersGroups; }, ThemeRiverView.type = 'themeRiver', ThemeRiverView; }(ChartView), ThemeRiverSeriesModel = function(_super) { function ThemeRiverSeriesModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = ThemeRiverSeriesModel.type, _this.useColorPaletteOnData = !0, _this; } return __extends(ThemeRiverSeriesModel, _super), ThemeRiverSeriesModel.prototype.init = function(option) { _super.prototype.init.apply(this, arguments), this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this)); }, ThemeRiverSeriesModel.prototype.fixData = function(data) { var rawDataLength = data.length, timeValueKeys = {}, groupResult = groupData(data, function(item) { return timeValueKeys.hasOwnProperty(item[0] + '') || (timeValueKeys[item[0] + ''] = -1), item[2]; }), layerData = []; groupResult.buckets.each(function(items, key) { layerData.push({ name: key, dataList: items }); }); for(var layerNum = layerData.length, k = 0; k < layerNum; ++k){ for(var name_1 = layerData[k].name, j = 0; j < layerData[k].dataList.length; ++j){ var timeValue = layerData[k].dataList[j][0] + ''; timeValueKeys[timeValue] = k; } for(var timeValue in timeValueKeys)timeValueKeys.hasOwnProperty(timeValue) && timeValueKeys[timeValue] !== k && (timeValueKeys[timeValue] = k, data[rawDataLength] = [ timeValue, 0, name_1 ], rawDataLength++); } return data; }, ThemeRiverSeriesModel.prototype.getInitialData = function(option, ecModel) { for(var axisType = this.getReferringComponents('singleAxis', SINGLE_REFERRING).models[0].get('type'), filterData = filter(option.data, function(dataItem) { return void 0 !== dataItem[2]; }), data = this.fixData(filterData || []), nameList = [], nameMap = this.nameMap = createHashMap(), count = 0, i = 0; i < data.length; ++i)nameList.push(data[i][2]), !nameMap.get(data[i][2]) && (nameMap.set(data[i][2], count), count++); var dimensionsInfo = createDimensions(data, { coordDimensions: [ 'single' ], dimensionsDefine: [ { name: 'time', type: getDimensionTypeByAxis(axisType) }, { name: 'value', type: 'float' }, { name: 'name', type: 'ordinal' } ], encodeDefine: { single: 0, value: 1, itemName: 2 } }), list = new List(dimensionsInfo, this); return list.initData(data), list; }, ThemeRiverSeriesModel.prototype.getLayerSeries = function() { for(var data = this.getData(), lenCount = data.count(), indexArr = [], i = 0; i < lenCount; ++i)indexArr[i] = i; var timeDim = data.mapDimension('single'), groupResult = groupData(indexArr, function(index) { return data.get('name', index); }), layerSeries = []; return groupResult.buckets.each(function(items, key) { items.sort(function(index1, index2) { return data.get(timeDim, index1) - data.get(timeDim, index2); }), layerSeries.push({ name: key, indices: items }); }), layerSeries; }, ThemeRiverSeriesModel.prototype.getAxisTooltipData = function(dim, value, baseAxis) { isArray(dim) || (dim = dim ? [ dim ] : []); for(var nestestValue, data = this.getData(), layerSeries = this.getLayerSeries(), indices = [], layerNum = layerSeries.length, i = 0; i < layerNum; ++i){ for(var minDist = Number.MAX_VALUE, nearestIdx = -1, pointNum = layerSeries[i].indices.length, j = 0; j < pointNum; ++j){ var theValue = data.get(dim[0], layerSeries[i].indices[j]), dist = Math.abs(theValue - value); dist <= minDist && (nestestValue = theValue, minDist = dist, nearestIdx = layerSeries[i].indices[j]); } indices.push(nearestIdx); } return { dataIndices: indices, nestestValue: nestestValue }; }, ThemeRiverSeriesModel.prototype.formatTooltip = function(dataIndex, multipleSeries, dataType) { var data = this.getData(); return createTooltipMarkup('nameValue', { name: data.getName(dataIndex), value: data.get(data.mapDimension('value'), dataIndex) }); }, ThemeRiverSeriesModel.type = 'series.themeRiver', ThemeRiverSeriesModel.dependencies = [ 'singleAxis' ], ThemeRiverSeriesModel.defaultOption = { zlevel: 0, z: 2, coordinateSystem: 'singleAxis', boundaryGap: [ '10%', '10%' ], singleAxisIndex: 0, animationEasing: 'linear', label: { margin: 4, show: !0, position: 'left', fontSize: 11 }, emphasis: { label: { show: !0 } } }, ThemeRiverSeriesModel; }(SeriesModel); function themeRiverLayout(ecModel, api) { ecModel.eachSeriesByType('themeRiver', function(seriesModel) { var data = seriesModel.getData(), single = seriesModel.coordinateSystem, layoutInfo = {}, rect = single.getRect(); layoutInfo.rect = rect; var boundaryGap = seriesModel.get('boundaryGap'), axis = single.getAxis(); layoutInfo.boundaryGap = boundaryGap, 'horizontal' === axis.orient ? (boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.height), boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.height), doThemeRiverLayout(data, seriesModel, rect.height - boundaryGap[0] - boundaryGap[1])) : (boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.width), boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.width), doThemeRiverLayout(data, seriesModel, rect.width - boundaryGap[0] - boundaryGap[1])), data.setLayout('layoutInfo', layoutInfo); }); } function doThemeRiverLayout(data, seriesModel, height) { if (data.count()) for(var baseY0, coordSys = seriesModel.coordinateSystem, layerSeries = seriesModel.getLayerSeries(), timeDim = data.mapDimension('single'), valueDim = data.mapDimension('value'), layerPoints = map(layerSeries, function(singleLayer) { return map(singleLayer.indices, function(idx) { var pt = coordSys.dataToPoint(data.get(timeDim, idx)); return pt[1] = data.get(valueDim, idx), pt; }); }), base = function(data) { for(var layerNum = data.length, pointNum = data[0].length, sums = [], y0 = [], max = 0, i = 0; i < pointNum; ++i){ for(var temp = 0, j = 0; j < layerNum; ++j)temp += data[j][i][1]; temp > max && (max = temp), sums.push(temp); } for(var k = 0; k < pointNum; ++k)y0[k] = (max - sums[k]) / 2; max = 0; for(var l = 0; l < pointNum; ++l){ var sum = sums[l] + y0[l]; sum > max && (max = sum); } return { y0: y0, max: max }; }(layerPoints), baseLine = base.y0, ky = height / base.max, n = layerSeries.length, m = layerSeries[0].indices.length, j = 0; j < m; ++j){ baseY0 = baseLine[j] * ky, data.setItemLayout(layerSeries[0].indices[j], { layerIndex: 0, x: layerPoints[0][j][0], y0: baseY0, y: layerPoints[0][j][1] * ky }); for(var i = 1; i < n; ++i)baseY0 += layerPoints[i - 1][j][1] * ky, data.setItemLayout(layerSeries[i].indices[j], { layerIndex: i, x: layerPoints[i][j][0], y0: baseY0, y: layerPoints[i][j][1] * ky }); } } var SunburstPiece = function(_super) { function SunburstPiece(node, seriesModel, ecModel, api) { var _this = _super.call(this) || this; _this.z2 = 2, _this.textConfig = { inside: !0 }, getECData(_this).seriesIndex = seriesModel.seriesIndex; var text = new ZRText({ z2: 4, silent: node.getModel().get([ 'label', 'silent' ]) }); return _this.setTextContent(text), _this.updateData(!0, node, seriesModel, ecModel, api), _this; } return __extends(SunburstPiece, _super), SunburstPiece.prototype.updateData = function(firstCreate, node, seriesModel, ecModel, api) { this.node = node, node.piece = this, seriesModel = seriesModel || this._seriesModel, ecModel = ecModel || this._ecModel; var sector = this; getECData(sector).dataIndex = node.dataIndex; var itemModel = node.getModel(), emphasisModel = itemModel.getModel('emphasis'), layout = node.getLayout(), sectorShape = extend({}, layout); sectorShape.label = null; var normalStyle = node.getVisual('style'); normalStyle.lineJoin = 'bevel'; var decal = node.getVisual('decal'); decal && (normalStyle.decal = createOrUpdatePatternFromDecal(decal, api)); var cornerRadius = getSectorCornerRadius(itemModel.getModel('itemStyle'), sectorShape); extend(sectorShape, cornerRadius), each(SPECIAL_STATES, function(stateName) { var state = sector.ensureState(stateName), itemStyleModel = itemModel.getModel([ stateName, 'itemStyle' ]); state.style = itemStyleModel.getItemStyle(); var cornerRadius = getSectorCornerRadius(itemStyleModel, sectorShape); cornerRadius && (state.shape = cornerRadius); }), firstCreate ? (sector.setShape(sectorShape), sector.shape.r = layout.r0, updateProps(sector, { shape: { r: layout.r } }, seriesModel, node.dataIndex)) : updateProps(sector, { shape: sectorShape }, seriesModel), sector.useStyle(normalStyle), this._updateLabel(seriesModel); var cursorStyle = itemModel.getShallow('cursor'); cursorStyle && sector.attr('cursor', cursorStyle), this._seriesModel = seriesModel || this._seriesModel, this._ecModel = ecModel || this._ecModel; var focus = emphasisModel.get('focus'); enableHoverEmphasis(this, 'ancestor' === focus ? node.getAncestorsIndices() : 'descendant' === focus ? node.getDescendantIndices() : focus, emphasisModel.get('blurScope')); }, SunburstPiece.prototype._updateLabel = function(seriesModel) { var _this = this, itemModel = this.node.getModel(), normalLabelModel = itemModel.getModel('label'), layout = this.node.getLayout(), angle = layout.endAngle - layout.startAngle, midAngle = (layout.startAngle + layout.endAngle) / 2, dx = Math.cos(midAngle), dy = Math.sin(midAngle), sector = this, label = sector.getTextContent(), dataIndex = this.node.dataIndex, labelMinAngle = normalLabelModel.get('minAngle') / 180 * Math.PI, isNormalShown = normalLabelModel.get('show') && !(null != labelMinAngle && Math.abs(angle) < labelMinAngle); function getLabelAttr(model, name) { var stateAttr = model.get(name); return null == stateAttr ? normalLabelModel.get(name) : stateAttr; } label.ignore = !isNormalShown, each(DISPLAY_STATES, function(stateName) { var r, labelStateModel = 'normal' === stateName ? itemModel.getModel('label') : itemModel.getModel([ stateName, 'label' ]), isNormal = 'normal' === stateName, state = isNormal ? label : label.ensureState(stateName), text = seriesModel.getFormattedLabel(dataIndex, stateName); isNormal && (text = text || _this.node.name), state.style = createTextStyle(labelStateModel, {}, null, 'normal' !== stateName, !0), text && (state.style.text = text); var isShown = labelStateModel.get('show'); null == isShown || isNormal || (state.ignore = !isShown); var labelPosition = getLabelAttr(labelStateModel, 'position'), sectorState = isNormal ? sector : sector.states[stateName], labelColor = sectorState.style.fill; sectorState.textConfig = { outsideFill: 'inherit' === labelStateModel.get('color') ? labelColor : null, inside: 'outside' !== labelPosition }; var labelPadding = getLabelAttr(labelStateModel, 'distance') || 0, textAlign = getLabelAttr(labelStateModel, 'align'); 'outside' === labelPosition ? (r = layout.r + labelPadding, textAlign = midAngle > Math.PI / 2 ? 'right' : 'left') : textAlign && 'center' !== textAlign ? 'left' === textAlign ? (r = layout.r0 + labelPadding, midAngle > Math.PI / 2 && (textAlign = 'right')) : 'right' === textAlign && (r = layout.r - labelPadding, midAngle > Math.PI / 2 && (textAlign = 'left')) : (r = (layout.r + layout.r0) / 2, textAlign = 'center'), state.style.align = textAlign, state.style.verticalAlign = getLabelAttr(labelStateModel, 'verticalAlign') || 'middle', state.x = r * dx + layout.cx, state.y = r * dy + layout.cy; var rotateType = getLabelAttr(labelStateModel, 'rotate'), rotate = 0; 'radial' === rotateType ? (rotate = -midAngle) < -Math.PI / 2 && (rotate += Math.PI) : 'tangential' === rotateType ? (rotate = Math.PI / 2 - midAngle) > Math.PI / 2 ? rotate -= Math.PI : rotate < -Math.PI / 2 && (rotate += Math.PI) : 'number' == typeof rotateType && (rotate = rotateType * Math.PI / 180), state.rotation = rotate; }), label.dirtyStyle(); }, SunburstPiece; }(Sector), ROOT_TO_NODE_ACTION = 'sunburstRootToNode', HIGHLIGHT_ACTION = 'sunburstHighlight', SunburstView = function(_super) { function SunburstView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = SunburstView.type, _this; } return __extends(SunburstView, _super), SunburstView.prototype.render = function(seriesModel, ecModel, api, payload) { var self1 = this; this.seriesModel = seriesModel, this.api = api, this.ecModel = ecModel; var data = seriesModel.getData(), virtualRoot = data.tree.root, newRoot = seriesModel.getViewRoot(), group = this.group, renderLabelForZeroData = seriesModel.get('renderLabelForZeroData'), newChildren = []; newRoot.eachNode(function(node) { newChildren.push(node); }), function(newChildren, oldChildren) { function getKey(node) { return node.getId(); } function processNode(newIdx, oldIdx) { (function(newNode, oldNode) { if (renderLabelForZeroData || !newNode || newNode.getValue() || (newNode = null), newNode !== virtualRoot && oldNode !== virtualRoot) { if (oldNode && oldNode.piece) { var node; newNode ? (oldNode.piece.updateData(!1, newNode, seriesModel, ecModel, api), data.setItemGraphicEl(newNode.dataIndex, oldNode.piece)) : !!(node = oldNode) && node.piece && (group.remove(node.piece), node.piece = null); } else if (newNode) { var piece = new SunburstPiece(newNode, seriesModel, ecModel, api); group.add(piece), data.setItemGraphicEl(newNode.dataIndex, piece); } } })(null == newIdx ? null : newChildren[newIdx], null == oldIdx ? null : oldChildren[oldIdx]); } (0 !== newChildren.length || 0 !== oldChildren.length) && new DataDiffer(oldChildren, newChildren, getKey, getKey).add(processNode).update(processNode).remove(curry(processNode, null)).execute(); }(newChildren, this._oldChildren || []), newRoot.depth > 0 ? (self1.virtualPiece ? self1.virtualPiece.updateData(!1, virtualRoot, seriesModel, ecModel, api) : (self1.virtualPiece = new SunburstPiece(virtualRoot, seriesModel, ecModel, api), group.add(self1.virtualPiece)), newRoot.piece.off('click'), self1.virtualPiece.on('click', function(e) { self1._rootToNode(newRoot.parentNode); })) : self1.virtualPiece && (group.remove(self1.virtualPiece), self1.virtualPiece = null), this._initEvents(), this._oldChildren = newChildren; }, SunburstView.prototype._initEvents = function() { var _this = this; this.group.off('click'), this.group.on('click', function(e) { var targetFound = !1; _this.seriesModel.getViewRoot().eachNode(function(node) { if (!targetFound && node.piece && node.piece === e.target) { var nodeClick = node.getModel().get('nodeClick'); if ('rootToNode' === nodeClick) _this._rootToNode(node); else if ('link' === nodeClick) { var itemModel = node.getModel(), link = itemModel.get('link'); link && windowOpen(link, itemModel.get('target', !0) || '_blank'); } targetFound = !0; } }); }); }, SunburstView.prototype._rootToNode = function(node) { node !== this.seriesModel.getViewRoot() && this.api.dispatchAction({ type: ROOT_TO_NODE_ACTION, from: this.uid, seriesId: this.seriesModel.id, targetNode: node }); }, SunburstView.prototype.containPoint = function(point, seriesModel) { var itemLayout = seriesModel.getData().getItemLayout(0); if (itemLayout) { var dx = point[0] - itemLayout.cx, dy = point[1] - itemLayout.cy, radius = Math.sqrt(dx * dx + dy * dy); return radius <= itemLayout.r && radius >= itemLayout.r0; } }, SunburstView.type = 'sunburst', SunburstView; }(ChartView), SunburstSeriesModel = function(_super) { function SunburstSeriesModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = SunburstSeriesModel.type, _this.ignoreStyleOnData = !0, _this; } return __extends(SunburstSeriesModel, _super), SunburstSeriesModel.prototype.getInitialData = function(option, ecModel) { var root = { name: option.name, children: option.data }; (function completeTreeValue$1(dataNode) { var sum = 0; each(dataNode.children, function(child) { completeTreeValue$1(child); var childValue = child.value; isArray(childValue) && (childValue = childValue[0]), sum += childValue; }); var thisValue = dataNode.value; isArray(thisValue) && (thisValue = thisValue[0]), (null == thisValue || isNaN(thisValue)) && (thisValue = sum), thisValue < 0 && (thisValue = 0), isArray(dataNode.value) ? dataNode.value[0] = thisValue : dataNode.value = thisValue; })(root); var levelModels = map(option.levels || [], function(levelDefine) { return new Model(levelDefine, this, ecModel); }, this), tree = Tree.createTree(root, this, function(nodeData) { nodeData.wrapMethod('getItemModel', function(model, idx) { var levelModel = levelModels[tree.getNodeByDataIndex(idx).depth]; return levelModel && (model.parentModel = levelModel), model; }); }); return tree.data; }, SunburstSeriesModel.prototype.optionUpdated = function() { this.resetViewRoot(); }, SunburstSeriesModel.prototype.getDataParams = function(dataIndex) { var params = _super.prototype.getDataParams.apply(this, arguments), node = this.getData().tree.getNodeByDataIndex(dataIndex); return params.treePathInfo = wrapTreePathInfo(node, this), params; }, SunburstSeriesModel.prototype.getViewRoot = function() { return this._viewRoot; }, SunburstSeriesModel.prototype.resetViewRoot = function(viewRoot) { viewRoot ? this._viewRoot = viewRoot : viewRoot = this._viewRoot; var root = this.getRawData().tree.root; viewRoot && (viewRoot === root || root.contains(viewRoot)) || (this._viewRoot = root); }, SunburstSeriesModel.prototype.enableAriaDecal = function() { enableAriaDecalForTree(this); }, SunburstSeriesModel.type = 'series.sunburst', SunburstSeriesModel.defaultOption = { zlevel: 0, z: 2, center: [ '50%', '50%' ], radius: [ 0, '75%' ], clockwise: !0, startAngle: 90, minAngle: 0, stillShowZeroSum: !0, nodeClick: 'rootToNode', renderLabelForZeroData: !1, label: { rotate: 'radial', show: !0, opacity: 1, align: 'center', position: 'inside', distance: 5, silent: !0 }, itemStyle: { borderWidth: 1, borderColor: 'white', borderType: 'solid', shadowBlur: 0, shadowColor: 'rgba(0, 0, 0, 0.2)', shadowOffsetX: 0, shadowOffsetY: 0, opacity: 1 }, emphasis: { focus: 'descendant' }, blur: { itemStyle: { opacity: 0.2 }, label: { opacity: 0.1 } }, animationType: 'expansion', animationDuration: 1000, animationDurationUpdate: 500, data: [], levels: [], sort: 'desc' }, SunburstSeriesModel; }(SeriesModel), RADIAN$2 = Math.PI / 180; function sunburstLayout(seriesType, ecModel, api) { ecModel.eachSeriesByType(seriesType, function(seriesModel) { var center = seriesModel.get('center'), radius = seriesModel.get('radius'); isArray(radius) || (radius = [ 0, radius ]), isArray(center) || (center = [ center, center ]); var width = api.getWidth(), height = api.getHeight(), size = Math.min(width, height), cx = parsePercent$1(center[0], width), cy = parsePercent$1(center[1], height), r0 = parsePercent$1(radius[0], size / 2), r = parsePercent$1(radius[1], size / 2), startAngle = -seriesModel.get('startAngle') * RADIAN$2, minAngle = seriesModel.get('minAngle') * RADIAN$2, virtualRoot = seriesModel.getData().tree.root, treeRoot = seriesModel.getViewRoot(), rootDepth = treeRoot.depth, sort = seriesModel.get('sort'); null != sort && function initChildren$1(node, sortOrder) { var children = node.children || []; node.children = function(children, sortOrder) { if ('function' == typeof sortOrder) { var sortTargets = map(children, function(child, idx) { var value = child.getValue(); return { params: { depth: child.depth, height: child.height, dataIndex: child.dataIndex, getValue: function() { return value; } }, index: idx }; }); return sortTargets.sort(function(a, b) { return sortOrder(a.params, b.params); }), map(sortTargets, function(target) { return children[target.index]; }); } var isAsc_1 = 'asc' === sortOrder; return children.sort(function(a, b) { var diff = (a.getValue() - b.getValue()) * (isAsc_1 ? 1 : -1); return 0 === diff ? (a.dataIndex - b.dataIndex) * (isAsc_1 ? -1 : 1) : diff; }); }(children, sortOrder), children.length && each(node.children, function(child) { initChildren$1(child, sortOrder); }); }(treeRoot, sort); var validDataCount = 0; each(treeRoot.children, function(child) { !isNaN(child.getValue()) && validDataCount++; }); var sum = treeRoot.getValue(), unitRadian = Math.PI / (sum || validDataCount) * 2, renderRollupNode = treeRoot.depth > 0, rPerLevel = (r - r0) / (treeRoot.height - (renderRollupNode ? -1 : 1) || 1), clockwise = seriesModel.get('clockwise'), stillShowZeroSum = seriesModel.get('stillShowZeroSum'), dir = clockwise ? 1 : -1, renderNode = function(node, startAngle) { if (node) { var endAngle = startAngle; if (node !== virtualRoot) { var value = node.getValue(), angle = 0 === sum && stillShowZeroSum ? unitRadian : value * unitRadian; angle < minAngle && (angle = minAngle), endAngle = startAngle + dir * angle; var depth = node.depth - rootDepth - (renderRollupNode ? -1 : 1), rStart = r0 + rPerLevel * depth, rEnd = r0 + rPerLevel * (depth + 1), itemModel = node.getModel(); null != itemModel.get('r0') && (rStart = parsePercent$1(itemModel.get('r0'), size / 2)), null != itemModel.get('r') && (rEnd = parsePercent$1(itemModel.get('r'), size / 2)), node.setLayout({ angle: angle, startAngle: startAngle, endAngle: endAngle, clockwise: clockwise, cx: cx, cy: cy, r0: rStart, r: rEnd }); } if (node.children && node.children.length) { var siblingAngle_1 = 0; each(node.children, function(node) { siblingAngle_1 += renderNode(node, startAngle + siblingAngle_1); }); } return endAngle - startAngle; } }; if (renderRollupNode) { var angle = 2 * Math.PI; virtualRoot.setLayout({ angle: angle, startAngle: startAngle, endAngle: startAngle + angle, clockwise: clockwise, cx: cx, cy: cy, r0: r0, r: r0 + rPerLevel }); } renderNode(treeRoot, startAngle); }); } function sunburstVisual(ecModel) { var paletteScope = {}; ecModel.eachSeriesByType('sunburst', function(seriesModel) { var data = seriesModel.getData(), tree = data.tree; tree.eachNode(function(node) { var style = node.getModel().getModel('itemStyle').getItemStyle(); style.fill || (style.fill = function(node, seriesModel, treeHeight) { for(var current = node; current && current.depth > 1;)current = current.parentNode; var color = seriesModel.getColorFromPalette(current.name || current.dataIndex + '', paletteScope); return node.depth > 1 && 'string' == typeof color && (color = lift(color, (node.depth - 1) / (treeHeight - 1) * 0.5)), color; }(node, seriesModel, tree.root.height)), extend(data.ensureUniqueItemVisual(node.dataIndex, 'style'), style); }); }); } function dataToCoordSize(dataSize, dataItem) { return dataItem = dataItem || [ 0, 0 ], map([ 'x', 'y' ], function(dim, dimIdx) { var axis = this.getAxis(dim), val = dataItem[dimIdx], halfSize = dataSize[dimIdx] / 2; return 'category' === axis.type ? axis.getBandWidth() : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize)); }, this); } function dataToCoordSize$1(dataSize, dataItem) { return dataItem = dataItem || [ 0, 0 ], map([ 0, 1 ], function(dimIdx) { var val = dataItem[dimIdx], halfSize = dataSize[dimIdx] / 2, p1 = [], p2 = []; return p1[dimIdx] = val - halfSize, p2[dimIdx] = val + halfSize, p1[1 - dimIdx] = p2[1 - dimIdx] = dataItem[1 - dimIdx], Math.abs(this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx]); }, this); } function dataToCoordSize$2(dataSize, dataItem) { var axis = this.getAxis(), val = dataItem instanceof Array ? dataItem[0] : dataItem, halfSize = (dataSize instanceof Array ? dataSize[0] : dataSize) / 2; return 'category' === axis.type ? axis.getBandWidth() : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize)); } function dataToCoordSize$3(dataSize, dataItem) { return dataItem = dataItem || [ 0, 0 ], map([ 'Radius', 'Angle' ], function(dim, dimIdx) { var axis = this['get' + dim + 'Axis'](), val = dataItem[dimIdx], halfSize = dataSize[dimIdx] / 2, result = 'category' === axis.type ? axis.getBandWidth() : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize)); return 'Angle' === dim && (result = result * Math.PI / 180), result; }, this); } var deprecatedLogs = {}; function isEC4CompatibleStyle(style, elType, hasOwnTextContentOption, hasOwnTextConfig) { return style && (style.legacy || !1 !== style.legacy && !hasOwnTextContentOption && !hasOwnTextConfig && 'tspan' !== elType && ('text' === elType || hasOwn(style, 'text'))); } function convertFromEC4CompatibleStyle(hostStyle, elType, isNormal) { var textConfig, textContent, textContentStyle; if ('text' === elType) textContentStyle = hostStyle; else { textContentStyle = {}, hasOwn(hostStyle, 'text') && (textContentStyle.text = hostStyle.text), hasOwn(hostStyle, 'rich') && (textContentStyle.rich = hostStyle.rich), hasOwn(hostStyle, 'textFill') && (textContentStyle.fill = hostStyle.textFill), hasOwn(hostStyle, 'textStroke') && (textContentStyle.stroke = hostStyle.textStroke), textContent = { type: 'text', style: textContentStyle, silent: !0 }, textConfig = {}; var hasOwnPos = hasOwn(hostStyle, 'textPosition'); isNormal ? textConfig.position = hasOwnPos ? hostStyle.textPosition : 'inside' : hasOwnPos && (textConfig.position = hostStyle.textPosition), hasOwn(hostStyle, 'textPosition') && (textConfig.position = hostStyle.textPosition), hasOwn(hostStyle, 'textOffset') && (textConfig.offset = hostStyle.textOffset), hasOwn(hostStyle, 'textRotation') && (textConfig.rotation = hostStyle.textRotation), hasOwn(hostStyle, 'textDistance') && (textConfig.distance = hostStyle.textDistance); } return convertEC4CompatibleRichItem(textContentStyle, hostStyle), each(textContentStyle.rich, function(richItem) { convertEC4CompatibleRichItem(richItem, richItem); }), { textConfig: textConfig, textContent: textContent }; } function convertEC4CompatibleRichItem(out, richItem) { richItem && (richItem.font = richItem.textFont || richItem.font, hasOwn(richItem, 'textStrokeWidth') && (out.lineWidth = richItem.textStrokeWidth), hasOwn(richItem, 'textAlign') && (out.align = richItem.textAlign), hasOwn(richItem, 'textVerticalAlign') && (out.verticalAlign = richItem.textVerticalAlign), hasOwn(richItem, 'textLineHeight') && (out.lineHeight = richItem.textLineHeight), hasOwn(richItem, 'textWidth') && (out.width = richItem.textWidth), hasOwn(richItem, 'textHeight') && (out.height = richItem.textHeight), hasOwn(richItem, 'textBackgroundColor') && (out.backgroundColor = richItem.textBackgroundColor), hasOwn(richItem, 'textPadding') && (out.padding = richItem.textPadding), hasOwn(richItem, 'textBorderColor') && (out.borderColor = richItem.textBorderColor), hasOwn(richItem, 'textBorderWidth') && (out.borderWidth = richItem.textBorderWidth), hasOwn(richItem, 'textBorderRadius') && (out.borderRadius = richItem.textBorderRadius), hasOwn(richItem, 'textBoxShadowColor') && (out.shadowColor = richItem.textBoxShadowColor), hasOwn(richItem, 'textBoxShadowBlur') && (out.shadowBlur = richItem.textBoxShadowBlur), hasOwn(richItem, 'textBoxShadowOffsetX') && (out.shadowOffsetX = richItem.textBoxShadowOffsetX), hasOwn(richItem, 'textBoxShadowOffsetY') && (out.shadowOffsetY = richItem.textBoxShadowOffsetY)); } function convertToEC4StyleForCustomSerise(itemStl, txStl, txCfg) { var out = itemStl; out.textPosition = out.textPosition || txCfg.position || 'inside', null != txCfg.offset && (out.textOffset = txCfg.offset), null != txCfg.rotation && (out.textRotation = txCfg.rotation), null != txCfg.distance && (out.textDistance = txCfg.distance); var isInside = out.textPosition.indexOf('inside') >= 0, hostFill = itemStl.fill || '#000'; convertToEC4RichItem(out, txStl); var textFillNotSet = null == out.textFill; return isInside ? textFillNotSet && (out.textFill = txCfg.insideFill || '#fff', !out.textStroke && txCfg.insideStroke && (out.textStroke = txCfg.insideStroke), out.textStroke || (out.textStroke = hostFill), null == out.textStrokeWidth && (out.textStrokeWidth = 2)) : (textFillNotSet && (out.textFill = itemStl.fill || txCfg.outsideFill || '#000'), !out.textStroke && txCfg.outsideStroke && (out.textStroke = txCfg.outsideStroke)), out.text = txStl.text, out.rich = txStl.rich, each(txStl.rich, function(richItem) { convertToEC4RichItem(richItem, richItem); }), out; } function convertToEC4RichItem(out, richItem) { richItem && (hasOwn(richItem, 'fill') && (out.textFill = richItem.fill), hasOwn(richItem, 'stroke') && (out.textStroke = richItem.fill), hasOwn(richItem, 'lineWidth') && (out.textStrokeWidth = richItem.lineWidth), hasOwn(richItem, 'font') && (out.font = richItem.font), hasOwn(richItem, 'fontStyle') && (out.fontStyle = richItem.fontStyle), hasOwn(richItem, 'fontWeight') && (out.fontWeight = richItem.fontWeight), hasOwn(richItem, 'fontSize') && (out.fontSize = richItem.fontSize), hasOwn(richItem, 'fontFamily') && (out.fontFamily = richItem.fontFamily), hasOwn(richItem, 'align') && (out.textAlign = richItem.align), hasOwn(richItem, 'verticalAlign') && (out.textVerticalAlign = richItem.verticalAlign), hasOwn(richItem, 'lineHeight') && (out.textLineHeight = richItem.lineHeight), hasOwn(richItem, 'width') && (out.textWidth = richItem.width), hasOwn(richItem, 'height') && (out.textHeight = richItem.height), hasOwn(richItem, 'backgroundColor') && (out.textBackgroundColor = richItem.backgroundColor), hasOwn(richItem, 'padding') && (out.textPadding = richItem.padding), hasOwn(richItem, 'borderColor') && (out.textBorderColor = richItem.borderColor), hasOwn(richItem, 'borderWidth') && (out.textBorderWidth = richItem.borderWidth), hasOwn(richItem, 'borderRadius') && (out.textBorderRadius = richItem.borderRadius), hasOwn(richItem, 'shadowColor') && (out.textBoxShadowColor = richItem.shadowColor), hasOwn(richItem, 'shadowBlur') && (out.textBoxShadowBlur = richItem.shadowBlur), hasOwn(richItem, 'shadowOffsetX') && (out.textBoxShadowOffsetX = richItem.shadowOffsetX), hasOwn(richItem, 'shadowOffsetY') && (out.textBoxShadowOffsetY = richItem.shadowOffsetY), hasOwn(richItem, 'textShadowColor') && (out.textShadowColor = richItem.textShadowColor), hasOwn(richItem, 'textShadowBlur') && (out.textShadowBlur = richItem.textShadowBlur), hasOwn(richItem, 'textShadowOffsetX') && (out.textShadowOffsetX = richItem.textShadowOffsetX), hasOwn(richItem, 'textShadowOffsetY') && (out.textShadowOffsetY = richItem.textShadowOffsetY)); } function warnDeprecated(deprecated, insteadApproach) { var key = deprecated + '^_^' + insteadApproach; deprecatedLogs[key] || (console.warn("[ECharts] DEPRECATED: \"" + deprecated + "\" has been deprecated. " + insteadApproach), deprecatedLogs[key] = !0); } var CMD$4 = PathProxy.CMD, PI2$a = 2 * Math.PI, PROP_XY = [ 'x', 'y' ], PROP_WH = [ 'width', 'height' ], tmpArr$1 = []; function aroundEqual(a, b) { return 1e-5 > Math.abs(a - b); } function pathToBezierCurves(path) { var currentSubpath, x1, y1, x2, y2, data = path.data, len = path.len(), bezierArray = [], xi = 0, yi = 0, x0 = 0, y0 = 0; function createNewSubpath(x, y) { currentSubpath && currentSubpath.length > 2 && bezierArray.push(currentSubpath), currentSubpath = [ x, y ]; } function addLine(x0, y0, x1, y1) { aroundEqual(x0, x1) && aroundEqual(y0, y1) || currentSubpath.push(x0, y0, x1, y1, x1, y1); } for(var i = 0; i < len;){ var cmd = data[i++], isFirst = 1 === i; switch(isFirst && (xi = data[i], yi = data[i + 1], x0 = xi, y0 = yi, (cmd === CMD$4.L || cmd === CMD$4.C || cmd === CMD$4.Q) && (currentSubpath = [ x0, y0 ])), cmd){ case CMD$4.M: xi = x0 = data[i++], yi = y0 = data[i++], createNewSubpath(x0, y0); break; case CMD$4.L: addLine(xi, yi, x1 = data[i++], y1 = data[i++]), xi = x1, yi = y1; break; case CMD$4.C: currentSubpath.push(data[i++], data[i++], data[i++], data[i++], xi = data[i++], yi = data[i++]); break; case CMD$4.Q: x1 = data[i++], y1 = data[i++], x2 = data[i++], y2 = data[i++], currentSubpath.push(xi + 2 / 3 * (x1 - xi), yi + 2 / 3 * (y1 - yi), x2 + 2 / 3 * (x1 - x2), y2 + 2 / 3 * (y1 - y2), x2, y2), xi = x2, yi = y2; break; case CMD$4.A: var cx = data[i++], cy = data[i++], rx = data[i++], ry = data[i++], startAngle = data[i++], endAngle = data[i++] + startAngle; i += 1; var anticlockwise = !data[i++]; x1 = Math.cos(startAngle) * rx + cx, y1 = Math.sin(startAngle) * ry + cy, isFirst ? createNewSubpath(x0 = x1, y0 = y1) : addLine(xi, yi, x1, y1), xi = Math.cos(endAngle) * rx + cx, yi = Math.sin(endAngle) * ry + cy; for(var step = (anticlockwise ? -1 : 1) * Math.PI / 2, angle = startAngle; anticlockwise ? angle > endAngle : angle < endAngle; angle += step){ var nextAngle = anticlockwise ? Math.max(angle + step, endAngle) : Math.min(angle + step, endAngle); !function(startAngle, endAngle, cx, cy, rx, ry) { var len = 4 * Math.tan(Math.abs(endAngle - startAngle) / 4) / 3, dir = endAngle < startAngle ? -1 : 1, c1 = Math.cos(startAngle), s1 = Math.sin(startAngle), c2 = Math.cos(endAngle), s2 = Math.sin(endAngle), x4 = c2 * rx + cx, y4 = s2 * ry + cy, hx = rx * len * dir, hy = ry * len * dir; currentSubpath.push(c1 * rx + cx - hx * s1, s1 * ry + cy + hy * c1, x4 + hx * s2, y4 - hy * c2, x4, y4); }(angle, nextAngle, cx, cy, rx, ry); } break; case CMD$4.R: x0 = xi = data[i++], y0 = yi = data[i++], x1 = x0 + data[i++], y1 = y0 + data[i++], createNewSubpath(x1, y0), addLine(x1, y0, x1, y1), addLine(x1, y1, x0, y1), addLine(x0, y1, x0, y0), addLine(x0, y0, x1, y0); break; case CMD$4.Z: currentSubpath && addLine(xi, yi, x0, y0), xi = x0, yi = y0; } } return currentSubpath && currentSubpath.length > 2 && bezierArray.push(currentSubpath), bezierArray; } function createSubpath(lastSubpathSubpath, otherSubpath) { for(var len = lastSubpathSubpath.length, lastX = lastSubpathSubpath[len - 2], lastY = lastSubpathSubpath[len - 1], newSubpath = [], i = 0; i < otherSubpath.length;)newSubpath[i++] = lastX, newSubpath[i++] = lastY; return newSubpath; } function centroid(array) { for(var signedArea = 0, cx = 0, cy = 0, len = array.length, i = 0, j = len - 2; i < len; j = i, i += 2){ var x0 = array[j], y0 = array[j + 1], x1 = array[i], y1 = array[i + 1], a = x0 * y1 - x1 * y0; signedArea += a, cx += (x0 + x1) * a, cy += (y0 + y1) * a; } return 0 === signedArea ? [ array[0] || 0, array[1] || 0 ] : [ cx / signedArea / 3, cy / signedArea / 3, signedArea ]; } function morphPath(fromPath, toPath, animationOpts) { if (!fromPath || !toPath) return toPath; fromPath.path || fromPath.createPathProxy(), (fromPathProxy = fromPath.path).beginPath(), fromPath.buildPath(fromPathProxy, fromPath.shape), toPath.path || toPath.createPathProxy(), (toPathProxy = toPath.path) === fromPathProxy && (toPathProxy = new PathProxy(!1)), toPathProxy.beginPath(), isIndividualMorphingPath(toPath) ? toPath.__oldBuildPath(toPathProxy, toPath.shape) : toPath.buildPath(toPathProxy, toPath.shape); var fromPathProxy, toPathProxy, _a = function(array1, array2) { for(var _a, lastSubpath1, lastSubpath2, newArray1 = [], newArray2 = [], i = 0; i < Math.max(array1.length, array2.length); i++){ var subpath1 = array1[i], subpath2 = array2[i], newSubpath1 = void 0, newSubpath2 = void 0; subpath1 ? subpath2 ? (newSubpath1 = (_a = function(subpath1, subpath2) { var len1 = subpath1.length, len2 = subpath2.length; if (len1 === len2) return [ subpath1, subpath2 ]; for(var shorterPath = len1 < len2 ? subpath1 : subpath2, shorterLen = Math.min(len1, len2), diff = Math.abs(len2 - len1) / 6, eachCurveSubDivCount = Math.ceil(diff / ((shorterLen - 2) / 6)) + 1, newSubpath = [ shorterPath[0], shorterPath[1] ], remained = diff, tmpSegX = [], tmpSegY = [], i = 2; i < shorterLen;){ var x0 = shorterPath[i - 2], y0 = shorterPath[i - 1], x1 = shorterPath[i++], y1 = shorterPath[i++], x2 = shorterPath[i++], y2 = shorterPath[i++], x3 = shorterPath[i++], y3 = shorterPath[i++]; if (remained <= 0) { newSubpath.push(x1, y1, x2, y2, x3, y3); continue; } for(var actualSubDivCount = Math.min(remained, eachCurveSubDivCount - 1) + 1, k = 1; k <= actualSubDivCount; k++){ var p = k / actualSubDivCount; cubicSubdivide(x0, x1, x2, x3, p, tmpSegX), cubicSubdivide(y0, y1, y2, y3, p, tmpSegY), x0 = tmpSegX[3], y0 = tmpSegY[3], newSubpath.push(tmpSegX[1], tmpSegY[1], tmpSegX[2], tmpSegY[2], x0, y0), x1 = tmpSegX[5], y1 = tmpSegY[5], x2 = tmpSegX[6], y2 = tmpSegY[6]; } remained -= actualSubDivCount - 1; } return shorterPath === subpath1 ? [ newSubpath, subpath2 ] : [ subpath1, newSubpath ]; }(subpath1, subpath2))[0], newSubpath2 = _a[1], lastSubpath1 = newSubpath1, lastSubpath2 = newSubpath2) : (newSubpath2 = createSubpath(lastSubpath2 || subpath1, subpath1), newSubpath1 = subpath1) : (newSubpath1 = createSubpath(lastSubpath1 || subpath2, subpath2), newSubpath2 = subpath2), newArray1.push(newSubpath1), newArray2.push(newSubpath2); } return [ newArray1, newArray2 ]; }(pathToBezierCurves(fromPathProxy), pathToBezierCurves(toPathProxy)); !function(path, morphingData, morphT) { if (isIndividualMorphingPath(path)) { updateIndividualMorphingPath(path, morphingData, morphT); return; } var morphingPath = path; morphingPath.__oldBuildPath = morphingPath.buildPath, morphingPath.buildPath = morphingPathBuildPath, updateIndividualMorphingPath(morphingPath, morphingData, morphT); }(toPath, function(fromArr, toArr, searchAngleIteration, searchAngleRange) { for(var fromNeedsReverse, result = [], i = 0; i < fromArr.length; i++){ var fromSubpathBezier = fromArr[i], toSubpathBezier = toArr[i], fromCp = centroid(fromSubpathBezier), toCp = centroid(toSubpathBezier); null == fromNeedsReverse && (fromNeedsReverse = fromCp[2] < 0 != toCp[2] < 0); var newFromSubpathBezier = [], newToSubpathBezier = [], bestAngle = 0, bestScore = 1 / 0, tmpArr_1 = [], len = fromSubpathBezier.length; fromNeedsReverse && (fromSubpathBezier = function(array) { for(var newArr = [], len = array.length, i = 0; i < len; i += 2)newArr[i] = array[len - i - 2], newArr[i + 1] = array[len - i - 1]; return newArr; }(fromSubpathBezier)); for(var offset = 6 * function(fromSubBeziers, toSubBeziers, fromCp, toCp) { for(var bezierCount = (fromSubBeziers.length - 2) / 6, bestScore = 1 / 0, bestOffset = 0, len = fromSubBeziers.length, len2 = len - 2, offset = 0; offset < bezierCount; offset++){ for(var cursorOffset = 6 * offset, score = 0, k = 0; k < len; k += 2){ var idx = 0 === k ? cursorOffset : (cursorOffset + k - 2) % len2 + 2, x0 = fromSubBeziers[idx] - fromCp[0], y0 = fromSubBeziers[idx + 1] - fromCp[1], x1 = toSubBeziers[k] - toCp[0], y1 = toSubBeziers[k + 1] - toCp[1], dx = x1 - x0, dy = y1 - y0; score += dx * dx + dy * dy; } score < bestScore && (bestScore = score, bestOffset = offset); } return bestOffset; }(fromSubpathBezier, toSubpathBezier, fromCp, toCp), len2 = len - 2, k = 0; k < len2; k += 2){ var idx = (offset + k) % len2 + 2; newFromSubpathBezier[k + 2] = fromSubpathBezier[idx] - fromCp[0], newFromSubpathBezier[k + 3] = fromSubpathBezier[idx + 1] - fromCp[1]; } if (newFromSubpathBezier[0] = fromSubpathBezier[offset] - fromCp[0], newFromSubpathBezier[1] = fromSubpathBezier[offset + 1] - fromCp[1], searchAngleIteration > 0) for(var step = searchAngleRange / searchAngleIteration, angle = -searchAngleRange / 2; angle <= searchAngleRange / 2; angle += step){ for(var sa = Math.sin(angle), ca = Math.cos(angle), score = 0, k = 0; k < fromSubpathBezier.length; k += 2){ var x0 = newFromSubpathBezier[k], y0 = newFromSubpathBezier[k + 1], x1 = toSubpathBezier[k] - toCp[0], y1 = toSubpathBezier[k + 1] - toCp[1], newX1 = x1 * ca - y1 * sa, newY1 = x1 * sa + y1 * ca; tmpArr_1[k] = newX1, tmpArr_1[k + 1] = newY1; var dx = newX1 - x0, dy = newY1 - y0; score += dx * dx + dy * dy; } if (score < bestScore) { bestScore = score, bestAngle = angle; for(var m = 0; m < tmpArr_1.length; m++)newToSubpathBezier[m] = tmpArr_1[m]; } } else for(var i_1 = 0; i_1 < len; i_1 += 2)newToSubpathBezier[i_1] = toSubpathBezier[i_1] - toCp[0], newToSubpathBezier[i_1 + 1] = toSubpathBezier[i_1 + 1] - toCp[1]; result.push({ from: newFromSubpathBezier, to: newToSubpathBezier, fromCp: fromCp, toCp: toCp, rotation: -bestAngle }); } return result; }(_a[0], _a[1], 10, Math.PI), 0); var oldDone = animationOpts && animationOpts.done, oldAborted = animationOpts && animationOpts.aborted, oldDuring = animationOpts && animationOpts.during; return toPath.animateTo({ __morphT: 1 }, defaults({ during: function(p) { toPath.dirtyShape(), oldDuring && oldDuring(p); }, done: function() { var path; isIndividualMorphingPath(path = toPath) && (path.buildPath = path.__oldBuildPath, path.__oldBuildPath = path.__morphingData = null), toPath.createPathProxy(), toPath.dirtyShape(), oldDone && oldDone(); }, aborted: function() { oldAborted && oldAborted(); } }, animationOpts)), toPath; } function morphingPathBuildPath(path) { for(var morphingData = this.__morphingData, t = this.__morphT, onet = 1 - t, newCp = [], i = 0; i < morphingData.length; i++){ var item = morphingData[i], from = item.from, to = item.to, angle = item.rotation * t, fromCp = item.fromCp, toCp = item.toCp, sa = Math.sin(angle), ca = Math.cos(angle); lerp(newCp, fromCp, toCp, t); for(var m = 0; m < from.length; m += 2){ var x0 = from[m], y0 = from[m + 1], x1 = to[m], y1 = to[m + 1], x = x0 * onet + x1 * t, y = y0 * onet + y1 * t; tmpArr$1[m] = x * ca - y * sa + newCp[0], tmpArr$1[m + 1] = x * sa + y * ca + newCp[1]; } for(var m = 0; m < from.length;)0 === m && path.moveTo(tmpArr$1[m++], tmpArr$1[m++]), path.bezierCurveTo(tmpArr$1[m++], tmpArr$1[m++], tmpArr$1[m++], tmpArr$1[m++], tmpArr$1[m++], tmpArr$1[m++]); } } function updateIndividualMorphingPath(morphingPath, morphingData, morphT) { morphingPath.__morphingData = morphingData, morphingPath.__morphT = morphT; } function isIndividualMorphingPath(path) { return null != path.__oldBuildPath; } function isCombiningPath(path) { return !!path.__combiningSubList; } function combine(fromPathList, toPath, animationOpts, copyPropsIfDivided) { for(var fromIndividuals = [], separateCount = 0, i = 0; i < fromPathList.length; i++){ var fromPath = fromPathList[i]; if (isCombiningPath(fromPath)) { for(var fromCombiningSubList = fromPath.__combiningSubList, j = 0; j < fromCombiningSubList.length; j++)fromIndividuals.push(fromCombiningSubList[j]); separateCount += fromCombiningSubList.length; } else fromIndividuals.push(fromPath), separateCount++; } if (separateCount) { var toPathSplittedList = divideShape(toPath, separateCount, animationOpts ? animationOpts.dividingMethod : null); assert(toPathSplittedList.length === separateCount); for(var oldDone = animationOpts && animationOpts.done, oldAborted = animationOpts && animationOpts.aborted, oldDuring = animationOpts && animationOpts.during, doneCount = 0, abortedCalled = !1, morphAnimationOpts = defaults({ during: function(p) { oldDuring && oldDuring(p); }, done: function() { ++doneCount === toPathSplittedList.length && (function(path) { if (isCombiningPath(path)) { var combiningPath = path; updateCombiningPathSubList(combiningPath, null), combiningPath.addSelfToZr = combiningPath.__oldAddSelfToZr, combiningPath.removeSelfFromZr = combiningPath.__oldRemoveSelfFromZr, combiningPath.buildPath = combiningPath.__oldBuildPath, combiningPath.childrenRef = combiningPath.__combiningSubList = combiningPath.__oldAddSelfToZr = combiningPath.__oldRemoveSelfFromZr = combiningPath.__oldBuildPath = null; } }(toPath), oldDone && oldDone()); }, aborted: function() { !abortedCalled && (abortedCalled = !0, oldAborted && oldAborted()); } }, animationOpts), i = 0; i < separateCount; i++){ var from = fromIndividuals[i], to = toPathSplittedList[i]; copyPropsIfDivided && copyPropsIfDivided(toPath, to, !0), morphPath(from, to, morphAnimationOpts); } return function(path, combiningSubList) { if (isCombiningPath(path)) { updateCombiningPathSubList(path, combiningSubList); return; } var combiningPath = path; updateCombiningPathSubList(combiningPath, combiningSubList), combiningPath.__oldAddSelfToZr = path.addSelfToZr, combiningPath.__oldRemoveSelfFromZr = path.removeSelfFromZr, combiningPath.addSelfToZr = combiningAddSelfToZr, combiningPath.removeSelfFromZr = combiningRemoveSelfFromZr, combiningPath.__oldBuildPath = combiningPath.buildPath, combiningPath.buildPath = noop, combiningPath.childrenRef = combiningChildrenRef; }(toPath, toPathSplittedList), { fromIndividuals: fromIndividuals, toIndividuals: toPathSplittedList, count: separateCount }; } } function updateCombiningPathSubList(combiningPath, combiningSubList) { if (combiningPath.__combiningSubList !== combiningSubList) { if (combiningPathSubListAddRemoveWithZr(combiningPath, 'removeSelfFromZr'), combiningPath.__combiningSubList = combiningSubList, combiningSubList) for(var i = 0; i < combiningSubList.length; i++)combiningSubList[i].parent = combiningPath; combiningPathSubListAddRemoveWithZr(combiningPath, 'addSelfToZr'); } } function combiningAddSelfToZr(zr) { this.__oldAddSelfToZr(zr), combiningPathSubListAddRemoveWithZr(this, 'addSelfToZr'); } function combiningPathSubListAddRemoveWithZr(path, method) { var combiningSubList = path.__combiningSubList, zr = path.__zr; if (combiningSubList && zr) for(var i = 0; i < combiningSubList.length; i++)combiningSubList[i][method](zr); } function combiningRemoveSelfFromZr(zr) { this.__oldRemoveSelfFromZr(zr); for(var combiningSubList = this.__combiningSubList, i = 0; i < combiningSubList.length; i++)combiningSubList[i].removeSelfFromZr(zr); } function combiningChildrenRef() { return this.__combiningSubList; } function divideShape(path, separateCount, dividingMethod) { return 'duplicate' === dividingMethod ? duplicateShape(path, separateCount) : function(path, separateCount) { var resultPaths = []; if (separateCount <= 0) return resultPaths; if (1 === separateCount) return duplicateShape(path, separateCount); if (path instanceof Rect) for(var toPathShape = path.shape, splitPropIdx = toPathShape.height > toPathShape.width ? 1 : 0, propWH = PROP_WH[splitPropIdx], propXY = PROP_XY[splitPropIdx], subWH = toPathShape[propWH] / separateCount, xyCurr = toPathShape[propXY], i = 0; i < separateCount; i++, xyCurr += subWH){ var subShape = { x: toPathShape.x, y: toPathShape.y, width: toPathShape.width, height: toPathShape.height }; subShape[propXY] = xyCurr, subShape[propWH] = i < separateCount - 1 ? subWH : toPathShape[propXY] + toPathShape[propWH] - xyCurr; var splitted = new Rect({ shape: subShape }); resultPaths.push(splitted); } else { if (!(path instanceof Sector)) return duplicateShape(path, separateCount); for(var end, toPathShape = path.shape, clockwise = toPathShape.clockwise, startAngle = toPathShape.startAngle, endAngle = toPathShape.endAngle, step = ((end = toPathShape.endAngle) + PI2$a * Math[clockwise ? 'ceil' : 'floor']((startAngle - end) / PI2$a) - startAngle) / separateCount, angleCurr = startAngle, i = 0; i < separateCount; i++, angleCurr += step){ var splitted = new Sector({ shape: { cx: toPathShape.cx, cy: toPathShape.cy, r: toPathShape.r, r0: toPathShape.r0, clockwise: clockwise, startAngle: angleCurr, endAngle: i === separateCount - 1 ? endAngle : angleCurr + step } }); resultPaths.push(splitted); } } return resultPaths; }(path, separateCount); } function duplicateShape(path, separateCount) { var resultPaths = []; if (separateCount <= 0) return resultPaths; for(var ctor = path.constructor, i = 0; i < separateCount; i++){ var sub = new ctor({ shape: clone(path.shape) }); resultPaths.push(sub); } return resultPaths; } var inner$9 = makeInner(), TRANSFORM_PROPS = { x: 1, y: 1, scaleX: 1, scaleY: 1, originX: 1, originY: 1, rotation: 1 }, transformPropNamesStr = keys(TRANSFORM_PROPS).join(', '), STYLE_VISUAL_TYPE = { color: 'fill', borderColor: 'stroke' }, NON_STYLE_VISUAL_PROPS = { symbol: 1, symbolSize: 1, symbolKeepAspect: 1, legendSymbol: 1, visualMeta: 1, liftZ: 1, decal: 1 }, EMPHASIS = 'emphasis', NORMAL = 'normal', BLUR = 'blur', SELECT = 'select', STATES = [ NORMAL, EMPHASIS, BLUR, SELECT ], PATH_ITEM_STYLE = { normal: [ 'itemStyle' ], emphasis: [ EMPHASIS, 'itemStyle' ], blur: [ BLUR, 'itemStyle' ], select: [ SELECT, 'itemStyle' ] }, PATH_LABEL = { normal: [ 'label' ], emphasis: [ EMPHASIS, 'label' ], blur: [ BLUR, 'label' ], select: [ SELECT, 'label' ] }, attachedTxInfoTmp = { normal: {}, emphasis: {}, blur: {}, select: {} }, LEGACY_TRANSFORM_PROPS = { position: [ 'x', 'y' ], scale: [ 'scaleX', 'scaleY' ], origin: [ 'originX', 'originY' ] }, tmpTransformable = new Transformable(), prepareCustoms = { cartesian2d: function(coordSys) { var rect = coordSys.master.getRect(); return { coordSys: { type: 'cartesian2d', x: rect.x, y: rect.y, width: rect.width, height: rect.height }, api: { coord: function(data) { return coordSys.dataToPoint(data); }, size: bind(dataToCoordSize, coordSys) } }; }, geo: function(coordSys) { var rect = coordSys.getBoundingRect(); return { coordSys: { type: 'geo', x: rect.x, y: rect.y, width: rect.width, height: rect.height, zoom: coordSys.getZoom() }, api: { coord: function(data) { return coordSys.dataToPoint(data); }, size: bind(dataToCoordSize$1, coordSys) } }; }, singleAxis: function(coordSys) { var rect = coordSys.getRect(); return { coordSys: { type: 'singleAxis', x: rect.x, y: rect.y, width: rect.width, height: rect.height }, api: { coord: function(val) { return coordSys.dataToPoint(val); }, size: bind(dataToCoordSize$2, coordSys) } }; }, polar: function(coordSys) { var radiusAxis = coordSys.getRadiusAxis(), angleAxis = coordSys.getAngleAxis(), radius = radiusAxis.getExtent(); return radius[0] > radius[1] && radius.reverse(), { coordSys: { type: 'polar', cx: coordSys.cx, cy: coordSys.cy, r: radius[1], r0: radius[0] }, api: { coord: function(data) { var radius = radiusAxis.dataToRadius(data[0]), angle = angleAxis.dataToAngle(data[1]), coord = coordSys.coordToPoint([ radius, angle ]); return coord.push(radius, angle * Math.PI / 180), coord; }, size: bind(dataToCoordSize$3, coordSys) } }; }, calendar: function(coordSys) { var rect = coordSys.getRect(), rangeInfo = coordSys.getRangeInfo(); return { coordSys: { type: 'calendar', x: rect.x, y: rect.y, width: rect.width, height: rect.height, cellWidth: coordSys.getCellWidth(), cellHeight: coordSys.getCellHeight(), rangeInfo: { start: rangeInfo.start, end: rangeInfo.end, weeks: rangeInfo.weeks, dayCount: rangeInfo.allDay } }, api: { coord: function(data, clamp) { return coordSys.dataToPoint(data, clamp); } } }; } }, CustomSeriesModel = function(_super) { function CustomSeriesModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = CustomSeriesModel.type, _this; } return __extends(CustomSeriesModel, _super), CustomSeriesModel.prototype.optionUpdated = function() { this.currentZLevel = this.get('zlevel', !0), this.currentZ = this.get('z', !0); }, CustomSeriesModel.prototype.getInitialData = function(option, ecModel) { return createListFromArray(this.getSource(), this); }, CustomSeriesModel.prototype.getDataParams = function(dataIndex, dataType, el) { var params = _super.prototype.getDataParams.call(this, dataIndex, dataType); return el && (params.info = inner$9(el).info), params; }, CustomSeriesModel.type = 'series.custom', CustomSeriesModel.dependencies = [ 'grid', 'polar', 'geo', 'singleAxis', 'calendar' ], CustomSeriesModel.defaultOption = { coordinateSystem: 'cartesian2d', zlevel: 0, z: 2, legendHoverLink: !0, clip: !1 }, CustomSeriesModel; }(SeriesModel), CustomSeriesView = function(_super) { function CustomSeriesView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = CustomSeriesView.type, _this; } return __extends(CustomSeriesView, _super), CustomSeriesView.prototype.render = function(customSeries, ecModel, api, payload) { var oldData = this._data, data = customSeries.getData(), group = this.group, renderItem = makeRenderItem(customSeries, data, ecModel, api), transOpt = customSeries.__transientTransitionOpt; if (transOpt && (null == transOpt.from || null == transOpt.to)) oldData && oldData.each(function(oldIdx) { doRemoveEl(oldData.getItemGraphicEl(oldIdx), customSeries, group); }), data.each(function(newIdx) { createOrUpdateItem(api, null, newIdx, renderItem(newIdx, payload), customSeries, group, data, null); }); else { var morphPreparation_1 = new MorphPreparation(customSeries, transOpt), diffMode = transOpt ? 'multiple' : 'oneToOne'; new DataDiffer(oldData ? oldData.getIndices() : [], data.getIndices(), createGetKey(oldData, diffMode, transOpt && transOpt.from), createGetKey(data, diffMode, transOpt && transOpt.to), null, diffMode).add(function(newIdx) { createOrUpdateItem(api, null, newIdx, renderItem(newIdx, payload), customSeries, group, data, null); }).remove(function(oldIdx) { doRemoveEl(oldData.getItemGraphicEl(oldIdx), customSeries, group); }).update(function(newIdx, oldIdx) { morphPreparation_1.reset('oneToOne'); var oldEl = oldData.getItemGraphicEl(oldIdx); morphPreparation_1.findAndAddFrom(oldEl), morphPreparation_1.hasFrom() && (removeElementDirectly(oldEl, group), oldEl = null), createOrUpdateItem(api, oldEl, newIdx, renderItem(newIdx, payload), customSeries, group, data, morphPreparation_1), morphPreparation_1.applyMorphing(); }).updateManyToOne(function(newIdx, oldIndices) { morphPreparation_1.reset('manyToOne'); for(var i = 0; i < oldIndices.length; i++){ var oldEl = oldData.getItemGraphicEl(oldIndices[i]); morphPreparation_1.findAndAddFrom(oldEl), removeElementDirectly(oldEl, group); } createOrUpdateItem(api, null, newIdx, renderItem(newIdx, payload), customSeries, group, data, morphPreparation_1), morphPreparation_1.applyMorphing(); }).updateOneToMany(function(newIndices, oldIdx) { morphPreparation_1.reset('oneToMany'); var newLen = newIndices.length, oldEl = oldData.getItemGraphicEl(oldIdx); morphPreparation_1.findAndAddFrom(oldEl), removeElementDirectly(oldEl, group); for(var i = 0; i < newLen; i++)createOrUpdateItem(api, null, newIndices[i], renderItem(newIndices[i], payload), customSeries, group, data, morphPreparation_1); morphPreparation_1.applyMorphing(); }).execute(); } var clipPath = customSeries.get('clip', !0) ? createClipPath(customSeries.coordinateSystem, !1, customSeries) : null; clipPath ? group.setClipPath(clipPath) : group.removeClipPath(), this._data = data; }, CustomSeriesView.prototype.incrementalPrepareRender = function(customSeries, ecModel, api) { this.group.removeAll(), this._data = null; }, CustomSeriesView.prototype.incrementalRender = function(params, customSeries, ecModel, api, payload) { var data = customSeries.getData(), renderItem = makeRenderItem(customSeries, data, ecModel, api); function setIncrementalAndHoverLayer(el) { el.isGroup || (el.incremental = !0, el.ensureState('emphasis').hoverLayer = !0); } for(var idx = params.start; idx < params.end; idx++)createOrUpdateItem(null, null, idx, renderItem(idx, payload), customSeries, this.group, data, null).traverse(setIncrementalAndHoverLayer); }, CustomSeriesView.prototype.filterForExposedEvent = function(eventType, query, targetEl, packedEvent) { var elementName = query.element; if (null == elementName || targetEl.name === elementName) return !0; for(; (targetEl = targetEl.__hostTarget || targetEl.parent) && targetEl !== this.group;)if (targetEl.name === elementName) return !0; return !1; }, CustomSeriesView.type = 'custom', CustomSeriesView; }(ChartView); function createGetKey(data, diffMode, dimension) { if (data) { if ('oneToOne' === diffMode) return function(rawIdx, dataIndex) { return data.getId(dataIndex); }; var diffByDimName = data.getDimension(dimension), dimInfo = data.getDimensionInfo(diffByDimName); !dimInfo && throwError(dimension + " is not a valid dimension."); var ordinalMeta = dimInfo.ordinalMeta; return function(rawIdx, dataIndex) { var value, key = data.get(diffByDimName, dataIndex); return ordinalMeta && (key = ordinalMeta.categories[key]), null == key || (value = key) != value ? rawIdx + '' : '_ec_' + key; }; } } function createEl(elOption) { var el, graphicType = elOption.type; if ('path' === graphicType) { var shape = elOption.shape, pathRect = null != shape.width && null != shape.height ? { x: shape.x || 0, y: shape.y || 0, width: shape.width, height: shape.height } : null, pathData = getPathData(shape); inner$9(el = makePath(pathData, null, pathRect, shape.layout || 'center')).customPathData = pathData; } else if ('image' === graphicType) inner$9(el = new ZRImage({})).customImagePath = elOption.style.image; else if ('text' === graphicType) el = new ZRText({}); else if ('group' === graphicType) el = new Group(); else if ('compoundPath' === graphicType) throw Error('"compoundPath" is not supported yet.'); else { var Clz = getShapeClass(graphicType); !Clz && throwError('graphic type "' + graphicType + '" can not be found.'), el = new Clz(); } return inner$9(el).customGraphicType = graphicType, el.name = elOption.name, el.z2EmphasisLift = 1, el.z2SelectLift = 1, el; } function updateElNormal(api, el, isMorphTo, dataIndex, elOption, styleOpt, attachedTxInfo, seriesModel, isInit, isTextContent) { var transFromProps = {}, allPropsFinal = {}, elDisplayable = el.isGroup ? null : el; isMorphTo || prepareShapeOrExtraTransitionFrom('shape', el, null, elOption, transFromProps, isInit), prepareShapeOrExtraAllPropsFinal('shape', elOption, allPropsFinal), isMorphTo || prepareShapeOrExtraTransitionFrom('extra', el, null, elOption, transFromProps, isInit), prepareShapeOrExtraAllPropsFinal('extra', elOption, allPropsFinal), isMorphTo || prepareTransformTransitionFrom(el, null, elOption, transFromProps, isInit), setLagecyTransformProp(elOption, allPropsFinal, 'position'), setLagecyTransformProp(elOption, allPropsFinal, 'scale'), setLagecyTransformProp(elOption, allPropsFinal, 'origin'), setTransformProp(elOption, allPropsFinal, 'x'), setTransformProp(elOption, allPropsFinal, 'y'), setTransformProp(elOption, allPropsFinal, 'scaleX'), setTransformProp(elOption, allPropsFinal, 'scaleY'), setTransformProp(elOption, allPropsFinal, 'originX'), setTransformProp(elOption, allPropsFinal, 'originY'), setTransformProp(elOption, allPropsFinal, 'rotation'); var txCfgOpt = attachedTxInfo && attachedTxInfo.normal.cfg; if (txCfgOpt && el.setTextConfig(txCfgOpt), 'text' === el.type && styleOpt) { var textOptionStyle = styleOpt; hasOwn(textOptionStyle, 'textFill') && (textOptionStyle.fill = textOptionStyle.textFill), hasOwn(textOptionStyle, 'textStroke') && (textOptionStyle.stroke = textOptionStyle.textStroke); } if (styleOpt) { var decalPattern = void 0, decalObj = isPath$1(el) ? styleOpt.decal : null; api && decalObj && (decalObj.dirty = !0, decalPattern = createOrUpdatePatternFromDecal(decalObj, api)), styleOpt.__decalPattern = decalPattern; } return isMorphTo || prepareStyleTransitionFrom(el, null, elOption, styleOpt, transFromProps, isInit), elDisplayable && hasOwn(elOption, 'invisible') && (elDisplayable.invisible = elOption.invisible), isMorphTo || (applyPropsFinal(el, allPropsFinal, styleOpt), applyTransitionFrom(el, dataIndex, elOption, seriesModel, transFromProps, isInit)), hasOwn(elOption, 'silent') && (el.silent = elOption.silent), hasOwn(elOption, 'ignore') && (el.ignore = elOption.ignore), !isTextContent && hasOwn(elOption, 'info') && (inner$9(el).info = elOption.info), styleOpt ? el.dirty() : el.markRedraw(), isMorphTo ? allPropsFinal : null; } function applyPropsFinal(el, allPropsFinal, styleOpt) { var elDisplayable = el.isGroup ? null : el; if (elDisplayable && styleOpt) { var decalPattern = styleOpt.__decalPattern, originalDecalObj = void 0; decalPattern && (originalDecalObj = styleOpt.decal, styleOpt.decal = decalPattern), elDisplayable.useStyle(styleOpt), decalPattern && (styleOpt.decal = originalDecalObj); for(var animators = elDisplayable.animators, i = 0; i < animators.length; i++){ var animator = animators[i]; 'style' === animator.targetName && animator.changeTarget(elDisplayable.style); } } allPropsFinal && el.attr(allPropsFinal); } function applyTransitionFrom(el, dataIndex, elOption, seriesModel, transFromProps, isInit) { if (transFromProps) { var userDuring = elOption.during; inner$9(el).userDuring = userDuring; var cfg = { dataIndex: dataIndex, isFrom: !0, during: userDuring ? bind(duringCall, { el: el, userDuring: userDuring }) : null }; isInit ? initProps(el, transFromProps, seriesModel, cfg) : updateProps(el, transFromProps, seriesModel, cfg); } } function prepareShapeOrExtraTransitionFrom(mainAttr, el, morphFromEl, elOption, transFromProps, isInit) { var transFromPropsInAttr, attrOpt = elOption[mainAttr]; if (attrOpt) { var elPropsInAttr = el[mainAttr], enterFrom = attrOpt.enterFrom; if (isInit && enterFrom) { transFromPropsInAttr || (transFromPropsInAttr = transFromProps[mainAttr] = {}); for(var enterFromKeys = keys(enterFrom), i = 0; i < enterFromKeys.length; i++){ var key = enterFromKeys[i]; transFromPropsInAttr[key] = enterFrom[key]; } } if (!isInit && elPropsInAttr && !(null != morphFromEl && 'shape' === mainAttr)) { if (attrOpt.transition) { transFromPropsInAttr || (transFromPropsInAttr = transFromProps[mainAttr] = {}); for(var transitionKeys = normalizeToArray(attrOpt.transition), i = 0; i < transitionKeys.length; i++){ var key = transitionKeys[i], elVal = elPropsInAttr[key]; checkNonStyleTansitionRefer(key, attrOpt[key], elVal), transFromPropsInAttr[key] = elVal; } } else if (indexOf(elOption.transition, mainAttr) >= 0) { transFromPropsInAttr || (transFromPropsInAttr = transFromProps[mainAttr] = {}); for(var elPropsInAttrKeys = keys(elPropsInAttr), i = 0; i < elPropsInAttrKeys.length; i++){ var optVal, elVal1, key = elPropsInAttrKeys[i], elVal = elPropsInAttr[key]; optVal = attrOpt[key], elVal1 = elVal, (isArrayLike(optVal) ? optVal !== elVal1 : null != optVal && isFinite(optVal)) && (transFromPropsInAttr[key] = elVal); } } } var leaveTo = attrOpt.leaveTo; if (leaveTo) for(var leaveToProps = getOrCreateLeaveToPropsFromEl(el), leaveToPropsInAttr = leaveToProps[mainAttr] || (leaveToProps[mainAttr] = {}), leaveToKeys = keys(leaveTo), i = 0; i < leaveToKeys.length; i++){ var key = leaveToKeys[i]; leaveToPropsInAttr[key] = leaveTo[key]; } } } function prepareShapeOrExtraAllPropsFinal(mainAttr, elOption, allProps) { var attrOpt = elOption[mainAttr]; if (attrOpt) for(var allPropsInAttr = allProps[mainAttr] = {}, keysInAttr = keys(attrOpt), i = 0; i < keysInAttr.length; i++){ var key = keysInAttr[i]; allPropsInAttr[key] = cloneValue(attrOpt[key]); } } function prepareTransformTransitionFrom(el, morphFromEl, elOption, transFromProps, isInit) { var enterFrom = elOption.enterFrom; if (isInit && enterFrom) for(var enterFromKeys = keys(enterFrom), i = 0; i < enterFromKeys.length; i++){ var key = enterFromKeys[i]; checkTransformPropRefer(key, 'el.enterFrom'), transFromProps[key] = enterFrom[key]; } if (!isInit) { if (morphFromEl) { var fromTransformable = function(oldEl, newEl) { if (!oldEl || oldEl === newEl || oldEl.parent === newEl.parent) return oldEl; var tmpM = tmpTransformable.transform || (tmpTransformable.transform = identity([])), oldGlobalTransform = oldEl.getComputedTransform(); oldGlobalTransform ? copy$1(tmpM, oldGlobalTransform) : identity(tmpM); var newParent = newEl.parent; return newParent && newParent.getComputedTransform(), tmpTransformable.originX = oldEl.originX, tmpTransformable.originY = oldEl.originY, tmpTransformable.parent = newParent, tmpTransformable.decomposeTransform(), tmpTransformable; }(morphFromEl, el); setTransformPropToTransitionFrom(transFromProps, 'x', fromTransformable), setTransformPropToTransitionFrom(transFromProps, 'y', fromTransformable), setTransformPropToTransitionFrom(transFromProps, 'scaleX', fromTransformable), setTransformPropToTransitionFrom(transFromProps, 'scaleY', fromTransformable), setTransformPropToTransitionFrom(transFromProps, 'originX', fromTransformable), setTransformPropToTransitionFrom(transFromProps, 'originY', fromTransformable), setTransformPropToTransitionFrom(transFromProps, 'rotation', fromTransformable); } else if (elOption.transition) for(var transitionKeys = normalizeToArray(elOption.transition), i = 0; i < transitionKeys.length; i++){ var key = transitionKeys[i]; if ('style' !== key && 'shape' !== key && 'extra' !== key) { var elVal = el[key]; checkTransformPropRefer(key, 'el.transition'), checkNonStyleTansitionRefer(key, elOption[key], elVal), transFromProps[key] = elVal; } } else setTransformPropToTransitionFrom(transFromProps, 'x', el), setTransformPropToTransitionFrom(transFromProps, 'y', el); } var leaveTo = elOption.leaveTo; if (leaveTo) for(var leaveToProps = getOrCreateLeaveToPropsFromEl(el), leaveToKeys = keys(leaveTo), i = 0; i < leaveToKeys.length; i++){ var key = leaveToKeys[i]; checkTransformPropRefer(key, 'el.leaveTo'), leaveToProps[key] = leaveTo[key]; } } function prepareStyleTransitionFrom(el, morphFromEl, elOption, styleOpt, transFromProps, isInit) { if (styleOpt) { var transFromStyleProps, fromElStyle = (morphFromEl || el).style, enterFrom = styleOpt.enterFrom; if (isInit && enterFrom) { var enterFromKeys = keys(enterFrom); transFromStyleProps || (transFromStyleProps = transFromProps.style = {}); for(var i = 0; i < enterFromKeys.length; i++){ var key = enterFromKeys[i]; transFromStyleProps[key] = enterFrom[key]; } } if (!isInit && fromElStyle) { if (styleOpt.transition) { var transitionKeys = normalizeToArray(styleOpt.transition); transFromStyleProps || (transFromStyleProps = transFromProps.style = {}); for(var i = 0; i < transitionKeys.length; i++){ var key = transitionKeys[i], elVal = fromElStyle[key]; transFromStyleProps[key] = elVal; } } else if (el.getAnimationStyleProps && indexOf(elOption.transition, 'style') >= 0) { var animationProps = el.getAnimationStyleProps(), animationStyleProps = animationProps ? animationProps.style : null; if (animationStyleProps) { transFromStyleProps || (transFromStyleProps = transFromProps.style = {}); for(var styleKeys = keys(styleOpt), i = 0; i < styleKeys.length; i++){ var key = styleKeys[i]; if (animationStyleProps[key]) { var elVal = fromElStyle[key]; transFromStyleProps[key] = elVal; } } } } } var leaveTo = styleOpt.leaveTo; if (leaveTo) for(var leaveToKeys = keys(leaveTo), leaveToProps = getOrCreateLeaveToPropsFromEl(el), leaveToStyleProps = leaveToProps.style || (leaveToProps.style = {}), i = 0; i < leaveToKeys.length; i++){ var key = leaveToKeys[i]; leaveToStyleProps[key] = leaveTo[key]; } } } function getOrCreateLeaveToPropsFromEl(el) { var innerEl = inner$9(el); return innerEl.leaveToProps || (innerEl.leaveToProps = {}); } checkNonStyleTansitionRefer = function(propName, optVal, elVal) { isArrayLike(optVal) ? assert(optVal !== elVal, 'Prop `' + propName + '` must use different Array object each time for transition.') : assert(null != optVal && isFinite(optVal), 'Prop `' + propName + '` must refer to a finite number or ArrayLike for transition.'); }, checkTransformPropRefer = function(key, usedIn) { assert(hasOwn(TRANSFORM_PROPS, key), 'Prop `' + key + '` is not a permitted in `' + usedIn + "`. Only `" + keys(TRANSFORM_PROPS).join('`, `') + '` are permitted.'); }; var tmpDuringScope = {}, customDuringAPI = { setTransform: function(key, val) { return assert(hasOwn(TRANSFORM_PROPS, key), 'Only ' + transformPropNamesStr + ' available in `setTransform`.'), tmpDuringScope.el[key] = val, this; }, getTransform: function(key) { return assert(hasOwn(TRANSFORM_PROPS, key), 'Only ' + transformPropNamesStr + ' available in `getTransform`.'), tmpDuringScope.el[key]; }, setShape: function(key, val) { return assertNotReserved(key), (tmpDuringScope.el.shape || (tmpDuringScope.el.shape = {}))[key] = val, tmpDuringScope.isShapeDirty = !0, this; }, getShape: function(key) { assertNotReserved(key); var shape = tmpDuringScope.el.shape; if (shape) return shape[key]; }, setStyle: function(key, val) { assertNotReserved(key); var style = tmpDuringScope.el.style; return style && (val != val && warn('style.' + key + ' must not be assigned with NaN.'), style[key] = val, tmpDuringScope.isStyleDirty = !0), this; }, getStyle: function(key) { assertNotReserved(key); var style = tmpDuringScope.el.style; if (style) return style[key]; }, setExtra: function(key, val) { return assertNotReserved(key), (tmpDuringScope.el.extra || (tmpDuringScope.el.extra = {}))[key] = val, this; }, getExtra: function(key) { assertNotReserved(key); var extra = tmpDuringScope.el.extra; if (extra) return extra[key]; } }; function assertNotReserved(key) { if ('transition' === key || 'enterFrom' === key || 'leaveTo' === key) throw Error('key must not be "' + key + '"'); } function duringCall() { var scope = this, el = scope.el; if (el) { var newstUserDuring = inner$9(el).userDuring, scopeUserDuring = scope.userDuring; if (newstUserDuring !== scopeUserDuring) { scope.el = scope.userDuring = null; return; } tmpDuringScope.el = el, tmpDuringScope.isShapeDirty = !1, tmpDuringScope.isStyleDirty = !1, scopeUserDuring(customDuringAPI), tmpDuringScope.isShapeDirty && el.dirtyShape && el.dirtyShape(), tmpDuringScope.isStyleDirty && el.dirtyStyle && el.dirtyStyle(); } } function updateElOnState(state, el, elStateOpt, styleOpt, attachedTxInfo, isRoot, isTextContent) { var elDisplayable = el.isGroup ? null : el, txCfgOpt = attachedTxInfo && attachedTxInfo[state].cfg; if (elDisplayable) { var stateObj = elDisplayable.ensureState(state); if (!1 === styleOpt) { var existingEmphasisState = elDisplayable.getState(state); existingEmphasisState && (existingEmphasisState.style = null); } else stateObj.style = styleOpt || null; txCfgOpt && (stateObj.textConfig = txCfgOpt), setDefaultStateProxy(elDisplayable); } } function setLagecyTransformProp(elOption, targetProps, legacyName, fromTransformable) { var legacyArr = elOption[legacyName], xyName = LEGACY_TRANSFORM_PROPS[legacyName]; legacyArr && (fromTransformable ? (targetProps[xyName[0]] = fromTransformable[xyName[0]], targetProps[xyName[1]] = fromTransformable[xyName[1]]) : (targetProps[xyName[0]] = legacyArr[0], targetProps[xyName[1]] = legacyArr[1])); } function setTransformProp(elOption, allProps, name, fromTransformable) { null != elOption[name] && (allProps[name] = fromTransformable ? fromTransformable[name] : elOption[name]); } function setTransformPropToTransitionFrom(transitionFrom, name, fromTransformable) { fromTransformable && (transitionFrom[name] = fromTransformable[name]); } function makeRenderItem(customSeries, data, ecModel, api) { var data1, encodeDef, currDataIndexInside, currItemModel, renderItem = customSeries.get('renderItem'), coordSys = customSeries.coordinateSystem, prepareResult = {}; coordSys && (assert(renderItem, 'series.render is required.'), assert(coordSys.prepareCustoms || prepareCustoms[coordSys.type], 'This coordSys does not support custom series.'), prepareResult = coordSys.prepareCustoms ? coordSys.prepareCustoms(coordSys) : prepareCustoms[coordSys.type](coordSys)); for(var userAPI = defaults({ getWidth: api.getWidth, getHeight: api.getHeight, getZr: api.getZr, getDevicePixelRatio: api.getDevicePixelRatio, value: function(dim, dataIndexInside) { return null == dataIndexInside && (dataIndexInside = currDataIndexInside), data.get(data.getDimension(dim || 0), dataIndexInside); }, style: function(userProps, dataIndexInside) { warnDeprecated('api.style', 'Please write literal style directly instead.'), null == dataIndexInside && (dataIndexInside = currDataIndexInside); var style = data.getItemVisual(dataIndexInside, 'style'), visualColor = style && style.fill, opacity = style && style.opacity, itemStyle = getItemStyleModel(dataIndexInside, NORMAL).getItemStyle(); null != visualColor && (itemStyle.fill = visualColor), null != opacity && (itemStyle.opacity = opacity); var opt = { inheritColor: isString(visualColor) ? visualColor : '#000' }, labelModel = getLabelModel(dataIndexInside, NORMAL), textStyle = createTextStyle(labelModel, null, opt, !1, !0); textStyle.text = labelModel.getShallow('show') ? retrieve2(customSeries.getFormattedLabel(dataIndexInside, NORMAL), getDefaultLabel(data, dataIndexInside)) : null; var textConfig = createTextConfig(labelModel, opt, !1); return preFetchFromExtra(userProps, itemStyle), itemStyle = convertToEC4StyleForCustomSerise(itemStyle, textStyle, textConfig), userProps && applyUserPropsAfter(itemStyle, userProps), itemStyle.legacy = !0, itemStyle; }, ordinalRawValue: function(dim, dataIndexInside) { null == dataIndexInside && (dataIndexInside = currDataIndexInside); var dimInfo = data.getDimensionInfo(dim || 0); if (dimInfo) { var val = data.get(dimInfo.name, dataIndexInside), ordinalMeta = dimInfo && dimInfo.ordinalMeta; return ordinalMeta ? ordinalMeta.categories[val] : val; } }, styleEmphasis: function(userProps, dataIndexInside) { warnDeprecated('api.styleEmphasis', 'Please write literal style directly instead.'), null == dataIndexInside && (dataIndexInside = currDataIndexInside); var itemStyle = getItemStyleModel(dataIndexInside, EMPHASIS).getItemStyle(), labelModel = getLabelModel(dataIndexInside, EMPHASIS), textStyle = createTextStyle(labelModel, null, null, !0, !0); textStyle.text = labelModel.getShallow('show') ? retrieve3(customSeries.getFormattedLabel(dataIndexInside, EMPHASIS), customSeries.getFormattedLabel(dataIndexInside, NORMAL), getDefaultLabel(data, dataIndexInside)) : null; var textConfig = createTextConfig(labelModel, null, !0); return preFetchFromExtra(userProps, itemStyle), itemStyle = convertToEC4StyleForCustomSerise(itemStyle, textStyle, textConfig), userProps && applyUserPropsAfter(itemStyle, userProps), itemStyle.legacy = !0, itemStyle; }, visual: function(visualType, dataIndexInside) { if (null == dataIndexInside && (dataIndexInside = currDataIndexInside), hasOwn(STYLE_VISUAL_TYPE, visualType)) { var style_1 = data.getItemVisual(dataIndexInside, 'style'); return style_1 ? style_1[STYLE_VISUAL_TYPE[visualType]] : null; } if (hasOwn(NON_STYLE_VISUAL_PROPS, visualType)) return data.getItemVisual(dataIndexInside, visualType); }, barLayout: function(opt) { if ('cartesian2d' === coordSys.type) return function(opt) { var params = [], baseAxis = opt.axis, axisKey = 'axis0'; if ('category' === baseAxis.type) { for(var bandWidth = baseAxis.getBandWidth(), i = 0; i < opt.count; i++)params.push(defaults({ bandWidth: bandWidth, axisKey: axisKey, stackId: STACK_PREFIX + i }, opt)); for(var widthAndOffsets = doCalBarWidthAndOffset(params), result = [], i = 0; i < opt.count; i++){ var item = widthAndOffsets[axisKey][STACK_PREFIX + i]; item.offsetCenter = item.offset + item.width / 2, result.push(item); } return result; } }(defaults({ axis: coordSys.getBaseAxis() }, opt)); }, currentSeriesIndices: function() { return ecModel.getCurrentSeriesIndices(); }, font: function(opt) { return getFont(opt, ecModel); } }, prepareResult.api || {}), userParams = { context: {}, seriesId: customSeries.id, seriesName: customSeries.name, seriesIndex: customSeries.seriesIndex, coordSys: prepareResult.coordSys, dataInsideLength: data.count(), encode: (data1 = customSeries.getData(), encodeDef = {}, each(data1.dimensions, function(dimName, dataDimIndex) { var dimInfo = data1.getDimensionInfo(dimName); if (!dimInfo.isExtraCoord) { var coordDim = dimInfo.coordDim; (encodeDef[coordDim] = encodeDef[coordDim] || [])[dimInfo.coordDimIndex] = dataDimIndex; } }), encodeDef) }, currItemStyleModels = {}, currLabelModels = {}, seriesItemStyleModels = {}, seriesLabelModels = {}, i = 0; i < STATES.length; i++){ var stateName = STATES[i]; seriesItemStyleModels[stateName] = customSeries.getModel(PATH_ITEM_STYLE[stateName]), seriesLabelModels[stateName] = customSeries.getModel(PATH_LABEL[stateName]); } function getItemModel(dataIndexInside) { return dataIndexInside === currDataIndexInside ? currItemModel || (currItemModel = data.getItemModel(dataIndexInside)) : data.getItemModel(dataIndexInside); } function getItemStyleModel(dataIndexInside, state) { return data.hasItemOption ? dataIndexInside === currDataIndexInside ? currItemStyleModels[state] || (currItemStyleModels[state] = getItemModel(dataIndexInside).getModel(PATH_ITEM_STYLE[state])) : getItemModel(dataIndexInside).getModel(PATH_ITEM_STYLE[state]) : seriesItemStyleModels[state]; } function getLabelModel(dataIndexInside, state) { return data.hasItemOption ? dataIndexInside === currDataIndexInside ? currLabelModels[state] || (currLabelModels[state] = getItemModel(dataIndexInside).getModel(PATH_LABEL[state])) : getItemModel(dataIndexInside).getModel(PATH_LABEL[state]) : seriesLabelModels[state]; } return function(dataIndexInside, payload) { return currDataIndexInside = dataIndexInside, currItemModel = null, currItemStyleModels = {}, currLabelModels = {}, renderItem && renderItem(defaults({ dataIndexInside: dataIndexInside, dataIndex: data.getRawIndex(dataIndexInside), actionType: payload ? payload.type : null }, userParams), userAPI); }; function applyUserPropsAfter(itemStyle, extra) { for(var key in extra)hasOwn(extra, key) && (itemStyle[key] = extra[key]); } function preFetchFromExtra(extra, itemStyle) { extra && (extra.textFill && (itemStyle.textFill = extra.textFill), extra.textPosition && (itemStyle.textPosition = extra.textPosition)); } } function createOrUpdateItem(api, el, dataIndex, elOption, seriesModel, group, data, morphPreparation) { if (!elOption) { removeElementDirectly(el, group); return; } return (el = doCreateOrUpdateEl(api, el, dataIndex, elOption, seriesModel, group, !0, morphPreparation)) && data.setItemGraphicEl(dataIndex, el), enableHoverEmphasis(el, elOption.focus, elOption.blurScope), el; } function doCreateOrUpdateEl(api, el, dataIndex, elOption, seriesModel, group, isRoot, morphPreparation) { assert(elOption, 'should not have an null/undefined element setting'); var toBeReplacedIdx = -1; el && doesElNeedRecreate(el, elOption) && (toBeReplacedIdx = group.childrenRef().indexOf(el), el = null); var elIsNewCreated = !el; el ? el.clearStates() : el = createEl(elOption); var thisElIsMorphTo = (inner$9(el).canMorph = elOption.morph && isPath$1(el)) && morphPreparation && morphPreparation.hasFrom(), isInit = elIsNewCreated && !thisElIsMorphTo; attachedTxInfoTmp.normal.cfg = attachedTxInfoTmp.normal.conOpt = attachedTxInfoTmp.emphasis.cfg = attachedTxInfoTmp.emphasis.conOpt = attachedTxInfoTmp.blur.cfg = attachedTxInfoTmp.blur.conOpt = attachedTxInfoTmp.select.cfg = attachedTxInfoTmp.select.conOpt = null, attachedTxInfoTmp.isLegacy = !1, function(el, dataIndex, elOption, seriesModel, isInit, attachedTxInfo) { if (!el.isGroup) { processTxInfo(elOption, null, attachedTxInfo), processTxInfo(elOption, EMPHASIS, attachedTxInfo); var txConOptNormal = attachedTxInfo.normal.conOpt, txConOptEmphasis = attachedTxInfo.emphasis.conOpt, txConOptBlur = attachedTxInfo.blur.conOpt, txConOptSelect = attachedTxInfo.select.conOpt; if (null != txConOptNormal || null != txConOptEmphasis || null != txConOptSelect || null != txConOptBlur) { var textContent = el.getTextContent(); if (!1 === txConOptNormal) textContent && el.removeTextContent(); else { txConOptNormal = attachedTxInfo.normal.conOpt = txConOptNormal || { type: 'text' }, textContent ? textContent.clearStates() : (textContent = createEl(txConOptNormal), el.setTextContent(textContent)); var txConStlOptNormal = txConOptNormal && txConOptNormal.style; updateElNormal(null, textContent, null, dataIndex, txConOptNormal, txConStlOptNormal, null, seriesModel, isInit, !0); for(var i = 0; i < STATES.length; i++){ var stateName = STATES[i]; if (stateName !== NORMAL) { var txConOptOtherState = attachedTxInfo[stateName].conOpt; updateElOnState(stateName, textContent, txConOptOtherState, retrieveStyleOptionOnState(txConOptNormal, txConOptOtherState, stateName), null); } } txConStlOptNormal ? textContent.dirty() : textContent.markRedraw(); } } } }(el, dataIndex, elOption, seriesModel, isInit, attachedTxInfoTmp), function(el, dataIndex, elOption, seriesModel, isInit) { var clipPathOpt = elOption.clipPath; if (!1 === clipPathOpt) el && el.getClipPath() && el.removeClipPath(); else if (clipPathOpt) { var clipPath = el.getClipPath(); clipPath && doesElNeedRecreate(clipPath, clipPathOpt) && (clipPath = null), clipPath || (assert((clipPath = createEl(clipPathOpt)) instanceof Path, 'Only any type of `path` can be used in `clipPath`, rather than ' + clipPath.type + '.'), el.setClipPath(clipPath)), updateElNormal(null, clipPath, null, dataIndex, clipPathOpt, null, null, seriesModel, isInit, !1); } }(el, dataIndex, elOption, seriesModel, isInit); var pendingAllPropsFinal = updateElNormal(api, el, thisElIsMorphTo, dataIndex, elOption, elOption.style, attachedTxInfoTmp, seriesModel, isInit, !1); thisElIsMorphTo && morphPreparation.addTo(el, elOption, dataIndex, pendingAllPropsFinal); for(var i = 0; i < STATES.length; i++){ var stateName = STATES[i]; if (stateName !== NORMAL) { var otherStateOpt = retrieveStateOption(elOption, stateName), otherStyleOpt = retrieveStyleOptionOnState(elOption, otherStateOpt, stateName); updateElOnState(stateName, el, otherStateOpt, otherStyleOpt, attachedTxInfoTmp); } } return !function(el, elOption, seriesModel, attachedTxInfo) { if (!el.isGroup) { var elDisplayable = el, currentZ = seriesModel.currentZ, currentZLevel = seriesModel.currentZLevel; elDisplayable.z = currentZ, elDisplayable.zlevel = currentZLevel; var optZ2 = elOption.z2; null != optZ2 && (elDisplayable.z2 = optZ2 || 0); for(var i = 0; i < STATES.length; i++)(function(elDisplayable, elOption, state) { var isNormal = state === NORMAL, elStateOpt = isNormal ? elOption : retrieveStateOption(elOption, state), optZ2 = elStateOpt ? elStateOpt.z2 : null; null != optZ2 && ((isNormal ? elDisplayable : elDisplayable.ensureState(state)).z2 = optZ2 || 0); })(elDisplayable, elOption, STATES[i]); } }(el, elOption, seriesModel), 'group' === elOption.type && function(api, el, dataIndex, elOption, seriesModel, morphPreparation) { var newChildren = elOption.children, newLen = newChildren ? newChildren.length : 0, mergeChildren = elOption.$mergeChildren, byName = 'byName' === mergeChildren || elOption.diffChildrenByName, notMerge = !1 === mergeChildren; if (newLen || byName || notMerge) { if (byName) { (function(context) { new DataDiffer(context.oldChildren, context.newChildren, getKey, getKey, context).add(processAddUpdate).update(processAddUpdate).remove(processRemove).execute(); })({ api: api, oldChildren: el.children() || [], newChildren: newChildren || [], dataIndex: dataIndex, seriesModel: seriesModel, group: el, morphPreparation: morphPreparation }); return; } notMerge && el.removeAll(); for(var index = 0; index < newLen; index++)newChildren[index] && doCreateOrUpdateEl(api, el.childAt(index), dataIndex, newChildren[index], seriesModel, el, !1, morphPreparation); for(var i = el.childCount() - 1; i >= index; i--)doRemoveEl(el.childAt(i), seriesModel, el); } }(api, el, dataIndex, elOption, seriesModel, morphPreparation), toBeReplacedIdx >= 0 ? group.replaceAt(el, toBeReplacedIdx) : group.add(el), el; } function doesElNeedRecreate(el, elOption) { var elInner = inner$9(el), elOptionType = elOption.type, elOptionShape = elOption.shape, elOptionStyle = elOption.style; return null != elOptionType && elOptionType !== elInner.customGraphicType || 'path' === elOptionType && elOptionShape && (hasOwn(elOptionShape, 'pathData') || hasOwn(elOptionShape, 'd')) && getPathData(elOptionShape) !== elInner.customPathData || 'image' === elOptionType && hasOwn(elOptionStyle, 'image') && elOptionStyle.image !== elInner.customImagePath; } function processTxInfo(elOption, state, attachedTxInfo) { var stateOpt = state ? retrieveStateOption(elOption, state) : elOption, styleOpt = state ? retrieveStyleOptionOnState(elOption, stateOpt, EMPHASIS) : elOption.style, elType = elOption.type, txCfg = stateOpt ? stateOpt.textConfig : null, txConOptNormal = elOption.textContent, txConOpt = txConOptNormal ? state ? retrieveStateOption(txConOptNormal, state) : txConOptNormal : null; if (styleOpt && (attachedTxInfo.isLegacy || isEC4CompatibleStyle(styleOpt, elType, !!txCfg, !!txConOpt))) { attachedTxInfo.isLegacy = !0; var convertResult = convertFromEC4CompatibleStyle(styleOpt, elType, !state); !txCfg && convertResult.textConfig && (txCfg = convertResult.textConfig), !txConOpt && convertResult.textContent && (txConOpt = convertResult.textContent); } if (!state && txConOpt) { var txConOptNormal_1 = txConOpt; txConOptNormal_1.type || (txConOptNormal_1.type = 'text'), 'text' !== txConOptNormal_1.type && assert('text' === txConOptNormal_1.type, 'textContent.type must be "text"'); } var info = state ? attachedTxInfo[state] : attachedTxInfo.normal; info.cfg = txCfg, info.conOpt = txConOpt; } function retrieveStateOption(elOption, state) { return state ? elOption ? elOption[state] : null : elOption; } function retrieveStyleOptionOnState(stateOptionNormal, stateOption, state) { var style = stateOption && stateOption.style; return null == style && state === EMPHASIS && stateOptionNormal && (style = stateOptionNormal.styleEmphasis), style; } function getKey(item, idx) { var name = item && item.name; return null != name ? name : 'e\0\0' + idx; } function processAddUpdate(newIndex, oldIndex) { var context = this.context, childOption = null != newIndex ? context.newChildren[newIndex] : null, child = null != oldIndex ? context.oldChildren[oldIndex] : null; doCreateOrUpdateEl(context.api, child, context.dataIndex, childOption, context.seriesModel, context.group, !1, context.morphPreparation); } function processRemove(oldIndex) { var context = this.context; doRemoveEl(context.oldChildren[oldIndex], context.seriesModel, context.group); } function doRemoveEl(el, seriesModel, group) { if (el) { var leaveToProps = inner$9(el).leaveToProps; leaveToProps ? updateProps(el, leaveToProps, seriesModel, { cb: function() { group.remove(el); } }) : group.remove(el); } } function getPathData(shape) { return shape && (shape.pathData || shape.d); } function isPath$1(el) { return el && el instanceof Path; } function removeElementDirectly(el, group) { el && group.remove(el); } var MorphPreparation = function() { function MorphPreparation(seriesModel, transOpt) { this._fromList = [], this._toList = [], this._toElOptionList = [], this._allPropsFinalList = [], this._toDataIndices = [], this._morphConfigList = [], this._seriesModel = seriesModel, this._transOpt = transOpt; } return MorphPreparation.prototype.hasFrom = function() { return !!this._fromList.length; }, MorphPreparation.prototype.findAndAddFrom = function(el) { if (el && (inner$9(el).canMorph && this._fromList.push(el), el.isGroup)) for(var children = el.childrenRef(), i = 0; i < children.length; i++)this.findAndAddFrom(children[i]); }, MorphPreparation.prototype.addTo = function(path, elOption, dataIndex, allPropsFinal) { path && (this._toList.push(path), this._toElOptionList.push(elOption), this._toDataIndices.push(dataIndex), this._allPropsFinalList.push(allPropsFinal)); }, MorphPreparation.prototype.applyMorphing = function() { var type = this._type, fromList = this._fromList, toListLen = this._toList.length, fromListLen = fromList.length; if (fromListLen && toListLen) { if ('oneToOne' === type) for(var toIdx = 0; toIdx < toListLen; toIdx++)this._oneToOneForSingleTo(toIdx, toIdx); else if ('manyToOne' === type) for(var fromSingleSegLen = Math.max(1, Math.floor(fromListLen / toListLen)), toIdx = 0, fromIdxStart = 0; toIdx < toListLen; toIdx++, fromIdxStart += fromSingleSegLen){ var fromCount = toIdx + 1 >= toListLen ? fromListLen - fromIdxStart : fromSingleSegLen; this._manyToOneForSingleTo(toIdx, fromIdxStart >= fromListLen ? null : fromIdxStart, fromCount); } else if ('oneToMany' === type) for(var toSingleSegLen = Math.max(1, Math.floor(toListLen / fromListLen)), toIdxStart = 0, fromIdx = 0; toIdxStart < toListLen; toIdxStart += toSingleSegLen, fromIdx++){ var toCount = toIdxStart + toSingleSegLen >= toListLen ? toListLen - toIdxStart : toSingleSegLen; this._oneToManyForSingleFrom(toIdxStart, toCount, fromIdx >= fromListLen ? null : fromIdx); } } }, MorphPreparation.prototype._oneToOneForSingleTo = function(toIdx, fromIdx) { var to = this._toList[toIdx], toElOption = this._toElOptionList[toIdx], toDataIndex = this._toDataIndices[toIdx], allPropsFinal = this._allPropsFinalList[toIdx], from = this._fromList[fromIdx], elAnimationConfig = this._getOrCreateMorphConfig(toDataIndex), morphDuration = elAnimationConfig.duration; if (from && isCombiningPath(from)) { if (applyPropsFinal(to, allPropsFinal, toElOption.style), morphDuration) { var combineResult = combine([ from ], to, elAnimationConfig, copyPropsWhenDivided); this._processResultIndividuals(combineResult, toIdx, null); } } else { var morphFrom = morphDuration && from && (from !== to || isIndividualMorphingPath(from) || isCombiningPath(from)) ? from : null, transFromProps = {}; prepareShapeOrExtraTransitionFrom('shape', to, morphFrom, toElOption, transFromProps, !1), prepareShapeOrExtraTransitionFrom('extra', to, morphFrom, toElOption, transFromProps, !1), prepareTransformTransitionFrom(to, morphFrom, toElOption, transFromProps, !1), prepareStyleTransitionFrom(to, morphFrom, toElOption, toElOption.style, transFromProps, !1), applyPropsFinal(to, allPropsFinal, toElOption.style), morphFrom && morphPath(morphFrom, to, elAnimationConfig), applyTransitionFrom(to, toDataIndex, toElOption, this._seriesModel, transFromProps, !1); } }, MorphPreparation.prototype._manyToOneForSingleTo = function(toIdx, fromIdxStart, fromCount) { var to = this._toList[toIdx], toElOption = this._toElOptionList[toIdx]; applyPropsFinal(to, this._allPropsFinalList[toIdx], toElOption.style); var elAnimationConfig = this._getOrCreateMorphConfig(this._toDataIndices[toIdx]); if (elAnimationConfig.duration && null != fromIdxStart) { for(var combineFromList = [], fromIdx = fromIdxStart; fromIdx < fromCount; fromIdx++)combineFromList.push(this._fromList[fromIdx]); var combineResult = combine(combineFromList, to, elAnimationConfig, copyPropsWhenDivided); this._processResultIndividuals(combineResult, toIdx, null); } }, MorphPreparation.prototype._oneToManyForSingleFrom = function(toIdxStart, toCount, fromIdx) { for(var from = null == fromIdx ? null : this._fromList[fromIdx], toList = this._toList, separateToList = [], toIdx = toIdxStart; toIdx < toCount; toIdx++){ var to = toList[toIdx]; applyPropsFinal(to, this._allPropsFinalList[toIdx], this._toElOptionList[toIdx].style), separateToList.push(to); } var elAnimationConfig = this._getOrCreateMorphConfig(this._toDataIndices[toIdxStart]); if (elAnimationConfig.duration && from) { var separateResult = function(fromPath, toPathList, animationOpts, copyPropsIfDivided) { var fromPathList, toPathListLen = toPathList.length, dividingMethod = animationOpts ? animationOpts.dividingMethod : null, copyProps = !1; if (isCombiningPath(fromPath)) { var fromCombiningSubList = fromPath.__combiningSubList; fromCombiningSubList.length === toPathListLen ? fromPathList = fromCombiningSubList : (fromPathList = divideShape(fromPath, toPathListLen, dividingMethod), copyProps = !0); } else fromPathList = divideShape(fromPath, toPathListLen, dividingMethod), copyProps = !0; assert(fromPathList.length === toPathListLen); for(var i = 0; i < toPathListLen; i++)copyProps && copyPropsIfDivided && copyPropsIfDivided(fromPath, fromPathList[i], !1), morphPath(fromPathList[i], toPathList[i], animationOpts); return { fromIndividuals: fromPathList, toIndividuals: toPathList, count: toPathListLen }; }(from, separateToList, elAnimationConfig, copyPropsWhenDivided); this._processResultIndividuals(separateResult, toIdxStart, toCount); } }, MorphPreparation.prototype._processResultIndividuals = function(combineSeparateResult, toIdxStart, toCount) { for(var isSeparate = null != toCount, i = 0; i < combineSeparateResult.count; i++){ var fromIndividual = combineSeparateResult.fromIndividuals[i], toIndividual = combineSeparateResult.toIndividuals[i], toIdx = toIdxStart + (isSeparate ? i : 0), toElOption = this._toElOptionList[toIdx], dataIndex = this._toDataIndices[toIdx], transFromProps = {}; prepareTransformTransitionFrom(toIndividual, fromIndividual, toElOption, transFromProps, !1), prepareStyleTransitionFrom(toIndividual, fromIndividual, toElOption, toElOption.style, transFromProps, !1), applyTransitionFrom(toIndividual, dataIndex, toElOption, this._seriesModel, transFromProps, !1); } }, MorphPreparation.prototype._getOrCreateMorphConfig = function(dataIndex) { var duration, easing, delay, morphConfigList = this._morphConfigList, config = morphConfigList[dataIndex]; if (config) return config; var seriesModel = this._seriesModel, transOpt = this._transOpt; if (seriesModel.isAnimationEnabled()) { var animationPayload = void 0; if (seriesModel && seriesModel.ecModel) { var updatePayload = seriesModel.ecModel.getUpdatePayload(); animationPayload = updatePayload && updatePayload.animation; } if (animationPayload) duration = animationPayload.duration || 0, easing = animationPayload.easing || 'cubicOut', delay = animationPayload.delay || 0; else { easing = seriesModel.get('animationEasingUpdate'); var delayOption = seriesModel.get('animationDelayUpdate'); delay = isFunction(delayOption) ? delayOption(dataIndex) : delayOption; var durationOption = seriesModel.get('animationDurationUpdate'); duration = isFunction(durationOption) ? durationOption(dataIndex) : durationOption; } } return config = { duration: duration || 0, delay: delay, easing: easing, dividingMethod: transOpt ? transOpt.dividingMethod : null }, morphConfigList[dataIndex] = config, config; }, MorphPreparation.prototype.reset = function(type) { this._type = type, this._fromList.length = this._toList.length = this._toElOptionList.length = this._allPropsFinalList.length = this._toDataIndices.length = 0; }, MorphPreparation; }(); function copyPropsWhenDivided(srcPath, tarPath, willClone) { tarPath.style = willClone ? clone(srcPath.style) : srcPath.style, tarPath.zlevel = srcPath.zlevel, tarPath.z = srcPath.z, tarPath.z2 = srcPath.z2; } var inner$a = makeInner(), BaseAxisPointer = function() { function BaseAxisPointer() { this._dragging = !1, this.animationThreshold = 15; } return BaseAxisPointer.prototype.render = function(axisModel, axisPointerModel, api, forceRender) { var value = axisPointerModel.get('value'), status = axisPointerModel.get('status'); if (this._axisModel = axisModel, this._axisPointerModel = axisPointerModel, this._api = api, forceRender || this._lastValue !== value || this._lastStatus !== status) { this._lastValue = value, this._lastStatus = status; var group = this._group, handle = this._handle; if (!status || 'hide' === status) { group && group.hide(), handle && handle.hide(); return; } group && group.show(), handle && handle.show(); var elOption = {}; this.makeElOption(elOption, value, axisModel, axisPointerModel, api); var graphicKey = elOption.graphicKey; graphicKey !== this._lastGraphicKey && this.clear(api), this._lastGraphicKey = graphicKey; var moveAnimation = this._moveAnimation = this.determineAnimation(axisModel, axisPointerModel); if (group) { var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation); this.updatePointerEl(group, elOption, doUpdateProps), this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel); } else group = this._group = new Group(), this.createPointerEl(group, elOption, axisModel, axisPointerModel), this.createLabelEl(group, elOption, axisModel, axisPointerModel), api.getZr().add(group); updateMandatoryProps(group, axisPointerModel, !0), this._renderHandle(value); } }, BaseAxisPointer.prototype.remove = function(api) { this.clear(api); }, BaseAxisPointer.prototype.dispose = function(api) { this.clear(api); }, BaseAxisPointer.prototype.determineAnimation = function(axisModel, axisPointerModel) { var animation = axisPointerModel.get('animation'), axis = axisModel.axis, isCategoryAxis = 'category' === axis.type, useSnap = axisPointerModel.get('snap'); if (!useSnap && !isCategoryAxis) return !1; if ('auto' === animation || null == animation) { var animationThreshold = this.animationThreshold; if (isCategoryAxis && axis.getBandWidth() > animationThreshold) return !0; if (useSnap) { var seriesDataCount = getAxisInfo(axisModel).seriesDataCount, axisExtent = axis.getExtent(); return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold; } return !1; } return !0 === animation; }, BaseAxisPointer.prototype.makeElOption = function(elOption, value, axisModel, axisPointerModel, api) {}, BaseAxisPointer.prototype.createPointerEl = function(group, elOption, axisModel, axisPointerModel) { var pointerOption = elOption.pointer; if (pointerOption) { var pointerEl = inner$a(group).pointerEl = new graphic[pointerOption.type](clone(elOption.pointer)); group.add(pointerEl); } }, BaseAxisPointer.prototype.createLabelEl = function(group, elOption, axisModel, axisPointerModel) { if (elOption.label) { var labelEl = inner$a(group).labelEl = new ZRText(clone(elOption.label)); group.add(labelEl), updateLabelShowHide(labelEl, axisPointerModel); } }, BaseAxisPointer.prototype.updatePointerEl = function(group, elOption, updateProps) { var pointerEl = inner$a(group).pointerEl; pointerEl && elOption.pointer && (pointerEl.setStyle(elOption.pointer.style), updateProps(pointerEl, { shape: elOption.pointer.shape })); }, BaseAxisPointer.prototype.updateLabelEl = function(group, elOption, updateProps, axisPointerModel) { var labelEl = inner$a(group).labelEl; labelEl && (labelEl.setStyle(elOption.label.style), updateProps(labelEl, { x: elOption.label.x, y: elOption.label.y }), updateLabelShowHide(labelEl, axisPointerModel)); }, BaseAxisPointer.prototype._renderHandle = function(value) { if (!this._dragging && this.updateHandleTransform) { var isInit, axisPointerModel = this._axisPointerModel, zr = this._api.getZr(), handle = this._handle, handleModel = axisPointerModel.getModel('handle'), status = axisPointerModel.get('status'); if (!handleModel.get('show') || !status || 'hide' === status) { handle && zr.remove(handle), this._handle = null; return; } this._handle || (isInit = !0, handle = this._handle = createIcon(handleModel.get('icon'), { cursor: 'move', draggable: !0, onmousemove: function(e) { stop(e.event); }, onmousedown: bind(this._onHandleDragMove, this, 0, 0), drift: bind(this._onHandleDragMove, this), ondragend: bind(this._onHandleDragEnd, this) }), zr.add(handle)), updateMandatoryProps(handle, axisPointerModel, !1), handle.setStyle(handleModel.getItemStyle(null, [ 'color', 'borderColor', 'borderWidth', 'opacity', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY' ])); var handleSize = handleModel.get('size'); isArray(handleSize) || (handleSize = [ handleSize, handleSize ]), handle.scaleX = handleSize[0] / 2, handle.scaleY = handleSize[1] / 2, createOrUpdate(this, '_doDispatchAxisPointer', handleModel.get('throttle') || 0, 'fixRate'), this._moveHandleToValue(value, isInit); } }, BaseAxisPointer.prototype._moveHandleToValue = function(value, isInit) { updateProps$1(this._axisPointerModel, !isInit && this._moveAnimation, this._handle, getHandleTransProps(this.getHandleTransform(value, this._axisModel, this._axisPointerModel))); }, BaseAxisPointer.prototype._onHandleDragMove = function(dx, dy) { var handle = this._handle; if (handle) { this._dragging = !0; var trans = this.updateHandleTransform(getHandleTransProps(handle), [ dx, dy ], this._axisModel, this._axisPointerModel); this._payloadInfo = trans, handle.stopAnimation(), handle.attr(getHandleTransProps(trans)), inner$a(handle).lastProp = null, this._doDispatchAxisPointer(); } }, BaseAxisPointer.prototype._doDispatchAxisPointer = function() { if (this._handle) { var payloadInfo = this._payloadInfo, axisModel = this._axisModel; this._api.dispatchAction({ type: 'updateAxisPointer', x: payloadInfo.cursorPoint[0], y: payloadInfo.cursorPoint[1], tooltipOption: payloadInfo.tooltipOption, axesInfo: [ { axisDim: axisModel.axis.dim, axisIndex: axisModel.componentIndex } ] }); } }, BaseAxisPointer.prototype._onHandleDragEnd = function() { if (this._dragging = !1, this._handle) { var value = this._axisPointerModel.get('value'); this._moveHandleToValue(value), this._api.dispatchAction({ type: 'hideTip' }); } }, BaseAxisPointer.prototype.clear = function(api) { this._lastValue = null, this._lastStatus = null; var zr = api.getZr(), group = this._group, handle = this._handle; zr && group && (this._lastGraphicKey = null, group && zr.remove(group), handle && zr.remove(handle), this._group = null, this._handle = null, this._payloadInfo = null); }, BaseAxisPointer.prototype.doClear = function() {}, BaseAxisPointer.prototype.buildLabel = function(xy, wh, xDimIndex) { return { x: xy[xDimIndex = xDimIndex || 0], y: xy[1 - xDimIndex], width: wh[xDimIndex], height: wh[1 - xDimIndex] }; }, BaseAxisPointer; }(); function updateProps$1(animationModel, moveAnimation, el, props) { !function propsEqual(lastProps, newProps) { if (!(isObject(lastProps) && isObject(newProps))) return lastProps === newProps; var equals_1 = !0; return each(newProps, function(item, key) { equals_1 = equals_1 && propsEqual(lastProps[key], item); }), !!equals_1; }(inner$a(el).lastProp, props) && (inner$a(el).lastProp = props, moveAnimation ? updateProps(el, props, animationModel) : (el.stopAnimation(), el.attr(props))); } function updateLabelShowHide(labelEl, axisPointerModel) { labelEl[axisPointerModel.get([ 'label', 'show' ]) ? 'show' : 'hide'](); } function getHandleTransProps(trans) { return { x: trans.x || 0, y: trans.y || 0, rotation: trans.rotation || 0 }; } function updateMandatoryProps(group, axisPointerModel, silent) { var z = axisPointerModel.get('z'), zlevel = axisPointerModel.get('zlevel'); group && group.traverse(function(el) { 'group' !== el.type && (null != z && (el.z = z), null != zlevel && (el.zlevel = zlevel), el.silent = silent); }); } function buildElStyle(axisPointerModel) { var style, axisPointerType = axisPointerModel.get('type'), styleModel = axisPointerModel.getModel(axisPointerType + 'Style'); return 'line' === axisPointerType ? (style = styleModel.getLineStyle()).fill = null : 'shadow' === axisPointerType && ((style = styleModel.getAreaStyle()).stroke = null), style; } function buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos) { var position, viewWidth, viewHeight, text = getValueLabel(axisPointerModel.get('value'), axisModel.axis, axisModel.ecModel, axisPointerModel.get('seriesDataIndices'), { precision: axisPointerModel.get([ 'label', 'precision' ]), formatter: axisPointerModel.get([ 'label', 'formatter' ]) }), labelModel = axisPointerModel.getModel('label'), paddings = normalizeCssArray(labelModel.get('padding') || 0), font = labelModel.getFont(), textRect = getBoundingRect(text, font), position1 = labelPos.position, width = textRect.width + paddings[1] + paddings[3], height = textRect.height + paddings[0] + paddings[2], align = labelPos.align; 'right' === align && (position1[0] -= width), 'center' === align && (position1[0] -= width / 2); var verticalAlign = labelPos.verticalAlign; 'bottom' === verticalAlign && (position1[1] -= height), 'middle' === verticalAlign && (position1[1] -= height / 2), position = position1, viewWidth = api.getWidth(), viewHeight = api.getHeight(), position[0] = Math.min(position[0] + width, viewWidth) - width, position[1] = Math.min(position[1] + height, viewHeight) - height, position[0] = Math.max(position[0], 0), position[1] = Math.max(position[1], 0); var bgColor = labelModel.get('backgroundColor'); bgColor && 'auto' !== bgColor || (bgColor = axisModel.get([ 'axisLine', 'lineStyle', 'color' ])), elOption.label = { x: position1[0], y: position1[1], style: createTextStyle(labelModel, { text: text, font: font, fill: labelModel.getTextColor(), padding: paddings, backgroundColor: bgColor }), z2: 10 }; } function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) { value = axis.scale.parse(value); var text = axis.scale.getLabel({ value: value }, { precision: opt.precision }), formatter = opt.formatter; if (formatter) { var params_1 = { value: getAxisRawValue(axis, { value: value }), axisDimension: axis.dim, axisIndex: axis.index, seriesData: [] }; each(seriesDataIndices, function(idxItem) { var series = ecModel.getSeriesByIndex(idxItem.seriesIndex), dataIndex = idxItem.dataIndexInside, dataParams = series && series.getDataParams(dataIndex); dataParams && params_1.seriesData.push(dataParams); }), isString(formatter) ? text = formatter.replace('{value}', text) : isFunction(formatter) && (text = formatter(params_1)); } return text; } function getTransformedPosition(axis, value, layoutInfo) { var transform = create$1(); return rotate(transform, transform, layoutInfo.rotation), translate(transform, transform, layoutInfo.position), applyTransform$1([ axis.dataToCoord(value), (layoutInfo.labelOffset || 0) + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0) ], transform); } function buildCartesianSingleLabelElOption(value, elOption, layoutInfo, axisModel, axisPointerModel, api) { var textLayout = AxisBuilder.innerTextLayout(layoutInfo.rotation, 0, layoutInfo.labelDirection); layoutInfo.labelMargin = axisPointerModel.get([ 'label', 'margin' ]), buildLabelElOption(elOption, axisModel, axisPointerModel, api, { position: getTransformedPosition(axisModel.axis, value, layoutInfo), align: textLayout.textAlign, verticalAlign: textLayout.textVerticalAlign }); } function makeLineShape(p1, p2, xDimIndex) { return { x1: p1[xDimIndex = xDimIndex || 0], y1: p1[1 - xDimIndex], x2: p2[xDimIndex], y2: p2[1 - xDimIndex] }; } function makeRectShape(xy, wh, xDimIndex) { return { x: xy[xDimIndex = xDimIndex || 0], y: xy[1 - xDimIndex], width: wh[xDimIndex], height: wh[1 - xDimIndex] }; } function makeSectorShape(cx, cy, r0, r, startAngle, endAngle) { return { cx: cx, cy: cy, r0: r0, r: r, startAngle: startAngle, endAngle: endAngle, clockwise: !0 }; } var CartesianAxisPointer = function(_super) { function CartesianAxisPointer() { return null !== _super && _super.apply(this, arguments) || this; } return __extends(CartesianAxisPointer, _super), CartesianAxisPointer.prototype.makeElOption = function(elOption, value, axisModel, axisPointerModel, api) { var axis = axisModel.axis, grid = axis.grid, axisPointerType = axisPointerModel.get('type'), otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent(), pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, !0)); if (axisPointerType && 'none' !== axisPointerType) { var elStyle = buildElStyle(axisPointerModel), pointerOption = pointerShapeBuilder[axisPointerType](axis, pixelValue, otherExtent); pointerOption.style = elStyle, elOption.graphicKey = pointerOption.type, elOption.pointer = pointerOption; } buildCartesianSingleLabelElOption(value, elOption, layout$1(grid.model, axisModel), axisModel, axisPointerModel, api); }, CartesianAxisPointer.prototype.getHandleTransform = function(value, axisModel, axisPointerModel) { var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, { labelInside: !1 }); layoutInfo.labelMargin = axisPointerModel.get([ 'handle', 'margin' ]); var pos = getTransformedPosition(axisModel.axis, value, layoutInfo); return { x: pos[0], y: pos[1], rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0) }; }, CartesianAxisPointer.prototype.updateHandleTransform = function(transform, delta, axisModel, axisPointerModel) { var axis = axisModel.axis, grid = axis.grid, axisExtent = axis.getGlobalExtent(!0), otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent(), dimIndex = 'x' === axis.dim ? 0 : 1, currPosition = [ transform.x, transform.y ]; currPosition[dimIndex] += delta[dimIndex], currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]), currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]); var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2, cursorPoint = [ cursorOtherValue, cursorOtherValue ]; return cursorPoint[dimIndex] = currPosition[dimIndex], { x: currPosition[0], y: currPosition[1], rotation: transform.rotation, cursorPoint: cursorPoint, tooltipOption: [ { verticalAlign: 'middle' }, { align: 'center' } ][dimIndex] }; }, CartesianAxisPointer; }(BaseAxisPointer); function getCartesian(grid, axis) { var opt = {}; return opt[axis.dim + 'AxisIndex'] = axis.index, grid.getCartesian(opt); } var pointerShapeBuilder = { line: function(axis, pixelValue, otherExtent) { return { type: 'Line', subPixelOptimize: !0, shape: makeLineShape([ pixelValue, otherExtent[0] ], [ pixelValue, otherExtent[1] ], getAxisDimIndex(axis)) }; }, shadow: function(axis, pixelValue, otherExtent) { var bandWidth = Math.max(1, axis.getBandWidth()), span = otherExtent[1] - otherExtent[0]; return { type: 'Rect', shape: makeRectShape([ pixelValue - bandWidth / 2, otherExtent[0] ], [ bandWidth, span ], getAxisDimIndex(axis)) }; } }; function getAxisDimIndex(axis) { return 'x' === axis.dim ? 0 : 1; } var AxisPointerModel = function(_super) { function AxisPointerModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = AxisPointerModel.type, _this; } return __extends(AxisPointerModel, _super), AxisPointerModel.type = 'axisPointer', AxisPointerModel.defaultOption = { show: 'auto', zlevel: 0, z: 50, type: 'line', snap: !1, triggerTooltip: !0, value: null, status: null, link: [], animation: null, animationDurationUpdate: 200, lineStyle: { color: '#B9BEC9', width: 1, type: 'dashed' }, shadowStyle: { color: 'rgba(210,219,238,0.2)' }, label: { show: !0, formatter: null, precision: 'auto', margin: 3, color: '#fff', padding: [ 5, 7, 5, 7 ], backgroundColor: 'auto', borderColor: null, borderWidth: 0, borderRadius: 3 }, handle: { show: !1, icon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7v-1.2h6.6z M13.3,22H6.7v-1.2h6.6z M13.3,19.6H6.7v-1.2h6.6z', size: 45, margin: 50, color: '#333', shadowBlur: 3, shadowColor: '#aaa', shadowOffsetX: 0, shadowOffsetY: 2, throttle: 40 } }, AxisPointerModel; }(ComponentModel), inner$b = makeInner(); function register(key, api, handler) { if (!env1.node) { var zr = api.getZr(); inner$b(zr).records || (inner$b(zr).records = {}), function(zr, api) { inner$b(zr).initialized || (inner$b(zr).initialized = !0, useHandler('click', curry(doEnter, 'click')), useHandler('mousemove', curry(doEnter, 'mousemove')), useHandler('globalout', onLeave)); function useHandler(eventType, cb) { zr.on(eventType, function(e) { var pendings, dispatchAction, pendings1, actuallyPayload, showLen, hideLen, dis = (pendings = { showTip: [], hideTip: [] }, { dispatchAction: dispatchAction = function(payload) { var pendingList = pendings[payload.type]; pendingList ? pendingList.push(payload) : (payload.dispatchAction = dispatchAction, api.dispatchAction(payload)); }, pendings: pendings }); each(inner$b(zr).records, function(record) { record && cb(record, e, dis.dispatchAction); }), showLen = (pendings1 = dis.pendings).showTip.length, hideLen = pendings1.hideTip.length, showLen ? actuallyPayload = pendings1.showTip[showLen - 1] : hideLen && (actuallyPayload = pendings1.hideTip[hideLen - 1]), actuallyPayload && (actuallyPayload.dispatchAction = null, api.dispatchAction(actuallyPayload)); }); } }(zr, api), (inner$b(zr).records[key] || (inner$b(zr).records[key] = {})).handler = handler; } } function onLeave(record, e, dispatchAction) { record.handler('leave', null, dispatchAction); } function doEnter(currTrigger, record, e, dispatchAction) { record.handler(currTrigger, e, dispatchAction); } function unregister(key, api) { if (!env1.node) { var zr = api.getZr(); (inner$b(zr).records || {})[key] && (inner$b(zr).records[key] = null); } } var AxisPointerView = function(_super) { function AxisPointerView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = AxisPointerView.type, _this; } return __extends(AxisPointerView, _super), AxisPointerView.prototype.render = function(globalAxisPointerModel, ecModel, api) { var globalTooltipModel = ecModel.getComponent('tooltip'), triggerOn = globalAxisPointerModel.get('triggerOn') || globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click'; register('axisPointer', api, function(currTrigger, e, dispatchAction) { 'none' !== triggerOn && ('leave' === currTrigger || triggerOn.indexOf(currTrigger) >= 0) && dispatchAction({ type: 'updateAxisPointer', currTrigger: currTrigger, x: e && e.offsetX, y: e && e.offsetY }); }); }, AxisPointerView.prototype.remove = function(ecModel, api) { unregister('axisPointer', api); }, AxisPointerView.prototype.dispose = function(ecModel, api) { unregister('axisPointer', api); }, AxisPointerView.type = 'axisPointer', AxisPointerView; }(ComponentView); function findPointFromSeries(finder, ecModel) { var seriesModel, point = [], seriesIndex = finder.seriesIndex; if (null == seriesIndex || !(seriesModel = ecModel.getSeriesByIndex(seriesIndex))) return { point: [] }; var data = seriesModel.getData(), dataIndex = queryDataIndex(data, finder); if (null == dataIndex || dataIndex < 0 || isArray(dataIndex)) return { point: [] }; var el = data.getItemGraphicEl(dataIndex), coordSys = seriesModel.coordinateSystem; if (seriesModel.getTooltipPosition) point = seriesModel.getTooltipPosition(dataIndex) || []; else if (coordSys && coordSys.dataToPoint) { if (finder.isStacked) { var baseAxis = coordSys.getBaseAxis(), valueAxisDim = coordSys.getOtherAxis(baseAxis).dim, baseAxisDim = baseAxis.dim, baseDataOffset = 'x' === valueAxisDim || 'radius' === valueAxisDim ? 1 : 0, baseDim = data.mapDimension(baseAxisDim), stackedData = []; stackedData[baseDataOffset] = data.get(baseDim, dataIndex), stackedData[1 - baseDataOffset] = data.get(data.getCalculationInfo('stackResultDimension'), dataIndex), point = coordSys.dataToPoint(stackedData) || []; } else point = coordSys.dataToPoint(data.getValues(map(coordSys.dimensions, function(dim) { return data.mapDimension(dim); }), dataIndex)) || []; } else if (el) { var rect = el.getBoundingRect().clone(); rect.applyTransform(el.transform), point = [ rect.x + rect.width / 2, rect.y + rect.height / 2 ]; } return { point: point, el: el }; } var inner$c = makeInner(); function axisTrigger(payload, ecModel, api) { var currTrigger = payload.currTrigger, point = [ payload.x, payload.y ], dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api), coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo; if (coordSysAxesInfo) { illegalPoint(point) && (point = findPointFromSeries({ seriesIndex: payload.seriesIndex, dataIndex: payload.dataIndex }, ecModel).point); var outputAxesInfo, zr, highDownKey, lastHighlights, newHighlights, toHighlight, toDownplay, isIllegalPoint = illegalPoint(point), inputAxesInfo = payload.axesInfo, axesInfo = coordSysAxesInfo.axesInfo, shouldHide = 'leave' === currTrigger || illegalPoint(point), outputPayload = {}, showValueMap = {}, dataByCoordSys = { list: [], map: {} }, updaters = { showPointer: curry(showPointer, showValueMap), showTooltip: curry(showTooltip, dataByCoordSys) }; each(coordSysAxesInfo.coordSysMap, function(coordSys, coordSysKey) { var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point); each(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function(axisInfo, key) { var axis = axisInfo.axis, inputAxisInfo = function(inputAxesInfo, axisInfo) { for(var i = 0; i < (inputAxesInfo || []).length; i++){ var inputAxisInfo = inputAxesInfo[i]; if (axisInfo.axis.dim === inputAxisInfo.axisDim && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex) return inputAxisInfo; } }(inputAxesInfo, axisInfo); if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) { var val = inputAxisInfo && inputAxisInfo.value; null != val || isIllegalPoint || (val = axis.pointToData(point)), null != val && processOnAxis(axisInfo, val, updaters, !1, outputPayload); } }); }); var linkTriggers = {}; return each(axesInfo, function(tarAxisInfo, tarKey) { var linkGroup = tarAxisInfo.linkGroup; linkGroup && !showValueMap[tarKey] && each(linkGroup.axesInfo, function(srcAxisInfo, srcKey) { var srcValItem = showValueMap[srcKey]; if (srcAxisInfo !== tarAxisInfo && srcValItem) { var val = srcValItem.value; linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo)))), linkTriggers[tarAxisInfo.key] = val; } }); }), each(linkTriggers, function(val, tarKey) { processOnAxis(axesInfo[tarKey], val, updaters, !0, outputPayload); }), outputAxesInfo = outputPayload.axesInfo = [], each(axesInfo, function(axisInfo, key) { var option = axisInfo.axisPointerModel.option, valItem = showValueMap[key]; valItem ? (axisInfo.useHandle || (option.status = 'show'), option.value = valItem.value, option.seriesDataIndices = (valItem.payloadBatch || []).slice()) : axisInfo.useHandle || (option.status = 'hide'), 'show' === option.status && outputAxesInfo.push({ axisDim: axisInfo.axis.dim, axisIndex: axisInfo.axis.model.componentIndex, value: option.value }); }), function(dataByCoordSys, point, payload, dispatchAction) { if (illegalPoint(point) || !dataByCoordSys.list.length) { dispatchAction({ type: 'hideTip' }); return; } var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {}; dispatchAction({ type: 'showTip', escapeConnect: !0, x: point[0], y: point[1], tooltipOption: payload.tooltipOption, position: payload.position, dataIndexInside: sampleItem.dataIndexInside, dataIndex: sampleItem.dataIndex, seriesIndex: sampleItem.seriesIndex, dataByCoordSys: dataByCoordSys.list }); }(dataByCoordSys, point, payload, dispatchAction), zr = api.getZr(), highDownKey = 'axisPointerLastHighlights', lastHighlights = inner$c(zr)[highDownKey] || {}, newHighlights = inner$c(zr)[highDownKey] = {}, each(axesInfo, function(axisInfo, key) { var option = axisInfo.axisPointerModel.option; 'show' === option.status && each(option.seriesDataIndices, function(batchItem) { newHighlights[batchItem.seriesIndex + ' | ' + batchItem.dataIndex] = batchItem; }); }), toHighlight = [], toDownplay = [], each(lastHighlights, function(batchItem, key) { newHighlights[key] || toDownplay.push(batchItem); }), each(newHighlights, function(batchItem, key) { lastHighlights[key] || toHighlight.push(batchItem); }), toDownplay.length && api.dispatchAction({ type: 'downplay', escapeConnect: !0, notBlur: !0, batch: toDownplay }), toHighlight.length && api.dispatchAction({ type: 'highlight', escapeConnect: !0, notBlur: !0, batch: toHighlight }), outputPayload; } } function processOnAxis(axisInfo, newValue, updaters, noSnap, outputFinder) { var axis = axisInfo.axis; if (!axis.scale.isBlank() && axis.containData(newValue)) { if (!axisInfo.involveSeries) { updaters.showPointer(axisInfo, newValue); return; } var value, axis1, dim, snapToValue, payloadBatch, minDist, minDiff, payloadInfo = (value = newValue, dim = (axis1 = axisInfo.axis).dim, snapToValue = value, payloadBatch = [], minDist = Number.MAX_VALUE, minDiff = -1, each(axisInfo.seriesModels, function(series, idx) { var seriesNestestValue, dataIndices, dataDim = series.getData().mapDimensionsAll(dim); if (series.getAxisTooltipData) { var result = series.getAxisTooltipData(dataDim, value, axis1); dataIndices = result.dataIndices, seriesNestestValue = result.nestestValue; } else { if (!(dataIndices = series.getData().indicesOfNearest(dataDim[0], value, 'category' === axis1.type ? 0.5 : null)).length) return; seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]); } if (null != seriesNestestValue && isFinite(seriesNestestValue)) { var diff = value - seriesNestestValue, dist = Math.abs(diff); dist <= minDist && ((dist < minDist || diff >= 0 && minDiff < 0) && (minDist = dist, minDiff = diff, snapToValue = seriesNestestValue, payloadBatch.length = 0), each(dataIndices, function(dataIndex) { payloadBatch.push({ seriesIndex: series.seriesIndex, dataIndexInside: dataIndex, dataIndex: series.getData().getRawIndex(dataIndex) }); })); } }), { payloadBatch: payloadBatch, snapToValue: snapToValue }), payloadBatch1 = payloadInfo.payloadBatch, snapToValue1 = payloadInfo.snapToValue; payloadBatch1[0] && null == outputFinder.seriesIndex && extend(outputFinder, payloadBatch1[0]), !noSnap && axisInfo.snap && axis.containData(snapToValue1) && null != snapToValue1 && (newValue = snapToValue1), updaters.showPointer(axisInfo, newValue, payloadBatch1), updaters.showTooltip(axisInfo, payloadInfo, snapToValue1); } } function showPointer(showValueMap, axisInfo, value, payloadBatch) { showValueMap[axisInfo.key] = { value: value, payloadBatch: payloadBatch }; } function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) { var payloadBatch = payloadInfo.payloadBatch, axis = axisInfo.axis, axisModel = axis.model, axisPointerModel = axisInfo.axisPointerModel; if (axisInfo.triggerTooltip && payloadBatch.length) { var coordSysModel = axisInfo.coordSys.model, coordSysKey = makeKey(coordSysModel), coordSysItem = dataByCoordSys.map[coordSysKey]; coordSysItem || (coordSysItem = dataByCoordSys.map[coordSysKey] = { coordSysId: coordSysModel.id, coordSysIndex: coordSysModel.componentIndex, coordSysType: coordSysModel.type, coordSysMainType: coordSysModel.mainType, dataByAxis: [] }, dataByCoordSys.list.push(coordSysItem)), coordSysItem.dataByAxis.push({ axisDim: axis.dim, axisIndex: axisModel.componentIndex, axisType: axisModel.type, axisId: axisModel.id, value: value, valueLabelOpt: { precision: axisPointerModel.get([ 'label', 'precision' ]), formatter: axisPointerModel.get([ 'label', 'formatter' ]) }, seriesDataIndices: payloadBatch.slice() }); } } function makeMapperParam(axisInfo) { var axisModel = axisInfo.axis.model, item = {}, dim = item.axisDim = axisInfo.axis.dim; return item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex, item.axisName = item[dim + 'AxisName'] = axisModel.name, item.axisId = item[dim + 'AxisId'] = axisModel.id, item; } function illegalPoint(point) { return !point || null == point[0] || isNaN(point[0]) || null == point[1] || isNaN(point[1]); } function install$s(registers) { AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer), registers.registerComponentModel(AxisPointerModel), registers.registerComponentView(AxisPointerView), registers.registerPreprocessor(function(option) { if (option) { option.axisPointer && 0 !== option.axisPointer.length || (option.axisPointer = {}); var link = option.axisPointer.link; link && !isArray(link) && (option.axisPointer.link = [ link ]); } }), registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, function(ecModel, api) { var result, result1, globalTooltipModel, globalAxisPointerModel, linksOption, linkGroups; ecModel.getComponent('axisPointer').coordSysAxesInfo = (result1 = result = { axesInfo: {}, seriesInvolved: !1, coordSysAxesInfo: {}, coordSysMap: {} }, globalTooltipModel = ecModel.getComponent('tooltip'), linksOption = (globalAxisPointerModel = ecModel.getComponent('axisPointer')).get('link', !0) || [], linkGroups = [], each(api.getCoordinateSystems(), function(coordSys) { if (coordSys.axisPointerEnabled) { var coordSysKey = makeKey(coordSys.model), axesInfoInCoordSys = result1.coordSysAxesInfo[coordSysKey] = {}; result1.coordSysMap[coordSysKey] = coordSys; var baseTooltipModel = coordSys.model.getModel('tooltip', globalTooltipModel); if (each(coordSys.getAxes(), curry(saveTooltipAxisInfo, !1, null)), coordSys.getTooltipAxes && globalTooltipModel && baseTooltipModel.get('show')) { var triggerAxis = 'axis' === baseTooltipModel.get('trigger'), cross = 'cross' === baseTooltipModel.get([ 'axisPointer', 'type' ]), tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get([ 'axisPointer', 'axis' ])); (triggerAxis || cross) && each(tooltipAxes.baseAxes, curry(saveTooltipAxisInfo, !cross || 'cross', triggerAxis)), cross && each(tooltipAxes.otherAxes, curry(saveTooltipAxisInfo, 'cross', !1)); } } function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) { var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel), axisPointerShow = axisPointerModel.get('show'); if (axisPointerShow && ('auto' !== axisPointerShow || fromTooltip || isHandleTrigger(axisPointerModel))) { null == triggerTooltip && (triggerTooltip = axisPointerModel.get('triggerTooltip')); var snap = (axisPointerModel = fromTooltip ? function(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) { var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer'), volatileOption = {}; each([ 'type', 'snap', 'lineStyle', 'shadowStyle', 'label', 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z' ], function(field) { volatileOption[field] = clone(tooltipAxisPointerModel.get(field)); }), volatileOption.snap = 'category' !== axis.type && !!triggerTooltip, 'cross' === tooltipAxisPointerModel.get('type') && (volatileOption.type = 'line'); var labelOption = volatileOption.label || (volatileOption.label = {}); if (null == labelOption.show && (labelOption.show = !1), 'cross' === fromTooltip) { var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get([ 'label', 'show' ]); if (labelOption.show = null == tooltipAxisPointerLabelShow || tooltipAxisPointerLabelShow, !triggerTooltip) { var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle'); crossStyle && defaults(labelOption, crossStyle.textStyle); } } return axis.model.getModel('axisPointer', new Model(volatileOption, globalAxisPointerModel, ecModel)); }(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) : axisPointerModel).get('snap'), axisKey = makeKey(axis.model), involveSeries = triggerTooltip || snap || 'category' === axis.type, axisInfo = result1.axesInfo[axisKey] = { key: axisKey, axis: axis, coordSys: coordSys, axisPointerModel: axisPointerModel, triggerTooltip: triggerTooltip, involveSeries: involveSeries, snap: snap, useHandle: isHandleTrigger(axisPointerModel), seriesModels: [], linkGroup: null }; axesInfoInCoordSys[axisKey] = axisInfo, result1.seriesInvolved = result1.seriesInvolved || involveSeries; var groupIndex = function(linksOption, axis) { for(var axisModel = axis.model, dim = axis.dim, i = 0; i < linksOption.length; i++){ var linkOption = linksOption[i] || {}; if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id) || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex) || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)) return i; } }(linksOption, axis); if (null != groupIndex) { var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = { axesInfo: {} }); linkGroup.axesInfo[axisKey] = axisInfo, linkGroup.mapper = linksOption[groupIndex].mapper, axisInfo.linkGroup = linkGroup; } } } }), result.seriesInvolved && function(result, ecModel) { ecModel.eachSeries(function(seriesModel) { var coordSys = seriesModel.coordinateSystem, seriesTooltipTrigger = seriesModel.get([ 'tooltip', 'trigger' ], !0), seriesTooltipShow = seriesModel.get([ 'tooltip', 'show' ], !0); coordSys && 'none' !== seriesTooltipTrigger && !1 !== seriesTooltipTrigger && 'item' !== seriesTooltipTrigger && !1 !== seriesTooltipShow && !1 !== seriesModel.get([ 'axisPointer', 'show' ], !0) && each(result.coordSysAxesInfo[makeKey(coordSys.model)], function(axisInfo) { var axis = axisInfo.axis; coordSys.getAxis(axis.dim) === axis && (axisInfo.seriesModels.push(seriesModel), null == axisInfo.seriesDataCount && (axisInfo.seriesDataCount = 0), axisInfo.seriesDataCount += seriesModel.getData().count()); }); }); }(result, ecModel), result); }), registers.registerAction({ type: 'updateAxisPointer', event: 'updateAxisPointer', update: ':updateAxisPointer' }, axisTrigger); } var PolarAxisPointer = function(_super) { function PolarAxisPointer() { return null !== _super && _super.apply(this, arguments) || this; } return __extends(PolarAxisPointer, _super), PolarAxisPointer.prototype.makeElOption = function(elOption, value, axisModel, axisPointerModel, api) { var axis = axisModel.axis; 'angle' === axis.dim && (this.animationThreshold = Math.PI / 18); var polar = axis.polar, otherExtent = polar.getOtherAxis(axis).getExtent(), coordValue = axis.dataToCoord(value), axisPointerType = axisPointerModel.get('type'); if (axisPointerType && 'none' !== axisPointerType) { var elStyle = buildElStyle(axisPointerModel), pointerOption = pointerShapeBuilder$1[axisPointerType](axis, polar, coordValue, otherExtent); pointerOption.style = elStyle, elOption.graphicKey = pointerOption.type, elOption.pointer = pointerOption; } var labelPos = function(value, axisModel, axisPointerModel, polar, labelMargin) { var position, align, verticalAlign, axis = axisModel.axis, coord = axis.dataToCoord(value), axisAngle = polar.getAngleAxis().getExtent()[0]; axisAngle = axisAngle / 180 * Math.PI; var radiusExtent = polar.getRadiusAxis().getExtent(); if ('radius' === axis.dim) { var transform = create$1(); rotate(transform, transform, axisAngle), translate(transform, transform, [ polar.cx, polar.cy ]), position = applyTransform$1([ coord, -labelMargin ], transform); var labelRotation = axisModel.getModel('axisLabel').get('rotate') || 0, labelLayout = AxisBuilder.innerTextLayout(axisAngle, labelRotation * Math.PI / 180, -1); align = labelLayout.textAlign, verticalAlign = labelLayout.textVerticalAlign; } else { var r = radiusExtent[1]; position = polar.coordToPoint([ r + labelMargin, coord ]); var cx = polar.cx, cy = polar.cy; align = Math.abs(position[0] - cx) / r < 0.3 ? 'center' : position[0] > cx ? 'left' : 'right', verticalAlign = Math.abs(position[1] - cy) / r < 0.3 ? 'middle' : position[1] > cy ? 'top' : 'bottom'; } return { position: position, align: align, verticalAlign: verticalAlign }; }(value, axisModel, 0, polar, axisPointerModel.get([ 'label', 'margin' ])); buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos); }, PolarAxisPointer; }(BaseAxisPointer), pointerShapeBuilder$1 = { line: function(axis, polar, coordValue, otherExtent) { return 'angle' === axis.dim ? { type: 'Line', shape: makeLineShape(polar.coordToPoint([ otherExtent[0], coordValue ]), polar.coordToPoint([ otherExtent[1], coordValue ])) } : { type: 'Circle', shape: { cx: polar.cx, cy: polar.cy, r: coordValue } }; }, shadow: function(axis, polar, coordValue, otherExtent) { var bandWidth = Math.max(1, axis.getBandWidth()), radian = Math.PI / 180; return 'angle' === axis.dim ? { type: 'Sector', shape: makeSectorShape(polar.cx, polar.cy, otherExtent[0], otherExtent[1], (-coordValue - bandWidth / 2) * radian, (-coordValue + bandWidth / 2) * radian) } : { type: 'Sector', shape: makeSectorShape(polar.cx, polar.cy, coordValue - bandWidth / 2, coordValue + bandWidth / 2, 0, 2 * Math.PI) }; } }, PolarModel = function(_super) { function PolarModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = PolarModel.type, _this; } return __extends(PolarModel, _super), PolarModel.prototype.findAxisModel = function(axisType) { var foundAxisModel; return this.ecModel.eachComponent(axisType, function(axisModel) { axisModel.getCoordSysModel() === this && (foundAxisModel = axisModel); }, this), foundAxisModel; }, PolarModel.type = 'polar', PolarModel.dependencies = [ 'radiusAxis', 'angleAxis' ], PolarModel.defaultOption = { zlevel: 0, z: 0, center: [ '50%', '50%' ], radius: '80%' }, PolarModel; }(ComponentModel), PolarAxisModel = function(_super) { function PolarAxisModel() { return null !== _super && _super.apply(this, arguments) || this; } return __extends(PolarAxisModel, _super), PolarAxisModel.prototype.getCoordSysModel = function() { return this.getReferringComponents('polar', SINGLE_REFERRING).models[0]; }, PolarAxisModel.type = 'polarAxis', PolarAxisModel; }(ComponentModel); mixin(PolarAxisModel, AxisModelCommonMixin); var AngleAxisModel = function(_super) { function AngleAxisModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = AngleAxisModel.type, _this; } return __extends(AngleAxisModel, _super), AngleAxisModel.type = 'angleAxis', AngleAxisModel; }(PolarAxisModel), RadiusAxisModel = function(_super) { function RadiusAxisModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = RadiusAxisModel.type, _this; } return __extends(RadiusAxisModel, _super), RadiusAxisModel.type = 'radiusAxis', RadiusAxisModel; }(PolarAxisModel), RadiusAxis = function(_super) { function RadiusAxis(scale, radiusExtent) { return _super.call(this, 'radius', scale, radiusExtent) || this; } return __extends(RadiusAxis, _super), RadiusAxis.prototype.pointToData = function(point, clamp) { return this.polar.pointToData(point, clamp)['radius' === this.dim ? 0 : 1]; }, RadiusAxis; }(Axis); RadiusAxis.prototype.dataToRadius = Axis.prototype.dataToCoord, RadiusAxis.prototype.radiusToData = Axis.prototype.coordToData; var inner$d = makeInner(), AngleAxis = function(_super) { function AngleAxis(scale, angleExtent) { return _super.call(this, 'angle', scale, angleExtent || [ 0, 360 ]) || this; } return __extends(AngleAxis, _super), AngleAxis.prototype.pointToData = function(point, clamp) { return this.polar.pointToData(point, clamp)['radius' === this.dim ? 0 : 1]; }, AngleAxis.prototype.calculateCategoryInterval = function() { var labelModel = this.getLabelModel(), ordinalScale = this.scale, ordinalExtent = ordinalScale.getExtent(), tickCount = ordinalScale.count(); if (ordinalExtent[1] - ordinalExtent[0] < 1) return 0; var tickValue = ordinalExtent[0], unitSpan = this.dataToCoord(tickValue + 1) - this.dataToCoord(tickValue), dh = Math.max(getBoundingRect(null == tickValue ? '' : tickValue + '', labelModel.getFont(), 'center', 'top').height, 7) / Math.abs(unitSpan); isNaN(dh) && (dh = 1 / 0); var interval = Math.max(0, Math.floor(dh)), cache = inner$d(this.model), lastAutoInterval = cache.lastAutoInterval, lastTickCount = cache.lastTickCount; return null != lastAutoInterval && null != lastTickCount && 1 >= Math.abs(lastAutoInterval - interval) && 1 >= Math.abs(lastTickCount - tickCount) && lastAutoInterval > interval ? interval = lastAutoInterval : (cache.lastTickCount = tickCount, cache.lastAutoInterval = interval), interval; }, AngleAxis; }(Axis); AngleAxis.prototype.dataToAngle = Axis.prototype.dataToCoord, AngleAxis.prototype.angleToData = Axis.prototype.coordToData; var Polar = function() { function Polar(name) { this.dimensions = [ 'radius', 'angle' ], this.type = 'polar', this.cx = 0, this.cy = 0, this._radiusAxis = new RadiusAxis(), this._angleAxis = new AngleAxis(), this.axisPointerEnabled = !0, this.name = name || '', this._radiusAxis.polar = this._angleAxis.polar = this; } return Polar.prototype.containPoint = function(point) { var coord = this.pointToCoord(point); return this._radiusAxis.contain(coord[0]) && this._angleAxis.contain(coord[1]); }, Polar.prototype.containData = function(data) { return this._radiusAxis.containData(data[0]) && this._angleAxis.containData(data[1]); }, Polar.prototype.getAxis = function(dim) { return this['_' + dim + 'Axis']; }, Polar.prototype.getAxes = function() { return [ this._radiusAxis, this._angleAxis ]; }, Polar.prototype.getAxesByScale = function(scaleType) { var axes = [], angleAxis = this._angleAxis, radiusAxis = this._radiusAxis; return angleAxis.scale.type === scaleType && axes.push(angleAxis), radiusAxis.scale.type === scaleType && axes.push(radiusAxis), axes; }, Polar.prototype.getAngleAxis = function() { return this._angleAxis; }, Polar.prototype.getRadiusAxis = function() { return this._radiusAxis; }, Polar.prototype.getOtherAxis = function(axis) { var angleAxis = this._angleAxis; return axis === angleAxis ? this._radiusAxis : angleAxis; }, Polar.prototype.getBaseAxis = function() { return this.getAxesByScale('ordinal')[0] || this.getAxesByScale('time')[0] || this.getAngleAxis(); }, Polar.prototype.getTooltipAxes = function(dim) { var baseAxis = null != dim && 'auto' !== dim ? this.getAxis(dim) : this.getBaseAxis(); return { baseAxes: [ baseAxis ], otherAxes: [ this.getOtherAxis(baseAxis) ] }; }, Polar.prototype.dataToPoint = function(data, clamp) { return this.coordToPoint([ this._radiusAxis.dataToRadius(data[0], clamp), this._angleAxis.dataToAngle(data[1], clamp) ]); }, Polar.prototype.pointToData = function(point, clamp) { var coord = this.pointToCoord(point); return [ this._radiusAxis.radiusToData(coord[0], clamp), this._angleAxis.angleToData(coord[1], clamp) ]; }, Polar.prototype.pointToCoord = function(point) { var dx = point[0] - this.cx, dy = point[1] - this.cy, angleAxis = this.getAngleAxis(), extent = angleAxis.getExtent(), minAngle = Math.min(extent[0], extent[1]), maxAngle = Math.max(extent[0], extent[1]); angleAxis.inverse ? minAngle = maxAngle - 360 : maxAngle = minAngle + 360; var radius = Math.sqrt(dx * dx + dy * dy); dx /= radius; for(var radian = Math.atan2(-(dy /= radius), dx) / Math.PI * 180, dir = radian < minAngle ? 1 : -1; radian < minAngle || radian > maxAngle;)radian += 360 * dir; return [ radius, radian ]; }, Polar.prototype.coordToPoint = function(coord) { var radius = coord[0], radian = coord[1] / 180 * Math.PI; return [ Math.cos(radian) * radius + this.cx, -Math.sin(radian) * radius + this.cy ]; }, Polar.prototype.getArea = function() { var angleAxis = this.getAngleAxis(), radiusExtent = this.getRadiusAxis().getExtent().slice(); radiusExtent[0] > radiusExtent[1] && radiusExtent.reverse(); var angleExtent = angleAxis.getExtent(), RADIAN = Math.PI / 180; return { cx: this.cx, cy: this.cy, r0: radiusExtent[0], r: radiusExtent[1], startAngle: -angleExtent[0] * RADIAN, endAngle: -angleExtent[1] * RADIAN, clockwise: angleAxis.inverse, contain: function(x, y) { var dx = x - this.cx, dy = y - this.cy, d2 = dx * dx + dy * dy, r = this.r, r0 = this.r0; return d2 <= r * r && d2 >= r0 * r0; } }; }, Polar.prototype.convertToPixel = function(ecModel, finder, value) { return getCoordSys$2(finder) === this ? this.dataToPoint(value) : null; }, Polar.prototype.convertFromPixel = function(ecModel, finder, pixel) { return getCoordSys$2(finder) === this ? this.pointToData(pixel) : null; }, Polar; }(); function getCoordSys$2(finder) { var seriesModel = finder.seriesModel, polarModel = finder.polarModel; return polarModel && polarModel.coordinateSystem || seriesModel && seriesModel.coordinateSystem; } function updatePolarScale(ecModel, api) { var polar = this, angleAxis = polar.getAngleAxis(), radiusAxis = polar.getRadiusAxis(); if (angleAxis.scale.setExtent(1 / 0, -1 / 0), radiusAxis.scale.setExtent(1 / 0, -1 / 0), ecModel.eachSeries(function(seriesModel) { if (seriesModel.coordinateSystem === polar) { var data_1 = seriesModel.getData(); each(getDataDimensionsOnAxis(data_1, 'radius'), function(dim) { radiusAxis.scale.unionExtentFromData(data_1, dim); }), each(getDataDimensionsOnAxis(data_1, 'angle'), function(dim) { angleAxis.scale.unionExtentFromData(data_1, dim); }); } }), niceScaleExtent(angleAxis.scale, angleAxis.model), niceScaleExtent(radiusAxis.scale, radiusAxis.model), 'category' === angleAxis.type && !angleAxis.onBand) { var extent = angleAxis.getExtent(), diff = 360 / angleAxis.scale.count(); angleAxis.inverse ? extent[1] += diff : extent[1] -= diff, angleAxis.setExtent(extent[0], extent[1]); } } function setAxis(axis, axisModel) { if (axis.type = axisModel.get('type'), axis.scale = createScaleByModel(axisModel), axis.onBand = axisModel.get('boundaryGap') && 'category' === axis.type, axis.inverse = axisModel.get('inverse'), 'angleAxis' === axisModel.mainType) { axis.inverse = axis.inverse !== axisModel.get('clockwise'); var startAngle = axisModel.get('startAngle'); axis.setExtent(startAngle, startAngle + (axis.inverse ? -360 : 360)); } axisModel.axis = axis, axis.model = axisModel; } var polarCreator = { dimensions: Polar.prototype.dimensions, create: function(ecModel, api) { var polarList = []; return ecModel.eachComponent('polar', function(polarModel, idx) { var polar, center, width, height, radiusAxis, size, radius, parsedRadius, polar1 = new Polar(idx + ''); polar1.update = updatePolarScale; var radiusAxis1 = polar1.getRadiusAxis(), angleAxis = polar1.getAngleAxis(), radiusAxisModel = polarModel.findAxisModel('radiusAxis'), angleAxisModel = polarModel.findAxisModel('angleAxis'); setAxis(radiusAxis1, radiusAxisModel), setAxis(angleAxis, angleAxisModel), polar = polar1, center = polarModel.get('center'), width = api.getWidth(), height = api.getHeight(), polar.cx = parsePercent$1(center[0], width), polar.cy = parsePercent$1(center[1], height), radiusAxis = polar.getRadiusAxis(), size = Math.min(width, height) / 2, null == (radius = polarModel.get('radius')) ? radius = [ 0, '100%' ] : isArray(radius) || (radius = [ 0, radius ]), parsedRadius = [ parsePercent$1(radius[0], size), parsePercent$1(radius[1], size) ], radiusAxis.inverse ? radiusAxis.setExtent(parsedRadius[1], parsedRadius[0]) : radiusAxis.setExtent(parsedRadius[0], parsedRadius[1]), polarList.push(polar1), polarModel.coordinateSystem = polar1, polar1.model = polarModel; }), ecModel.eachSeries(function(seriesModel) { if ('polar' === seriesModel.get('coordinateSystem')) { var polarModel = seriesModel.getReferringComponents('polar', SINGLE_REFERRING).models[0]; if (!polarModel) throw Error('Polar "' + retrieve(seriesModel.get('polarIndex'), seriesModel.get('polarId'), 0) + '" not found'); seriesModel.coordinateSystem = polarModel.coordinateSystem; } }), polarList; } }, elementList$1 = [ 'axisLine', 'axisLabel', 'axisTick', 'minorTick', 'splitLine', 'minorSplitLine', 'splitArea' ]; function getAxisLineShape(polar, rExtent, angle) { rExtent[1] > rExtent[0] && (rExtent = rExtent.slice().reverse()); var start = polar.coordToPoint([ rExtent[0], angle ]), end = polar.coordToPoint([ rExtent[1], angle ]); return { x1: start[0], y1: start[1], x2: end[0], y2: end[1] }; } function getRadiusIdx(polar) { return polar.getRadiusAxis().inverse ? 0 : 1; } function fixAngleOverlap(list) { var firstItem = list[0], lastItem = list[list.length - 1]; firstItem && lastItem && 1e-4 > Math.abs(Math.abs(firstItem.coord - lastItem.coord) - 360) && list.pop(); } var AngleAxisView = function(_super) { function AngleAxisView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = AngleAxisView.type, _this.axisPointerClass = 'PolarAxisPointer', _this; } return __extends(AngleAxisView, _super), AngleAxisView.prototype.render = function(angleAxisModel, ecModel) { if (this.group.removeAll(), angleAxisModel.get('show')) { var angleAxis = angleAxisModel.axis, polar = angleAxis.polar, radiusExtent = polar.getRadiusAxis().getExtent(), ticksAngles = angleAxis.getTicksCoords(), minorTickAngles = angleAxis.getMinorTicksCoords(), labels = map(angleAxis.getViewLabels(), function(labelItem) { labelItem = clone(labelItem); var scale = angleAxis.scale, tickValue = 'ordinal' === scale.type ? scale.getRawOrdinalNumber(labelItem.tickValue) : labelItem.tickValue; return labelItem.coord = angleAxis.dataToCoord(tickValue), labelItem; }); fixAngleOverlap(labels), fixAngleOverlap(ticksAngles), each(elementList$1, function(name) { angleAxisModel.get([ name, 'show' ]) && (!angleAxis.scale.isBlank() || 'axisLine' === name) && angelAxisElementsBuilders[name](this.group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent, labels); }, this); } }, AngleAxisView.type = 'angleAxis', AngleAxisView; }(AxisView), angelAxisElementsBuilders = { axisLine: function(group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) { var shape, lineStyleModel = angleAxisModel.getModel([ 'axisLine', 'lineStyle' ]), rId = getRadiusIdx(polar), r0Id = rId ? 0 : 1; (shape = 0 === radiusExtent[r0Id] ? new Circle({ shape: { cx: polar.cx, cy: polar.cy, r: radiusExtent[rId] }, style: lineStyleModel.getLineStyle(), z2: 1, silent: !0 }) : new Ring({ shape: { cx: polar.cx, cy: polar.cy, r: radiusExtent[rId], r0: radiusExtent[r0Id] }, style: lineStyleModel.getLineStyle(), z2: 1, silent: !0 })).style.fill = null, group.add(shape); }, axisTick: function(group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) { var tickModel = angleAxisModel.getModel('axisTick'), tickLen = (tickModel.get('inside') ? -1 : 1) * tickModel.get('length'), radius = radiusExtent[getRadiusIdx(polar)], lines = map(ticksAngles, function(tickAngleItem) { return new Line({ shape: getAxisLineShape(polar, [ radius, radius + tickLen ], tickAngleItem.coord) }); }); group.add(mergePath$1(lines, { style: defaults(tickModel.getModel('lineStyle').getLineStyle(), { stroke: angleAxisModel.get([ 'axisLine', 'lineStyle', 'color' ]) }) })); }, minorTick: function(group, angleAxisModel, polar, tickAngles, minorTickAngles, radiusExtent) { if (minorTickAngles.length) { for(var tickModel = angleAxisModel.getModel('axisTick'), minorTickModel = angleAxisModel.getModel('minorTick'), tickLen = (tickModel.get('inside') ? -1 : 1) * minorTickModel.get('length'), radius = radiusExtent[getRadiusIdx(polar)], lines = [], i = 0; i < minorTickAngles.length; i++)for(var k = 0; k < minorTickAngles[i].length; k++)lines.push(new Line({ shape: getAxisLineShape(polar, [ radius, radius + tickLen ], minorTickAngles[i][k].coord) })); group.add(mergePath$1(lines, { style: defaults(minorTickModel.getModel('lineStyle').getLineStyle(), defaults(tickModel.getLineStyle(), { stroke: angleAxisModel.get([ 'axisLine', 'lineStyle', 'color' ]) })) })); } }, axisLabel: function(group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent, labels) { var rawCategoryData = angleAxisModel.getCategories(!0), commonLabelModel = angleAxisModel.getModel('axisLabel'), labelMargin = commonLabelModel.get('margin'), triggerEvent = angleAxisModel.get('triggerEvent'); each(labels, function(labelItem, idx) { var labelModel = commonLabelModel, tickValue = labelItem.tickValue, r = radiusExtent[getRadiusIdx(polar)], p = polar.coordToPoint([ r + labelMargin, labelItem.coord ]), cx = polar.cx, cy = polar.cy, labelTextAlign = Math.abs(p[0] - cx) / r < 0.3 ? 'center' : p[0] > cx ? 'left' : 'right', labelTextVerticalAlign = Math.abs(p[1] - cy) / r < 0.3 ? 'middle' : p[1] > cy ? 'top' : 'bottom'; if (rawCategoryData && rawCategoryData[tickValue]) { var rawCategoryItem = rawCategoryData[tickValue]; isObject(rawCategoryItem) && rawCategoryItem.textStyle && (labelModel = new Model(rawCategoryItem.textStyle, commonLabelModel, commonLabelModel.ecModel)); } var textEl = new ZRText({ silent: AxisBuilder.isLabelSilent(angleAxisModel), style: createTextStyle(labelModel, { x: p[0], y: p[1], fill: labelModel.getTextColor() || angleAxisModel.get([ 'axisLine', 'lineStyle', 'color' ]), text: labelItem.formattedLabel, align: labelTextAlign, verticalAlign: labelTextVerticalAlign }) }); if (group.add(textEl), triggerEvent) { var eventData = AxisBuilder.makeAxisEventDataBase(angleAxisModel); eventData.targetType = 'axisLabel', eventData.value = labelItem.rawLabel, getECData(textEl).eventData = eventData; } }, this); }, splitLine: function(group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) { var lineStyleModel = angleAxisModel.getModel('splitLine').getModel('lineStyle'), lineColors = lineStyleModel.get('color'), lineCount = 0; lineColors = lineColors instanceof Array ? lineColors : [ lineColors ]; for(var splitLines = [], i = 0; i < ticksAngles.length; i++){ var colorIndex = lineCount++ % lineColors.length; splitLines[colorIndex] = splitLines[colorIndex] || [], splitLines[colorIndex].push(new Line({ shape: getAxisLineShape(polar, radiusExtent, ticksAngles[i].coord) })); } for(var i = 0; i < splitLines.length; i++)group.add(mergePath$1(splitLines[i], { style: defaults({ stroke: lineColors[i % lineColors.length] }, lineStyleModel.getLineStyle()), silent: !0, z: angleAxisModel.get('z') })); }, minorSplitLine: function(group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) { if (minorTickAngles.length) { for(var lineStyleModel = angleAxisModel.getModel('minorSplitLine').getModel('lineStyle'), lines = [], i = 0; i < minorTickAngles.length; i++)for(var k = 0; k < minorTickAngles[i].length; k++)lines.push(new Line({ shape: getAxisLineShape(polar, radiusExtent, minorTickAngles[i][k].coord) })); group.add(mergePath$1(lines, { style: lineStyleModel.getLineStyle(), silent: !0, z: angleAxisModel.get('z') })); } }, splitArea: function(group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) { if (ticksAngles.length) { var areaStyleModel = angleAxisModel.getModel('splitArea').getModel('areaStyle'), areaColors = areaStyleModel.get('color'), lineCount = 0; areaColors = areaColors instanceof Array ? areaColors : [ areaColors ]; for(var splitAreas = [], RADIAN = Math.PI / 180, prevAngle = -ticksAngles[0].coord * RADIAN, r0 = Math.min(radiusExtent[0], radiusExtent[1]), r1 = Math.max(radiusExtent[0], radiusExtent[1]), clockwise = angleAxisModel.get('clockwise'), i = 1, len = ticksAngles.length; i <= len; i++){ var coord = i === len ? ticksAngles[0].coord : ticksAngles[i].coord, colorIndex = lineCount++ % areaColors.length; splitAreas[colorIndex] = splitAreas[colorIndex] || [], splitAreas[colorIndex].push(new Sector({ shape: { cx: polar.cx, cy: polar.cy, r0: r0, r: r1, startAngle: prevAngle, endAngle: -coord * RADIAN, clockwise: clockwise }, silent: !0 })), prevAngle = -coord * RADIAN; } for(var i = 0; i < splitAreas.length; i++)group.add(mergePath$1(splitAreas[i], { style: defaults({ fill: areaColors[i % areaColors.length] }, areaStyleModel.getAreaStyle()), silent: !0 })); } } }, axisBuilderAttrs$2 = [ 'axisLine', 'axisTickLabel', 'axisName' ], selfBuilderAttrs$1 = [ 'splitLine', 'splitArea', 'minorSplitLine' ], RadiusAxisView = function(_super) { function RadiusAxisView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = RadiusAxisView.type, _this.axisPointerClass = 'PolarAxisPointer', _this; } return __extends(RadiusAxisView, _super), RadiusAxisView.prototype.render = function(radiusAxisModel, ecModel) { if (this.group.removeAll(), radiusAxisModel.get('show')) { var oldAxisGroup = this._axisGroup, newAxisGroup = this._axisGroup = new Group(); this.group.add(newAxisGroup); var radiusAxis = radiusAxisModel.axis, polar = radiusAxis.polar, angleAxis = polar.getAngleAxis(), ticksCoords = radiusAxis.getTicksCoords(), minorTicksCoords = radiusAxis.getMinorTicksCoords(), axisAngle = angleAxis.getExtent()[0], radiusExtent = radiusAxis.getExtent(), layout = { position: [ polar.cx, polar.cy ], rotation: axisAngle / 180 * Math.PI, labelDirection: -1, tickDirection: -1, nameDirection: 1, labelRotate: radiusAxisModel.getModel('axisLabel').get('rotate'), z2: 1 }, axisBuilder = new AxisBuilder(radiusAxisModel, layout); each(axisBuilderAttrs$2, axisBuilder.add, axisBuilder), newAxisGroup.add(axisBuilder.getGroup()), groupTransition(oldAxisGroup, newAxisGroup, radiusAxisModel), each(selfBuilderAttrs$1, function(name) { radiusAxisModel.get([ name, 'show' ]) && !radiusAxis.scale.isBlank() && axisElementBuilders$1[name](this.group, radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords, minorTicksCoords); }, this); } }, RadiusAxisView.type = 'radiusAxis', RadiusAxisView; }(AxisView), axisElementBuilders$1 = { splitLine: function(group, radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) { var lineStyleModel = radiusAxisModel.getModel('splitLine').getModel('lineStyle'), lineColors = lineStyleModel.get('color'), lineCount = 0; lineColors = lineColors instanceof Array ? lineColors : [ lineColors ]; for(var splitLines = [], i = 0; i < ticksCoords.length; i++){ var colorIndex = lineCount++ % lineColors.length; splitLines[colorIndex] = splitLines[colorIndex] || [], splitLines[colorIndex].push(new Circle({ shape: { cx: polar.cx, cy: polar.cy, r: ticksCoords[i].coord } })); } for(var i = 0; i < splitLines.length; i++)group.add(mergePath$1(splitLines[i], { style: defaults({ stroke: lineColors[i % lineColors.length], fill: null }, lineStyleModel.getLineStyle()), silent: !0 })); }, minorSplitLine: function(group, radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords, minorTicksCoords) { if (minorTicksCoords.length) { for(var lineStyleModel = radiusAxisModel.getModel('minorSplitLine').getModel('lineStyle'), lines = [], i = 0; i < minorTicksCoords.length; i++)for(var k = 0; k < minorTicksCoords[i].length; k++)lines.push(new Circle({ shape: { cx: polar.cx, cy: polar.cy, r: minorTicksCoords[i][k].coord } })); group.add(mergePath$1(lines, { style: defaults({ fill: null }, lineStyleModel.getLineStyle()), silent: !0 })); } }, splitArea: function(group, radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) { if (ticksCoords.length) { var areaStyleModel = radiusAxisModel.getModel('splitArea').getModel('areaStyle'), areaColors = areaStyleModel.get('color'), lineCount = 0; areaColors = areaColors instanceof Array ? areaColors : [ areaColors ]; for(var splitAreas = [], prevRadius = ticksCoords[0].coord, i = 1; i < ticksCoords.length; i++){ var colorIndex = lineCount++ % areaColors.length; splitAreas[colorIndex] = splitAreas[colorIndex] || [], splitAreas[colorIndex].push(new Sector({ shape: { cx: polar.cx, cy: polar.cy, r0: prevRadius, r: ticksCoords[i].coord, startAngle: 0, endAngle: 2 * Math.PI }, silent: !0 })), prevRadius = ticksCoords[i].coord; } for(var i = 0; i < splitAreas.length; i++)group.add(mergePath$1(splitAreas[i], { style: defaults({ fill: areaColors[i % areaColors.length] }, areaStyleModel.getAreaStyle()), silent: !0 })); } } }; function getSeriesStackId$1(seriesModel) { return seriesModel.get('stack') || '__ec_stack_' + seriesModel.seriesIndex; } function getAxisKey$1(polar, axis) { return axis.dim + polar.model.componentIndex; } function barLayoutPolar(seriesType, ecModel, api) { var barSeries, columnsMap, result, lastStackCoords = {}, barWidthAndOffset = (barSeries = filter(ecModel.getSeriesByType(seriesType), function(seriesModel) { return !ecModel.isSeriesFiltered(seriesModel) && seriesModel.coordinateSystem && 'polar' === seriesModel.coordinateSystem.type; }), columnsMap = {}, each(barSeries, function(seriesModel, idx) { var data = seriesModel.getData(), polar = seriesModel.coordinateSystem, baseAxis = polar.getBaseAxis(), axisKey = getAxisKey$1(polar, baseAxis), axisExtent = baseAxis.getExtent(), bandWidth = 'category' === baseAxis.type ? baseAxis.getBandWidth() : Math.abs(axisExtent[1] - axisExtent[0]) / data.count(), columnsOnAxis = columnsMap[axisKey] || { bandWidth: bandWidth, remainedWidth: bandWidth, autoWidthCount: 0, categoryGap: '20%', gap: '30%', stacks: {} }, stacks = columnsOnAxis.stacks; columnsMap[axisKey] = columnsOnAxis; var stackId = getSeriesStackId$1(seriesModel); !stacks[stackId] && columnsOnAxis.autoWidthCount++, stacks[stackId] = stacks[stackId] || { width: 0, maxWidth: 0 }; var barWidth = parsePercent$1(seriesModel.get('barWidth'), bandWidth), barMaxWidth = parsePercent$1(seriesModel.get('barMaxWidth'), bandWidth), barGap = seriesModel.get('barGap'), barCategoryGap = seriesModel.get('barCategoryGap'); barWidth && !stacks[stackId].width && (barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth), stacks[stackId].width = barWidth, columnsOnAxis.remainedWidth -= barWidth), barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth), null != barGap && (columnsOnAxis.gap = barGap), null != barCategoryGap && (columnsOnAxis.categoryGap = barCategoryGap); }), result = {}, each(columnsMap, function(columnsOnAxis, coordSysName) { result[coordSysName] = {}; var lastColumn, stacks = columnsOnAxis.stacks, bandWidth = columnsOnAxis.bandWidth, categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth), barGapPercent = parsePercent$1(columnsOnAxis.gap, 1), remainedWidth = columnsOnAxis.remainedWidth, autoWidthCount = columnsOnAxis.autoWidthCount, autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent); autoWidth = Math.max(autoWidth, 0), each(stacks, function(column, stack) { var maxWidth = column.maxWidth; maxWidth && maxWidth < autoWidth && (maxWidth = Math.min(maxWidth, remainedWidth), column.width && (maxWidth = Math.min(maxWidth, column.width)), remainedWidth -= maxWidth, column.width = maxWidth, autoWidthCount--); }), autoWidth = Math.max(autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent), 0); var widthSum = 0; each(stacks, function(column, idx) { column.width || (column.width = autoWidth), lastColumn = column, widthSum += column.width * (1 + barGapPercent); }), lastColumn && (widthSum -= lastColumn.width * barGapPercent); var offset = -widthSum / 2; each(stacks, function(column, stackId) { result[coordSysName][stackId] = result[coordSysName][stackId] || { offset: offset, width: column.width }, offset += column.width * (1 + barGapPercent); }); }), result); ecModel.eachSeriesByType(seriesType, function(seriesModel) { if ('polar' === seriesModel.coordinateSystem.type) { var data = seriesModel.getData(), polar = seriesModel.coordinateSystem, baseAxis = polar.getBaseAxis(), axisKey = getAxisKey$1(polar, baseAxis), stackId = getSeriesStackId$1(seriesModel), columnLayoutInfo = barWidthAndOffset[axisKey][stackId], columnOffset = columnLayoutInfo.offset, columnWidth = columnLayoutInfo.width, valueAxis = polar.getOtherAxis(baseAxis), cx = seriesModel.coordinateSystem.cx, cy = seriesModel.coordinateSystem.cy, barMinHeight = seriesModel.get('barMinHeight') || 0, barMinAngle = seriesModel.get('barMinAngle') || 0; lastStackCoords[stackId] = lastStackCoords[stackId] || []; for(var valueDim = data.mapDimension(valueAxis.dim), baseDim = data.mapDimension(baseAxis.dim), stacked = isDimensionStacked(data, valueDim), clampLayout = 'radius' !== baseAxis.dim || !seriesModel.get('roundCap', !0), valueAxisStart = valueAxis.dataToCoord(0), idx = 0, len = data.count(); idx < len; idx++){ var value = data.get(valueDim, idx), baseValue = data.get(baseDim, idx), sign = value >= 0 ? 'p' : 'n', baseCoord = valueAxisStart; stacked && (lastStackCoords[stackId][baseValue] || (lastStackCoords[stackId][baseValue] = { p: valueAxisStart, n: valueAxisStart }), baseCoord = lastStackCoords[stackId][baseValue][sign]); var r0 = void 0, r = void 0, startAngle = void 0, endAngle = void 0; if ('radius' === valueAxis.dim) { var radiusSpan = valueAxis.dataToCoord(value) - valueAxisStart, angle = baseAxis.dataToCoord(baseValue); Math.abs(radiusSpan) < barMinHeight && (radiusSpan = (radiusSpan < 0 ? -1 : 1) * barMinHeight), r0 = baseCoord, r = baseCoord + radiusSpan, endAngle = (startAngle = angle - columnOffset) - columnWidth, stacked && (lastStackCoords[stackId][baseValue][sign] = r); } else { var angleSpan = valueAxis.dataToCoord(value, clampLayout) - valueAxisStart, radius = baseAxis.dataToCoord(baseValue); Math.abs(angleSpan) < barMinAngle && (angleSpan = (angleSpan < 0 ? -1 : 1) * barMinAngle), r = (r0 = radius + columnOffset) + columnWidth, startAngle = baseCoord, endAngle = baseCoord + angleSpan, stacked && (lastStackCoords[stackId][baseValue][sign] = endAngle); } data.setItemLayout(idx, { cx: cx, cy: cy, r0: r0, r: r, startAngle: -startAngle * Math.PI / 180, endAngle: -endAngle * Math.PI / 180 }); } } }); } var angleAxisExtraOption = { startAngle: 90, clockwise: !0, splitNumber: 12, axisLabel: { rotate: 0 } }, radiusAxisExtraOption = { splitNumber: 5 }, PolarView = function(_super) { function PolarView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = PolarView.type, _this; } return __extends(PolarView, _super), PolarView.type = 'polar', PolarView; }(ComponentView); function layout$2(axisModel, opt) { opt = opt || {}; var single = axisModel.coordinateSystem, axis = axisModel.axis, layout = {}, axisPosition = axis.position, orient = axis.orient, rect = single.getRect(), rectBound = [ rect.x, rect.x + rect.width, rect.y, rect.y + rect.height ], positionMap = { horizontal: { top: rectBound[2], bottom: rectBound[3] }, vertical: { left: rectBound[0], right: rectBound[1] } }; layout.position = [ 'vertical' === orient ? positionMap.vertical[axisPosition] : rectBound[0], 'horizontal' === orient ? positionMap.horizontal[axisPosition] : rectBound[3] ], layout.rotation = Math.PI / 2 * ({ horizontal: 0, vertical: 1 })[orient], layout.labelDirection = layout.tickDirection = layout.nameDirection = ({ top: -1, bottom: 1, right: 1, left: -1 })[axisPosition], axisModel.get([ 'axisTick', 'inside' ]) && (layout.tickDirection = -layout.tickDirection), retrieve(opt.labelInside, axisModel.get([ 'axisLabel', 'inside' ])) && (layout.labelDirection = -layout.labelDirection); var labelRotation = opt.rotate; return null == labelRotation && (labelRotation = axisModel.get([ 'axisLabel', 'rotate' ])), layout.labelRotation = 'top' === axisPosition ? -labelRotation : labelRotation, layout.z2 = 1, layout; } var axisBuilderAttrs$3 = [ 'axisLine', 'axisTickLabel', 'axisName' ], selfBuilderAttrs$2 = [ 'splitArea', 'splitLine' ], SingleAxisView = function(_super) { function SingleAxisView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = SingleAxisView.type, _this.axisPointerClass = 'SingleAxisPointer', _this; } return __extends(SingleAxisView, _super), SingleAxisView.prototype.render = function(axisModel, ecModel, api, payload) { var group = this.group; group.removeAll(); var oldAxisGroup = this._axisGroup; this._axisGroup = new Group(); var layout = layout$2(axisModel), axisBuilder = new AxisBuilder(axisModel, layout); each(axisBuilderAttrs$3, axisBuilder.add, axisBuilder), group.add(this._axisGroup), group.add(axisBuilder.getGroup()), each(selfBuilderAttrs$2, function(name) { axisModel.get([ name, 'show' ]) && axisElementBuilders$2[name](this, this.group, this._axisGroup, axisModel); }, this), groupTransition(oldAxisGroup, this._axisGroup, axisModel), _super.prototype.render.call(this, axisModel, ecModel, api, payload); }, SingleAxisView.prototype.remove = function() { rectCoordAxisHandleRemove(this); }, SingleAxisView.type = 'singleAxis', SingleAxisView; }(AxisView), axisElementBuilders$2 = { splitLine: function(axisView, group, axisGroup, axisModel) { var axis = axisModel.axis; if (!axis.scale.isBlank()) { var splitLineModel = axisModel.getModel('splitLine'), lineStyleModel = splitLineModel.getModel('lineStyle'), lineColors = lineStyleModel.get('color'); lineColors = lineColors instanceof Array ? lineColors : [ lineColors ]; for(var gridRect = axisModel.coordinateSystem.getRect(), isHorizontal = axis.isHorizontal(), splitLines = [], lineCount = 0, ticksCoords = axis.getTicksCoords({ tickModel: splitLineModel }), p1 = [], p2 = [], i = 0; i < ticksCoords.length; ++i){ var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord); isHorizontal ? (p1[0] = tickCoord, p1[1] = gridRect.y, p2[0] = tickCoord, p2[1] = gridRect.y + gridRect.height) : (p1[0] = gridRect.x, p1[1] = tickCoord, p2[0] = gridRect.x + gridRect.width, p2[1] = tickCoord); var colorIndex = lineCount++ % lineColors.length; splitLines[colorIndex] = splitLines[colorIndex] || [], splitLines[colorIndex].push(new Line({ subPixelOptimize: !0, shape: { x1: p1[0], y1: p1[1], x2: p2[0], y2: p2[1] }, silent: !0 })); } for(var lineStyle = lineStyleModel.getLineStyle([ 'color' ]), i = 0; i < splitLines.length; ++i)group.add(mergePath$1(splitLines[i], { style: defaults({ stroke: lineColors[i % lineColors.length] }, lineStyle), silent: !0 })); } }, splitArea: function(axisView, group, axisGroup, axisModel) { rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, axisModel); } }, SingleAxisModel = function(_super) { function SingleAxisModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = SingleAxisModel.type, _this; } return __extends(SingleAxisModel, _super), SingleAxisModel.prototype.getCoordSysModel = function() { return this; }, SingleAxisModel.type = 'singleAxis', SingleAxisModel.layoutMode = 'box', SingleAxisModel.defaultOption = { left: '5%', top: '5%', right: '5%', bottom: '5%', type: 'value', position: 'bottom', orient: 'horizontal', axisLine: { show: !0, lineStyle: { width: 1, type: 'solid' } }, tooltip: { show: !0 }, axisTick: { show: !0, length: 6, lineStyle: { width: 1 } }, axisLabel: { show: !0, interval: 'auto' }, splitLine: { show: !0, lineStyle: { type: 'dashed', opacity: 0.2 } } }, SingleAxisModel; }(ComponentModel); mixin(SingleAxisModel, AxisModelCommonMixin.prototype); var SingleAxis = function(_super) { function SingleAxis(dim, scale, coordExtent, axisType, position) { var _this = _super.call(this, dim, scale, coordExtent) || this; return _this.type = axisType || 'value', _this.position = position || 'bottom', _this; } return __extends(SingleAxis, _super), SingleAxis.prototype.isHorizontal = function() { var position = this.position; return 'top' === position || 'bottom' === position; }, SingleAxis.prototype.pointToData = function(point, clamp) { return this.coordinateSystem.pointToData(point)[0]; }, SingleAxis; }(Axis), Single = function() { function Single(axisModel, ecModel, api) { this.type = 'single', this.dimension = 'single', this.dimensions = [ 'single' ], this.axisPointerEnabled = !0, this.model = axisModel, this._init(axisModel, ecModel, api); } return Single.prototype._init = function(axisModel, ecModel, api) { var dim = this.dimension, axis = new SingleAxis(dim, createScaleByModel(axisModel), [ 0, 0 ], axisModel.get('type'), axisModel.get('position')), isCategory = 'category' === axis.type; axis.onBand = isCategory && axisModel.get('boundaryGap'), axis.inverse = axisModel.get('inverse'), axis.orient = axisModel.get('orient'), axisModel.axis = axis, axis.model = axisModel, axis.coordinateSystem = this, this._axis = axis; }, Single.prototype.update = function(ecModel, api) { ecModel.eachSeries(function(seriesModel) { if (seriesModel.coordinateSystem === this) { var data_1 = seriesModel.getData(); each(data_1.mapDimensionsAll(this.dimension), function(dim) { this._axis.scale.unionExtentFromData(data_1, dim); }, this), niceScaleExtent(this._axis.scale, this._axis.model); } }, this); }, Single.prototype.resize = function(axisModel, api) { this._rect = getLayoutRect({ left: axisModel.get('left'), top: axisModel.get('top'), right: axisModel.get('right'), bottom: axisModel.get('bottom'), width: axisModel.get('width'), height: axisModel.get('height') }, { width: api.getWidth(), height: api.getHeight() }), this._adjustAxis(); }, Single.prototype.getRect = function() { return this._rect; }, Single.prototype._adjustAxis = function() { var rect = this._rect, axis = this._axis, isHorizontal = axis.isHorizontal(), extent = isHorizontal ? [ 0, rect.width ] : [ 0, rect.height ], idx = axis.reverse ? 1 : 0; axis.setExtent(extent[idx], extent[1 - idx]), this._updateAxisTransform(axis, isHorizontal ? rect.x : rect.y); }, Single.prototype._updateAxisTransform = function(axis, coordBase) { var axisExtent = axis.getExtent(), extentSum = axisExtent[0] + axisExtent[1], isHorizontal = axis.isHorizontal(); axis.toGlobalCoord = isHorizontal ? function(coord) { return coord + coordBase; } : function(coord) { return extentSum - coord + coordBase; }, axis.toLocalCoord = isHorizontal ? function(coord) { return coord - coordBase; } : function(coord) { return extentSum - coord + coordBase; }; }, Single.prototype.getAxis = function() { return this._axis; }, Single.prototype.getBaseAxis = function() { return this._axis; }, Single.prototype.getAxes = function() { return [ this._axis ]; }, Single.prototype.getTooltipAxes = function() { return { baseAxes: [ this.getAxis() ], otherAxes: [] }; }, Single.prototype.containPoint = function(point) { var rect = this.getRect(), axis = this.getAxis(); return 'horizontal' === axis.orient ? axis.contain(axis.toLocalCoord(point[0])) && point[1] >= rect.y && point[1] <= rect.y + rect.height : axis.contain(axis.toLocalCoord(point[1])) && point[0] >= rect.y && point[0] <= rect.y + rect.height; }, Single.prototype.pointToData = function(point) { var axis = this.getAxis(); return [ axis.coordToData(axis.toLocalCoord(point['horizontal' === axis.orient ? 0 : 1])) ]; }, Single.prototype.dataToPoint = function(val) { var axis = this.getAxis(), rect = this.getRect(), pt = [], idx = 'horizontal' === axis.orient ? 0 : 1; return val instanceof Array && (val = val[0]), pt[idx] = axis.toGlobalCoord(axis.dataToCoord(+val)), pt[1 - idx] = 0 === idx ? rect.y + rect.height / 2 : rect.x + rect.width / 2, pt; }, Single.prototype.convertToPixel = function(ecModel, finder, value) { return getCoordSys$3(finder) === this ? this.dataToPoint(value) : null; }, Single.prototype.convertFromPixel = function(ecModel, finder, pixel) { return getCoordSys$3(finder) === this ? this.pointToData(pixel) : null; }, Single; }(); function getCoordSys$3(finder) { var seriesModel = finder.seriesModel, singleModel = finder.singleAxisModel; return singleModel && singleModel.coordinateSystem || seriesModel && seriesModel.coordinateSystem; } var singleCreator = { create: function(ecModel, api) { var singles = []; return ecModel.eachComponent('singleAxis', function(axisModel, idx) { var single = new Single(axisModel, ecModel, api); single.name = 'single_' + idx, single.resize(axisModel, api), axisModel.coordinateSystem = single, singles.push(single); }), ecModel.eachSeries(function(seriesModel) { if ('singleAxis' === seriesModel.get('coordinateSystem')) { var singleAxisModel = seriesModel.getReferringComponents('singleAxis', SINGLE_REFERRING).models[0]; seriesModel.coordinateSystem = singleAxisModel && singleAxisModel.coordinateSystem; } }), singles; }, dimensions: Single.prototype.dimensions }, XY = [ 'x', 'y' ], WH = [ 'width', 'height' ], SingleAxisPointer = function(_super) { function SingleAxisPointer() { return null !== _super && _super.apply(this, arguments) || this; } return __extends(SingleAxisPointer, _super), SingleAxisPointer.prototype.makeElOption = function(elOption, value, axisModel, axisPointerModel, api) { var axis = axisModel.axis, coordSys = axis.coordinateSystem, otherExtent = getGlobalExtent(coordSys, 1 - getPointDimIndex(axis)), pixelValue = coordSys.dataToPoint(value)[0], axisPointerType = axisPointerModel.get('type'); if (axisPointerType && 'none' !== axisPointerType) { var elStyle = buildElStyle(axisPointerModel), pointerOption = pointerShapeBuilder$2[axisPointerType](axis, pixelValue, otherExtent); pointerOption.style = elStyle, elOption.graphicKey = pointerOption.type, elOption.pointer = pointerOption; } buildCartesianSingleLabelElOption(value, elOption, layout$2(axisModel), axisModel, axisPointerModel, api); }, SingleAxisPointer.prototype.getHandleTransform = function(value, axisModel, axisPointerModel) { var layoutInfo = layout$2(axisModel, { labelInside: !1 }); layoutInfo.labelMargin = axisPointerModel.get([ 'handle', 'margin' ]); var position = getTransformedPosition(axisModel.axis, value, layoutInfo); return { x: position[0], y: position[1], rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0) }; }, SingleAxisPointer.prototype.updateHandleTransform = function(transform, delta, axisModel, axisPointerModel) { var axis = axisModel.axis, coordSys = axis.coordinateSystem, dimIndex = getPointDimIndex(axis), axisExtent = getGlobalExtent(coordSys, dimIndex), currPosition = [ transform.x, transform.y ]; currPosition[dimIndex] += delta[dimIndex], currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]), currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]); var otherExtent = getGlobalExtent(coordSys, 1 - dimIndex), cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2, cursorPoint = [ cursorOtherValue, cursorOtherValue ]; return cursorPoint[dimIndex] = currPosition[dimIndex], { x: currPosition[0], y: currPosition[1], rotation: transform.rotation, cursorPoint: cursorPoint, tooltipOption: { verticalAlign: 'middle' } }; }, SingleAxisPointer; }(BaseAxisPointer), pointerShapeBuilder$2 = { line: function(axis, pixelValue, otherExtent) { return { type: 'Line', subPixelOptimize: !0, shape: makeLineShape([ pixelValue, otherExtent[0] ], [ pixelValue, otherExtent[1] ], getPointDimIndex(axis)) }; }, shadow: function(axis, pixelValue, otherExtent) { var bandWidth = axis.getBandWidth(), span = otherExtent[1] - otherExtent[0]; return { type: 'Rect', shape: makeRectShape([ pixelValue - bandWidth / 2, otherExtent[0] ], [ bandWidth, span ], getPointDimIndex(axis)) }; } }; function getPointDimIndex(axis) { return axis.isHorizontal() ? 0 : 1; } function getGlobalExtent(coordSys, dimIndex) { var rect = coordSys.getRect(); return [ rect[XY[dimIndex]], rect[XY[dimIndex]] + rect[WH[dimIndex]] ]; } var SingleView = function(_super) { function SingleView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = SingleView.type, _this; } return __extends(SingleView, _super), SingleView.type = 'single', SingleView; }(ComponentView), CalendarModel = function(_super) { function CalendarModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = CalendarModel.type, _this; } return __extends(CalendarModel, _super), CalendarModel.prototype.init = function(option, parentModel, ecModel) { var inputPositionParams = getLayoutParams(option); _super.prototype.init.apply(this, arguments), mergeAndNormalizeLayoutParams(option, inputPositionParams); }, CalendarModel.prototype.mergeOption = function(option) { _super.prototype.mergeOption.apply(this, arguments), mergeAndNormalizeLayoutParams(this.option, option); }, CalendarModel.prototype.getCellSize = function() { return this.option.cellSize; }, CalendarModel.type = 'calendar', CalendarModel.defaultOption = { zlevel: 0, z: 2, left: 80, top: 60, cellSize: 20, orient: 'horizontal', splitLine: { show: !0, lineStyle: { color: '#000', width: 1, type: 'solid' } }, itemStyle: { color: '#fff', borderWidth: 1, borderColor: '#ccc' }, dayLabel: { show: !0, firstDay: 0, position: 'start', margin: '50%', nameMap: 'en', color: '#000' }, monthLabel: { show: !0, position: 'start', margin: 5, align: 'center', nameMap: 'en', formatter: null, color: '#000' }, yearLabel: { show: !0, position: null, margin: 30, formatter: null, color: '#ccc', fontFamily: 'sans-serif', fontWeight: 'bolder', fontSize: 20 } }, CalendarModel; }(ComponentModel); function mergeAndNormalizeLayoutParams(target, raw) { var cellSizeArr, cellSize = target.cellSize; 1 === (cellSizeArr = isArray(cellSize) ? cellSize : target.cellSize = [ cellSize, cellSize ]).length && (cellSizeArr[1] = cellSizeArr[0]); var ignoreSize = map([ 0, 1 ], function(hvIdx) { return (null != raw[HV_NAMES[hvIdx][0]] || null != raw[HV_NAMES[hvIdx][1]] && null != raw[HV_NAMES[hvIdx][2]]) && (cellSizeArr[hvIdx] = 'auto'), null != cellSizeArr[hvIdx] && 'auto' !== cellSizeArr[hvIdx]; }); mergeLayoutParam(target, raw, { type: 'box', ignoreSize: ignoreSize }); } var MONTH_TEXT = { EN: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ], CN: [ '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月' ] }, WEEK_TEXT = { EN: [ 'S', 'M', 'T', 'W', 'T', 'F', 'S' ], CN: [ '日', '一', '二', '三', '四', '五', '六' ] }, CalendarView = function(_super) { function CalendarView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = CalendarView.type, _this; } return __extends(CalendarView, _super), CalendarView.prototype.render = function(calendarModel, ecModel, api) { var group = this.group; group.removeAll(); var coordSys = calendarModel.coordinateSystem, rangeData = coordSys.getRangeInfo(), orient = coordSys.getOrient(); this._renderDayRect(calendarModel, rangeData, group), this._renderLines(calendarModel, rangeData, orient, group), this._renderYearText(calendarModel, rangeData, orient, group), this._renderMonthText(calendarModel, orient, group), this._renderWeekText(calendarModel, rangeData, orient, group); }, CalendarView.prototype._renderDayRect = function(calendarModel, rangeData, group) { for(var coordSys = calendarModel.coordinateSystem, itemRectStyleModel = calendarModel.getModel('itemStyle').getItemStyle(), sw = coordSys.getCellWidth(), sh = coordSys.getCellHeight(), i = rangeData.start.time; i <= rangeData.end.time; i = coordSys.getNextNDay(i, 1).time){ var point = coordSys.dataToRect([ i ], !1).tl, rect = new Rect({ shape: { x: point[0], y: point[1], width: sw, height: sh }, cursor: 'default', style: itemRectStyleModel }); group.add(rect); } }, CalendarView.prototype._renderLines = function(calendarModel, rangeData, orient, group) { var self1 = this, coordSys = calendarModel.coordinateSystem, lineStyleModel = calendarModel.getModel([ 'splitLine', 'lineStyle' ]).getLineStyle(), show = calendarModel.get([ 'splitLine', 'show' ]), lineWidth = lineStyleModel.lineWidth; this._tlpoints = [], this._blpoints = [], this._firstDayOfMonth = [], this._firstDayPoints = []; for(var firstDay = rangeData.start, i = 0; firstDay.time <= rangeData.end.time; i++){ addPoints(firstDay.formatedDate), 0 === i && (firstDay = coordSys.getDateInfo(rangeData.start.y + '-' + rangeData.start.m)); var date = firstDay.date; date.setMonth(date.getMonth() + 1), firstDay = coordSys.getDateInfo(date); } function addPoints(date) { self1._firstDayOfMonth.push(coordSys.getDateInfo(date)), self1._firstDayPoints.push(coordSys.dataToRect([ date ], !1).tl); var points = self1._getLinePointsOfOneWeek(calendarModel, date, orient); self1._tlpoints.push(points[0]), self1._blpoints.push(points[points.length - 1]), show && self1._drawSplitline(points, lineStyleModel, group); } addPoints(coordSys.getNextNDay(rangeData.end.time, 1).formatedDate), show && this._drawSplitline(self1._getEdgesPoints(self1._tlpoints, lineWidth, orient), lineStyleModel, group), show && this._drawSplitline(self1._getEdgesPoints(self1._blpoints, lineWidth, orient), lineStyleModel, group); }, CalendarView.prototype._getEdgesPoints = function(points, lineWidth, orient) { var rs = [ points[0].slice(), points[points.length - 1].slice() ], idx = 'horizontal' === orient ? 0 : 1; return rs[0][idx] = rs[0][idx] - lineWidth / 2, rs[1][idx] = rs[1][idx] + lineWidth / 2, rs; }, CalendarView.prototype._drawSplitline = function(points, lineStyle, group) { var poyline = new Polyline({ z2: 20, shape: { points: points }, style: lineStyle }); group.add(poyline); }, CalendarView.prototype._getLinePointsOfOneWeek = function(calendarModel, date, orient) { for(var coordSys = calendarModel.coordinateSystem, parsedDate = coordSys.getDateInfo(date), points = [], i = 0; i < 7; i++){ var tmpD = coordSys.getNextNDay(parsedDate.time, i), point = coordSys.dataToRect([ tmpD.time ], !1); points[2 * tmpD.day] = point.tl, points[2 * tmpD.day + 1] = point['horizontal' === orient ? 'bl' : 'tr']; } return points; }, CalendarView.prototype._formatterLabel = function(formatter, params) { if ('string' == typeof formatter && formatter) { var tpl; return tpl = formatter, each(params, function(value, key) { tpl = tpl.replace('{' + key + '}', value); }), tpl; } return 'function' == typeof formatter ? formatter(params) : params.nameMap; }, CalendarView.prototype._yearTextPositionControl = function(textEl, point, orient, position, margin) { var x = point[0], y = point[1], aligns = [ 'center', 'bottom' ]; 'bottom' === position ? (y += margin, aligns = [ 'center', 'top' ]) : 'left' === position ? x -= margin : 'right' === position ? (x += margin, aligns = [ 'center', 'top' ]) : y -= margin; var rotate = 0; return ('left' === position || 'right' === position) && (rotate = Math.PI / 2), { rotation: rotate, x: x, y: y, style: { align: aligns[0], verticalAlign: aligns[1] } }; }, CalendarView.prototype._renderYearText = function(calendarModel, rangeData, orient, group) { var yearLabel = calendarModel.getModel('yearLabel'); if (yearLabel.get('show')) { var margin = yearLabel.get('margin'), pos = yearLabel.get('position'); pos || (pos = 'horizontal' !== orient ? 'top' : 'left'); var points = [ this._tlpoints[this._tlpoints.length - 1], this._blpoints[0] ], xc = (points[0][0] + points[1][0]) / 2, yc = (points[0][1] + points[1][1]) / 2, idx = 'horizontal' === orient ? 0 : 1, posPoints = { top: [ xc, points[idx][1] ], bottom: [ xc, points[1 - idx][1] ], left: [ points[1 - idx][0], yc ], right: [ points[idx][0], yc ] }, name = rangeData.start.y; +rangeData.end.y > +rangeData.start.y && (name = name + '-' + rangeData.end.y); var formatter = yearLabel.get('formatter'), params = { start: rangeData.start.y, end: rangeData.end.y, nameMap: name }, content = this._formatterLabel(formatter, params), yearText = new ZRText({ z2: 30, style: createTextStyle(yearLabel, { text: content }) }); yearText.attr(this._yearTextPositionControl(yearText, posPoints[pos], orient, pos, margin)), group.add(yearText); } }, CalendarView.prototype._monthTextPositionControl = function(point, isCenter, orient, position, margin) { var align = 'left', vAlign = 'top', x = point[0], y = point[1]; return 'horizontal' === orient ? (y += margin, isCenter && (align = 'center'), 'start' === position && (vAlign = 'bottom')) : (x += margin, isCenter && (vAlign = 'middle'), 'start' === position && (align = 'right')), { x: x, y: y, align: align, verticalAlign: vAlign }; }, CalendarView.prototype._renderMonthText = function(calendarModel, orient, group) { var monthLabel = calendarModel.getModel('monthLabel'); if (monthLabel.get('show')) { var nameMap = monthLabel.get('nameMap'), margin = monthLabel.get('margin'), pos = monthLabel.get('position'), align = monthLabel.get('align'), termPoints = [ this._tlpoints, this._blpoints ]; isString(nameMap) && (nameMap = MONTH_TEXT[nameMap.toUpperCase()] || []); var idx = 'start' === pos ? 0 : 1, axis = 'horizontal' === orient ? 0 : 1; margin = 'start' === pos ? -margin : margin; for(var isCenter = 'center' === align, i = 0; i < termPoints[idx].length - 1; i++){ var tmp = termPoints[idx][i].slice(), firstDay = this._firstDayOfMonth[i]; if (isCenter) { var firstDayPoints = this._firstDayPoints[i]; tmp[axis] = (firstDayPoints[axis] + termPoints[0][i + 1][axis]) / 2; } var formatter = monthLabel.get('formatter'), name_1 = nameMap[+firstDay.m - 1], params = { yyyy: firstDay.y, yy: (firstDay.y + '').slice(2), MM: firstDay.m, M: +firstDay.m, nameMap: name_1 }, content = this._formatterLabel(formatter, params), monthText = new ZRText({ z2: 30, style: extend(createTextStyle(monthLabel, { text: content }), this._monthTextPositionControl(tmp, isCenter, orient, pos, margin)) }); group.add(monthText); } } }, CalendarView.prototype._weekTextPositionControl = function(point, orient, position, margin, cellSize) { var align = 'center', vAlign = 'middle', x = point[0], y = point[1], isStart = 'start' === position; return 'horizontal' === orient ? (x = x + margin + (isStart ? 1 : -1) * cellSize[0] / 2, align = isStart ? 'right' : 'left') : (y = y + margin + (isStart ? 1 : -1) * cellSize[1] / 2, vAlign = isStart ? 'bottom' : 'top'), { x: x, y: y, align: align, verticalAlign: vAlign }; }, CalendarView.prototype._renderWeekText = function(calendarModel, rangeData, orient, group) { var dayLabel = calendarModel.getModel('dayLabel'); if (dayLabel.get('show')) { var coordSys = calendarModel.coordinateSystem, pos = dayLabel.get('position'), nameMap = dayLabel.get('nameMap'), margin = dayLabel.get('margin'), firstDayOfWeek = coordSys.getFirstDayOfWeek(); isString(nameMap) && (nameMap = WEEK_TEXT[nameMap.toUpperCase()] || []); var start = coordSys.getNextNDay(rangeData.end.time, 7 - rangeData.lweek).time, cellSize = [ coordSys.getCellWidth(), coordSys.getCellHeight() ]; margin = parsePercent$1(margin, Math.min(cellSize[1], cellSize[0])), 'start' === pos && (start = coordSys.getNextNDay(rangeData.start.time, -(7 + rangeData.fweek)).time, margin = -margin); for(var i = 0; i < 7; i++){ var tmpD = coordSys.getNextNDay(start, i), point = coordSys.dataToRect([ tmpD.time ], !1).center, day = i; day = Math.abs((i + firstDayOfWeek) % 7); var weekText = new ZRText({ z2: 30, style: extend(createTextStyle(dayLabel, { text: nameMap[day] }), this._weekTextPositionControl(point, orient, pos, margin, cellSize)) }); group.add(weekText); } } }, CalendarView.type = 'calendar', CalendarView; }(ComponentView), Calendar = function() { function Calendar(calendarModel, ecModel, api) { this.type = 'calendar', this.dimensions = Calendar.dimensions, this.getDimensionsInfo = Calendar.getDimensionsInfo, this._model = calendarModel; } return Calendar.getDimensionsInfo = function() { return [ { name: 'time', type: 'time' }, 'value' ]; }, Calendar.prototype.getRangeInfo = function() { return this._rangeInfo; }, Calendar.prototype.getModel = function() { return this._model; }, Calendar.prototype.getRect = function() { return this._rect; }, Calendar.prototype.getCellWidth = function() { return this._sw; }, Calendar.prototype.getCellHeight = function() { return this._sh; }, Calendar.prototype.getOrient = function() { return this._orient; }, Calendar.prototype.getFirstDayOfWeek = function() { return this._firstDayOfWeek; }, Calendar.prototype.getDateInfo = function(date) { var y = (date = parseDate(date)).getFullYear(), m = date.getMonth() + 1, mStr = m < 10 ? '0' + m : '' + m, d = date.getDate(), dStr = d < 10 ? '0' + d : '' + d, day = date.getDay(); return { y: y + '', m: mStr, d: dStr, day: day = Math.abs((day + 7 - this.getFirstDayOfWeek()) % 7), time: date.getTime(), formatedDate: y + '-' + mStr + '-' + dStr, date: date }; }, Calendar.prototype.getNextNDay = function(date, n) { return 0 === (n = n || 0) || (date = new Date(this.getDateInfo(date).time)).setDate(date.getDate() + n), this.getDateInfo(date); }, Calendar.prototype.update = function(ecModel, api) { this._firstDayOfWeek = +this._model.getModel('dayLabel').get('firstDay'), this._orient = this._model.get('orient'), this._lineWidth = this._model.getModel('itemStyle').getItemStyle().lineWidth || 0, this._rangeInfo = this._getRangeInfo(this._initRangeOption()); var weeks = this._rangeInfo.weeks || 1, whNames = [ 'width', 'height' ], cellSize = this._model.getCellSize().slice(), layoutParams = this._model.getBoxLayoutParams(), cellNumbers = 'horizontal' === this._orient ? [ weeks, 7 ] : [ 7, weeks ]; each([ 0, 1 ], function(idx) { cellSizeSpecified(cellSize, idx) && (layoutParams[whNames[idx]] = cellSize[idx] * cellNumbers[idx]); }); var whGlobal = { width: api.getWidth(), height: api.getHeight() }, calendarRect = this._rect = getLayoutRect(layoutParams, whGlobal); function cellSizeSpecified(cellSize, idx) { return null != cellSize[idx] && 'auto' !== cellSize[idx]; } each([ 0, 1 ], function(idx) { cellSizeSpecified(cellSize, idx) || (cellSize[idx] = calendarRect[whNames[idx]] / cellNumbers[idx]); }), this._sw = cellSize[0], this._sh = cellSize[1]; }, Calendar.prototype.dataToPoint = function(data, clamp) { isArray(data) && (data = data[0]), null == clamp && (clamp = !0); var dayInfo = this.getDateInfo(data), range = this._rangeInfo, date = dayInfo.formatedDate; if (clamp && !(dayInfo.time >= range.start.time && dayInfo.time < range.end.time + 86400000)) return [ NaN, NaN ]; var week = dayInfo.day, nthWeek = this._getRangeInfo([ range.start.time, date ]).nthWeek; return 'vertical' === this._orient ? [ this._rect.x + week * this._sw + this._sw / 2, this._rect.y + nthWeek * this._sh + this._sh / 2 ] : [ this._rect.x + nthWeek * this._sw + this._sw / 2, this._rect.y + week * this._sh + this._sh / 2 ]; }, Calendar.prototype.pointToData = function(point) { var date = this.pointToDate(point); return date && date.time; }, Calendar.prototype.dataToRect = function(data, clamp) { var point = this.dataToPoint(data, clamp); return { contentShape: { x: point[0] - (this._sw - this._lineWidth) / 2, y: point[1] - (this._sh - this._lineWidth) / 2, width: this._sw - this._lineWidth, height: this._sh - this._lineWidth }, center: point, tl: [ point[0] - this._sw / 2, point[1] - this._sh / 2 ], tr: [ point[0] + this._sw / 2, point[1] - this._sh / 2 ], br: [ point[0] + this._sw / 2, point[1] + this._sh / 2 ], bl: [ point[0] - this._sw / 2, point[1] + this._sh / 2 ] }; }, Calendar.prototype.pointToDate = function(point) { var nthX = Math.floor((point[0] - this._rect.x) / this._sw) + 1, nthY = Math.floor((point[1] - this._rect.y) / this._sh) + 1, range = this._rangeInfo.range; return 'vertical' === this._orient ? this._getDateByWeeksAndDay(nthY, nthX - 1, range) : this._getDateByWeeksAndDay(nthX, nthY - 1, range); }, Calendar.prototype.convertToPixel = function(ecModel, finder, value) { var coordSys = getCoordSys$4(finder); return coordSys === this ? coordSys.dataToPoint(value) : null; }, Calendar.prototype.convertFromPixel = function(ecModel, finder, pixel) { var coordSys = getCoordSys$4(finder); return coordSys === this ? coordSys.pointToData(pixel) : null; }, Calendar.prototype.containPoint = function(point) { return console.warn('Not implemented.'), !1; }, Calendar.prototype._initRangeOption = function() { var normalizedRange, range = this._model.get('range'); if (isArray(range) && 1 === range.length && (range = range[0]), isArray(range)) normalizedRange = range; else { var rangeStr = range.toString(); if (/^\d{4}$/.test(rangeStr) && (normalizedRange = [ rangeStr + '-01-01', rangeStr + '-12-31' ]), /^\d{4}[\/|-]\d{1,2}$/.test(rangeStr)) { var start = this.getDateInfo(rangeStr), firstDay = start.date; firstDay.setMonth(firstDay.getMonth() + 1); var end = this.getNextNDay(firstDay, -1); normalizedRange = [ start.formatedDate, end.formatedDate ]; } /^\d{4}[\/|-]\d{1,2}[\/|-]\d{1,2}$/.test(rangeStr) && (normalizedRange = [ rangeStr, rangeStr ]); } if (!normalizedRange) return logError('Invalid date range.'), range; var tmp = this._getRangeInfo(normalizedRange); return tmp.start.time > tmp.end.time && normalizedRange.reverse(), normalizedRange; }, Calendar.prototype._getRangeInfo = function(range) { var reversed, parsedRange = [ this.getDateInfo(range[0]), this.getDateInfo(range[1]) ]; parsedRange[0].time > parsedRange[1].time && (reversed = !0, parsedRange.reverse()); var allDay = Math.floor(parsedRange[1].time / 86400000) - Math.floor(parsedRange[0].time / 86400000) + 1, date = new Date(parsedRange[0].time), startDateNum = date.getDate(), endDateNum = parsedRange[1].date.getDate(); date.setDate(startDateNum + allDay - 1); var dateNum = date.getDate(); if (dateNum !== endDateNum) for(var sign = date.getTime() - parsedRange[1].time > 0 ? 1 : -1; (dateNum = date.getDate()) !== endDateNum && (date.getTime() - parsedRange[1].time) * sign > 0;)allDay -= sign, date.setDate(dateNum - sign); var weeks = Math.floor((allDay + parsedRange[0].day + 6) / 7), nthWeek = reversed ? -weeks + 1 : weeks - 1; return reversed && parsedRange.reverse(), { range: [ parsedRange[0].formatedDate, parsedRange[1].formatedDate ], start: parsedRange[0], end: parsedRange[1], allDay: allDay, weeks: weeks, nthWeek: nthWeek, fweek: parsedRange[0].day, lweek: parsedRange[1].day }; }, Calendar.prototype._getDateByWeeksAndDay = function(nthWeek, day, range) { var rangeInfo = this._getRangeInfo(range); if (nthWeek > rangeInfo.weeks || 0 === nthWeek && day < rangeInfo.fweek || nthWeek === rangeInfo.weeks && day > rangeInfo.lweek) return null; var nthDay = (nthWeek - 1) * 7 - rangeInfo.fweek + day, date = new Date(rangeInfo.start.time); return date.setDate(+rangeInfo.start.d + nthDay), this.getDateInfo(date); }, Calendar.create = function(ecModel, api) { var calendarList = []; return ecModel.eachComponent('calendar', function(calendarModel) { var calendar = new Calendar(calendarModel, ecModel, api); calendarList.push(calendar), calendarModel.coordinateSystem = calendar; }), ecModel.eachSeries(function(calendarSeries) { 'calendar' === calendarSeries.get('coordinateSystem') && (calendarSeries.coordinateSystem = calendarList[calendarSeries.get('calendarIndex') || 0]); }), calendarList; }, Calendar.dimensions = [ 'time', 'value' ], Calendar; }(); function getCoordSys$4(finder) { var calendarModel = finder.calendarModel, seriesModel = finder.seriesModel; return calendarModel ? calendarModel.coordinateSystem : seriesModel ? seriesModel.coordinateSystem : null; } var inner$e = makeInner(), _nonShapeGraphicElements = { path: null, compoundPath: null, group: Group, image: ZRImage, text: ZRText }, preprocessor = function(option) { var graphicOption = option.graphic; isArray(graphicOption) ? graphicOption[0] && graphicOption[0].elements ? option.graphic = [ option.graphic[0] ] : option.graphic = [ { elements: graphicOption } ] : graphicOption && !graphicOption.elements && (option.graphic = [ { elements: [ graphicOption ] } ]); }, GraphicComponentModel = function(_super) { function GraphicComponentModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = GraphicComponentModel.type, _this.preventAutoZ = !0, _this; } return __extends(GraphicComponentModel, _super), GraphicComponentModel.prototype.mergeOption = function(option, ecModel) { var elements = this.option.elements; this.option.elements = null, _super.prototype.mergeOption.call(this, option, ecModel), this.option.elements = elements; }, GraphicComponentModel.prototype.optionUpdated = function(newOption, isInit) { var thisOption = this.option, newList = (isInit ? thisOption : newOption).elements, existList = thisOption.elements = isInit ? [] : thisOption.elements, flattenedList = []; this._flatten(newList, flattenedList, null); var mappingResult = mappingToExists(existList, flattenedList, 'normalMerge'), elOptionsToUpdate = this._elOptionsToUpdate = []; each(mappingResult, function(resultItem, index) { var newElOption = resultItem.newOption; assert(isObject(newElOption) || resultItem.existing, 'Empty graphic option definition'), newElOption && (elOptionsToUpdate.push(newElOption), function(resultItem, newElOption) { var existElOption = resultItem.existing; if (newElOption.id = resultItem.keyInfo.id, !newElOption.type && existElOption && (newElOption.type = existElOption.type), null == newElOption.parentId) { var newElParentOption = newElOption.parentOption; newElParentOption ? newElOption.parentId = newElParentOption.id : existElOption && (newElOption.parentId = existElOption.parentId); } newElOption.parentOption = null; }(resultItem, newElOption), function(existList, index, newElOption) { var newElOptCopy = extend({}, newElOption), existElOption = existList[index], $action = newElOption.$action || 'merge'; if ('merge' === $action) { if (existElOption) { var newType = newElOption.type; assert(!newType || existElOption.type === newType, 'Please set $action: "replace" to change `type`'), merge(existElOption, newElOptCopy, !0), mergeLayoutParam(existElOption, newElOptCopy, { ignoreSize: !0 }), copyLayoutParams(newElOption, existElOption); } else existList[index] = newElOptCopy; } else 'replace' === $action ? existList[index] = newElOptCopy : 'remove' === $action && existElOption && (existList[index] = null); }(existList, index, newElOption), function(existItem, newElOption) { if (existItem && (existItem.hv = newElOption.hv = [ isSetLoc(newElOption, [ 'left', 'right' ]), isSetLoc(newElOption, [ 'top', 'bottom' ]) ], 'group' === existItem.type)) { var existingGroupOpt = existItem, newGroupOpt = newElOption; null == existingGroupOpt.width && (existingGroupOpt.width = newGroupOpt.width = 0), null == existingGroupOpt.height && (existingGroupOpt.height = newGroupOpt.height = 0); } }(existList[index], newElOption)); }, this); for(var i = existList.length - 1; i >= 0; i--)null == existList[i] ? existList.splice(i, 1) : delete existList[i].$action; }, GraphicComponentModel.prototype._flatten = function(optionList, result, parentOption) { each(optionList, function(option) { if (option) { parentOption && (option.parentOption = parentOption), result.push(option); var children = option.children; 'group' === option.type && children && this._flatten(children, result, option), delete option.children; } }, this); }, GraphicComponentModel.prototype.useElOptionsToUpdate = function() { var els = this._elOptionsToUpdate; return this._elOptionsToUpdate = null, els; }, GraphicComponentModel.type = 'graphic', GraphicComponentModel.defaultOption = { elements: [] }, GraphicComponentModel; }(ComponentModel), GraphicComponentView = function(_super) { function GraphicComponentView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = GraphicComponentView.type, _this; } return __extends(GraphicComponentView, _super), GraphicComponentView.prototype.init = function() { this._elMap = createHashMap(); }, GraphicComponentView.prototype.render = function(graphicModel, ecModel, api) { graphicModel !== this._lastGraphicModel && this._clear(), this._lastGraphicModel = graphicModel, this._updateElements(graphicModel), this._relocate(graphicModel, api); }, GraphicComponentView.prototype._updateElements = function(graphicModel) { var elOptionsToUpdate = graphicModel.useElOptionsToUpdate(); if (elOptionsToUpdate) { var elMap = this._elMap, rootGroup = this.group; each(elOptionsToUpdate, function(elOption) { var id = convertOptionIdName(elOption.id, null), elExisting = null != id ? elMap.get(id) : null, parentId = convertOptionIdName(elOption.parentId, null), targetElParent = null != parentId ? elMap.get(parentId) : rootGroup, elType = elOption.type, elOptionStyle = elOption.style; 'text' === elType && elOptionStyle && elOption.hv && elOption.hv[1] && (elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = elOptionStyle.verticalAlign = elOptionStyle.align = null); var textContentOption = elOption.textContent, textConfig = elOption.textConfig; if (elOptionStyle && isEC4CompatibleStyle(elOptionStyle, elType, !!textConfig, !!textContentOption)) { var convertResult = convertFromEC4CompatibleStyle(elOptionStyle, elType, !0); !textConfig && convertResult.textConfig && (textConfig = elOption.textConfig = convertResult.textConfig), !textContentOption && convertResult.textContent && (textContentOption = convertResult.textContent); } var elOptionCleaned = (elOption1 = extend({}, elOption1 = elOption), each([ 'id', 'parentId', '$action', 'hv', 'bounding', 'textContent' ].concat(LOCATION_PARAMS), function(name) { delete elOption1[name]; }), elOption1); elExisting && assert(targetElParent === elExisting.parent, 'Changing parent is not supported.'); var $action = elOption.$action || 'merge'; 'merge' === $action ? elExisting ? elExisting.attr(elOptionCleaned) : createEl$1(id, targetElParent, elOptionCleaned, elMap) : 'replace' === $action ? (removeEl(elExisting, elMap), createEl$1(id, targetElParent, elOptionCleaned, elMap)) : 'remove' === $action && removeEl(elExisting, elMap); var el = elMap.get(id); if (el && textContentOption) { if ('merge' === $action) { var textContentExisting = el.getTextContent(); textContentExisting ? textContentExisting.attr(textContentOption) : el.setTextContent(new ZRText(textContentOption)); } else 'replace' === $action && el.setTextContent(new ZRText(textContentOption)); } if (el) { var elOption1, eventData, elInner = inner$e(el); elInner.__ecGraphicWidthOption = elOption.width, elInner.__ecGraphicHeightOption = elOption.height, eventData = getECData(el).eventData, el.silent || el.ignore || eventData || (eventData = getECData(el).eventData = { componentType: 'graphic', componentIndex: graphicModel.componentIndex, name: el.name }), eventData && (eventData.info = elOption.info), setTooltipConfig({ el: el, componentModel: graphicModel, itemName: el.name, itemTooltipOption: elOption.tooltip }); } }); } }, GraphicComponentView.prototype._relocate = function(graphicModel, api) { for(var elOptions = graphicModel.option.elements, rootGroup = this.group, elMap = this._elMap, apiWidth = api.getWidth(), apiHeight = api.getHeight(), i = 0; i < elOptions.length; i++){ var elOption = elOptions[i], id = convertOptionIdName(elOption.id, null), el = null != id ? elMap.get(id) : null; if (el && el.isGroup) { var parentEl = el.parent, isParentRoot = parentEl === rootGroup, elInner = inner$e(el), parentElInner = inner$e(parentEl); elInner.__ecGraphicWidth = parsePercent$1(elInner.__ecGraphicWidthOption, isParentRoot ? apiWidth : parentElInner.__ecGraphicWidth) || 0, elInner.__ecGraphicHeight = parsePercent$1(elInner.__ecGraphicHeightOption, isParentRoot ? apiHeight : parentElInner.__ecGraphicHeight) || 0; } } for(var i = elOptions.length - 1; i >= 0; i--){ var elOption = elOptions[i], id = convertOptionIdName(elOption.id, null), el = null != id ? elMap.get(id) : null; if (el) { var parentEl = el.parent, parentElInner = inner$e(parentEl); positionElement(el, elOption, parentEl === rootGroup ? { width: apiWidth, height: apiHeight } : { width: parentElInner.__ecGraphicWidth, height: parentElInner.__ecGraphicHeight }, null, { hv: elOption.hv, boundingMode: elOption.bounding }); } } }, GraphicComponentView.prototype._clear = function() { var elMap = this._elMap; elMap.each(function(el) { removeEl(el, elMap); }), this._elMap = createHashMap(); }, GraphicComponentView.prototype.dispose = function() { this._clear(); }, GraphicComponentView.type = 'graphic', GraphicComponentView; }(ComponentView); function createEl$1(id, targetElParent, elOption, elMap) { var graphicType = elOption.type; assert(graphicType, 'graphic type MUST be set'); var Clz = hasOwn(_nonShapeGraphicElements, graphicType) ? _nonShapeGraphicElements[graphicType] : getShapeClass(graphicType); assert(Clz, 'graphic type can not be found'); var el = new Clz(elOption); targetElParent.add(el), elMap.set(id, el), inner$e(el).__ecGraphicId = id; } function removeEl(elExisting, elMap) { var existElParent = elExisting && elExisting.parent; existElParent && ('group' === elExisting.type && elExisting.traverse(function(el) { removeEl(el, elMap); }), elMap.removeKey(inner$e(elExisting).__ecGraphicId), existElParent.remove(elExisting)); } function isSetLoc(obj, props) { var isSet; return each(props, function(prop) { null != obj[prop] && 'auto' !== obj[prop] && (isSet = !0); }), isSet; } var DATA_ZOOM_AXIS_DIMENSIONS = [ 'x', 'y', 'radius', 'angle', 'single' ], SERIES_COORDS = [ 'cartesian2d', 'polar', 'singleAxis' ]; function getAxisMainType(axisDim) { return assert(axisDim), axisDim + 'Axis'; } function collectReferCoordSysModelInfo(dataZoomModel) { var ecModel = dataZoomModel.ecModel, coordSysInfoWrap = { infoList: [], infoMap: createHashMap() }; return dataZoomModel.eachTargetAxis(function(axisDim, axisIndex) { var axisModel = ecModel.getComponent(getAxisMainType(axisDim), axisIndex); if (axisModel) { var coordSysModel = axisModel.getCoordSysModel(); if (coordSysModel) { var coordSysUid = coordSysModel.uid, coordSysInfo = coordSysInfoWrap.infoMap.get(coordSysUid); coordSysInfo || (coordSysInfo = { model: coordSysModel, axisModels: [] }, coordSysInfoWrap.infoList.push(coordSysInfo), coordSysInfoWrap.infoMap.set(coordSysUid, coordSysInfo)), coordSysInfo.axisModels.push(axisModel); } } }), coordSysInfoWrap; } var DataZoomAxisInfo = function() { function DataZoomAxisInfo() { this.indexList = [], this.indexMap = []; } return DataZoomAxisInfo.prototype.add = function(axisCmptIdx) { this.indexMap[axisCmptIdx] || (this.indexList.push(axisCmptIdx), this.indexMap[axisCmptIdx] = !0); }, DataZoomAxisInfo; }(), DataZoomModel = function(_super) { function DataZoomModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = DataZoomModel.type, _this._autoThrottle = !0, _this._noTarget = !0, _this._rangePropMode = [ 'percent', 'percent' ], _this; } return __extends(DataZoomModel, _super), DataZoomModel.prototype.init = function(option, parentModel, ecModel) { var inputRawOption = retrieveRawOption(option); this.settledOption = inputRawOption, this.mergeDefaultAndTheme(option, ecModel), this._doInit(inputRawOption); }, DataZoomModel.prototype.mergeOption = function(newOption) { var inputRawOption = retrieveRawOption(newOption); merge(this.option, newOption, !0), merge(this.settledOption, inputRawOption, !0), this._doInit(inputRawOption); }, DataZoomModel.prototype._doInit = function(inputRawOption) { var thisOption = this.option; this._setDefaultThrottle(inputRawOption), this._updateRangeUse(inputRawOption); var settledOption = this.settledOption; each([ [ 'start', 'startValue' ], [ 'end', 'endValue' ] ], function(names, index) { 'value' === this._rangePropMode[index] && (thisOption[names[0]] = settledOption[names[0]] = null); }, this), this._resetTarget(); }, DataZoomModel.prototype._resetTarget = function() { var optionOrient = this.get('orient', !0), targetAxisIndexMap = this._targetAxisInfoMap = createHashMap(); this._fillSpecifiedTargetAxis(targetAxisIndexMap) ? this._orient = optionOrient || this._makeAutoOrientByTargetAxis() : (this._orient = optionOrient || 'horizontal', this._fillAutoTargetAxisByOrient(targetAxisIndexMap, this._orient)), this._noTarget = !0, targetAxisIndexMap.each(function(axisInfo) { axisInfo.indexList.length && (this._noTarget = !1); }, this); }, DataZoomModel.prototype._fillSpecifiedTargetAxis = function(targetAxisIndexMap) { var hasAxisSpecified = !1; return each(DATA_ZOOM_AXIS_DIMENSIONS, function(axisDim) { var refering = this.getReferringComponents(getAxisMainType(axisDim), MULTIPLE_REFERRING); if (refering.specified) { hasAxisSpecified = !0; var axisInfo = new DataZoomAxisInfo(); each(refering.models, function(axisModel) { axisInfo.add(axisModel.componentIndex); }), targetAxisIndexMap.set(axisDim, axisInfo); } }, this), hasAxisSpecified; }, DataZoomModel.prototype._fillAutoTargetAxisByOrient = function(targetAxisIndexMap, orient) { var ecModel = this.ecModel, needAuto = !0, axisDim = 'vertical' === orient ? 'y' : 'x', axisModels = ecModel.findComponents({ mainType: axisDim + 'Axis' }); if (setParallelAxis(axisModels, axisDim), needAuto) { var axisModels = ecModel.findComponents({ mainType: 'singleAxis', filter: function(axisModel) { return axisModel.get('orient', !0) === orient; } }); setParallelAxis(axisModels, 'single'); } function setParallelAxis(axisModels, axisDim) { var axisModel = axisModels[0]; if (axisModel) { var axisInfo = new DataZoomAxisInfo(); if (axisInfo.add(axisModel.componentIndex), targetAxisIndexMap.set(axisDim, axisInfo), needAuto = !1, 'x' === axisDim || 'y' === axisDim) { var gridModel_1 = axisModel.getReferringComponents('grid', SINGLE_REFERRING).models[0]; gridModel_1 && each(axisModels, function(axModel) { axisModel.componentIndex !== axModel.componentIndex && gridModel_1 === axModel.getReferringComponents('grid', SINGLE_REFERRING).models[0] && axisInfo.add(axModel.componentIndex); }); } } } needAuto && each(DATA_ZOOM_AXIS_DIMENSIONS, function(axisDim) { if (needAuto) { var axisModels = ecModel.findComponents({ mainType: getAxisMainType(axisDim), filter: function(axisModel) { return 'category' === axisModel.get('type', !0); } }); if (axisModels[0]) { var axisInfo = new DataZoomAxisInfo(); axisInfo.add(axisModels[0].componentIndex), targetAxisIndexMap.set(axisDim, axisInfo), needAuto = !1; } } }, this); }, DataZoomModel.prototype._makeAutoOrientByTargetAxis = function() { var dim; return this.eachTargetAxis(function(axisDim) { dim || (dim = axisDim); }, this), 'y' === dim ? 'vertical' : 'horizontal'; }, DataZoomModel.prototype._setDefaultThrottle = function(inputRawOption) { if (inputRawOption.hasOwnProperty('throttle') && (this._autoThrottle = !1), this._autoThrottle) { var globalOption = this.ecModel.option; this.option.throttle = globalOption.animation && globalOption.animationDurationUpdate > 0 ? 100 : 20; } }, DataZoomModel.prototype._updateRangeUse = function(inputRawOption) { var rangePropMode = this._rangePropMode, rangeModeInOption = this.get('rangeMode'); each([ [ 'start', 'startValue' ], [ 'end', 'endValue' ] ], function(names, index) { var percentSpecified = null != inputRawOption[names[0]], valueSpecified = null != inputRawOption[names[1]]; percentSpecified && !valueSpecified ? rangePropMode[index] = 'percent' : !percentSpecified && valueSpecified ? rangePropMode[index] = 'value' : rangeModeInOption ? rangePropMode[index] = rangeModeInOption[index] : percentSpecified && (rangePropMode[index] = 'percent'); }); }, DataZoomModel.prototype.noTarget = function() { return this._noTarget; }, DataZoomModel.prototype.getFirstTargetAxisModel = function() { var firstAxisModel; return this.eachTargetAxis(function(axisDim, axisIndex) { null == firstAxisModel && (firstAxisModel = this.ecModel.getComponent(getAxisMainType(axisDim), axisIndex)); }, this), firstAxisModel; }, DataZoomModel.prototype.eachTargetAxis = function(callback, context) { this._targetAxisInfoMap.each(function(axisInfo, axisDim) { each(axisInfo.indexList, function(axisIndex) { callback.call(context, axisDim, axisIndex); }); }); }, DataZoomModel.prototype.getAxisProxy = function(axisDim, axisIndex) { var axisModel = this.getAxisModel(axisDim, axisIndex); if (axisModel) return axisModel.__dzAxisProxy; }, DataZoomModel.prototype.getAxisModel = function(axisDim, axisIndex) { assert(axisDim && null != axisIndex); var axisInfo = this._targetAxisInfoMap.get(axisDim); if (axisInfo && axisInfo.indexMap[axisIndex]) return this.ecModel.getComponent(getAxisMainType(axisDim), axisIndex); }, DataZoomModel.prototype.setRawRange = function(opt) { var thisOption = this.option, settledOption = this.settledOption; each([ [ 'start', 'startValue' ], [ 'end', 'endValue' ] ], function(names) { (null != opt[names[0]] || null != opt[names[1]]) && (thisOption[names[0]] = settledOption[names[0]] = opt[names[0]], thisOption[names[1]] = settledOption[names[1]] = opt[names[1]]); }, this), this._updateRangeUse(opt); }, DataZoomModel.prototype.setCalculatedRange = function(opt) { var option = this.option; each([ 'start', 'startValue', 'end', 'endValue' ], function(name) { option[name] = opt[name]; }); }, DataZoomModel.prototype.getPercentRange = function() { var axisProxy = this.findRepresentativeAxisProxy(); if (axisProxy) return axisProxy.getDataPercentWindow(); }, DataZoomModel.prototype.getValueRange = function(axisDim, axisIndex) { if (null != axisDim || null != axisIndex) return this.getAxisProxy(axisDim, axisIndex).getDataValueWindow(); var axisProxy = this.findRepresentativeAxisProxy(); if (axisProxy) return axisProxy.getDataValueWindow(); }, DataZoomModel.prototype.findRepresentativeAxisProxy = function(axisModel) { if (axisModel) return axisModel.__dzAxisProxy; for(var firstProxy, axisDimList = this._targetAxisInfoMap.keys(), i = 0; i < axisDimList.length; i++)for(var axisDim = axisDimList[i], axisInfo = this._targetAxisInfoMap.get(axisDim), j = 0; j < axisInfo.indexList.length; j++){ var proxy = this.getAxisProxy(axisDim, axisInfo.indexList[j]); if (proxy.hostedBy(this)) return proxy; firstProxy || (firstProxy = proxy); } return firstProxy; }, DataZoomModel.prototype.getRangePropMode = function() { return this._rangePropMode.slice(); }, DataZoomModel.prototype.getOrient = function() { return assert(this._orient), this._orient; }, DataZoomModel.type = 'dataZoom', DataZoomModel.dependencies = [ 'xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series', 'toolbox' ], DataZoomModel.defaultOption = { zlevel: 0, z: 4, filterMode: 'filter', start: 0, end: 100 }, DataZoomModel; }(ComponentModel); function retrieveRawOption(option) { var ret = {}; return each([ 'start', 'end', 'startValue', 'endValue', 'throttle' ], function(name) { option.hasOwnProperty(name) && (ret[name] = option[name]); }), ret; } var SelectDataZoomModel = function(_super) { function SelectDataZoomModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = SelectDataZoomModel.type, _this; } return __extends(SelectDataZoomModel, _super), SelectDataZoomModel.type = 'dataZoom.select', SelectDataZoomModel; }(DataZoomModel), DataZoomView = function(_super) { function DataZoomView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = DataZoomView.type, _this; } return __extends(DataZoomView, _super), DataZoomView.prototype.render = function(dataZoomModel, ecModel, api, payload) { this.dataZoomModel = dataZoomModel, this.ecModel = ecModel, this.api = api; }, DataZoomView.type = 'dataZoom', DataZoomView; }(ComponentView), SelectDataZoomView = function(_super) { function SelectDataZoomView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = SelectDataZoomView.type, _this; } return __extends(SelectDataZoomView, _super), SelectDataZoomView.type = 'dataZoom.select', SelectDataZoomView; }(DataZoomView), AxisProxy = function() { function AxisProxy(dimName, axisIndex, dataZoomModel, ecModel) { this._dimName = dimName, this._axisIndex = axisIndex, this.ecModel = ecModel, this._dataZoomModel = dataZoomModel; } return AxisProxy.prototype.hostedBy = function(dataZoomModel) { return this._dataZoomModel === dataZoomModel; }, AxisProxy.prototype.getDataValueWindow = function() { return this._valueWindow.slice(); }, AxisProxy.prototype.getDataPercentWindow = function() { return this._percentWindow.slice(); }, AxisProxy.prototype.getTargetSeriesModels = function() { var seriesModels = []; return this.ecModel.eachSeries(function(seriesModel) { if (indexOf(SERIES_COORDS, seriesModel.get('coordinateSystem')) >= 0) { var axisMainType = getAxisMainType(this._dimName), axisModel = seriesModel.getReferringComponents(axisMainType, SINGLE_REFERRING).models[0]; axisModel && this._axisIndex === axisModel.componentIndex && seriesModels.push(seriesModel); } }, this), seriesModels; }, AxisProxy.prototype.getAxisModel = function() { return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex); }, AxisProxy.prototype.getMinMaxSpan = function() { return clone(this._minMaxSpan); }, AxisProxy.prototype.calculateDataWindow = function(opt) { var hasPropModeValue, dataExtent = this._dataExtent, scale = this.getAxisModel().axis.scale, rangePropMode = this._dataZoomModel.getRangePropMode(), percentExtent = [ 0, 100 ], percentWindow = [], valueWindow = []; each([ 'start', 'end' ], function(prop, idx) { var boundPercent = opt[prop], boundValue = opt[prop + 'Value']; 'percent' === rangePropMode[idx] ? (null == boundPercent && (boundPercent = percentExtent[idx]), boundValue = scale.parse(linearMap(boundPercent, percentExtent, dataExtent))) : (hasPropModeValue = !0, boundPercent = linearMap(boundValue = null == boundValue ? dataExtent[idx] : scale.parse(boundValue), dataExtent, percentExtent)), valueWindow[idx] = boundValue, percentWindow[idx] = boundPercent; }), asc(valueWindow), asc(percentWindow); var spans = this._minMaxSpan; function restrictSet(fromWindow, toWindow, fromExtent, toExtent, toValue) { var suffix = toValue ? 'Span' : 'ValueSpan'; sliderMove(0, fromWindow, fromExtent, 'all', spans['min' + suffix], spans['max' + suffix]); for(var i = 0; i < 2; i++)toWindow[i] = linearMap(fromWindow[i], fromExtent, toExtent, !0), toValue && (toWindow[i] = scale.parse(toWindow[i])); } return hasPropModeValue ? restrictSet(valueWindow, percentWindow, dataExtent, percentExtent, !1) : restrictSet(percentWindow, valueWindow, percentExtent, dataExtent, !0), { valueWindow: valueWindow, percentWindow: percentWindow }; }, AxisProxy.prototype.reset = function(dataZoomModel) { if (dataZoomModel === this._dataZoomModel) { var axisDim, dataExtent, axisModel, rawExtentResult, targetSeries = this.getTargetSeriesModels(); this._dataExtent = (axisDim = this._dimName, dataExtent = [ 1 / 0, -1 / 0 ], each(targetSeries, function(seriesModel) { var dataExtent1, data; dataExtent1 = dataExtent, (data = seriesModel.getData()) && each(getDataDimensionsOnAxis(data, axisDim), function(dim) { var seriesExtent = data.getApproximateExtent(dim); seriesExtent[0] < dataExtent1[0] && (dataExtent1[0] = seriesExtent[0]), seriesExtent[1] > dataExtent1[1] && (dataExtent1[1] = seriesExtent[1]); }); }), [ (rawExtentResult = ensureScaleRawExtentInfo((axisModel = this.getAxisModel()).axis.scale, axisModel, dataExtent).calculate()).min, rawExtentResult.max ]), this._updateMinMaxSpan(); var dataWindow = this.calculateDataWindow(dataZoomModel.settledOption); this._valueWindow = dataWindow.valueWindow, this._percentWindow = dataWindow.percentWindow, this._setAxisModel(); } }, AxisProxy.prototype.filterData = function(dataZoomModel, api) { if (dataZoomModel === this._dataZoomModel) { var axisDim = this._dimName, seriesModels = this.getTargetSeriesModels(), filterMode = dataZoomModel.get('filterMode'), valueWindow = this._valueWindow; 'none' !== filterMode && each(seriesModels, function(seriesModel) { var seriesData = seriesModel.getData(), dataDims = seriesData.mapDimensionsAll(axisDim); dataDims.length && ('weakFilter' === filterMode ? seriesData.filterSelf(function(dataIndex) { for(var leftOut, rightOut, hasValue, i = 0; i < dataDims.length; i++){ var value = seriesData.get(dataDims[i], dataIndex), thisHasValue = !isNaN(value), thisLeftOut = value < valueWindow[0], thisRightOut = value > valueWindow[1]; if (thisHasValue && !thisLeftOut && !thisRightOut) return !0; thisHasValue && (hasValue = !0), thisLeftOut && (leftOut = !0), thisRightOut && (rightOut = !0); } return hasValue && leftOut && rightOut; }) : each(dataDims, function(dim) { if ('empty' === filterMode) seriesModel.setData(seriesData = seriesData.map(dim, function(value) { return value >= valueWindow[0] && value <= valueWindow[1] ? value : NaN; })); else { var range = {}; range[dim] = valueWindow, seriesData.selectRange(range); } }), each(dataDims, function(dim) { seriesData.setApproximateExtent(valueWindow, dim); })); }); } }, AxisProxy.prototype._updateMinMaxSpan = function() { var minMaxSpan = this._minMaxSpan = {}, dataZoomModel = this._dataZoomModel, dataExtent = this._dataExtent; each([ 'min', 'max' ], function(minMax) { var percentSpan = dataZoomModel.get(minMax + 'Span'), valueSpan = dataZoomModel.get(minMax + 'ValueSpan'); null != valueSpan && (valueSpan = this.getAxisModel().axis.scale.parse(valueSpan)), null != valueSpan ? percentSpan = linearMap(dataExtent[0] + valueSpan, dataExtent, [ 0, 100 ], !0) : null != percentSpan && (valueSpan = linearMap(percentSpan, [ 0, 100 ], dataExtent, !0) - dataExtent[0]), minMaxSpan[minMax + 'Span'] = percentSpan, minMaxSpan[minMax + 'ValueSpan'] = valueSpan; }, this); }, AxisProxy.prototype._setAxisModel = function() { var axisModel = this.getAxisModel(), percentWindow = this._percentWindow, valueWindow = this._valueWindow; if (percentWindow) { var precision = getPixelPrecision(valueWindow, [ 0, 500 ]); precision = Math.min(precision, 20); var rawExtentInfo = axisModel.axis.scale.rawExtentInfo; 0 !== percentWindow[0] && rawExtentInfo.setDeterminedMinMax('min', +valueWindow[0].toFixed(precision)), 100 !== percentWindow[1] && rawExtentInfo.setDeterminedMinMax('max', +valueWindow[1].toFixed(precision)), rawExtentInfo.freeze(); } }, AxisProxy; }(), dataZoomProcessor = { getTargetSeries: function(ecModel) { function eachAxisModel(cb) { ecModel.eachComponent('dataZoom', function(dataZoomModel) { dataZoomModel.eachTargetAxis(function(axisDim, axisIndex) { var axisModel = ecModel.getComponent(getAxisMainType(axisDim), axisIndex); cb(axisDim, axisIndex, axisModel, dataZoomModel); }); }); } eachAxisModel(function(axisDim, axisIndex, axisModel, dataZoomModel) { axisModel.__dzAxisProxy = null; }); var proxyList = []; eachAxisModel(function(axisDim, axisIndex, axisModel, dataZoomModel) { axisModel.__dzAxisProxy || (axisModel.__dzAxisProxy = new AxisProxy(axisDim, axisIndex, dataZoomModel, ecModel), proxyList.push(axisModel.__dzAxisProxy)); }); var seriesModelMap = createHashMap(); return each(proxyList, function(axisProxy) { each(axisProxy.getTargetSeriesModels(), function(seriesModel) { seriesModelMap.set(seriesModel.uid, seriesModel); }); }), seriesModelMap; }, overallReset: function(ecModel, api) { ecModel.eachComponent('dataZoom', function(dataZoomModel) { dataZoomModel.eachTargetAxis(function(axisDim, axisIndex) { dataZoomModel.getAxisProxy(axisDim, axisIndex).reset(dataZoomModel); }), dataZoomModel.eachTargetAxis(function(axisDim, axisIndex) { dataZoomModel.getAxisProxy(axisDim, axisIndex).filterData(dataZoomModel, api); }); }), ecModel.eachComponent('dataZoom', function(dataZoomModel) { var axisProxy = dataZoomModel.findRepresentativeAxisProxy(); if (axisProxy) { var percentRange = axisProxy.getDataPercentWindow(), valueRange = axisProxy.getDataValueWindow(); dataZoomModel.setCalculatedRange({ start: percentRange[0], end: percentRange[1], startValue: valueRange[0], endValue: valueRange[1] }); } }); } }, installed = !1; function installCommon(registers) { installed || (installed = !0, registers.registerProcessor(registers.PRIORITY.PROCESSOR.FILTER, dataZoomProcessor), function(registers) { registers.registerAction('dataZoom', function(payload, ecModel) { each(function(ecModel, payload) { var foundNewLink, axisRecords = createHashMap(), effectedModels = [], effectedModelMap = createHashMap(); ecModel.eachComponent({ mainType: 'dataZoom', query: payload }, function(dataZoomModel) { effectedModelMap.get(dataZoomModel.uid) || addToEffected(dataZoomModel); }); do foundNewLink = !1, ecModel.eachComponent('dataZoom', processSingle); while (foundNewLink) function processSingle(dataZoomModel) { var isLink; !effectedModelMap.get(dataZoomModel.uid) && (isLink = !1, dataZoomModel.eachTargetAxis(function(axisDim, axisIndex) { var axisIdxArr = axisRecords.get(axisDim); axisIdxArr && axisIdxArr[axisIndex] && (isLink = !0); }), isLink) && (addToEffected(dataZoomModel), foundNewLink = !0); } function addToEffected(dataZoom) { effectedModelMap.set(dataZoom.uid, !0), effectedModels.push(dataZoom), function(dataZoomModel) { dataZoomModel.eachTargetAxis(function(axisDim, axisIndex) { (axisRecords.get(axisDim) || axisRecords.set(axisDim, []))[axisIndex] = !0; }); }(dataZoom); } return effectedModels; }(ecModel, payload), function(dataZoomModel) { dataZoomModel.setRawRange({ start: payload.start, end: payload.end, startValue: payload.startValue, endValue: payload.endValue }); }); }); }(registers), registers.registerSubTypeDefaulter('dataZoom', function() { return 'slider'; })); } function install$y(registers) { registers.registerComponentModel(SelectDataZoomModel), registers.registerComponentView(SelectDataZoomView), installCommon(registers); } var ToolboxFeature = function() {}, features = {}, ToolboxModel = function(_super) { function ToolboxModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = ToolboxModel.type, _this; } return __extends(ToolboxModel, _super), ToolboxModel.prototype.optionUpdated = function() { _super.prototype.optionUpdated.apply(this, arguments); var ecModel = this.ecModel; each(this.option.feature, function(featureOpt, featureName) { var Feature = features[featureName]; Feature && (Feature.getDefaultOption && (Feature.defaultOption = Feature.getDefaultOption(ecModel)), merge(featureOpt, Feature.defaultOption)); }); }, ToolboxModel.type = 'toolbox', ToolboxModel.layoutMode = { type: 'box', ignoreSize: !0 }, ToolboxModel.defaultOption = { show: !0, z: 6, zlevel: 0, orient: 'horizontal', left: 'right', top: 'top', backgroundColor: 'transparent', borderColor: '#ccc', borderRadius: 0, borderWidth: 0, padding: 5, itemSize: 15, itemGap: 8, showTitle: !0, iconStyle: { borderColor: '#666', color: 'none' }, emphasis: { iconStyle: { borderColor: '#3E98C5' } }, tooltip: { show: !1, position: 'bottom' } }, ToolboxModel; }(ComponentModel); function makeBackground(rect, componentModel) { var padding = normalizeCssArray(componentModel.get('padding')), style = componentModel.getItemStyle([ 'color', 'opacity' ]); return style.fill = componentModel.get('backgroundColor'), rect = new Rect({ shape: { x: rect.x - padding[3], y: rect.y - padding[0], width: rect.width + padding[1] + padding[3], height: rect.height + padding[0] + padding[2], r: componentModel.get('borderRadius') }, style: style, silent: !0, z2: -1 }); } var ToolboxView = function(_super) { function ToolboxView() { return null !== _super && _super.apply(this, arguments) || this; } return __extends(ToolboxView, _super), ToolboxView.prototype.render = function(toolboxModel, ecModel, api, payload) { var boxLayoutParams, padding, viewportSize, rect, group = this.group; if (group.removeAll(), toolboxModel.get('show')) { var itemSize = +toolboxModel.get('itemSize'), featureOpts = toolboxModel.get('feature') || {}, features1 = this._features || (this._features = {}), featureNames = []; each(featureOpts, function(opt, name) { featureNames.push(name); }), new DataDiffer(this._featureNames || [], featureNames).add(processFeature).update(processFeature).remove(curry(processFeature, null)).execute(), this._featureNames = featureNames, boxLayoutParams = toolboxModel.getBoxLayoutParams(), padding = toolboxModel.get('padding'), rect = getLayoutRect(boxLayoutParams, viewportSize = { width: api.getWidth(), height: api.getHeight() }, padding), boxLayout(toolboxModel.get('orient'), group, toolboxModel.get('itemGap'), rect.width, rect.height), positionElement(group, boxLayoutParams, viewportSize, padding), group.add(makeBackground(group.getBoundingRect(), toolboxModel)), group.eachChild(function(icon) { var titleText = icon.__title, emphasisState = icon.ensureState('emphasis'), emphasisTextConfig = emphasisState.textConfig || (emphasisState.textConfig = {}), textContent = icon.getTextContent(), emphasisTextState = textContent && textContent.states.emphasis; if (emphasisTextState && !isFunction(emphasisTextState) && titleText) { var emphasisTextStyle = emphasisTextState.style || (emphasisTextState.style = {}), rect = getBoundingRect(titleText, ZRText.makeFont(emphasisTextStyle)), offsetX = icon.x + group.x, offsetY = icon.y + group.y + itemSize, needPutOnTop = !1; offsetY + rect.height > api.getHeight() && (emphasisTextConfig.position = 'top', needPutOnTop = !0); var topOffset = needPutOnTop ? -5 - rect.height : itemSize + 8; offsetX + rect.width / 2 > api.getWidth() ? (emphasisTextConfig.position = [ '100%', topOffset ], emphasisTextStyle.align = 'right') : offsetX - rect.width / 2 < 0 && (emphasisTextConfig.position = [ 0, topOffset ], emphasisTextStyle.align = 'left'); } }); } function processFeature(newIndex, oldIndex) { var featureModel, feature, iconsMap, titlesMap, iconStyleModel, iconStyleEmphasisModel, icons, titles, iconPaths, feature1, featureName = featureNames[newIndex], oldName = featureNames[oldIndex], featureOpt = featureOpts[featureName], featureModel1 = new Model(featureOpt, toolboxModel, toolboxModel.ecModel); if (payload && null != payload.newTitle && payload.featureName === featureName && (featureOpt.title = payload.newTitle), featureName && !oldName) { if (0 === featureName.indexOf('my')) feature1 = { onclick: featureModel1.option.onclick, featureName: featureName }; else { var Feature = features[featureName]; if (!Feature) return; feature1 = new Feature(); } features1[featureName] = feature1; } else if (!(feature1 = features1[oldName])) return; if (feature1.uid = getUID('toolbox-feature'), feature1.model = featureModel1, feature1.ecModel = ecModel, feature1.api = api, feature1 instanceof ToolboxFeature) { if (!featureName && oldName) { feature1.dispose && feature1.dispose(ecModel, api); return; } if (!featureModel1.get('show') || feature1.unusable) { feature1.remove && feature1.remove(ecModel, api); return; } } featureModel = featureModel1, feature = feature1, iconStyleModel = featureModel.getModel('iconStyle'), iconStyleEmphasisModel = featureModel.getModel([ 'emphasis', 'iconStyle' ]), icons = feature instanceof ToolboxFeature && feature.getIcons ? feature.getIcons() : featureModel.get('icon'), titles = featureModel.get('title') || {}, 'string' == typeof icons ? (iconsMap = {})[featureName] = icons : iconsMap = icons, 'string' == typeof titles ? (titlesMap = {})[featureName] = titles : titlesMap = titles, iconPaths = featureModel.iconPaths = {}, each(iconsMap, function(iconStr, iconName) { var path = createIcon(iconStr, {}, { x: -itemSize / 2, y: -itemSize / 2, width: itemSize, height: itemSize }); path.setStyle(iconStyleModel.getItemStyle()), path.ensureState('emphasis').style = iconStyleEmphasisModel.getItemStyle(); var textContent = new ZRText({ style: { text: titlesMap[iconName], align: iconStyleEmphasisModel.get('textAlign'), borderRadius: iconStyleEmphasisModel.get('textBorderRadius'), padding: iconStyleEmphasisModel.get('textPadding'), fill: null }, ignore: !0 }); path.setTextContent(textContent), setTooltipConfig({ el: path, componentModel: toolboxModel, itemName: iconName, formatterParamsExtra: { title: titlesMap[iconName] } }), path.__title = titlesMap[iconName], path.on('mouseover', function() { var hoverStyle = iconStyleEmphasisModel.getItemStyle(), defaultTextPosition = 'vertical' === toolboxModel.get('orient') ? null == toolboxModel.get('right') ? 'right' : 'left' : null == toolboxModel.get('bottom') ? 'bottom' : 'top'; textContent.setStyle({ fill: iconStyleEmphasisModel.get('textFill') || hoverStyle.fill || hoverStyle.stroke || '#000', backgroundColor: iconStyleEmphasisModel.get('textBackgroundColor') }), path.setTextConfig({ position: iconStyleEmphasisModel.get('textPosition') || defaultTextPosition }), textContent.ignore = !toolboxModel.get('showTitle'), enterEmphasis(this); }).on('mouseout', function() { 'emphasis' !== featureModel.get([ 'iconStatus', iconName ]) && leaveEmphasis(this), textContent.hide(); }), ('emphasis' === featureModel.get([ 'iconStatus', iconName ]) ? enterEmphasis : leaveEmphasis)(path), group.add(path), path.on('click', bind(feature.onclick, feature, ecModel, api, iconName)), iconPaths[iconName] = path; }), featureModel1.setIconStatus = function(iconName, status) { var option = this.option, iconPaths = this.iconPaths; option.iconStatus = option.iconStatus || {}, option.iconStatus[iconName] = status, iconPaths[iconName] && ('emphasis' === status ? enterEmphasis : leaveEmphasis)(iconPaths[iconName]); }, feature1 instanceof ToolboxFeature && feature1.render && feature1.render(featureModel1, ecModel, api, payload); } }, ToolboxView.prototype.updateView = function(toolboxModel, ecModel, api, payload) { each(this._features, function(feature) { feature instanceof ToolboxFeature && feature.updateView && feature.updateView(feature.model, ecModel, api, payload); }); }, ToolboxView.prototype.remove = function(ecModel, api) { each(this._features, function(feature) { feature instanceof ToolboxFeature && feature.remove && feature.remove(ecModel, api); }), this.group.removeAll(); }, ToolboxView.prototype.dispose = function(ecModel, api) { each(this._features, function(feature) { feature instanceof ToolboxFeature && feature.dispose && feature.dispose(ecModel, api); }); }, ToolboxView.type = 'toolbox', ToolboxView; }(ComponentView), SaveAsImage = function(_super) { function SaveAsImage() { return null !== _super && _super.apply(this, arguments) || this; } return __extends(SaveAsImage, _super), SaveAsImage.prototype.onclick = function(ecModel, api) { var model = this.model, title = model.get('name') || ecModel.get('title.0.text') || 'echarts', isSvg = 'svg' === api.getZr().painter.getType(), type = isSvg ? 'svg' : model.get('type', !0) || 'png', url = api.getConnectedDataURL({ type: type, backgroundColor: model.get('backgroundColor', !0) || ecModel.get('backgroundColor') || '#fff', connectedBackgroundColor: model.get('connectedBackgroundColor'), excludeComponents: model.get('excludeComponents'), pixelRatio: model.get('pixelRatio') }); if ('function' != typeof MouseEvent || !env1.browser.newEdge && (env1.browser.ie || env1.browser.edge)) { if (window.navigator.msSaveOrOpenBlob || isSvg) { var parts = url.split(','), base64Encoded = parts[0].indexOf('base64') > -1, bstr = isSvg ? decodeURIComponent(parts[1]) : parts[1]; base64Encoded && (bstr = atob(bstr)); var filename = title + '.' + type; if (window.navigator.msSaveOrOpenBlob) { for(var n = bstr.length, u8arr = new Uint8Array(n); n--;)u8arr[n] = bstr.charCodeAt(n); var blob = new Blob([ u8arr ]); window.navigator.msSaveOrOpenBlob(blob, filename); } else { var frame = document.createElement('iframe'); document.body.appendChild(frame); var cw = frame.contentWindow, doc = cw.document; doc.open('image/svg+xml', 'replace'), doc.write(bstr), doc.close(), cw.focus(), doc.execCommand('SaveAs', !0, filename), document.body.removeChild(frame); } } else { var lang = model.get('lang'), html = '', tab = window.open(); tab.document.write(html), tab.document.title = title; } } else { var $a = document.createElement('a'); $a.download = title + '.' + type, $a.target = '_blank', $a.href = url; var evt = new MouseEvent('click', { view: document.defaultView, bubbles: !0, cancelable: !1 }); $a.dispatchEvent(evt); } }, SaveAsImage.getDefaultOption = function(ecModel) { return { show: !0, icon: 'M4.7,22.9L29.3,45.5L54.7,23.4M4.6,43.6L4.6,58L53.8,58L53.8,43.6M29.2,45.1L29.2,0', title: ecModel.getLocale([ 'toolbox', 'saveAsImage', 'title' ]), type: 'png', connectedBackgroundColor: '#fff', name: '', excludeComponents: [ 'toolbox' ], lang: ecModel.getLocale([ 'toolbox', 'saveAsImage', 'lang' ]) }; }, SaveAsImage; }(ToolboxFeature); SaveAsImage.prototype.unusable = !env1.canvasSupported; var INNER_STACK_KEYWORD = '__ec_magicType_stack__', radioTypes = [ [ 'line', 'bar' ], [ 'stack' ] ], MagicType = function(_super) { function MagicType() { return null !== _super && _super.apply(this, arguments) || this; } return __extends(MagicType, _super), MagicType.prototype.getIcons = function() { var model = this.model, availableIcons = model.get('icon'), icons = {}; return each(model.get('type'), function(type) { availableIcons[type] && (icons[type] = availableIcons[type]); }), icons; }, MagicType.getDefaultOption = function(ecModel) { return { show: !0, type: [], icon: { line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4', bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7', stack: 'M8.2,38.4l-8.4,4.1l30.6,15.3L60,42.5l-8.1-4.1l-21.5,11L8.2,38.4z M51.9,30l-8.1,4.2l-13.4,6.9l-13.9-6.9L8.2,30l-8.4,4.2l8.4,4.2l22.2,11l21.5-11l8.1-4.2L51.9,30z M51.9,21.7l-8.1,4.2L35.7,30l-5.3,2.8L24.9,30l-8.4-4.1l-8.3-4.2l-8.4,4.2L8.2,30l8.3,4.2l13.9,6.9l13.4-6.9l8.1-4.2l8.1-4.1L51.9,21.7zM30.4,2.2L-0.2,17.5l8.4,4.1l8.3,4.2l8.4,4.2l5.5,2.7l5.3-2.7l8.1-4.2l8.1-4.2l8.1-4.1L30.4,2.2z' }, title: ecModel.getLocale([ 'toolbox', 'magicType', 'title' ]), option: {}, seriesIndex: {} }; }, MagicType.prototype.onclick = function(ecModel, api, type) { var newTitle, model = this.model, seriesIndex = model.get([ 'seriesIndex', type ]); if (seriesOptGenreator[type]) { var newOption = { series: [] }, generateNewSeriesTypes = function(seriesModel) { var seriesType = seriesModel.subType, seriesId = seriesModel.id, newSeriesOpt = seriesOptGenreator[type](seriesType, seriesId, seriesModel, model); newSeriesOpt && (defaults(newSeriesOpt, seriesModel.option), newOption.series.push(newSeriesOpt)); var coordSys = seriesModel.coordinateSystem; if (coordSys && 'cartesian2d' === coordSys.type && ('line' === type || 'bar' === type)) { var categoryAxis = coordSys.getAxesByScale('ordinal')[0]; if (categoryAxis) { var axisType = categoryAxis.dim + 'Axis', axisIndex = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0].componentIndex; newOption[axisType] = newOption[axisType] || []; for(var i = 0; i <= axisIndex; i++)newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {}; newOption[axisType][axisIndex].boundaryGap = 'bar' === type; } } }; each(radioTypes, function(radio) { indexOf(radio, type) >= 0 && each(radio, function(item) { model.setIconStatus(item, 'normal'); }); }), model.setIconStatus(type, 'emphasis'), ecModel.eachComponent({ mainType: 'series', query: null == seriesIndex ? null : { seriesIndex: seriesIndex } }, generateNewSeriesTypes), 'stack' === type && (newTitle = merge({ stack: model.option.title.tiled, tiled: model.option.title.stack }, model.option.title)), api.dispatchAction({ type: 'changeMagicType', currentType: type, newOption: newOption, newTitle: newTitle, featureName: 'magicType' }); } }, MagicType; }(ToolboxFeature), seriesOptGenreator = { line: function(seriesType, seriesId, seriesModel, model) { if ('bar' === seriesType) return merge({ id: seriesId, type: 'line', data: seriesModel.get('data'), stack: seriesModel.get('stack'), markPoint: seriesModel.get('markPoint'), markLine: seriesModel.get('markLine') }, model.get([ 'option', 'line' ]) || {}, !0); }, bar: function(seriesType, seriesId, seriesModel, model) { if ('line' === seriesType) return merge({ id: seriesId, type: 'bar', data: seriesModel.get('data'), stack: seriesModel.get('stack'), markPoint: seriesModel.get('markPoint'), markLine: seriesModel.get('markLine') }, model.get([ 'option', 'bar' ]) || {}, !0); }, stack: function(seriesType, seriesId, seriesModel, model) { var isStack = seriesModel.get('stack') === INNER_STACK_KEYWORD; if ('line' === seriesType || 'bar' === seriesType) return model.setIconStatus('stack', isStack ? 'normal' : 'emphasis'), merge({ id: seriesId, stack: isStack ? '' : INNER_STACK_KEYWORD }, model.get([ 'option', 'stack' ]) || {}, !0); } }; registerAction({ type: 'changeMagicType', event: 'magicTypeChanged', update: 'prepareAndUpdate' }, function(payload, ecModel) { ecModel.mergeOption(payload.newOption); }); var BLOCK_SPLITER = Array(60).join('-'); function trim$1(str) { return str.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); } var itemSplitRegex = RegExp("[ ]+", 'g'), DataView = function(_super) { function DataView() { return null !== _super && _super.apply(this, arguments) || this; } return __extends(DataView, _super), DataView.prototype.onclick = function(ecModel, api) { var seriesGroupByCategoryAxis, otherSeries, meta, groups, tables, result, container = api.getDom(), model = this.model; this._dom && container.removeChild(this._dom); var root = document.createElement('div'); root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;', root.style.backgroundColor = model.get('backgroundColor') || '#fff'; var header = document.createElement('h4'), lang = model.get('lang') || []; header.innerHTML = lang[0] || model.get('title'), header.style.cssText = 'margin: 10px 20px;', header.style.color = model.get('textColor'); var viewMain = document.createElement('div'), textarea = document.createElement('textarea'); viewMain.style.cssText = 'display:block;width:100%;overflow:auto;'; var optionToContent = model.get('optionToContent'), contentToOption = model.get('contentToOption'), result1 = { value: filter([ (groups = (seriesGroupByCategoryAxis = {}, otherSeries = [], meta = [], ecModel.eachRawSeries(function(seriesModel) { var coordSys = seriesModel.coordinateSystem; if (coordSys && ('cartesian2d' === coordSys.type || 'polar' === coordSys.type)) { var baseAxis = coordSys.getBaseAxis(); if ('category' === baseAxis.type) { var key = baseAxis.dim + '_' + baseAxis.index; seriesGroupByCategoryAxis[key] || (seriesGroupByCategoryAxis[key] = { categoryAxis: baseAxis, valueAxis: coordSys.getOtherAxis(baseAxis), series: [] }, meta.push({ axisDim: baseAxis.dim, axisIndex: baseAxis.index })), seriesGroupByCategoryAxis[key].series.push(seriesModel); } else otherSeries.push(seriesModel); } else otherSeries.push(seriesModel); }), result = { seriesGroupByCategoryAxis: seriesGroupByCategoryAxis, other: otherSeries, meta: meta }).seriesGroupByCategoryAxis, tables = [], each(groups, function(group, key) { var categoryAxis = group.categoryAxis, valueAxisDim = group.valueAxis.dim, headers = [ ' ' ].concat(map(group.series, function(series) { return series.name; })), columns = [ categoryAxis.model.getCategories() ]; each(group.series, function(series) { var rawData = series.getRawData(); columns.push(series.getRawData().mapArray(rawData.mapDimension(valueAxisDim), function(val) { return val; })); }); for(var lines = [ headers.join('\t') ], i = 0; i < columns[0].length; i++){ for(var items = [], j = 0; j < columns.length; j++)items.push(columns[j][i]); lines.push(items.join('\t')); } tables.push(lines.join('\n')); }), tables.join('\n\n' + BLOCK_SPLITER + '\n\n')), map(result.other, function(series) { var data = series.getRawData(), lines = [ series.name ], vals = []; return data.each(data.dimensions, function() { for(var argLen = arguments.length, dataIndex = arguments[argLen - 1], name = data.getName(dataIndex), i = 0; i < argLen - 1; i++)vals[i] = arguments[i]; lines.push((name ? name + '\t' : '') + vals.join('\t')); }), lines.join('\n'); }).join('\n\n' + BLOCK_SPLITER + '\n\n') ], function(str) { return !!str.replace(/[\n\t\s]/g, ''); }).join('\n\n' + BLOCK_SPLITER + '\n\n'), meta: result.meta }; if ('function' == typeof optionToContent) { var htmlOrDom = optionToContent(api.getOption()); 'string' == typeof htmlOrDom ? viewMain.innerHTML = htmlOrDom : isDom(htmlOrDom) && viewMain.appendChild(htmlOrDom); } else viewMain.appendChild(textarea), textarea.readOnly = model.get('readOnly'), textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;', textarea.style.color = model.get('textColor'), textarea.style.borderColor = model.get('textareaBorderColor'), textarea.style.backgroundColor = model.get('textareaColor'), textarea.value = result1.value; var blockMetaList = result1.meta, buttonContainer = document.createElement('div'); buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;'; var buttonStyle = "float:right;margin-right:20px;border:none;cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px", closeButton = document.createElement('div'), refreshButton = document.createElement('div'); buttonStyle += ';background-color:' + model.get('buttonColor'), buttonStyle += ';color:' + model.get('buttonTextColor'); var self1 = this; function close() { container.removeChild(root), self1._dom = null; } addEventListener(closeButton, 'click', close), addEventListener(refreshButton, 'click', function() { var newOption, blocks, newOption1; if (null == contentToOption && null != optionToContent || null != contentToOption && null == optionToContent) { console.warn('It seems you have just provided one of `contentToOption` and `optionToContent` functions but missed the other one. Data change is ignored.'), close(); return; } try { 'function' == typeof contentToOption ? newOption = contentToOption(viewMain, api.getOption()) : (blocks = textarea.value.split(RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g')), newOption1 = { series: [] }, each(blocks, function(block, idx) { if (function(block) { if (block.slice(0, block.indexOf('\n')).indexOf('\t') >= 0) return !0; }(block)) { var result = function(tsv) { for(var tsvLines = tsv.split(/\n+/g), headers = trim$1(tsvLines.shift()).split(itemSplitRegex), categories = [], series = map(headers, function(header) { return { name: header, data: [] }; }), i = 0; i < tsvLines.length; i++){ var items = trim$1(tsvLines[i]).split(itemSplitRegex); categories.push(items.shift()); for(var j = 0; j < items.length; j++)series[j] && (series[j].data[i] = items[j]); } return { series: series, categories: categories }; }(block), blockMeta = blockMetaList[idx], axisKey = blockMeta.axisDim + 'Axis'; blockMeta && (newOption1[axisKey] = newOption1[axisKey] || [], newOption1[axisKey][blockMeta.axisIndex] = { data: result.categories }, newOption1.series = newOption1.series.concat(result.series)); } else { var result = function(str) { for(var lines = str.split(/\n+/g), seriesName = trim$1(lines.shift()), data = [], i = 0; i < lines.length; i++){ var line = trim$1(lines[i]); if (line) { var items = line.split(itemSplitRegex), name_1 = '', value = void 0, hasName = !1; isNaN(items[0]) ? (hasName = !0, name_1 = items[0], items = items.slice(1), data[i] = { name: name_1, value: [] }, value = data[i].value) : value = data[i] = []; for(var j = 0; j < items.length; j++)value.push(+items[j]); 1 === value.length && (hasName ? data[i].value = value[0] : data[i] = value[0]); } } return { name: seriesName, data: data }; }(block); newOption1.series.push(result); } }), newOption = newOption1); } catch (e) { throw close(), Error('Data view format error ' + e); } newOption && api.dispatchAction({ type: 'changeDataView', newOption: newOption }), close(); }), closeButton.innerHTML = lang[1], refreshButton.innerHTML = lang[2], refreshButton.style.cssText = buttonStyle, closeButton.style.cssText = buttonStyle, model.get('readOnly') || buttonContainer.appendChild(refreshButton), buttonContainer.appendChild(closeButton), root.appendChild(header), root.appendChild(viewMain), root.appendChild(buttonContainer), viewMain.style.height = container.clientHeight - 80 + 'px', container.appendChild(root), this._dom = root; }, DataView.prototype.remove = function(ecModel, api) { this._dom && api.getDom().removeChild(this._dom); }, DataView.prototype.dispose = function(ecModel, api) { this.remove(ecModel, api); }, DataView.getDefaultOption = function(ecModel) { return { show: !0, readOnly: !1, optionToContent: null, contentToOption: null, icon: 'M17.5,17.3H33 M17.5,17.3H33 M45.4,29.5h-28 M11.5,2v56H51V14.8L38.4,2H11.5z M38.4,2.2v12.7H51 M45.4,41.7h-28', title: ecModel.getLocale([ 'toolbox', 'dataView', 'title' ]), lang: ecModel.getLocale([ 'toolbox', 'dataView', 'lang' ]), backgroundColor: '#fff', textColor: '#000', textareaColor: '#fff', textareaBorderColor: '#333', buttonColor: '#c23531', buttonTextColor: '#fff' }; }, DataView; }(ToolboxFeature); registerAction({ type: 'changeDataView', event: 'dataViewChanged', update: 'prepareAndUpdate' }, function(payload, ecModel) { var newSeriesOptList = []; each(payload.newOption.series, function(seriesOpt) { var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0]; if (seriesModel) { var originalData = seriesModel.get('data'); newSeriesOptList.push({ name: seriesOpt.name, data: map(seriesOpt.data, function(newVal, idx) { var original = originalData && originalData[idx]; if (!isObject(original) || isArray(original)) return newVal; isObject(newVal) && !isArray(newVal) || (newVal = { value: newVal }); var shouldDeleteName = null != original.name && null == newVal.name; return newVal = defaults(newVal, original), shouldDeleteName && delete newVal.name, newVal; }) }); } else newSeriesOptList.push(extend({ type: 'scatter' }, seriesOpt)); }), ecModel.mergeOption(defaults({ series: newSeriesOptList }, payload.newOption)); }); var inner$f = makeInner(); function getStoreSnapshots(ecModel) { var store = inner$f(ecModel); return store.snapshots || (store.snapshots = [ {} ]), store.snapshots; } var RestoreOption = function(_super) { function RestoreOption() { return null !== _super && _super.apply(this, arguments) || this; } return __extends(RestoreOption, _super), RestoreOption.prototype.onclick = function(ecModel, api) { inner$f(ecModel).snapshots = null, api.dispatchAction({ type: 'restore', from: this.uid }); }, RestoreOption.getDefaultOption = function(ecModel) { return { show: !0, icon: 'M3.8,33.4 M47,18.9h9.8V8.7 M56.3,20.1 C52.1,9,40.5,0.6,26.8,2.1C12.6,3.7,1.6,16.2,2.1,30.6 M13,41.1H3.1v10.2 M3.7,39.9c4.2,11.1,15.8,19.5,29.5,18 c14.2-1.6,25.2-14.1,24.7-28.5', title: ecModel.getLocale([ 'toolbox', 'restore', 'title' ]) }; }, RestoreOption; }(ToolboxFeature); registerAction({ type: 'restore', event: 'restore', update: 'prepareAndUpdate' }, function(payload, ecModel) { ecModel.resetOption('recreate'); }); var COORD_CONVERTS = [ 'dataToPoint', 'pointToData' ], INCLUDE_FINDER_MAIN_TYPES = [ 'grid', 'xAxis', 'yAxis', 'geo', 'graph', 'polar', 'radiusAxis', 'angleAxis', 'bmap' ], BrushTargetManager = function() { function BrushTargetManager(finder, ecModel, opt) { var _this = this; this._targetInfoList = []; var foundCpts = parseFinder$1(ecModel, finder); each(targetInfoBuilders, function(builder, type) { (!opt || !opt.include || indexOf(opt.include, type) >= 0) && builder(foundCpts, _this._targetInfoList); }); } return BrushTargetManager.prototype.setOutputRanges = function(areas, ecModel) { return this.matchOutputRanges(areas, ecModel, function(area, coordRange, coordSys) { if ((area.coordRanges || (area.coordRanges = [])).push(coordRange), !area.coordRange) { area.coordRange = coordRange; var result = coordConvert[area.brushType](0, coordSys, coordRange); area.__rangeOffset = { offset: diffProcessor[area.brushType](result.values, area.range, [ 1, 1 ]), xyMinMax: result.xyMinMax }; } }), areas; }, BrushTargetManager.prototype.matchOutputRanges = function(areas, ecModel, cb) { each(areas, function(area) { var targetInfo = this.findTargetInfo(area, ecModel); targetInfo && !0 !== targetInfo && each(targetInfo.coordSyses, function(coordSys) { var result = coordConvert[area.brushType](1, coordSys, area.range); cb(area, result.values, coordSys, ecModel); }); }, this); }, BrushTargetManager.prototype.setInputRanges = function(areas, ecModel) { each(areas, function(area) { var targetInfo = this.findTargetInfo(area, ecModel); if (assert(!targetInfo || !0 === targetInfo || area.coordRange, 'coordRange must be specified when coord index specified.'), assert(!targetInfo || !0 !== targetInfo || area.range, 'range must be specified in global brush.'), area.range = area.range || [], targetInfo && !0 !== targetInfo) { area.panelId = targetInfo.panelId; var xyMinMaxCurr, xyMinMaxOrigin, sizeCurr, sizeOrigin, scales, result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange), rangeOffset = area.__rangeOffset; area.range = rangeOffset ? diffProcessor[area.brushType](result.values, rangeOffset.offset, (xyMinMaxCurr = result.xyMinMax, xyMinMaxOrigin = rangeOffset.xyMinMax, sizeCurr = getSize(xyMinMaxCurr), sizeOrigin = getSize(xyMinMaxOrigin), isNaN((scales = [ sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1] ])[0]) && (scales[0] = 1), isNaN(scales[1]) && (scales[1] = 1), scales)) : result.values; } }, this); }, BrushTargetManager.prototype.makePanelOpts = function(api, getDefaultBrushType) { return map(this._targetInfoList, function(targetInfo) { var rect = targetInfo.getPanelRect(); return { panelId: targetInfo.panelId, defaultBrushType: getDefaultBrushType ? getDefaultBrushType(targetInfo) : null, clipPath: makeRectPanelClipPath(rect), isTargetByCursor: makeRectIsTargetByCursor(rect, api, targetInfo.coordSysModel), getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect) }; }); }, BrushTargetManager.prototype.controlSeries = function(area, seriesModel, ecModel) { var targetInfo = this.findTargetInfo(area, ecModel); return !0 === targetInfo || targetInfo && indexOf(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0; }, BrushTargetManager.prototype.findTargetInfo = function(area, ecModel) { for(var targetInfoList = this._targetInfoList, foundCpts = parseFinder$1(ecModel, area), i = 0; i < targetInfoList.length; i++){ var targetInfo = targetInfoList[i], areaPanelId = area.panelId; if (areaPanelId) { if (targetInfo.panelId === areaPanelId) return targetInfo; } else for(var j = 0; j < targetInfoMatchers.length; j++)if (targetInfoMatchers[j](foundCpts, targetInfo)) return targetInfo; } return !0; }, BrushTargetManager; }(); function formatMinMax(minMax) { return minMax[0] > minMax[1] && minMax.reverse(), minMax; } function parseFinder$1(ecModel, finder) { return parseFinder(ecModel, finder, { includeMainTypes: INCLUDE_FINDER_MAIN_TYPES }); } var targetInfoBuilders = { grid: function(foundCpts, targetInfoList) { var xAxisModels = foundCpts.xAxisModels, yAxisModels = foundCpts.yAxisModels, gridModels = foundCpts.gridModels, gridModelMap = createHashMap(), xAxesHas = {}, yAxesHas = {}; (xAxisModels || yAxisModels || gridModels) && (each(xAxisModels, function(axisModel) { var gridModel = axisModel.axis.grid.model; gridModelMap.set(gridModel.id, gridModel), xAxesHas[gridModel.id] = !0; }), each(yAxisModels, function(axisModel) { var gridModel = axisModel.axis.grid.model; gridModelMap.set(gridModel.id, gridModel), yAxesHas[gridModel.id] = !0; }), each(gridModels, function(gridModel) { gridModelMap.set(gridModel.id, gridModel), xAxesHas[gridModel.id] = !0, yAxesHas[gridModel.id] = !0; }), gridModelMap.each(function(gridModel) { var grid = gridModel.coordinateSystem, cartesians = []; each(grid.getCartesians(), function(cartesian, index) { (indexOf(xAxisModels, cartesian.getAxis('x').model) >= 0 || indexOf(yAxisModels, cartesian.getAxis('y').model) >= 0) && cartesians.push(cartesian); }), targetInfoList.push({ panelId: 'grid--' + gridModel.id, gridModel: gridModel, coordSysModel: gridModel, coordSys: cartesians[0], coordSyses: cartesians, getPanelRect: panelRectBuilders.grid, xAxisDeclared: xAxesHas[gridModel.id], yAxisDeclared: yAxesHas[gridModel.id] }); })); }, geo: function(foundCpts, targetInfoList) { each(foundCpts.geoModels, function(geoModel) { var coordSys = geoModel.coordinateSystem; targetInfoList.push({ panelId: 'geo--' + geoModel.id, geoModel: geoModel, coordSysModel: geoModel, coordSys: coordSys, coordSyses: [ coordSys ], getPanelRect: panelRectBuilders.geo }); }); } }, targetInfoMatchers = [ function(foundCpts, targetInfo) { var xAxisModel = foundCpts.xAxisModel, yAxisModel = foundCpts.yAxisModel, gridModel = foundCpts.gridModel; return !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model), !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model), gridModel && gridModel === targetInfo.gridModel; }, function(foundCpts, targetInfo) { var geoModel = foundCpts.geoModel; return geoModel && geoModel === targetInfo.geoModel; } ], panelRectBuilders = { grid: function() { return this.coordSys.master.getRect().clone(); }, geo: function() { var coordSys = this.coordSys, rect = coordSys.getBoundingRect().clone(); return rect.applyTransform(getTransform(coordSys)), rect; } }, coordConvert = { lineX: curry(axisConvert, 0), lineY: curry(axisConvert, 1), rect: function(to, coordSys, rangeOrCoordRange) { var xminymin = coordSys[COORD_CONVERTS[to]]([ rangeOrCoordRange[0][0], rangeOrCoordRange[1][0] ]), xmaxymax = coordSys[COORD_CONVERTS[to]]([ rangeOrCoordRange[0][1], rangeOrCoordRange[1][1] ]), values = [ formatMinMax([ xminymin[0], xmaxymax[0] ]), formatMinMax([ xminymin[1], xmaxymax[1] ]) ]; return { values: values, xyMinMax: values }; }, polygon: function(to, coordSys, rangeOrCoordRange) { var xyMinMax = [ [ 1 / 0, -1 / 0 ], [ 1 / 0, -1 / 0 ] ]; return { values: map(rangeOrCoordRange, function(item) { var p = coordSys[COORD_CONVERTS[to]](item); return xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]), xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]), xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]), xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]), p; }), xyMinMax: xyMinMax }; } }; function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) { assert('cartesian2d' === coordSys.type, 'lineX/lineY brush is available only in cartesian2d.'); var axis = coordSys.getAxis([ 'x', 'y' ][axisNameIndex]), values = formatMinMax(map([ 0, 1 ], function(i) { return to ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i])) : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i])); })), xyMinMax = []; return xyMinMax[axisNameIndex] = values, xyMinMax[1 - axisNameIndex] = [ NaN, NaN ], { values: values, xyMinMax: xyMinMax }; } var diffProcessor = { lineX: curry(axisDiffProcessor, 0), lineY: curry(axisDiffProcessor, 1), rect: function(values, refer, scales) { return [ [ values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1] ], [ values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1] ] ]; }, polygon: function(values, refer, scales) { return map(values, function(item, idx) { return [ item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1] ]; }); } }; function axisDiffProcessor(axisNameIndex, values, refer, scales) { return [ values[0] - scales[axisNameIndex] * refer[0], values[1] - scales[axisNameIndex] * refer[1] ]; } function getSize(xyMinMax) { return xyMinMax ? [ xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0] ] : [ NaN, NaN ]; } var DATA_ZOOM_ID_BASE = INTERNAL_COMPONENT_ID_PREFIX + 'toolbox-dataZoom_', DataZoomFeature = function(_super) { function DataZoomFeature() { return null !== _super && _super.apply(this, arguments) || this; } return __extends(DataZoomFeature, _super), DataZoomFeature.prototype.render = function(featureModel, ecModel, api, payload) { this._brushController || (this._brushController = new BrushController(api.getZr()), this._brushController.on('brush', bind(this._onBrush, this)).mount()), function(featureModel, ecModel, view, payload, api) { var zoomActive = view._isZoomActive; payload && 'takeGlobalCursor' === payload.type && (zoomActive = 'dataZoomSelect' === payload.key && payload.dataZoomSelectActive), view._isZoomActive = zoomActive, featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal'); var panels = new BrushTargetManager(makeAxisFinder(featureModel), ecModel, { include: [ 'grid' ] }).makePanelOpts(api, function(targetInfo) { return targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared ? 'lineX' : !targetInfo.xAxisDeclared && targetInfo.yAxisDeclared ? 'lineY' : 'rect'; }); view._brushController.setPanels(panels).enableBrush(!!zoomActive && !!panels.length && { brushType: 'auto', brushStyle: featureModel.getModel('brushStyle').getItemStyle() }); }(featureModel, ecModel, this, payload, api), function(featureModel, ecModel) { featureModel.setIconStatus('back', getStoreSnapshots(ecModel).length > 1 ? 'emphasis' : 'normal'); }(featureModel, ecModel); }, DataZoomFeature.prototype.onclick = function(ecModel, api, type) { handlers$1[type].call(this); }, DataZoomFeature.prototype.remove = function(ecModel, api) { this._brushController && this._brushController.unmount(); }, DataZoomFeature.prototype.dispose = function(ecModel, api) { this._brushController && this._brushController.dispose(); }, DataZoomFeature.prototype._onBrush = function(eventParam) { var storedSnapshots, areas = eventParam.areas; if (eventParam.isEnd && areas.length) { var snapshot = {}, ecModel = this.ecModel; this._brushController.updateCovers([]), new BrushTargetManager(makeAxisFinder(this.model), ecModel, { include: [ 'grid' ] }).matchOutputRanges(areas, ecModel, function(area, coordRange, coordSys) { if ('cartesian2d' === coordSys.type) { var brushType = area.brushType; 'rect' === brushType ? (setBatch('x', coordSys, coordRange[0]), setBatch('y', coordSys, coordRange[1])) : setBatch({ lineX: 'x', lineY: 'y' }[brushType], coordSys, coordRange); } }), storedSnapshots = getStoreSnapshots(ecModel), each(snapshot, function(batchItem, dataZoomId) { for(var i = storedSnapshots.length - 1; i >= 0 && !storedSnapshots[i][dataZoomId]; i--); if (i < 0) { var dataZoomModel = ecModel.queryComponents({ mainType: 'dataZoom', subType: 'select', id: dataZoomId })[0]; if (dataZoomModel) { var percentRange = dataZoomModel.getPercentRange(); storedSnapshots[0][dataZoomId] = { dataZoomId: dataZoomId, start: percentRange[0], end: percentRange[1] }; } } }), storedSnapshots.push(snapshot), this._dispatchZoomAction(snapshot); } function setBatch(dimName, coordSys, minMax) { var found, axis = coordSys.getAxis(dimName), axisModel = axis.model, dataZoomModel = (ecModel.eachComponent({ mainType: 'dataZoom', subType: 'select' }, function(dzModel) { dzModel.getAxisModel(dimName, axisModel.componentIndex) && (found = dzModel); }), found), minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan(); (null != minMaxSpan.minValueSpan || null != minMaxSpan.maxValueSpan) && (minMax = sliderMove(0, minMax.slice(), axis.scale.getExtent(), 0, minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan)), dataZoomModel && (snapshot[dataZoomModel.id] = { dataZoomId: dataZoomModel.id, startValue: minMax[0], endValue: minMax[1] }); } }, DataZoomFeature.prototype._dispatchZoomAction = function(snapshot) { var batch = []; each(snapshot, function(batchItem, dataZoomId) { batch.push(clone(batchItem)); }), batch.length && this.api.dispatchAction({ type: 'dataZoom', from: this.uid, batch: batch }); }, DataZoomFeature.getDefaultOption = function(ecModel) { return { show: !0, filterMode: 'filter', icon: { zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1', back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26' }, title: ecModel.getLocale([ 'toolbox', 'dataZoom', 'title' ]), brushStyle: { borderWidth: 0, color: 'rgba(210,219,238,0.2)' } }; }, DataZoomFeature; }(ToolboxFeature), handlers$1 = { zoom: function() { var nextActive = !this._isZoomActive; this.api.dispatchAction({ type: 'takeGlobalCursor', key: 'dataZoomSelect', dataZoomSelectActive: nextActive }); }, back: function() { var storedSnapshots, head, snapshot; this._dispatchZoomAction((head = (storedSnapshots = getStoreSnapshots(this.ecModel))[storedSnapshots.length - 1], storedSnapshots.length > 1 && storedSnapshots.pop(), snapshot = {}, each(head, function(batchItem, dataZoomId) { for(var i = storedSnapshots.length - 1; i >= 0; i--)if (batchItem = storedSnapshots[i][dataZoomId]) { snapshot[dataZoomId] = batchItem; break; } }), snapshot)); } }; function makeAxisFinder(dzFeatureModel) { var setting = { xAxisIndex: dzFeatureModel.get('xAxisIndex', !0), yAxisIndex: dzFeatureModel.get('yAxisIndex', !0), xAxisId: dzFeatureModel.get('xAxisId', !0), yAxisId: dzFeatureModel.get('yAxisId', !0) }; return null == setting.xAxisIndex && null == setting.xAxisId && (setting.xAxisIndex = 'all'), null == setting.yAxisIndex && null == setting.yAxisId && (setting.yAxisIndex = 'all'), setting; } mainType = 'dataZoom', creator = function(ecModel) { var toolboxModel = ecModel.getComponent('toolbox', 0); if (toolboxModel) { var dzFeatureModel = toolboxModel.getModel([ 'feature', 'dataZoom' ]), dzOptions = [], finderResult = parseFinder(ecModel, makeAxisFinder(dzFeatureModel)); return each(finderResult.xAxisModels, function(axisModel) { return buildInternalOptions(axisModel, 'xAxis', 'xAxisIndex'); }), each(finderResult.yAxisModels, function(axisModel) { return buildInternalOptions(axisModel, 'yAxis', 'yAxisIndex'); }), dzOptions; } function buildInternalOptions(axisModel, axisMainType, axisIndexPropName) { var axisIndex = axisModel.componentIndex, newOpt = { type: 'select', $fromToolbox: !0, filterMode: dzFeatureModel.get('filterMode', !0) || 'filter', id: DATA_ZOOM_ID_BASE + axisMainType + axisIndex }; newOpt[axisIndexPropName] = axisIndex, dzOptions.push(newOpt); } }, assert(null == internalOptionCreatorMap.get(mainType) && creator), internalOptionCreatorMap.set(mainType, creator); var TooltipModel = function(_super) { function TooltipModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = TooltipModel.type, _this; } return __extends(TooltipModel, _super), TooltipModel.type = 'tooltip', TooltipModel.dependencies = [ 'axisPointer' ], TooltipModel.defaultOption = { zlevel: 0, z: 60, show: !0, showContent: !0, trigger: 'item', triggerOn: 'mousemove|click', alwaysShowContent: !1, displayMode: 'single', renderMode: 'auto', confine: null, showDelay: 0, hideDelay: 100, transitionDuration: 0.4, enterable: !1, backgroundColor: '#fff', shadowBlur: 10, shadowColor: 'rgba(0, 0, 0, .2)', shadowOffsetX: 1, shadowOffsetY: 2, borderRadius: 4, borderWidth: 1, padding: null, extraCssText: '', axisPointer: { type: 'line', axis: 'auto', animation: 'auto', animationDurationUpdate: 200, animationEasingUpdate: 'exponentialOut', crossStyle: { color: '#999', width: 1, type: 'dashed', textStyle: {} } }, textStyle: { color: '#666', fontSize: 14 } }, TooltipModel; }(ComponentModel); function shouldTooltipConfine(tooltipModel) { var confineOption = tooltipModel.get('confine'); return null != confineOption ? !!confineOption : 'richText' === tooltipModel.get('renderMode'); } function testStyle(styleProps) { if (env1.domSupported) { for(var style = document.documentElement.style, i = 0, len = styleProps.length; i < len; i++)if (styleProps[i] in style) return styleProps[i]; } } var TRANSFORM_VENDOR = testStyle([ 'transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform' ]), TRANSITION_VENDOR = testStyle([ 'webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition' ]); function toCSSVendorPrefix(styleVendor, styleProp) { if (!styleVendor) return styleProp; styleProp = toCamelCase(styleProp, !0); var idx = styleVendor.indexOf(styleProp); return (styleVendor = -1 === idx ? styleProp : "-" + styleVendor.slice(0, idx) + "-" + styleProp).toLowerCase(); } function getComputedStyle(el, style) { var stl = el.currentStyle || document.defaultView && document.defaultView.getComputedStyle(el); return stl ? style ? stl[style] : stl : null; } var CSS_TRANSITION_VENDOR = toCSSVendorPrefix(TRANSITION_VENDOR, 'transition'), CSS_TRANSFORM_VENDOR = toCSSVendorPrefix(TRANSFORM_VENDOR, 'transform'), gCssText = "position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;" + (env1.transform3dSupported ? 'will-change:transform;' : ''); function assembleTransform(x, y, toString) { var x0 = x.toFixed(0) + 'px', y0 = y.toFixed(0) + 'px'; if (!env1.transformSupported) return toString ? "top:" + y0 + ";left:" + x0 + ";" : [ [ 'top', y0 ], [ 'left', x0 ] ]; var is3d = env1.transform3dSupported, translate = "translate" + (is3d ? '3d' : '') + "(" + x0 + "," + y0 + (is3d ? ',0' : '') + ")"; return toString ? 'top:0;left:0;' + CSS_TRANSFORM_VENDOR + ':' + translate + ';' : [ [ 'top', 0 ], [ 'left', 0 ], [ TRANSFORM_VENDOR, translate ] ]; } function makeStyleCoord(out, zr, appendToBody, zrX, zrY) { var zrPainter = zr && zr.painter; if (appendToBody) { var elTarget, zrViewportRoot = zrPainter && zrPainter.getViewportRoot(); zrViewportRoot && (elTarget = document.body, transformCoordWithViewport(_calcOut, zrViewportRoot, zrX, zrY, !0) && transformCoordWithViewport(out, elTarget, _calcOut[0], _calcOut[1])); } else { out[0] = zrX, out[1] = zrY; var viewportRootOffset = zrPainter && zrPainter.getViewportRootOffset(); viewportRootOffset && (out[0] += viewportRootOffset.offsetLeft, out[1] += viewportRootOffset.offsetTop); } out[2] = out[0] / zr.getWidth(), out[3] = out[1] / zr.getHeight(); } var TooltipHTMLContent = function() { function TooltipHTMLContent(container, api, opt) { if (this._show = !1, this._styleCoord = [ 0, 0, 0, 0 ], this._enterable = !0, this._firstShow = !0, this._longHide = !0, env1.wxa) return null; var el = document.createElement('div'); el.domBelongToZr = !0, this.el = el; var zr = this._zr = api.getZr(), appendToBody = this._appendToBody = opt && opt.appendToBody; makeStyleCoord(this._styleCoord, zr, appendToBody, api.getWidth() / 2, api.getHeight() / 2), appendToBody ? document.body.appendChild(el) : container.appendChild(el), this._container = container; var self1 = this; el.onmouseenter = function() { self1._enterable && (clearTimeout(self1._hideTimeout), self1._show = !0), self1._inContent = !0; }, el.onmousemove = function(e) { if (e = e || window.event, !self1._enterable) { var handler = zr.handler; normalizeEvent(zr.painter.getViewportRoot(), e, !0), handler.dispatch('mousemove', e); } }, el.onmouseleave = function() { self1._inContent = !1, self1._enterable && self1._show && self1.hideLater(self1._hideDelay); }; } return TooltipHTMLContent.prototype.update = function(tooltipModel) { var container = this._container, position = getComputedStyle(container, 'position'), domStyle = container.style; 'absolute' !== domStyle.position && 'absolute' !== position && (domStyle.position = 'relative'), tooltipModel.get('alwaysShowContent') && this._moveIfResized(), this.el.className = tooltipModel.get('className') || ''; }, TooltipHTMLContent.prototype.show = function(tooltipModel, nearPointColor) { clearTimeout(this._hideTimeout), clearTimeout(this._longHideTimeout); var enableTransition, onlyFade, cssText, transitionDuration, backgroundColor, shadowBlur, shadowColor, shadowOffsetX, shadowOffsetY, textStyleModel, padding, transitionCurve, transitionOption, transitionText, cssText1, fontSize, color, shadowColor1, shadowBlur1, shadowOffsetX1, shadowOffsetY1, el = this.el, style = el.style, styleCoord = this._styleCoord; el.innerHTML ? style.cssText = gCssText + (enableTransition = !this._firstShow, onlyFade = this._longHide, cssText = [], transitionDuration = tooltipModel.get('transitionDuration'), backgroundColor = tooltipModel.get('backgroundColor'), shadowBlur = tooltipModel.get('shadowBlur'), shadowColor = tooltipModel.get('shadowColor'), shadowOffsetX = tooltipModel.get('shadowOffsetX'), shadowOffsetY = tooltipModel.get('shadowOffsetY'), textStyleModel = tooltipModel.getModel('textStyle'), padding = getPaddingFromTooltipModel(tooltipModel, 'html'), cssText.push('box-shadow:' + (shadowOffsetX + "px " + shadowOffsetY + "px ") + shadowBlur + "px " + shadowColor), enableTransition && transitionDuration && cssText.push((transitionText = "opacity" + (transitionOption = " " + transitionDuration / 2 + "s " + (transitionCurve = 'cubic-bezier(0.23,1,0.32,1)')) + ",visibility" + transitionOption, onlyFade || (transitionOption = " " + transitionDuration + "s " + transitionCurve, transitionText += env1.transformSupported ? "," + TRANSFORM_VENDOR + transitionOption : ",left" + transitionOption + ",top" + transitionOption), CSS_TRANSITION_VENDOR + ':' + transitionText)), backgroundColor && (env1.canvasSupported ? cssText.push('background-color:' + backgroundColor) : (cssText.push('background-color:#' + toHex(backgroundColor)), cssText.push('filter:alpha(opacity=70)'))), each([ 'width', 'color', 'radius' ], function(name) { var borderName = 'border-' + name, camelCase = toCamelCase(borderName), val = tooltipModel.get(camelCase); null != val && cssText.push(borderName + ':' + val + ('color' === name ? '' : 'px')); }), cssText.push((cssText1 = [], fontSize = textStyleModel.get('fontSize'), (color = textStyleModel.getTextColor()) && cssText1.push('color:' + color), cssText1.push('font:' + textStyleModel.getFont()), fontSize && cssText1.push('line-height:' + Math.round(3 * fontSize / 2) + 'px'), shadowColor1 = textStyleModel.get('textShadowColor'), shadowBlur1 = textStyleModel.get('textShadowBlur') || 0, shadowOffsetX1 = textStyleModel.get('textShadowOffsetX') || 0, shadowOffsetY1 = textStyleModel.get('textShadowOffsetY') || 0, shadowColor1 && shadowBlur1 && cssText1.push('text-shadow:' + shadowOffsetX1 + 'px ' + shadowOffsetY1 + 'px ' + shadowBlur1 + 'px ' + shadowColor1), each([ 'decoration', 'align' ], function(name) { var val = textStyleModel.get(name); val && cssText1.push('text-' + name + ':' + val); }), cssText1.join(';'))), null != padding && cssText.push('padding:' + normalizeCssArray(padding).join('px ') + 'px'), cssText.join(';') + ';') + assembleTransform(styleCoord[0], styleCoord[1], !0) + "border-color:" + convertToColorString(nearPointColor) + ";" + (tooltipModel.get('extraCssText') || '') + ";pointer-event:" + (this._enterable ? 'auto' : 'none') : style.display = 'none', this._show = !0, this._firstShow = !1, this._longHide = !1; }, TooltipHTMLContent.prototype.setContent = function(content, markers, tooltipModel, borderColor, arrowPosition) { if (null != content) { var el = this.el; if (isString(arrowPosition) && 'item' === tooltipModel.get('trigger') && !shouldTooltipConfine(tooltipModel) && (content += function(backgroundColor, borderColor, arrowPosition) { if (!isString(arrowPosition) || 'inside' === arrowPosition) return ''; borderColor = convertToColorString(borderColor); var pos, arrowPos = pos = 'left' === (pos = arrowPosition) ? 'right' : 'right' === pos ? 'left' : 'top' === pos ? 'bottom' : 'top', positionStyle = arrowPos + ":-6px;", transformStyle = CSS_TRANSFORM_VENDOR + ':'; indexOf([ 'left', 'right' ], arrowPos) > -1 ? (positionStyle += 'top:50%', transformStyle += "translateY(-50%) rotate(" + ('left' === arrowPos ? -225 : -45) + "deg)") : (positionStyle += 'left:50%', transformStyle += "translateX(-50%) rotate(" + ('top' === arrowPos ? 225 : 45) + "deg)"); var borderStyle = borderColor + " solid 1px;"; return "
"; }(tooltipModel.get('backgroundColor'), borderColor, arrowPosition)), isString(content)) el.innerHTML = content; else if (content) { el.innerHTML = '', isArray(content) || (content = [ content ]); for(var i = 0; i < content.length; i++)isDom(content[i]) && content[i].parentNode !== el && el.appendChild(content[i]); } } }, TooltipHTMLContent.prototype.setEnterable = function(enterable) { this._enterable = enterable; }, TooltipHTMLContent.prototype.getSize = function() { var el = this.el; return [ el.clientWidth, el.clientHeight ]; }, TooltipHTMLContent.prototype.moveTo = function(zrX, zrY) { var styleCoord = this._styleCoord; if (makeStyleCoord(styleCoord, this._zr, this._appendToBody, zrX, zrY), null != styleCoord[0] && null != styleCoord[1]) { var style_1 = this.el.style; each(assembleTransform(styleCoord[0], styleCoord[1]), function(transform) { style_1[transform[0]] = transform[1]; }); } }, TooltipHTMLContent.prototype._moveIfResized = function() { var ratioX = this._styleCoord[2], ratioY = this._styleCoord[3]; this.moveTo(ratioX * this._zr.getWidth(), ratioY * this._zr.getHeight()); }, TooltipHTMLContent.prototype.hide = function() { var _this = this, style = this.el.style; style.visibility = 'hidden', style.opacity = '0', env1.transform3dSupported && (style.willChange = ''), this._show = !1, this._longHideTimeout = setTimeout(function() { return _this._longHide = !0; }, 500); }, TooltipHTMLContent.prototype.hideLater = function(time) { this._show && !(this._inContent && this._enterable) && (time ? (this._hideDelay = time, this._show = !1, this._hideTimeout = setTimeout(bind(this.hide, this), time)) : this.hide()); }, TooltipHTMLContent.prototype.isShow = function() { return this._show; }, TooltipHTMLContent.prototype.dispose = function() { this.el.parentNode.removeChild(this.el); }, TooltipHTMLContent.prototype.getOuterSize = function() { var width = this.el.clientWidth, height = this.el.clientHeight, stl = getComputedStyle(this.el); return stl && (width += parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10), height += parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10)), { width: width, height: height }; }, TooltipHTMLContent; }(), TooltipRichContent = function() { function TooltipRichContent(api) { this._show = !1, this._styleCoord = [ 0, 0, 0, 0 ], this._enterable = !0, this._zr = api.getZr(), makeStyleCoord$1(this._styleCoord, this._zr, api.getWidth() / 2, api.getHeight() / 2); } return TooltipRichContent.prototype.update = function(tooltipModel) { tooltipModel.get('alwaysShowContent') && this._moveIfResized(); }, TooltipRichContent.prototype.show = function() { this._hideTimeout && clearTimeout(this._hideTimeout), this.el.show(), this._show = !0; }, TooltipRichContent.prototype.setContent = function(content, markupStyleCreator, tooltipModel, borderColor, arrowPosition) { isObject(content) && throwError('Passing DOM nodes as content is not supported in richText tooltip!'), this.el && this._zr.remove(this.el); var textStyleModel = tooltipModel.getModel('textStyle'); this.el = new ZRText({ style: { rich: markupStyleCreator.richTextStyles, text: content, lineHeight: 22, backgroundColor: tooltipModel.get('backgroundColor'), borderRadius: tooltipModel.get('borderRadius'), borderWidth: 1, borderColor: borderColor, shadowColor: tooltipModel.get('shadowColor'), shadowBlur: tooltipModel.get('shadowBlur'), shadowOffsetX: tooltipModel.get('shadowOffsetX'), shadowOffsetY: tooltipModel.get('shadowOffsetY'), textShadowColor: textStyleModel.get('textShadowColor'), textShadowBlur: textStyleModel.get('textShadowBlur') || 0, textShadowOffsetX: textStyleModel.get('textShadowOffsetX') || 0, textShadowOffsetY: textStyleModel.get('textShadowOffsetY') || 0, fill: tooltipModel.get([ 'textStyle', 'color' ]), padding: getPaddingFromTooltipModel(tooltipModel, 'richText'), verticalAlign: 'top', align: 'left' }, z: tooltipModel.get('z') }), this._zr.add(this.el); var self1 = this; this.el.on('mouseover', function() { self1._enterable && (clearTimeout(self1._hideTimeout), self1._show = !0), self1._inContent = !0; }), this.el.on('mouseout', function() { self1._enterable && self1._show && self1.hideLater(self1._hideDelay), self1._inContent = !1; }); }, TooltipRichContent.prototype.setEnterable = function(enterable) { this._enterable = enterable; }, TooltipRichContent.prototype.getSize = function() { var el = this.el, bounding = this.el.getBoundingRect(), shadowOuterSize = calcShadowOuterSize(el.style); return [ bounding.width + shadowOuterSize.left + shadowOuterSize.right, bounding.height + shadowOuterSize.top + shadowOuterSize.bottom ]; }, TooltipRichContent.prototype.moveTo = function(x, y) { var el = this.el; if (el) { var styleCoord = this._styleCoord; makeStyleCoord$1(styleCoord, this._zr, x, y), x = styleCoord[0], y = styleCoord[1]; var style = el.style, borderWidth = mathMaxWith0(style.borderWidth || 0), shadowOuterSize = calcShadowOuterSize(style); el.x = x + borderWidth + shadowOuterSize.left, el.y = y + borderWidth + shadowOuterSize.top, el.markRedraw(); } }, TooltipRichContent.prototype._moveIfResized = function() { var ratioX = this._styleCoord[2], ratioY = this._styleCoord[3]; this.moveTo(ratioX * this._zr.getWidth(), ratioY * this._zr.getHeight()); }, TooltipRichContent.prototype.hide = function() { this.el && this.el.hide(), this._show = !1; }, TooltipRichContent.prototype.hideLater = function(time) { this._show && !(this._inContent && this._enterable) && (time ? (this._hideDelay = time, this._show = !1, this._hideTimeout = setTimeout(bind(this.hide, this), time)) : this.hide()); }, TooltipRichContent.prototype.isShow = function() { return this._show; }, TooltipRichContent.prototype.getOuterSize = function() { var size = this.getSize(); return { width: size[0], height: size[1] }; }, TooltipRichContent.prototype.dispose = function() { this._zr.remove(this.el); }, TooltipRichContent; }(); function mathMaxWith0(val) { return Math.max(0, val); } function calcShadowOuterSize(style) { var shadowBlur = mathMaxWith0(style.shadowBlur || 0), shadowOffsetX = mathMaxWith0(style.shadowOffsetX || 0), shadowOffsetY = mathMaxWith0(style.shadowOffsetY || 0); return { left: mathMaxWith0(shadowBlur - shadowOffsetX), right: mathMaxWith0(shadowBlur + shadowOffsetX), top: mathMaxWith0(shadowBlur - shadowOffsetY), bottom: mathMaxWith0(shadowBlur + shadowOffsetY) }; } function makeStyleCoord$1(out, zr, zrX, zrY) { out[0] = zrX, out[1] = zrY, out[2] = out[0] / zr.getWidth(), out[3] = out[1] / zr.getHeight(); } var proxyRect = new Rect({ shape: { x: -1, y: -1, width: 2, height: 2 } }), TooltipView = function(_super) { function TooltipView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = TooltipView.type, _this; } return __extends(TooltipView, _super), TooltipView.prototype.init = function(ecModel, api) { if (!env1.node) { var tooltipModel = ecModel.getComponent('tooltip'), renderMode = tooltipModel.get('renderMode'); this._renderMode = 'auto' === renderMode ? env1.domSupported ? 'html' : 'richText' : renderMode || 'html', this._tooltipContent = 'richText' === this._renderMode ? new TooltipRichContent(api) : new TooltipHTMLContent(api.getDom(), api, { appendToBody: tooltipModel.get('appendToBody', !0) }); } }, TooltipView.prototype.render = function(tooltipModel, ecModel, api) { if (!env1.node) { this.group.removeAll(), this._tooltipModel = tooltipModel, this._ecModel = ecModel, this._api = api, this._alwaysShowContent = tooltipModel.get('alwaysShowContent'); var tooltipContent = this._tooltipContent; tooltipContent.update(tooltipModel), tooltipContent.setEnterable(tooltipModel.get('enterable')), this._initGlobalListener(), this._keepShow(); } }, TooltipView.prototype._initGlobalListener = function() { var triggerOn = this._tooltipModel.get('triggerOn'); register('itemTooltip', this._api, bind(function(currTrigger, e, dispatchAction) { 'none' !== triggerOn && (triggerOn.indexOf(currTrigger) >= 0 ? this._tryShow(e, dispatchAction) : 'leave' === currTrigger && this._hide(dispatchAction)); }, this)); }, TooltipView.prototype._keepShow = function() { var tooltipModel = this._tooltipModel, ecModel = this._ecModel, api = this._api; if (null != this._lastX && null != this._lastY && 'none' !== tooltipModel.get('triggerOn')) { var self_1 = this; clearTimeout(this._refreshUpdateTimeout), this._refreshUpdateTimeout = setTimeout(function() { api.isDisposed() || self_1.manuallyShowTip(tooltipModel, ecModel, api, { x: self_1._lastX, y: self_1._lastY, dataByCoordSys: self_1._lastDataByCoordSys }); }); } }, TooltipView.prototype.manuallyShowTip = function(tooltipModel, ecModel, api, payload) { if (payload.from !== this.uid && !env1.node) { var dispatchAction = makeDispatchAction$1(payload, api); this._ticket = ''; var dataByCoordSys = payload.dataByCoordSys, cmptRef = function(payload, ecModel, api) { var el, queryOptionMap = preParseFinder(payload).queryOptionMap, componentMainType = queryOptionMap.keys()[0]; if (componentMainType && 'series' !== componentMainType) { var model = queryReferringComponents(ecModel, componentMainType, queryOptionMap.get(componentMainType), { useDefault: !1, enableAll: !1, enableNone: !1 }).models[0]; if (model && (api.getViewOfComponentModel(model).group.traverse(function(subEl) { var tooltipConfig = getECData(subEl).tooltipConfig; if (tooltipConfig && tooltipConfig.name === payload.name) return el = subEl, !0; }), el)) return { componentMainType: componentMainType, componentIndex: model.componentIndex, el: el }; } }(payload, ecModel, api); if (cmptRef) { var rect = cmptRef.el.getBoundingRect().clone(); rect.applyTransform(cmptRef.el.transform), this._tryShow({ offsetX: rect.x + rect.width / 2, offsetY: rect.y + rect.height / 2, target: cmptRef.el, position: payload.position, positionDefault: 'bottom' }, dispatchAction); } else if (payload.tooltip && null != payload.x && null != payload.y) { var el = proxyRect; el.x = payload.x, el.y = payload.y, el.update(), getECData(el).tooltipConfig = { name: null, option: payload.tooltip }, this._tryShow({ offsetX: payload.x, offsetY: payload.y, target: el }, dispatchAction); } else if (dataByCoordSys) this._tryShow({ offsetX: payload.x, offsetY: payload.y, position: payload.position, dataByCoordSys: dataByCoordSys, tooltipOption: payload.tooltipOption }, dispatchAction); else if (null != payload.seriesIndex) { if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) return; var pointInfo = findPointFromSeries(payload, ecModel), cx = pointInfo.point[0], cy = pointInfo.point[1]; null != cx && null != cy && this._tryShow({ offsetX: cx, offsetY: cy, target: pointInfo.el, position: payload.position, positionDefault: 'bottom' }, dispatchAction); } else null != payload.x && null != payload.y && (api.dispatchAction({ type: 'updateAxisPointer', x: payload.x, y: payload.y }), this._tryShow({ offsetX: payload.x, offsetY: payload.y, position: payload.position, target: api.getZr().findHover(payload.x, payload.y).target }, dispatchAction)); } }, TooltipView.prototype.manuallyHideTip = function(tooltipModel, ecModel, api, payload) { var tooltipContent = this._tooltipContent; !this._alwaysShowContent && this._tooltipModel && tooltipContent.hideLater(this._tooltipModel.get('hideDelay')), this._lastX = this._lastY = this._lastDataByCoordSys = null, payload.from !== this.uid && this._hide(makeDispatchAction$1(payload, api)); }, TooltipView.prototype._manuallyAxisShowTip = function(tooltipModel, ecModel, api, payload) { var seriesIndex = payload.seriesIndex, dataIndex = payload.dataIndex, coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo; if (null != seriesIndex && null != dataIndex && null != coordSysAxesInfo) { var seriesModel = ecModel.getSeriesByIndex(seriesIndex); if (seriesModel && 'axis' === buildTooltipModel([ seriesModel.getData().getItemModel(dataIndex), seriesModel, (seriesModel.coordinateSystem || {}).model ], this._tooltipModel).get('trigger')) return api.dispatchAction({ type: 'updateAxisPointer', seriesIndex: seriesIndex, dataIndex: dataIndex, position: payload.position }), !0; } }, TooltipView.prototype._tryShow = function(e, dispatchAction) { var seriesDispatcher_1, cmptDispatcher_1, el = e.target; if (this._tooltipModel) { this._lastX = e.offsetX, this._lastY = e.offsetY; var dataByCoordSys = e.dataByCoordSys; dataByCoordSys && dataByCoordSys.length ? this._showAxisTooltip(dataByCoordSys, e) : el ? (this._lastDataByCoordSys = null, findEventDispatcher(el, function(target) { return null != getECData(target).dataIndex ? (seriesDispatcher_1 = target, !0) : null != getECData(target).tooltipConfig ? (cmptDispatcher_1 = target, !0) : void 0; }, !0), seriesDispatcher_1 ? this._showSeriesItemTooltip(e, seriesDispatcher_1, dispatchAction) : cmptDispatcher_1 ? this._showComponentItemTooltip(e, cmptDispatcher_1, dispatchAction) : this._hide(dispatchAction)) : (this._lastDataByCoordSys = null, this._hide(dispatchAction)); } }, TooltipView.prototype._showOrMove = function(tooltipModel, cb) { var delay = tooltipModel.get('showDelay'); cb = bind(cb, this), clearTimeout(this._showTimout), delay > 0 ? this._showTimout = setTimeout(cb, delay) : cb(); }, TooltipView.prototype._showAxisTooltip = function(dataByCoordSys, e) { var ecModel = this._ecModel, globalTooltipModel = this._tooltipModel, point = [ e.offsetX, e.offsetY ], singleTooltipModel = buildTooltipModel([ e.tooltipOption ], globalTooltipModel), renderMode = this._renderMode, cbParamsList = [], articleMarkup = createTooltipMarkup('section', { blocks: [], noHeader: !0 }), markupTextArrLegacy = [], markupStyleCreator = new TooltipMarkupStyleCreator(); each(dataByCoordSys, function(itemCoordSys) { each(itemCoordSys.dataByAxis, function(axisItem) { var axisModel = ecModel.getComponent(axisItem.axisDim + 'Axis', axisItem.axisIndex), axisValue = axisItem.value; if (axisModel && null != axisValue) { var axisValueLabel = getValueLabel(axisValue, axisModel.axis, ecModel, axisItem.seriesDataIndices, axisItem.valueLabelOpt), axisSectionMarkup = createTooltipMarkup('section', { header: axisValueLabel, noHeader: !trim(axisValueLabel), sortBlocks: !0, blocks: [] }); articleMarkup.blocks.push(axisSectionMarkup), each(axisItem.seriesDataIndices, function(idxItem) { var series = ecModel.getSeriesByIndex(idxItem.seriesIndex), dataIndex = idxItem.dataIndexInside, cbParams = series.getDataParams(dataIndex); cbParams.axisDim = axisItem.axisDim, cbParams.axisIndex = axisItem.axisIndex, cbParams.axisType = axisItem.axisType, cbParams.axisId = axisItem.axisId, cbParams.axisValue = getAxisRawValue(axisModel.axis, { value: axisValue }), cbParams.axisValueLabel = axisValueLabel, cbParams.marker = markupStyleCreator.makeTooltipMarker('item', convertToColorString(cbParams.color), renderMode); var seriesTooltipResult = normalizeTooltipFormatResult(series.formatTooltip(dataIndex, !0, null)); seriesTooltipResult.markupFragment && axisSectionMarkup.blocks.push(seriesTooltipResult.markupFragment), seriesTooltipResult.markupText && markupTextArrLegacy.push(seriesTooltipResult.markupText), cbParamsList.push(cbParams); }); } }); }), articleMarkup.blocks.reverse(), markupTextArrLegacy.reverse(); var positionExpr = e.position, builtMarkupText = buildTooltipMarkup(articleMarkup, markupStyleCreator, renderMode, singleTooltipModel.get('order'), ecModel.get('useUTC'), singleTooltipModel.get('textStyle')); builtMarkupText && markupTextArrLegacy.unshift(builtMarkupText); var allMarkupText = markupTextArrLegacy.join('richText' === renderMode ? '\n\n' : '
'); this._showOrMove(singleTooltipModel, function() { this._updateContentNotChangedOnAxis(dataByCoordSys) ? this._updatePosition(singleTooltipModel, positionExpr, point[0], point[1], this._tooltipContent, cbParamsList) : this._showTooltipContent(singleTooltipModel, allMarkupText, cbParamsList, Math.random() + '', point[0], point[1], positionExpr, null, markupStyleCreator); }); }, TooltipView.prototype._showSeriesItemTooltip = function(e, dispatcher, dispatchAction) { var ecModel = this._ecModel, ecData = getECData(dispatcher), seriesIndex = ecData.seriesIndex, seriesModel = ecModel.getSeriesByIndex(seriesIndex), dataModel = ecData.dataModel || seriesModel, dataIndex = ecData.dataIndex, dataType = ecData.dataType, data = dataModel.getData(dataType), renderMode = this._renderMode, positionDefault = e.positionDefault, tooltipModel = buildTooltipModel([ data.getItemModel(dataIndex), dataModel, seriesModel && (seriesModel.coordinateSystem || {}).model ], this._tooltipModel, positionDefault ? { position: positionDefault } : null), tooltipTrigger = tooltipModel.get('trigger'); if (null == tooltipTrigger || 'item' === tooltipTrigger) { var params = dataModel.getDataParams(dataIndex, dataType), markupStyleCreator = new TooltipMarkupStyleCreator(); params.marker = markupStyleCreator.makeTooltipMarker('item', convertToColorString(params.color), renderMode); var seriesTooltipResult = normalizeTooltipFormatResult(dataModel.formatTooltip(dataIndex, !1, dataType)), orderMode = tooltipModel.get('order'), markupText = seriesTooltipResult.markupFragment ? buildTooltipMarkup(seriesTooltipResult.markupFragment, markupStyleCreator, renderMode, orderMode, ecModel.get('useUTC'), tooltipModel.get('textStyle')) : seriesTooltipResult.markupText, asyncTicket = 'item_' + dataModel.name + '_' + dataIndex; this._showOrMove(tooltipModel, function() { this._showTooltipContent(tooltipModel, markupText, params, asyncTicket, e.offsetX, e.offsetY, e.position, e.target, markupStyleCreator); }), dispatchAction({ type: 'showTip', dataIndexInside: dataIndex, dataIndex: data.getRawIndex(dataIndex), seriesIndex: seriesIndex, from: this.uid }); } }, TooltipView.prototype._showComponentItemTooltip = function(e, el, dispatchAction) { var ecData = getECData(el), tooltipOpt = ecData.tooltipConfig.option; if (isString(tooltipOpt)) { var content = tooltipOpt; tooltipOpt = { content: content, formatter: content }; } var tooltipModelCascade = [ tooltipOpt ], cmpt = this._ecModel.getComponent(ecData.componentMainType, ecData.componentIndex); cmpt && tooltipModelCascade.push(cmpt); var positionDefault = e.positionDefault, subTooltipModel = buildTooltipModel(tooltipModelCascade, this._tooltipModel, positionDefault ? { position: positionDefault } : null), defaultHtml = subTooltipModel.get('content'), asyncTicket = Math.random() + '', markupStyleCreator = new TooltipMarkupStyleCreator(); this._showOrMove(subTooltipModel, function() { var formatterParams = clone(subTooltipModel.get('formatterParams') || {}); this._showTooltipContent(subTooltipModel, defaultHtml, formatterParams, asyncTicket, e.offsetX, e.offsetY, e.position, el, markupStyleCreator); }), dispatchAction({ type: 'showTip', from: this.uid }); }, TooltipView.prototype._showTooltipContent = function(tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el, markupStyleCreator) { if (this._ticket = '', tooltipModel.get('showContent') && tooltipModel.get('show')) { var tooltipContent = this._tooltipContent, formatter = tooltipModel.get('formatter'); positionExpr = positionExpr || tooltipModel.get('position'); var html = defaultHtml, nearPointColor = this._getNearestPoint([ x, y ], params, tooltipModel.get('trigger'), tooltipModel.get('borderColor')).color; if (formatter && isString(formatter)) { var useUTC = tooltipModel.ecModel.get('useUTC'), params0 = isArray(params) ? params[0] : params, isTimeAxis = params0 && params0.axisType && params0.axisType.indexOf('time') >= 0; html = formatter, isTimeAxis && (html = format(params0.axisValue, html, useUTC)), html = formatTpl(html, params, !0); } else if (isFunction(formatter)) { var callback = bind(function(cbTicket, html) { cbTicket === this._ticket && (tooltipContent.setContent(html, markupStyleCreator, tooltipModel, nearPointColor, positionExpr), this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el)); }, this); this._ticket = asyncTicket, html = formatter(params, asyncTicket, callback); } tooltipContent.setContent(html, markupStyleCreator, tooltipModel, nearPointColor, positionExpr), tooltipContent.show(tooltipModel, nearPointColor), this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el); } }, TooltipView.prototype._getNearestPoint = function(point, tooltipDataParams, trigger, borderColor) { return 'axis' === trigger || isArray(tooltipDataParams) ? { color: borderColor || ('html' === this._renderMode ? '#fff' : 'none') } : isArray(tooltipDataParams) ? void 0 : { color: borderColor || tooltipDataParams.color || tooltipDataParams.borderColor }; }, TooltipView.prototype._updatePosition = function(tooltipModel, positionExpr, x, y, content, params, el) { var viewWidth = this._api.getWidth(), viewHeight = this._api.getHeight(); positionExpr = positionExpr || tooltipModel.get('position'); var contentSize = content.getSize(), align = tooltipModel.get('align'), vAlign = tooltipModel.get('verticalAlign'), rect = el && el.getBoundingRect().clone(); if (el && rect.applyTransform(el.transform), isFunction(positionExpr) && (positionExpr = positionExpr([ x, y ], params, content.el, rect, { viewSize: [ viewWidth, viewHeight ], contentSize: contentSize.slice() })), isArray(positionExpr)) x = parsePercent$1(positionExpr[0], viewWidth), y = parsePercent$1(positionExpr[1], viewHeight); else if (isObject(positionExpr)) { var boxLayoutPosition = positionExpr; boxLayoutPosition.width = contentSize[0], boxLayoutPosition.height = contentSize[1]; var layoutRect = getLayoutRect(boxLayoutPosition, { width: viewWidth, height: viewHeight }); x = layoutRect.x, y = layoutRect.y, align = null, vAlign = null; } else if (isString(positionExpr) && el) { var pos = function(position, rect, contentSize) { var domWidth = contentSize[0], domHeight = contentSize[1], x = 0, y = 0, rectWidth = rect.width, rectHeight = rect.height; switch(position){ case 'inside': x = rect.x + rectWidth / 2 - domWidth / 2, y = rect.y + rectHeight / 2 - domHeight / 2; break; case 'top': x = rect.x + rectWidth / 2 - domWidth / 2, y = rect.y - domHeight - 10; break; case 'bottom': x = rect.x + rectWidth / 2 - domWidth / 2, y = rect.y + rectHeight + 10; break; case 'left': x = rect.x - domWidth - 10 - 5, y = rect.y + rectHeight / 2 - domHeight / 2; break; case 'right': x = rect.x + rectWidth + 10 + 5, y = rect.y + rectHeight / 2 - domHeight / 2; } return [ x, y ]; }(positionExpr, rect, contentSize); x = pos[0], y = pos[1]; } else { var x1, y1, gapH, gapV, size, width, height, pos = (x1 = x, y1 = y, gapH = align ? null : 20, gapV = vAlign ? null : 20, width = (size = content.getOuterSize()).width, height = size.height, null != gapH && (x1 + width + gapH + 2 > viewWidth ? x1 -= width + gapH : x1 += gapH), null != gapV && (y1 + height + gapV > viewHeight ? y1 -= height + gapV : y1 += gapV), [ x1, y1 ]); x = pos[0], y = pos[1]; } if (align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : 'right' === align ? contentSize[0] : 0), vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : 'bottom' === vAlign ? contentSize[1] : 0), shouldTooltipConfine(tooltipModel)) { var x2, y2, size1, width1, height1, pos = (x2 = x, y2 = y, width1 = (size1 = content.getOuterSize()).width, height1 = size1.height, x2 = Math.min(x2 + width1, viewWidth) - width1, y2 = Math.min(y2 + height1, viewHeight) - height1, [ x2 = Math.max(x2, 0), y2 = Math.max(y2, 0) ]); x = pos[0], y = pos[1]; } content.moveTo(x, y); }, TooltipView.prototype._updateContentNotChangedOnAxis = function(dataByCoordSys) { var lastCoordSys = this._lastDataByCoordSys, contentNotChanged = !!lastCoordSys && lastCoordSys.length === dataByCoordSys.length; return contentNotChanged && each(lastCoordSys, function(lastItemCoordSys, indexCoordSys) { var lastDataByAxis = lastItemCoordSys.dataByAxis || [], thisDataByAxis = (dataByCoordSys[indexCoordSys] || {}).dataByAxis || []; (contentNotChanged = contentNotChanged && lastDataByAxis.length === thisDataByAxis.length) && each(lastDataByAxis, function(lastItem, indexAxis) { var thisItem = thisDataByAxis[indexAxis] || {}, lastIndices = lastItem.seriesDataIndices || [], newIndices = thisItem.seriesDataIndices || []; (contentNotChanged = contentNotChanged && lastItem.value === thisItem.value && lastItem.axisType === thisItem.axisType && lastItem.axisId === thisItem.axisId && lastIndices.length === newIndices.length) && each(lastIndices, function(lastIdxItem, j) { var newIdxItem = newIndices[j]; contentNotChanged = contentNotChanged && lastIdxItem.seriesIndex === newIdxItem.seriesIndex && lastIdxItem.dataIndex === newIdxItem.dataIndex; }); }); }), this._lastDataByCoordSys = dataByCoordSys, !!contentNotChanged; }, TooltipView.prototype._hide = function(dispatchAction) { this._lastDataByCoordSys = null, dispatchAction({ type: 'hideTip', from: this.uid }); }, TooltipView.prototype.dispose = function(ecModel, api) { env1.node || (this._tooltipContent.dispose(), unregister('itemTooltip', api)); }, TooltipView.type = 'tooltip', TooltipView; }(ComponentView); function buildTooltipModel(modelCascade, globalTooltipModel, defaultTooltipOption) { var resultModel, ecModel = globalTooltipModel.ecModel; defaultTooltipOption ? (resultModel = new Model(defaultTooltipOption, ecModel, ecModel), resultModel = new Model(globalTooltipModel.option, resultModel, ecModel)) : resultModel = globalTooltipModel; for(var i = modelCascade.length - 1; i >= 0; i--){ var tooltipOpt = modelCascade[i]; tooltipOpt && (tooltipOpt instanceof Model && (tooltipOpt = tooltipOpt.get('tooltip', !0)), isString(tooltipOpt) && (tooltipOpt = { formatter: tooltipOpt }), tooltipOpt && (resultModel = new Model(tooltipOpt, resultModel, ecModel))); } return resultModel; } function makeDispatchAction$1(payload, api) { return payload.dispatchAction || bind(api.dispatchAction, api); } function isCenterAlign(align) { return 'center' === align || 'middle' === align; } var DEFAULT_TOOLBOX_BTNS = [ 'rect', 'polygon', 'keep', 'clear' ]; function brushPreprocessor(option, isNew) { var brushComponents = normalizeToArray(option ? option.brush : []); if (brushComponents.length) { var arr, map, brushComponentSpecifiedBtns = []; each(brushComponents, function(brushOpt) { var tbs = brushOpt.hasOwnProperty('toolbox') ? brushOpt.toolbox : []; tbs instanceof Array && (brushComponentSpecifiedBtns = brushComponentSpecifiedBtns.concat(tbs)); }); var toolbox = option && option.toolbox; isArray(toolbox) && (toolbox = toolbox[0]), toolbox || (toolbox = { feature: {} }, option.toolbox = [ toolbox ]); var toolboxFeature = toolbox.feature || (toolbox.feature = {}), toolboxBrush = toolboxFeature.brush || (toolboxFeature.brush = {}), brushTypes = toolboxBrush.type || (toolboxBrush.type = []); brushTypes.push.apply(brushTypes, brushComponentSpecifiedBtns), map = {}, each(arr = brushTypes, function(val) { map[val] = 1; }), arr.length = 0, each(map, function(flag, val) { arr.push(val); }), isNew && !brushTypes.length && brushTypes.push.apply(brushTypes, DEFAULT_TOOLBOX_BTNS); } } function hasKeys(obj) { if (obj) { for(var name_1 in obj)if (obj.hasOwnProperty(name_1)) return !0; } } function createVisualMappings(option, stateList, supplementVisualOption) { var visualMappings = {}; return each(stateList, function(state) { var Creater, mappings = visualMappings[state] = ((Creater = function() {}).prototype.__hidden = Creater.prototype, new Creater()); each(option[state], function(visualData, visualType) { if (VisualMapping.isValidType(visualType)) { var mappingOption = { type: visualType, visual: visualData }; supplementVisualOption && supplementVisualOption(mappingOption, state), mappings[visualType] = new VisualMapping(mappingOption), 'opacity' === visualType && ((mappingOption = clone(mappingOption)).type = 'colorAlpha', mappings.__hidden.__alphaForOpacity = new VisualMapping(mappingOption)); } }); }), visualMappings; } function replaceVisualOption(thisOption, newOption, keys) { var has; each(keys, function(key) { newOption.hasOwnProperty(key) && hasKeys(newOption[key]) && (has = !0); }), has && each(keys, function(key) { newOption.hasOwnProperty(key) && hasKeys(newOption[key]) ? thisOption[key] = clone(newOption[key]) : delete thisOption[key]; }); } var selector = { lineX: getLineSelectors(0), lineY: getLineSelectors(1), rect: { point: function(itemLayout, selectors, area) { return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]); }, rect: function(itemLayout, selectors, area) { return itemLayout && area.boundingRect.intersect(itemLayout); } }, polygon: { point: function(itemLayout, selectors, area) { return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]) && contain$1(area.range, itemLayout[0], itemLayout[1]); }, rect: function(itemLayout, selectors, area) { var points = area.range; if (!itemLayout || points.length <= 1) return !1; var x = itemLayout.x, y = itemLayout.y, width = itemLayout.width, height = itemLayout.height, p = points[0]; if (contain$1(points, x, y) || contain$1(points, x + width, y) || contain$1(points, x, y + height) || contain$1(points, x + width, y + height) || BoundingRect.create(itemLayout).contain(p[0], p[1]) || linePolygonIntersect(x, y, x + width, y, points) || linePolygonIntersect(x, y, x, y + height, points) || linePolygonIntersect(x + width, y, x + width, y + height, points) || linePolygonIntersect(x, y + height, x + width, y + height, points)) return !0; } } }; function getLineSelectors(xyIndex) { var xy = [ 'x', 'y' ], wh = [ 'width', 'height' ]; return { point: function(itemLayout, selectors, area) { if (itemLayout) { var range = area.range; return inLineRange(itemLayout[xyIndex], range); } }, rect: function(itemLayout, selectors, area) { if (itemLayout) { var range = area.range, layoutRange = [ itemLayout[xy[xyIndex]], itemLayout[xy[xyIndex]] + itemLayout[wh[xyIndex]] ]; return layoutRange[1] < layoutRange[0] && layoutRange.reverse(), inLineRange(layoutRange[0], range) || inLineRange(layoutRange[1], range) || inLineRange(range[0], layoutRange) || inLineRange(range[1], layoutRange); } } }; } function inLineRange(p, range) { return range[0] <= p && p <= range[1]; } var STATE_LIST = [ 'inBrush', 'outOfBrush' ], DISPATCH_METHOD = '__ecBrushSelect', DISPATCH_FLAG = '__ecInBrushSelectEvent'; function layoutCovers(ecModel) { ecModel.eachComponent({ mainType: 'brush' }, function(brushModel) { (brushModel.brushTargetManager = new BrushTargetManager(brushModel.option, ecModel)).setInputRanges(brushModel.areas, ecModel); }); } function brushVisual(ecModel, api, payload) { var throttleType, throttleDelay, brushSelected = []; ecModel.eachComponent({ mainType: 'brush' }, function(brushModel) { payload && 'takeGlobalCursor' === payload.type && brushModel.setBrushOption('brush' === payload.key ? payload.brushOption : { brushType: !1 }); }), layoutCovers(ecModel), ecModel.eachComponent({ mainType: 'brush' }, function(brushModel, brushIndex) { var thisBrushSelected = { brushId: brushModel.id, brushIndex: brushIndex, brushName: brushModel.name, areas: clone(brushModel.areas), selected: [] }; brushSelected.push(thisBrushSelected); var brushOption = brushModel.option, brushLink = brushOption.brushLink, linkedSeriesMap = [], selectedDataIndexForLink = [], rangeInfoBySeries = [], hasBrushExists = !1; brushIndex || (throttleType = brushOption.throttleType, throttleDelay = brushOption.throttleDelay); var areas = map(brushModel.areas, function(area) { var brushType, selectors, builder = boundingRectBuilders[area.brushType], selectableArea = defaults({ boundingRect: builder ? builder(area) : void 0 }, area); return selectableArea.selectors = (brushType = selectableArea.brushType, selectors = { point: function(itemLayout) { return selector[brushType].point(itemLayout, selectors, selectableArea); }, rect: function(itemLayout) { return selector[brushType].rect(itemLayout, selectors, selectableArea); } }), selectableArea; }), visualMappings = createVisualMappings(brushModel.option, STATE_LIST, function(mappingOption) { mappingOption.mappingMethod = 'fixed'; }); function linkOthers(seriesIndex) { return 'all' === brushLink || !!linkedSeriesMap[seriesIndex]; } function brushed(rangeInfoList) { return !!rangeInfoList.length; } isArray(brushLink) && each(brushLink, function(seriesIndex) { linkedSeriesMap[seriesIndex] = 1; }), ecModel.eachSeries(function(seriesModel, seriesIndex) { var coordSys, rangeInfoList = rangeInfoBySeries[seriesIndex] = []; 'parallel' === seriesModel.subType ? (coordSys = seriesModel.coordinateSystem, hasBrushExists = hasBrushExists || coordSys.hasAxisBrushed(), linkOthers(seriesIndex) && coordSys.eachActiveState(seriesModel.getData(), function(activeState, dataIndex) { 'active' === activeState && (selectedDataIndexForLink[dataIndex] = 1); })) : function(seriesModel, seriesIndex, rangeInfoList) { if (!(!seriesModel.brushSelector || (brushModel1 = brushModel, seriesIndex1 = seriesIndex, null != (seriesIndices = brushModel1.option.seriesIndex) && 'all' !== seriesIndices && (isArray(seriesIndices) ? 0 > indexOf(seriesIndices, seriesIndex1) : seriesIndex1 !== seriesIndices))) && (each(areas, function(area) { brushModel.brushTargetManager.controlSeries(area, seriesModel, ecModel) && rangeInfoList.push(area), hasBrushExists = hasBrushExists || brushed(rangeInfoList); }), linkOthers(seriesIndex) && brushed(rangeInfoList))) { var brushModel1, seriesIndex1, seriesIndices, data_1 = seriesModel.getData(); data_1.each(function(dataIndex) { checkInRange(seriesModel, rangeInfoList, data_1, dataIndex) && (selectedDataIndexForLink[dataIndex] = 1); }); } }(seriesModel, seriesIndex, rangeInfoList); }), ecModel.eachSeries(function(seriesModel, seriesIndex) { var seriesBrushSelected = { seriesId: seriesModel.id, seriesIndex: seriesIndex, seriesName: seriesModel.name, dataIndex: [] }; thisBrushSelected.selected.push(seriesBrushSelected); var rangeInfoList = rangeInfoBySeries[seriesIndex], data = seriesModel.getData(), getValueState = linkOthers(seriesIndex) ? function(dataIndex) { return selectedDataIndexForLink[dataIndex] ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush') : 'outOfBrush'; } : function(dataIndex) { return checkInRange(seriesModel, rangeInfoList, data, dataIndex) ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush') : 'outOfBrush'; }; (linkOthers(seriesIndex) ? hasBrushExists : brushed(rangeInfoList)) && function(stateList, visualMappings, data, getValueState, scope, dimension) { var dataIndex, visualTypesMap = {}; function getVisual(key) { return getItemVisualFromData(data, dataIndex, key); } function setVisual(key, value) { setItemVisualFromData(data, dataIndex, key, value); } function eachItem(valueOrIndex, index) { dataIndex = null == dimension ? valueOrIndex : index; var rawDataItem = data.getRawDataItem(dataIndex); if (!rawDataItem || !1 !== rawDataItem.visualMap) for(var valueState = getValueState.call(void 0, valueOrIndex), mappings = visualMappings[valueState], visualTypes = visualTypesMap[valueState], i = 0, len = visualTypes.length; i < len; i++){ var type = visualTypes[i]; mappings[type] && mappings[type].applyVisual(valueOrIndex, getVisual, setVisual); } } each(stateList, function(state) { var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]); visualTypesMap[state] = visualTypes; }), null == dimension ? data.each(eachItem) : data.each([ dimension ], eachItem); }(STATE_LIST, visualMappings, data, getValueState); }); }), function(api, throttleType, throttleDelay, brushSelected, payload) { if (payload) { var zr = api.getZr(); zr[DISPATCH_FLAG] || (zr[DISPATCH_METHOD] || (zr[DISPATCH_METHOD] = doDispatch), createOrUpdate(zr, DISPATCH_METHOD, throttleDelay, throttleType)(api, brushSelected)); } }(api, throttleType, throttleDelay, brushSelected, payload); } function doDispatch(api, brushSelected) { if (!api.isDisposed()) { var zr = api.getZr(); zr[DISPATCH_FLAG] = !0, api.dispatchAction({ type: 'brushSelect', batch: brushSelected }), zr[DISPATCH_FLAG] = !1; } } function checkInRange(seriesModel, rangeInfoList, data, dataIndex) { for(var i = 0, len = rangeInfoList.length; i < len; i++){ var area = rangeInfoList[i]; if (seriesModel.brushSelector(dataIndex, data, area.selectors, area)) return !0; } } var boundingRectBuilders = { rect: function(area) { return getBoundingRectFromMinMax(area.range); }, polygon: function(area) { for(var minMax, range = area.range, i = 0, len = range.length; i < len; i++){ minMax = minMax || [ [ 1 / 0, -1 / 0 ], [ 1 / 0, -1 / 0 ] ]; var rg = range[i]; rg[0] < minMax[0][0] && (minMax[0][0] = rg[0]), rg[0] > minMax[0][1] && (minMax[0][1] = rg[0]), rg[1] < minMax[1][0] && (minMax[1][0] = rg[1]), rg[1] > minMax[1][1] && (minMax[1][1] = rg[1]); } return minMax && getBoundingRectFromMinMax(minMax); } }; function getBoundingRectFromMinMax(minMax) { return new BoundingRect(minMax[0][0], minMax[1][0], minMax[0][1] - minMax[0][0], minMax[1][1] - minMax[1][0]); } var BrushView = function(_super) { function BrushView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = BrushView.type, _this; } return __extends(BrushView, _super), BrushView.prototype.init = function(ecModel, api) { this.ecModel = ecModel, this.api = api, this.model, (this._brushController = new BrushController(api.getZr())).on('brush', bind(this._onBrush, this)).mount(); }, BrushView.prototype.render = function(brushModel, ecModel, api, payload) { this.model = brushModel, this._updateController(brushModel, ecModel, api, payload); }, BrushView.prototype.updateTransform = function(brushModel, ecModel, api, payload) { layoutCovers(ecModel), this._updateController(brushModel, ecModel, api, payload); }, BrushView.prototype.updateVisual = function(brushModel, ecModel, api, payload) { this.updateTransform(brushModel, ecModel, api, payload); }, BrushView.prototype.updateView = function(brushModel, ecModel, api, payload) { this._updateController(brushModel, ecModel, api, payload); }, BrushView.prototype._updateController = function(brushModel, ecModel, api, payload) { payload && payload.$from === brushModel.id || this._brushController.setPanels(brushModel.brushTargetManager.makePanelOpts(api)).enableBrush(brushModel.brushOption).updateCovers(brushModel.areas.slice()); }, BrushView.prototype.dispose = function() { this._brushController.dispose(); }, BrushView.prototype._onBrush = function(eventParam) { var modelId = this.model.id, areas = this.model.brushTargetManager.setOutputRanges(eventParam.areas, this.ecModel); (!eventParam.isEnd || eventParam.removeOnClick) && this.api.dispatchAction({ type: 'brush', brushId: modelId, areas: clone(areas), $from: modelId }), eventParam.isEnd && this.api.dispatchAction({ type: 'brushEnd', brushId: modelId, areas: clone(areas), $from: modelId }); }, BrushView.type = 'brush', BrushView; }(ComponentView), BrushModel = function(_super) { function BrushModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = BrushModel.type, _this.areas = [], _this.brushOption = {}, _this; } return __extends(BrushModel, _super), BrushModel.prototype.optionUpdated = function(newOption, isInit) { var thisOption = this.option; isInit || replaceVisualOption(thisOption, newOption, [ 'inBrush', 'outOfBrush' ]); var inBrush = thisOption.inBrush = thisOption.inBrush || {}; thisOption.outOfBrush = thisOption.outOfBrush || { color: '#ddd' }, inBrush.hasOwnProperty('liftZ') || (inBrush.liftZ = 5); }, BrushModel.prototype.setAreas = function(areas) { assert(isArray(areas)), each(areas, function(area) { assert(area.brushType, 'Illegal areas'); }), areas && (this.areas = map(areas, function(area) { return generateBrushOption(this.option, area); }, this)); }, BrushModel.prototype.setBrushOption = function(brushOption) { this.brushOption = generateBrushOption(this.option, brushOption), this.brushType = this.brushOption.brushType; }, BrushModel.type = 'brush', BrushModel.dependencies = [ 'geo', 'grid', 'xAxis', 'yAxis', 'parallel', 'series' ], BrushModel.defaultOption = { seriesIndex: 'all', brushType: 'rect', brushMode: 'single', transformable: !0, brushStyle: { borderWidth: 1, color: 'rgba(210,219,238,0.3)', borderColor: '#D2DBEE' }, throttleType: 'fixRate', throttleDelay: 0, removeOnClick: !0, z: 10000 }, BrushModel; }(ComponentModel); function generateBrushOption(option, brushOption) { return merge({ brushType: option.brushType, brushMode: option.brushMode, transformable: option.transformable, brushStyle: new Model(option.brushStyle).getItemStyle(), removeOnClick: option.removeOnClick, z: option.z }, brushOption, !0); } var ICON_TYPES = [ 'rect', 'polygon', 'lineX', 'lineY', 'keep', 'clear' ], BrushFeature = function(_super) { function BrushFeature() { return null !== _super && _super.apply(this, arguments) || this; } return __extends(BrushFeature, _super), BrushFeature.prototype.render = function(featureModel, ecModel, api) { var brushType, brushMode, isBrushed; ecModel.eachComponent({ mainType: 'brush' }, function(brushModel) { brushType = brushModel.brushType, brushMode = brushModel.brushOption.brushMode || 'single', isBrushed = isBrushed || !!brushModel.areas.length; }), this._brushType = brushType, this._brushMode = brushMode, each(featureModel.get('type', !0), function(type) { featureModel.setIconStatus(type, ('keep' === type ? 'multiple' === brushMode : 'clear' === type ? isBrushed : type === brushType) ? 'emphasis' : 'normal'); }); }, BrushFeature.prototype.updateView = function(featureModel, ecModel, api) { this.render(featureModel, ecModel, api); }, BrushFeature.prototype.getIcons = function() { var model = this.model, availableIcons = model.get('icon', !0), icons = {}; return each(model.get('type', !0), function(type) { availableIcons[type] && (icons[type] = availableIcons[type]); }), icons; }, BrushFeature.prototype.onclick = function(ecModel, api, type) { var brushType = this._brushType, brushMode = this._brushMode; 'clear' === type ? (api.dispatchAction({ type: 'axisAreaSelect', intervals: [] }), api.dispatchAction({ type: 'brush', command: 'clear', areas: [] })) : api.dispatchAction({ type: 'takeGlobalCursor', key: 'brush', brushOption: { brushType: 'keep' === type ? brushType : brushType !== type && type, brushMode: 'keep' === type ? 'multiple' === brushMode ? 'single' : 'multiple' : brushMode } }); }, BrushFeature.getDefaultOption = function(ecModel) { return { show: !0, type: ICON_TYPES.slice(), icon: { rect: 'M7.3,34.7 M0.4,10V-0.2h9.8 M89.6,10V-0.2h-9.8 M0.4,60v10.2h9.8 M89.6,60v10.2h-9.8 M12.3,22.4V10.5h13.1 M33.6,10.5h7.8 M49.1,10.5h7.8 M77.5,22.4V10.5h-13 M12.3,31.1v8.2 M77.7,31.1v8.2 M12.3,47.6v11.9h13.1 M33.6,59.5h7.6 M49.1,59.5 h7.7 M77.5,47.6v11.9h-13', polygon: 'M55.2,34.9c1.7,0,3.1,1.4,3.1,3.1s-1.4,3.1-3.1,3.1 s-3.1-1.4-3.1-3.1S53.5,34.9,55.2,34.9z M50.4,51c1.7,0,3.1,1.4,3.1,3.1c0,1.7-1.4,3.1-3.1,3.1c-1.7,0-3.1-1.4-3.1-3.1 C47.3,52.4,48.7,51,50.4,51z M55.6,37.1l1.5-7.8 M60.1,13.5l1.6-8.7l-7.8,4 M59,19l-1,5.3 M24,16.1l6.4,4.9l6.4-3.3 M48.5,11.6 l-5.9,3.1 M19.1,12.8L9.7,5.1l1.1,7.7 M13.4,29.8l1,7.3l6.6,1.6 M11.6,18.4l1,6.1 M32.8,41.9 M26.6,40.4 M27.3,40.2l6.1,1.6 M49.9,52.1l-5.6-7.6l-4.9-1.2', lineX: 'M15.2,30 M19.7,15.6V1.9H29 M34.8,1.9H40.4 M55.3,15.6V1.9H45.9 M19.7,44.4V58.1H29 M34.8,58.1H40.4 M55.3,44.4 V58.1H45.9 M12.5,20.3l-9.4,9.6l9.6,9.8 M3.1,29.9h16.5 M62.5,20.3l9.4,9.6L62.3,39.7 M71.9,29.9H55.4', lineY: 'M38.8,7.7 M52.7,12h13.2v9 M65.9,26.6V32 M52.7,46.3h13.2v-9 M24.9,12H11.8v9 M11.8,26.6V32 M24.9,46.3H11.8v-9 M48.2,5.1l-9.3-9l-9.4,9.2 M38.9-3.9V12 M48.2,53.3l-9.3,9l-9.4-9.2 M38.9,62.3V46.4', keep: 'M4,10.5V1h10.3 M20.7,1h6.1 M33,1h6.1 M55.4,10.5V1H45.2 M4,17.3v6.6 M55.6,17.3v6.6 M4,30.5V40h10.3 M20.7,40 h6.1 M33,40h6.1 M55.4,30.5V40H45.2 M21,18.9h62.9v48.6H21V18.9z', clear: 'M22,14.7l30.9,31 M52.9,14.7L22,45.7 M4.7,16.8V4.2h13.1 M26,4.2h7.8 M41.6,4.2h7.8 M70.3,16.8V4.2H57.2 M4.7,25.9v8.6 M70.3,25.9v8.6 M4.7,43.2v12.6h13.1 M26,55.8h7.8 M41.6,55.8h7.8 M70.3,43.2v12.6H57.2' }, title: ecModel.getLocale([ 'toolbox', 'brush', 'title' ]) }; }, BrushFeature; }(ToolboxFeature), TitleModel = function(_super) { function TitleModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = TitleModel.type, _this.layoutMode = { type: 'box', ignoreSize: !0 }, _this; } return __extends(TitleModel, _super), TitleModel.type = 'title', TitleModel.defaultOption = { zlevel: 0, z: 6, show: !0, text: '', target: 'blank', subtext: '', subtarget: 'blank', left: 0, top: 0, backgroundColor: 'rgba(0,0,0,0)', borderColor: '#ccc', borderWidth: 0, padding: 5, itemGap: 10, textStyle: { fontSize: 18, fontWeight: 'bold', color: '#464646' }, subtextStyle: { fontSize: 12, color: '#6E7079' } }, TitleModel; }(ComponentModel), TitleView = function(_super) { function TitleView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = TitleView.type, _this; } return __extends(TitleView, _super), TitleView.prototype.render = function(titleModel, ecModel, api) { if (this.group.removeAll(), titleModel.get('show')) { var group = this.group, textStyleModel = titleModel.getModel('textStyle'), subtextStyleModel = titleModel.getModel('subtextStyle'), textAlign = titleModel.get('textAlign'), textVerticalAlign = retrieve2(titleModel.get('textBaseline'), titleModel.get('textVerticalAlign')), textEl = new ZRText({ style: createTextStyle(textStyleModel, { text: titleModel.get('text'), fill: textStyleModel.getTextColor() }, { disableBox: !0 }), z2: 10 }), textRect = textEl.getBoundingRect(), subText = titleModel.get('subtext'), subTextEl = new ZRText({ style: createTextStyle(subtextStyleModel, { text: subText, fill: subtextStyleModel.getTextColor(), y: textRect.height + titleModel.get('itemGap'), verticalAlign: 'top' }, { disableBox: !0 }), z2: 10 }), link = titleModel.get('link'), sublink = titleModel.get('sublink'), triggerEvent = titleModel.get('triggerEvent', !0); textEl.silent = !link && !triggerEvent, subTextEl.silent = !sublink && !triggerEvent, link && textEl.on('click', function() { windowOpen(link, '_' + titleModel.get('target')); }), sublink && subTextEl.on('click', function() { windowOpen(sublink, '_' + titleModel.get('subtarget')); }), getECData(textEl).eventData = getECData(subTextEl).eventData = triggerEvent ? { componentType: 'title', componentIndex: titleModel.componentIndex } : null, group.add(textEl), subText && group.add(subTextEl); var groupRect = group.getBoundingRect(), layoutOption = titleModel.getBoxLayoutParams(); layoutOption.width = groupRect.width, layoutOption.height = groupRect.height; var layoutRect = getLayoutRect(layoutOption, { width: api.getWidth(), height: api.getHeight() }, titleModel.get('padding')); textAlign || ('middle' === (textAlign = titleModel.get('left') || titleModel.get('right')) && (textAlign = 'center'), 'right' === textAlign ? layoutRect.x += layoutRect.width : 'center' !== textAlign || (layoutRect.x += layoutRect.width / 2)), textVerticalAlign || ('center' === (textVerticalAlign = titleModel.get('top') || titleModel.get('bottom')) && (textVerticalAlign = 'middle'), 'bottom' === textVerticalAlign ? layoutRect.y += layoutRect.height : 'middle' === textVerticalAlign && (layoutRect.y += layoutRect.height / 2), textVerticalAlign = textVerticalAlign || 'top'), group.x = layoutRect.x, group.y = layoutRect.y, group.markRedraw(); var alignStyle = { align: textAlign, verticalAlign: textVerticalAlign }; textEl.setStyle(alignStyle), subTextEl.setStyle(alignStyle), groupRect = group.getBoundingRect(); var padding = layoutRect.margin, style = titleModel.getItemStyle([ 'color', 'opacity' ]); style.fill = titleModel.get('backgroundColor'); var rect = new Rect({ shape: { x: groupRect.x - padding[3], y: groupRect.y - padding[0], width: groupRect.width + padding[1] + padding[3], height: groupRect.height + padding[0] + padding[2], r: titleModel.get('borderRadius') }, style: style, subPixelOptimize: !0, silent: !0 }); group.add(rect); } }, TitleView.type = 'title', TitleView; }(ComponentView), TimelineModel = function(_super) { function TimelineModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = TimelineModel.type, _this.layoutMode = 'box', _this; } return __extends(TimelineModel, _super), TimelineModel.prototype.init = function(option, parentModel, ecModel) { this.mergeDefaultAndTheme(option, ecModel), this._initData(); }, TimelineModel.prototype.mergeOption = function(option) { _super.prototype.mergeOption.apply(this, arguments), this._initData(); }, TimelineModel.prototype.setCurrentIndex = function(currentIndex) { null == currentIndex && (currentIndex = this.option.currentIndex); var count = this._data.count(); this.option.loop ? currentIndex = (currentIndex % count + count) % count : (currentIndex >= count && (currentIndex = count - 1), currentIndex < 0 && (currentIndex = 0)), this.option.currentIndex = currentIndex; }, TimelineModel.prototype.getCurrentIndex = function() { return this.option.currentIndex; }, TimelineModel.prototype.isIndexMax = function() { return this.getCurrentIndex() >= this._data.count() - 1; }, TimelineModel.prototype.setPlayState = function(state) { this.option.autoPlay = !!state; }, TimelineModel.prototype.getPlayState = function() { return !!this.option.autoPlay; }, TimelineModel.prototype._initData = function() { var processedDataArr, thisOption = this.option, dataArr = thisOption.data || [], axisType = thisOption.axisType, names = this._names = []; 'category' === axisType ? (processedDataArr = [], each(dataArr, function(item, index) { var newItem, value = convertOptionIdName(getDataItemValue(item), ''); isObject(item) ? (newItem = clone(item)).value = index : newItem = index, processedDataArr.push(newItem), names.push(value); })) : processedDataArr = dataArr, (this._data = new List([ { name: 'value', type: { category: 'ordinal', time: 'time', value: 'number' }[axisType] || 'number' } ], this)).initData(processedDataArr, names); }, TimelineModel.prototype.getData = function() { return this._data; }, TimelineModel.prototype.getCategories = function() { if ('category' === this.get('axisType')) return this._names.slice(); }, TimelineModel.type = 'timeline', TimelineModel.defaultOption = { zlevel: 0, z: 4, show: !0, axisType: 'time', realtime: !0, left: '20%', top: null, right: '20%', bottom: 0, width: null, height: 40, padding: 5, controlPosition: 'left', autoPlay: !1, rewind: !1, loop: !0, playInterval: 2000, currentIndex: 0, itemStyle: {}, label: { color: '#000' }, data: [] }, TimelineModel; }(ComponentModel), SliderTimelineModel = function(_super) { function SliderTimelineModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = SliderTimelineModel.type, _this; } return __extends(SliderTimelineModel, _super), SliderTimelineModel.type = 'timeline.slider', SliderTimelineModel.defaultOption = inheritDefaultOption(TimelineModel.defaultOption, { backgroundColor: 'rgba(0,0,0,0)', borderColor: '#ccc', borderWidth: 0, orient: 'horizontal', inverse: !1, tooltip: { trigger: 'item' }, symbol: 'circle', symbolSize: 12, lineStyle: { show: !0, width: 2, color: '#DAE1F5' }, label: { position: 'auto', show: !0, interval: 'auto', rotate: 0, color: '#A4B1D7' }, itemStyle: { color: '#A4B1D7', borderWidth: 1 }, checkpointStyle: { symbol: 'circle', symbolSize: 15, color: '#316bf3', borderColor: '#fff', borderWidth: 2, shadowBlur: 2, shadowOffsetX: 1, shadowOffsetY: 1, shadowColor: 'rgba(0, 0, 0, 0.3)', animation: !0, animationDuration: 300, animationEasing: 'quinticInOut' }, controlStyle: { show: !0, showPlayBtn: !0, showPrevBtn: !0, showNextBtn: !0, itemSize: 24, itemGap: 12, position: 'left', playIcon: 'path://M31.6,53C17.5,53,6,41.5,6,27.4S17.5,1.8,31.6,1.8C45.7,1.8,57.2,13.3,57.2,27.4S45.7,53,31.6,53z M31.6,3.3 C18.4,3.3,7.5,14.1,7.5,27.4c0,13.3,10.8,24.1,24.1,24.1C44.9,51.5,55.7,40.7,55.7,27.4C55.7,14.1,44.9,3.3,31.6,3.3z M24.9,21.3 c0-2.2,1.6-3.1,3.5-2l10.5,6.1c1.899,1.1,1.899,2.9,0,4l-10.5,6.1c-1.9,1.1-3.5,0.2-3.5-2V21.3z', stopIcon: 'path://M30.9,53.2C16.8,53.2,5.3,41.7,5.3,27.6S16.8,2,30.9,2C45,2,56.4,13.5,56.4,27.6S45,53.2,30.9,53.2z M30.9,3.5C17.6,3.5,6.8,14.4,6.8,27.6c0,13.3,10.8,24.1,24.101,24.1C44.2,51.7,55,40.9,55,27.6C54.9,14.4,44.1,3.5,30.9,3.5z M36.9,35.8c0,0.601-0.4,1-0.9,1h-1.3c-0.5,0-0.9-0.399-0.9-1V19.5c0-0.6,0.4-1,0.9-1H36c0.5,0,0.9,0.4,0.9,1V35.8z M27.8,35.8 c0,0.601-0.4,1-0.9,1h-1.3c-0.5,0-0.9-0.399-0.9-1V19.5c0-0.6,0.4-1,0.9-1H27c0.5,0,0.9,0.4,0.9,1L27.8,35.8L27.8,35.8z', nextIcon: 'M2,18.5A1.52,1.52,0,0,1,.92,18a1.49,1.49,0,0,1,0-2.12L7.81,9.36,1,3.11A1.5,1.5,0,1,1,3,.89l8,7.34a1.48,1.48,0,0,1,.49,1.09,1.51,1.51,0,0,1-.46,1.1L3,18.08A1.5,1.5,0,0,1,2,18.5Z', prevIcon: 'M10,.5A1.52,1.52,0,0,1,11.08,1a1.49,1.49,0,0,1,0,2.12L4.19,9.64,11,15.89a1.5,1.5,0,1,1-2,2.22L1,10.77A1.48,1.48,0,0,1,.5,9.68,1.51,1.51,0,0,1,1,8.58L9,.92A1.5,1.5,0,0,1,10,.5Z', prevBtnSize: 18, nextBtnSize: 18, color: '#A4B1D7', borderColor: '#A4B1D7', borderWidth: 1 }, emphasis: { label: { show: !0, color: '#6f778d' }, itemStyle: { color: '#316BF3' }, controlStyle: { color: '#316BF3', borderColor: '#316BF3', borderWidth: 2 } }, progress: { lineStyle: { color: '#316BF3' }, itemStyle: { color: '#316BF3' }, label: { color: '#6f778d' } }, data: [] }), SliderTimelineModel; }(TimelineModel); mixin(SliderTimelineModel, DataFormatMixin.prototype); var TimelineView = function(_super) { function TimelineView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = TimelineView.type, _this; } return __extends(TimelineView, _super), TimelineView.type = 'timeline', TimelineView; }(ComponentView), TimelineAxis = function(_super) { function TimelineAxis(dim, scale, coordExtent, axisType) { var _this = _super.call(this, dim, scale, coordExtent) || this; return _this.type = axisType || 'value', _this; } return __extends(TimelineAxis, _super), TimelineAxis.prototype.getLabelModel = function() { return this.model.getModel('label'); }, TimelineAxis.prototype.isHorizontal = function() { return 'horizontal' === this.model.get('orient'); }, TimelineAxis; }(Axis), PI$8 = Math.PI, labelDataIndexStore = makeInner(), SliderTimelineView = function(_super) { function SliderTimelineView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = SliderTimelineView.type, _this; } return __extends(SliderTimelineView, _super), SliderTimelineView.prototype.init = function(ecModel, api) { this.api = api; }, SliderTimelineView.prototype.render = function(timelineModel, ecModel, api) { if (this.model = timelineModel, this.api = api, this.ecModel = ecModel, this.group.removeAll(), timelineModel.get('show', !0)) { var layoutInfo_1 = this._layout(timelineModel, api), mainGroup_1 = this._createGroup('_mainGroup'), labelGroup = this._createGroup('_labelGroup'), axis_1 = this._axis = this._createAxis(layoutInfo_1, timelineModel); timelineModel.formatTooltip = function(dataIndex) { return createTooltipMarkup('nameValue', { noName: !0, value: axis_1.scale.getLabel({ value: dataIndex }) }); }, each([ 'AxisLine', 'AxisTick', 'Control', 'CurrentPointer' ], function(name) { this['_render' + name](layoutInfo_1, mainGroup_1, axis_1, timelineModel); }, this), this._renderAxisLabel(layoutInfo_1, labelGroup, axis_1, timelineModel), this._position(layoutInfo_1, timelineModel); } this._doPlayStop(), this._updateTicksStatus(); }, SliderTimelineView.prototype.remove = function() { this._clearTimer(), this.group.removeAll(); }, SliderTimelineView.prototype.dispose = function() { this._clearTimer(); }, SliderTimelineView.prototype._layout = function(timelineModel, api) { var parsedLabelPos, playPosition, prevBtnPosition, nextBtnPosition, labelPosOpt = timelineModel.get([ 'label', 'position' ]), orient = timelineModel.get('orient'), viewRect = getLayoutRect(timelineModel.getBoxLayoutParams(), { width: api.getWidth(), height: api.getHeight() }, timelineModel.get('padding')), labelAlignMap = { horizontal: 'center', vertical: (parsedLabelPos = null == labelPosOpt || 'auto' === labelPosOpt ? 'horizontal' === orient ? viewRect.y + viewRect.height / 2 < api.getHeight() / 2 ? '-' : '+' : viewRect.x + viewRect.width / 2 < api.getWidth() / 2 ? '+' : '-' : isString(labelPosOpt) ? ({ horizontal: { top: '-', bottom: '+' }, vertical: { left: '-', right: '+' } })[orient][labelPosOpt] : labelPosOpt) >= 0 || '+' === parsedLabelPos ? 'left' : 'right' }, mainLength = 'vertical' === orient ? viewRect.height : viewRect.width, controlModel = timelineModel.getModel('controlStyle'), showControl = controlModel.get('show', !0), controlSize = showControl ? controlModel.get('itemSize') : 0, controlGap = showControl ? controlModel.get('itemGap') : 0, sizePlusGap = controlSize + controlGap, labelRotation = timelineModel.get([ 'label', 'rotate' ]) || 0; labelRotation = labelRotation * PI$8 / 180; var controlPosition = controlModel.get('position', !0), showPlayBtn = showControl && controlModel.get('showPlayBtn', !0), showPrevBtn = showControl && controlModel.get('showPrevBtn', !0), showNextBtn = showControl && controlModel.get('showNextBtn', !0), xLeft = 0, xRight = mainLength; 'left' === controlPosition || 'bottom' === controlPosition ? (showPlayBtn && (playPosition = [ 0, 0 ], xLeft += sizePlusGap), showPrevBtn && (prevBtnPosition = [ xLeft, 0 ], xLeft += sizePlusGap), showNextBtn && (nextBtnPosition = [ xRight - controlSize, 0 ], xRight -= sizePlusGap)) : (showPlayBtn && (playPosition = [ xRight - controlSize, 0 ], xRight -= sizePlusGap), showPrevBtn && (prevBtnPosition = [ 0, 0 ], xLeft += sizePlusGap), showNextBtn && (nextBtnPosition = [ xRight - controlSize, 0 ], xRight -= sizePlusGap)); var axisExtent = [ xLeft, xRight ]; return timelineModel.get('inverse') && axisExtent.reverse(), { viewRect: viewRect, mainLength: mainLength, orient: orient, rotation: ({ horizontal: 0, vertical: PI$8 / 2 })[orient], labelRotation: labelRotation, labelPosOpt: parsedLabelPos, labelAlign: timelineModel.get([ 'label', 'align' ]) || labelAlignMap[orient], labelBaseline: timelineModel.get([ 'label', 'verticalAlign' ]) || timelineModel.get([ 'label', 'baseline' ]) || ({ horizontal: parsedLabelPos >= 0 || '+' === parsedLabelPos ? 'top' : 'bottom', vertical: 'middle' })[orient], playPosition: playPosition, prevBtnPosition: prevBtnPosition, nextBtnPosition: nextBtnPosition, axisExtent: axisExtent, controlSize: controlSize, controlGap: controlGap }; }, SliderTimelineView.prototype._position = function(layoutInfo, timelineModel) { var mainGroup = this._mainGroup, labelGroup = this._labelGroup, viewRect = layoutInfo.viewRect; if ('vertical' === layoutInfo.orient) { var m = create$1(), rotateOriginX = viewRect.x, rotateOriginY = viewRect.y + viewRect.height; translate(m, m, [ -rotateOriginX, -rotateOriginY ]), rotate(m, m, -PI$8 / 2), translate(m, m, [ rotateOriginX, rotateOriginY ]), (viewRect = viewRect.clone()).applyTransform(m); } var viewBound = getBound(viewRect), mainBound = getBound(mainGroup.getBoundingRect()), labelBound = getBound(labelGroup.getBoundingRect()), mainPosition = [ mainGroup.x, mainGroup.y ], labelsPosition = [ labelGroup.x, labelGroup.y ]; labelsPosition[0] = mainPosition[0] = viewBound[0][0]; var labelPosOpt = layoutInfo.labelPosOpt; if (null == labelPosOpt || isString(labelPosOpt)) { var mainBoundIdx = '+' === labelPosOpt ? 0 : 1; toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx), toBound(labelsPosition, labelBound, viewBound, 1, 1 - mainBoundIdx); } else { var mainBoundIdx = labelPosOpt >= 0 ? 0 : 1; toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx), labelsPosition[1] = mainPosition[1] + labelPosOpt; } function setOrigin(targetGroup) { targetGroup.originX = viewBound[0][0] - targetGroup.x, targetGroup.originY = viewBound[1][0] - targetGroup.y; } function getBound(rect) { return [ [ rect.x, rect.x + rect.width ], [ rect.y, rect.y + rect.height ] ]; } function toBound(fromPos, from, to, dimIdx, boundIdx) { fromPos[dimIdx] += to[dimIdx][boundIdx] - from[dimIdx][boundIdx]; } mainGroup.setPosition(mainPosition), labelGroup.setPosition(labelsPosition), mainGroup.rotation = labelGroup.rotation = layoutInfo.rotation, setOrigin(mainGroup), setOrigin(labelGroup); }, SliderTimelineView.prototype._createAxis = function(layoutInfo, timelineModel) { var data = timelineModel.getData(), axisType = timelineModel.get('axisType'), scale = function(model, axisType) { if (axisType = axisType || model.get('type')) switch(axisType){ case 'category': return new OrdinalScale({ ordinalMeta: model.getCategories(), extent: [ 1 / 0, -1 / 0 ] }); case 'time': return new TimeScale({ locale: model.ecModel.getLocaleModel(), useUTC: model.ecModel.get('useUTC') }); default: return new IntervalScale(); } }(timelineModel, axisType); scale.getTicks = function() { return data.mapArray([ 'value' ], function(value) { return { value: value }; }); }; var dataExtent = data.getDataExtent('value'); scale.setExtent(dataExtent[0], dataExtent[1]), scale.niceTicks(); var axis = new TimelineAxis('value', scale, layoutInfo.axisExtent, axisType); return axis.model = timelineModel, axis; }, SliderTimelineView.prototype._createGroup = function(key) { var newGroup = this[key] = new Group(); return this.group.add(newGroup), newGroup; }, SliderTimelineView.prototype._renderAxisLine = function(layoutInfo, group, axis, timelineModel) { var axisExtent = axis.getExtent(); if (timelineModel.get([ 'lineStyle', 'show' ])) { var line = new Line({ shape: { x1: axisExtent[0], y1: 0, x2: axisExtent[1], y2: 0 }, style: extend({ lineCap: 'round' }, timelineModel.getModel('lineStyle').getLineStyle()), silent: !0, z2: 1 }); group.add(line); var progressLine = this._progressLine = new Line({ shape: { x1: axisExtent[0], x2: this._currentPointer ? this._currentPointer.x : axisExtent[0], y1: 0, y2: 0 }, style: defaults({ lineCap: 'round', lineWidth: line.style.lineWidth }, timelineModel.getModel([ 'progress', 'lineStyle' ]).getLineStyle()), silent: !0, z2: 1 }); group.add(progressLine); } }, SliderTimelineView.prototype._renderAxisTick = function(layoutInfo, group, axis, timelineModel) { var _this = this, data = timelineModel.getData(), ticks = axis.scale.getTicks(); this._tickSymbols = [], each(ticks, function(tick) { var tickCoord = axis.dataToCoord(tick.value), itemModel = data.getItemModel(tick.value), itemStyleModel = itemModel.getModel('itemStyle'), hoverStyleModel = itemModel.getModel([ 'emphasis', 'itemStyle' ]), progressStyleModel = itemModel.getModel([ 'progress', 'itemStyle' ]), el = giveSymbol(itemModel, itemStyleModel, group, { x: tickCoord, y: 0, onclick: bind(_this._changeTimeline, _this, tick.value) }); el.ensureState('emphasis').style = hoverStyleModel.getItemStyle(), el.ensureState('progress').style = progressStyleModel.getItemStyle(), enableHoverEmphasis(el); var ecData = getECData(el); itemModel.get('tooltip') ? (ecData.dataIndex = tick.value, ecData.dataModel = timelineModel) : ecData.dataIndex = ecData.dataModel = null, _this._tickSymbols.push(el); }); }, SliderTimelineView.prototype._renderAxisLabel = function(layoutInfo, group, axis, timelineModel) { var _this = this; if (axis.getLabelModel().get('show')) { var data = timelineModel.getData(), labels = axis.getViewLabels(); this._tickLabels = [], each(labels, function(labelItem) { var dataIndex = labelItem.tickValue, itemModel = data.getItemModel(dataIndex), normalLabelModel = itemModel.getModel('label'), hoverLabelModel = itemModel.getModel([ 'emphasis', 'label' ]), progressLabelModel = itemModel.getModel([ 'progress', 'label' ]), tickCoord = axis.dataToCoord(labelItem.tickValue), textEl = new ZRText({ x: tickCoord, y: 0, rotation: layoutInfo.labelRotation - layoutInfo.rotation, onclick: bind(_this._changeTimeline, _this, dataIndex), silent: !1, style: createTextStyle(normalLabelModel, { text: labelItem.formattedLabel, align: layoutInfo.labelAlign, verticalAlign: layoutInfo.labelBaseline }) }); textEl.ensureState('emphasis').style = createTextStyle(hoverLabelModel), textEl.ensureState('progress').style = createTextStyle(progressLabelModel), group.add(textEl), enableHoverEmphasis(textEl), labelDataIndexStore(textEl).dataIndex = dataIndex, _this._tickLabels.push(textEl); }); } }, SliderTimelineView.prototype._renderControl = function(layoutInfo, group, axis, timelineModel) { var controlSize = layoutInfo.controlSize, rotation = layoutInfo.rotation, itemStyle = timelineModel.getModel('controlStyle').getItemStyle(), hoverStyle = timelineModel.getModel([ 'emphasis', 'controlStyle' ]).getItemStyle(), playState = timelineModel.getPlayState(), inverse = timelineModel.get('inverse', !0); function makeBtn(position, iconName, onclick, willRotate) { if (position) { var rect, opts, style, icon, iconSize = parsePercent(retrieve2(timelineModel.get([ 'controlStyle', iconName + 'BtnSize' ]), controlSize), controlSize), btn = (rect = [ 0, -iconSize / 2, iconSize, iconSize ], style = (opts = { x: position[0], y: position[1], originX: controlSize / 2, originY: 0, rotation: willRotate ? -rotation : 0, rectHover: !0, style: itemStyle, onclick: onclick }).style, icon = createIcon(timelineModel.get([ 'controlStyle', iconName + 'Icon' ]), opts || {}, new BoundingRect(rect[0], rect[1], rect[2], rect[3])), style && icon.setStyle(style), icon); btn.ensureState('emphasis').style = hoverStyle, group.add(btn), enableHoverEmphasis(btn); } } makeBtn(layoutInfo.nextBtnPosition, 'next', bind(this._changeTimeline, this, inverse ? '-' : '+')), makeBtn(layoutInfo.prevBtnPosition, 'prev', bind(this._changeTimeline, this, inverse ? '+' : '-')), makeBtn(layoutInfo.playPosition, playState ? 'stop' : 'play', bind(this._handlePlayClick, this, !playState), !0); }, SliderTimelineView.prototype._renderCurrentPointer = function(layoutInfo, group, axis, timelineModel) { var data = timelineModel.getData(), currentIndex = timelineModel.getCurrentIndex(), pointerModel = data.getItemModel(currentIndex).getModel('checkpointStyle'), me = this; this._currentPointer = giveSymbol(pointerModel, pointerModel, this._mainGroup, {}, this._currentPointer, { onCreate: function(pointer) { pointer.draggable = !0, pointer.drift = bind(me._handlePointerDrag, me), pointer.ondragend = bind(me._handlePointerDragend, me), pointerMoveTo(pointer, me._progressLine, currentIndex, axis, timelineModel, !0); }, onUpdate: function(pointer) { pointerMoveTo(pointer, me._progressLine, currentIndex, axis, timelineModel); } }); }, SliderTimelineView.prototype._handlePlayClick = function(nextState) { this._clearTimer(), this.api.dispatchAction({ type: 'timelinePlayChange', playState: nextState, from: this.uid }); }, SliderTimelineView.prototype._handlePointerDrag = function(dx, dy, e) { this._clearTimer(), this._pointerChangeTimeline([ e.offsetX, e.offsetY ]); }, SliderTimelineView.prototype._handlePointerDragend = function(e) { this._pointerChangeTimeline([ e.offsetX, e.offsetY ], !0); }, SliderTimelineView.prototype._pointerChangeTimeline = function(mousePos, trigger) { var toCoord = this._toAxisCoord(mousePos)[0], axisExtent = asc(this._axis.getExtent().slice()); toCoord > axisExtent[1] && (toCoord = axisExtent[1]), toCoord < axisExtent[0] && (toCoord = axisExtent[0]), this._currentPointer.x = toCoord, this._currentPointer.markRedraw(), this._progressLine.shape.x2 = toCoord, this._progressLine.dirty(); var targetDataIndex = this._findNearestTick(toCoord), timelineModel = this.model; (trigger || targetDataIndex !== timelineModel.getCurrentIndex() && timelineModel.get('realtime')) && this._changeTimeline(targetDataIndex); }, SliderTimelineView.prototype._doPlayStop = function() { var _this = this; this._clearTimer(), this.model.getPlayState() && (this._timer = setTimeout(function() { var timelineModel = _this.model; _this._changeTimeline(timelineModel.getCurrentIndex() + (timelineModel.get('rewind', !0) ? -1 : 1)); }, this.model.get('playInterval'))); }, SliderTimelineView.prototype._toAxisCoord = function(vertex) { return applyTransform$1(vertex, this._mainGroup.getLocalTransform(), !0); }, SliderTimelineView.prototype._findNearestTick = function(axisCoord) { var targetDataIndex, data = this.model.getData(), dist = 1 / 0, axis = this._axis; return data.each([ 'value' ], function(value, dataIndex) { var d = Math.abs(axis.dataToCoord(value) - axisCoord); d < dist && (dist = d, targetDataIndex = dataIndex); }), targetDataIndex; }, SliderTimelineView.prototype._clearTimer = function() { this._timer && (clearTimeout(this._timer), this._timer = null); }, SliderTimelineView.prototype._changeTimeline = function(nextIndex) { var currentIndex = this.model.getCurrentIndex(); '+' === nextIndex ? nextIndex = currentIndex + 1 : '-' === nextIndex && (nextIndex = currentIndex - 1), this.api.dispatchAction({ type: 'timelineChange', currentIndex: nextIndex, from: this.uid }); }, SliderTimelineView.prototype._updateTicksStatus = function() { var currentIndex = this.model.getCurrentIndex(), tickSymbols = this._tickSymbols, tickLabels = this._tickLabels; if (tickSymbols) for(var i = 0; i < tickSymbols.length; i++)tickSymbols && tickSymbols[i] && tickSymbols[i].toggleState('progress', i < currentIndex); if (tickLabels) for(var i = 0; i < tickLabels.length; i++)tickLabels && tickLabels[i] && tickLabels[i].toggleState('progress', labelDataIndexStore(tickLabels[i]).dataIndex <= currentIndex); }, SliderTimelineView.type = 'timeline.slider', SliderTimelineView; }(TimelineView); function giveSymbol(hostModel, itemStyleModel, group, opt, symbol, callback) { var color = itemStyleModel.get('color'); symbol ? (symbol.setColor(color), group.add(symbol), callback && callback.onUpdate(symbol)) : ((symbol = createSymbol(hostModel.get('symbol'), -1, -1, 2, 2, color)).setStyle('strokeNoScale', !0), group.add(symbol), callback && callback.onCreate(symbol)); var itemStyle = itemStyleModel.getItemStyle([ 'color' ]); symbol.setStyle(itemStyle), opt = merge({ rectHover: !0, z2: 100 }, opt, !0); var symbolSize = hostModel.get('symbolSize'); symbolSize = symbolSize instanceof Array ? symbolSize.slice() : [ +symbolSize, +symbolSize ], opt.scaleX = symbolSize[0] / 2, opt.scaleY = symbolSize[1] / 2; var symbolOffset = hostModel.get('symbolOffset'); symbolOffset && (opt.x = opt.x || 0, opt.y = opt.y || 0, opt.x += parsePercent$1(symbolOffset[0], symbolSize[0]), opt.y += parsePercent$1(symbolOffset[1], symbolSize[1])); var symbolRotate = hostModel.get('symbolRotate'); return opt.rotation = (symbolRotate || 0) * Math.PI / 180 || 0, symbol.attr(opt), symbol.updateTransform(), symbol; } function pointerMoveTo(pointer, progressLine, dataIndex, axis, timelineModel, noAnimation) { if (!pointer.dragging) { var pointerModel = timelineModel.getModel('checkpointStyle'), toCoord = axis.dataToCoord(timelineModel.getData().get('value', dataIndex)); if (noAnimation || !pointerModel.get('animation', !0)) pointer.attr({ x: toCoord, y: 0 }), progressLine && progressLine.attr({ shape: { x2: toCoord } }); else { var animationCfg = { duration: pointerModel.get('animationDuration', !0), easing: pointerModel.get('animationEasing', !0) }; pointer.stopAnimation(null, !0), pointer.animateTo({ x: toCoord, y: 0 }, animationCfg), progressLine && progressLine.animateTo({ shape: { x2: toCoord } }, animationCfg); } } } function timelinePreprocessor(option) { var timelineOpt = option && option.timeline; isArray(timelineOpt) || (timelineOpt = timelineOpt ? [ timelineOpt ] : []), each(timelineOpt, function(opt) { opt && function(opt) { var type = opt.type, ec2Types = { number: 'value', time: 'time' }; if (ec2Types[type] && (opt.axisType = ec2Types[type], delete opt.type), transferItem(opt), has(opt, 'controlPosition')) { var controlStyle = opt.controlStyle || (opt.controlStyle = {}); has(controlStyle, 'position') || (controlStyle.position = opt.controlPosition), 'none' !== controlStyle.position || has(controlStyle, 'show') || (controlStyle.show = !1, delete controlStyle.position), delete opt.controlPosition; } each(opt.data || [], function(dataItem) { isObject(dataItem) && !isArray(dataItem) && (!has(dataItem, 'value') && has(dataItem, 'name') && (dataItem.value = dataItem.name), transferItem(dataItem)); }); }(opt); }); } function transferItem(opt) { var itemStyle = opt.itemStyle || (opt.itemStyle = {}), itemStyleEmphasis = itemStyle.emphasis || (itemStyle.emphasis = {}), label = opt.label || opt.label || {}, labelNormal = label.normal || (label.normal = {}), excludeLabelAttr = { normal: 1, emphasis: 1 }; each(label, function(value, name) { excludeLabelAttr[name] || has(labelNormal, name) || (labelNormal[name] = value); }), itemStyleEmphasis.label && !has(label, 'emphasis') && (label.emphasis = itemStyleEmphasis.label, delete itemStyleEmphasis.label); } function has(obj, attr) { return obj.hasOwnProperty(attr); } function checkMarkerInSeries(seriesOpts, markerType) { if (!seriesOpts) return !1; for(var seriesOptArr = isArray(seriesOpts) ? seriesOpts : [ seriesOpts ], idx = 0; idx < seriesOptArr.length; idx++)if (seriesOptArr[idx] && seriesOptArr[idx][markerType]) return !0; return !1; } function fillLabel(opt) { defaultEmphasis(opt, 'label', [ 'show' ]); } var inner$g = makeInner(), MarkerModel = function(_super) { function MarkerModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = MarkerModel.type, _this.createdBySelf = !1, _this; } return __extends(MarkerModel, _super), MarkerModel.prototype.init = function(option, parentModel, ecModel) { if ('marker' === this.type) throw Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.'); this.mergeDefaultAndTheme(option, ecModel), this._mergeOption(option, ecModel, !1, !0); }, MarkerModel.prototype.isAnimationEnabled = function() { if (env1.node) return !1; var hostSeries = this.__hostSeries; return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled(); }, MarkerModel.prototype.mergeOption = function(newOpt, ecModel) { this._mergeOption(newOpt, ecModel, !1, !1); }, MarkerModel.prototype._mergeOption = function(newOpt, ecModel, createdBySelf, isInit) { var componentType = this.mainType; createdBySelf || ecModel.eachSeries(function(seriesModel) { var markerOpt = seriesModel.get(this.mainType, !0), markerModel = inner$g(seriesModel)[componentType]; if (!markerOpt || !markerOpt.data) { inner$g(seriesModel)[componentType] = null; return; } markerModel ? markerModel._mergeOption(markerOpt, ecModel, !0) : (isInit && fillLabel(markerOpt), each(markerOpt.data, function(item) { item instanceof Array ? (fillLabel(item[0]), fillLabel(item[1])) : fillLabel(item); }), extend(markerModel = this.createMarkerModelFromSeries(markerOpt, this, ecModel), { mainType: this.mainType, seriesIndex: seriesModel.seriesIndex, name: seriesModel.name, createdBySelf: !0 }), markerModel.__hostSeries = seriesModel), inner$g(seriesModel)[componentType] = markerModel; }, this); }, MarkerModel.prototype.formatTooltip = function(dataIndex, multipleSeries, dataType) { var data = this.getData(), value = this.getRawValue(dataIndex), itemName = data.getName(dataIndex); return createTooltipMarkup('section', { header: this.name, blocks: [ createTooltipMarkup('nameValue', { name: itemName, value: value, noName: !itemName, noValue: null == value }) ] }); }, MarkerModel.prototype.getData = function() { return this._data; }, MarkerModel.prototype.setData = function(data) { this._data = data; }, MarkerModel.getMarkerModelFromSeries = function(seriesModel, componentType) { return inner$g(seriesModel)[componentType]; }, MarkerModel.type = 'marker', MarkerModel.dependencies = [ 'series', 'grid', 'polar', 'geo' ], MarkerModel; }(ComponentModel); mixin(MarkerModel, DataFormatMixin.prototype); var MarkPointModel = function(_super) { function MarkPointModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = MarkPointModel.type, _this; } return __extends(MarkPointModel, _super), MarkPointModel.prototype.createMarkerModelFromSeries = function(markerOpt, masterMarkerModel, ecModel) { return new MarkPointModel(markerOpt, masterMarkerModel, ecModel); }, MarkPointModel.type = 'markPoint', MarkPointModel.defaultOption = { zlevel: 0, z: 5, symbol: 'pin', symbolSize: 50, tooltip: { trigger: 'item' }, label: { show: !0, position: 'inside' }, itemStyle: { borderWidth: 2 }, emphasis: { label: { show: !0 } } }, MarkPointModel; }(MarkerModel); function markerTypeCalculatorWithExtent(markerType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex) { var coordArr = [], calcDataDim = isDimensionStacked(data, targetDataDim) ? data.getCalculationInfo('stackResultDimension') : targetDataDim, value = numCalculate(data, calcDataDim, markerType), dataIndex = data.indicesOfNearest(calcDataDim, value)[0]; coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex), coordArr[targetCoordIndex] = data.get(calcDataDim, dataIndex); var coordArrValue = data.get(targetDataDim, dataIndex), precision = getPrecision(data.get(targetDataDim, dataIndex)); return (precision = Math.min(precision, 20)) >= 0 && (coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision)), [ coordArr, coordArrValue ]; } var markerTypeCalculator = { min: curry(markerTypeCalculatorWithExtent, 'min'), max: curry(markerTypeCalculatorWithExtent, 'max'), average: curry(markerTypeCalculatorWithExtent, 'average'), median: curry(markerTypeCalculatorWithExtent, 'median') }; function dataTransform(seriesModel, item) { var item1, data = seriesModel.getData(), coordSys = seriesModel.coordinateSystem; if (item && !(!isNaN(parseFloat((item1 = item).x)) && !isNaN(parseFloat(item1.y))) && !isArray(item.coord) && coordSys) { var dims = coordSys.dimensions, axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel); if ((item = clone(item)).type && markerTypeCalculator[item.type] && axisInfo.baseAxis && axisInfo.valueAxis) { var otherCoordIndex = indexOf(dims, axisInfo.baseAxis.dim), targetCoordIndex = indexOf(dims, axisInfo.valueAxis.dim), coordInfo = markerTypeCalculator[item.type](data, axisInfo.baseDataDim, axisInfo.valueDataDim, otherCoordIndex, targetCoordIndex); item.coord = coordInfo[0], item.value = coordInfo[1]; } else { for(var coord = [ null != item.xAxis ? item.xAxis : item.radiusAxis, null != item.yAxis ? item.yAxis : item.angleAxis ], i = 0; i < 2; i++)markerTypeCalculator[coord[i]] && (coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i])); item.coord = coord; } } return item; } function getAxisInfo$1(item, data, coordSys, seriesModel) { var ret = {}; return null != item.valueIndex || null != item.valueDim ? (ret.valueDataDim = null != item.valueIndex ? data.getDimension(item.valueIndex) : item.valueDim, ret.valueAxis = coordSys.getAxis(function(seriesModel, dataDim) { var data = seriesModel.getData(), dimensions = data.dimensions; dataDim = data.getDimension(dataDim); for(var i = 0; i < dimensions.length; i++){ var dimItem = data.getDimensionInfo(dimensions[i]); if (dimItem.name === dataDim) return dimItem.coordDim; } }(seriesModel, ret.valueDataDim)), ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis), ret.baseDataDim = data.mapDimension(ret.baseAxis.dim)) : (ret.baseAxis = seriesModel.getBaseAxis(), ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis), ret.baseDataDim = data.mapDimension(ret.baseAxis.dim), ret.valueDataDim = data.mapDimension(ret.valueAxis.dim)), ret; } function dataFilter$1(coordSys, item) { return !coordSys || !coordSys.containData || !item.coord || !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y))) || coordSys.containData(item.coord); } function dimValueGetter(item, dimName, dataIndex, dimIndex) { return dimIndex < 2 ? item.coord && item.coord[dimIndex] : item.value; } function numCalculate(data, valueDataDim, type) { if ('average' === type) { var sum_1 = 0, count_1 = 0; return data.each(valueDataDim, function(val, idx) { !isNaN(val) && (sum_1 += val, count_1++); }), sum_1 / count_1; } return 'median' === type ? data.getMedian(valueDataDim) : data.getDataExtent(valueDataDim)['max' === type ? 1 : 0]; } var inner$h = makeInner(), MarkerView = function(_super) { function MarkerView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = MarkerView.type, _this; } return __extends(MarkerView, _super), MarkerView.prototype.init = function() { this.markerGroupMap = createHashMap(); }, MarkerView.prototype.render = function(markerModel, ecModel, api) { var _this = this, markerGroupMap = this.markerGroupMap; markerGroupMap.each(function(item) { inner$h(item).keep = !1; }), ecModel.eachSeries(function(seriesModel) { var markerModel = MarkerModel.getMarkerModelFromSeries(seriesModel, _this.type); markerModel && _this.renderSeries(seriesModel, markerModel, ecModel, api); }), markerGroupMap.each(function(item) { inner$h(item).keep || _this.group.remove(item.group); }); }, MarkerView.prototype.markKeep = function(drawGroup) { inner$h(drawGroup).keep = !0; }, MarkerView.prototype.blurSeries = function(seriesModelList) { var _this = this; each(seriesModelList, function(seriesModel) { var markerModel = MarkerModel.getMarkerModelFromSeries(seriesModel, _this.type); markerModel && markerModel.getData().eachItemGraphicEl(function(el) { el && traverseUpdateState(el, singleEnterBlur); }); }); }, MarkerView.type = 'marker', MarkerView; }(ComponentView); function updateMarkerLayout(mpData, seriesModel, api) { var coordSys = seriesModel.coordinateSystem; mpData.each(function(idx) { var point, itemModel = mpData.getItemModel(idx), xPx = parsePercent$1(itemModel.get('x'), api.getWidth()), yPx = parsePercent$1(itemModel.get('y'), api.getHeight()); if (isNaN(xPx) || isNaN(yPx)) { if (seriesModel.getMarkerPosition) point = seriesModel.getMarkerPosition(mpData.getValues(mpData.dimensions, idx)); else if (coordSys) { var x = mpData.get(coordSys.dimensions[0], idx), y = mpData.get(coordSys.dimensions[1], idx); point = coordSys.dataToPoint([ x, y ]); } } else point = [ xPx, yPx ]; isNaN(xPx) || (point[0] = xPx), isNaN(yPx) || (point[1] = yPx), mpData.setItemLayout(idx, point); }); } var MarkPointView = function(_super) { function MarkPointView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = MarkPointView.type, _this; } return __extends(MarkPointView, _super), MarkPointView.prototype.updateTransform = function(markPointModel, ecModel, api) { ecModel.eachSeries(function(seriesModel) { var mpModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markPoint'); mpModel && (updateMarkerLayout(mpModel.getData(), seriesModel, api), this.markerGroupMap.get(seriesModel.id).updateLayout()); }, this); }, MarkPointView.prototype.renderSeries = function(seriesModel, mpModel, ecModel, api) { var coordDimsInfos, mpData, dataOpt, coordSys = seriesModel.coordinateSystem, seriesId = seriesModel.id, seriesData = seriesModel.getData(), symbolDrawMap = this.markerGroupMap, symbolDraw = symbolDrawMap.get(seriesId) || symbolDrawMap.set(seriesId, new SymbolDraw()), mpData1 = (coordDimsInfos = coordSys ? map(coordSys && coordSys.dimensions, function(coordDim) { var info = seriesModel.getData().getDimensionInfo(seriesModel.getData().mapDimension(coordDim)) || {}; return defaults({ name: coordDim }, info); }) : [ { name: 'value', type: 'float' } ], mpData = new List(coordDimsInfos, mpModel), dataOpt = map(mpModel.get('data'), curry(dataTransform, seriesModel)), coordSys && (dataOpt = filter(dataOpt, curry(dataFilter$1, coordSys))), mpData.initData(dataOpt, null, coordSys ? dimValueGetter : function(item) { return item.value; }), mpData); mpModel.setData(mpData1), updateMarkerLayout(mpModel.getData(), seriesModel, api), mpData1.each(function(idx) { var itemModel = mpData1.getItemModel(idx), symbol = itemModel.getShallow('symbol'), symbolSize = itemModel.getShallow('symbolSize'), symbolRotate = itemModel.getShallow('symbolRotate'); if (isFunction(symbol) || isFunction(symbolSize) || isFunction(symbolRotate)) { var rawIdx = mpModel.getRawValue(idx), dataParams = mpModel.getDataParams(idx); isFunction(symbol) && (symbol = symbol(rawIdx, dataParams)), isFunction(symbolSize) && (symbolSize = symbolSize(rawIdx, dataParams)), isFunction(symbolRotate) && (symbolRotate = symbolRotate(rawIdx, dataParams)); } var style = itemModel.getModel('itemStyle').getItemStyle(), color = getVisualFromData(seriesData, 'color'); style.fill || (style.fill = color), mpData1.setItemVisual(idx, { symbol: symbol, symbolSize: symbolSize, symbolRotate: symbolRotate, style: style }); }), symbolDraw.updateData(mpData1), this.group.add(symbolDraw.group), mpData1.eachItemGraphicEl(function(el) { el.traverse(function(child) { getECData(child).dataModel = mpModel; }); }), this.markKeep(symbolDraw), symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent'); }, MarkPointView.type = 'markPoint', MarkPointView; }(MarkerView), MarkLineModel = function(_super) { function MarkLineModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = MarkLineModel.type, _this; } return __extends(MarkLineModel, _super), MarkLineModel.prototype.createMarkerModelFromSeries = function(markerOpt, masterMarkerModel, ecModel) { return new MarkLineModel(markerOpt, masterMarkerModel, ecModel); }, MarkLineModel.type = 'markLine', MarkLineModel.defaultOption = { zlevel: 0, z: 5, symbol: [ 'circle', 'arrow' ], symbolSize: [ 8, 16 ], symbolOffset: 0, precision: 2, tooltip: { trigger: 'item' }, label: { show: !0, position: 'end', distance: 5 }, lineStyle: { type: 'dashed' }, emphasis: { label: { show: !0 }, lineStyle: { width: 3 } }, animationEasing: 'linear' }, MarkLineModel; }(MarkerModel), inner$i = makeInner(), markLineTransform = function(seriesModel, coordSys, mlModel, item) { var itemArray, data = seriesModel.getData(); if (isArray(item)) itemArray = item; else { var mlType = item.type; if ('min' === mlType || 'max' === mlType || 'average' === mlType || 'median' === mlType || null != item.xAxis || null != item.yAxis) { var valueAxis = void 0, value = void 0; if (null != item.yAxis || null != item.xAxis) valueAxis = coordSys.getAxis(null != item.yAxis ? 'y' : 'x'), value = retrieve(item.yAxis, item.xAxis); else { var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel); valueAxis = axisInfo.valueAxis; var valueDataDim = getStackedDimension(data, axisInfo.valueDataDim); value = numCalculate(data, valueDataDim, mlType); } var valueIndex = 'x' === valueAxis.dim ? 0 : 1, baseIndex = 1 - valueIndex, mlFrom = clone(item), mlTo = { coord: [] }; mlFrom.type = null, mlFrom.coord = [], mlFrom.coord[baseIndex] = -1 / 0, mlTo.coord[baseIndex] = 1 / 0; var precision = mlModel.get('precision'); precision >= 0 && 'number' == typeof value && (value = +value.toFixed(Math.min(precision, 20))), mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value, itemArray = [ mlFrom, mlTo, { type: mlType, valueIndex: item.valueIndex, value: value } ]; } else logError('Invalid markLine data.'), itemArray = []; } var normalizedItem = [ dataTransform(seriesModel, itemArray[0]), dataTransform(seriesModel, itemArray[1]), extend({}, itemArray[2]) ]; return normalizedItem[2].type = normalizedItem[2].type || null, merge(normalizedItem[2], normalizedItem[0]), merge(normalizedItem[2], normalizedItem[1]), normalizedItem; }; function isInifinity(val) { return !isNaN(val) && !isFinite(val); } function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) { var otherDimIndex = 1 - dimIndex, dimName = coordSys.dimensions[dimIndex]; return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex]) && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]); } function markLineFilter(coordSys, item) { if ('cartesian2d' === coordSys.type) { var fromCoord = item[0].coord, toCoord = item[1].coord; if (fromCoord && toCoord && (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys) || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))) return !0; } return dataFilter$1(coordSys, item[0]) && dataFilter$1(coordSys, item[1]); } function updateSingleMarkerEndLayout(data, idx, isFrom, seriesModel, api) { var point, coordSys = seriesModel.coordinateSystem, itemModel = data.getItemModel(idx), xPx = parsePercent$1(itemModel.get('x'), api.getWidth()), yPx = parsePercent$1(itemModel.get('y'), api.getHeight()); if (isNaN(xPx) || isNaN(yPx)) { if (seriesModel.getMarkerPosition) point = seriesModel.getMarkerPosition(data.getValues(data.dimensions, idx)); else { var dims = coordSys.dimensions, x = data.get(dims[0], idx), y = data.get(dims[1], idx); point = coordSys.dataToPoint([ x, y ]); } if (isCoordinateSystemType(coordSys, 'cartesian2d')) { var xAxis = coordSys.getAxis('x'), yAxis = coordSys.getAxis('y'), dims = coordSys.dimensions; isInifinity(data.get(dims[0], idx)) ? point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]) : isInifinity(data.get(dims[1], idx)) && (point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1])); } isNaN(xPx) || (point[0] = xPx), isNaN(yPx) || (point[1] = yPx); } else point = [ xPx, yPx ]; data.setItemLayout(idx, point); } var MarkLineView = function(_super) { function MarkLineView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = MarkLineView.type, _this; } return __extends(MarkLineView, _super), MarkLineView.prototype.updateTransform = function(markLineModel, ecModel, api) { ecModel.eachSeries(function(seriesModel) { var mlModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markLine'); if (mlModel) { var mlData_1 = mlModel.getData(), fromData_1 = inner$i(mlModel).from, toData_1 = inner$i(mlModel).to; fromData_1.each(function(idx) { updateSingleMarkerEndLayout(fromData_1, idx, !0, seriesModel, api), updateSingleMarkerEndLayout(toData_1, idx, !1, seriesModel, api); }), mlData_1.each(function(idx) { mlData_1.setItemLayout(idx, [ fromData_1.getItemLayout(idx), toData_1.getItemLayout(idx) ]); }), this.markerGroupMap.get(seriesModel.id).updateLayout(); } }, this); }, MarkLineView.prototype.renderSeries = function(seriesModel, mlModel, ecModel, api) { var coordDimsInfos, fromData, toData, lineData, optData, dimValueGetter$1, coordSys = seriesModel.coordinateSystem, seriesId = seriesModel.id, seriesData = seriesModel.getData(), lineDrawMap = this.markerGroupMap, lineDraw = lineDrawMap.get(seriesId) || lineDrawMap.set(seriesId, new LineDraw()); this.group.add(lineDraw.group); var mlData = (coordDimsInfos = coordSys ? map(coordSys && coordSys.dimensions, function(coordDim) { var info = seriesModel.getData().getDimensionInfo(seriesModel.getData().mapDimension(coordDim)) || {}; return defaults({ name: coordDim }, info); }) : [ { name: 'value', type: 'float' } ], fromData = new List(coordDimsInfos, mlModel), toData = new List(coordDimsInfos, mlModel), lineData = new List([], mlModel), optData = map(mlModel.get('data'), curry(markLineTransform, seriesModel, coordSys, mlModel)), coordSys && (optData = filter(optData, curry(markLineFilter, coordSys))), dimValueGetter$1 = coordSys ? dimValueGetter : function(item) { return item.value; }, fromData.initData(map(optData, function(item) { return item[0]; }), null, dimValueGetter$1), toData.initData(map(optData, function(item) { return item[1]; }), null, dimValueGetter$1), lineData.initData(map(optData, function(item) { return item[2]; })), lineData.hasItemOption = !0, { from: fromData, to: toData, line: lineData }), fromData1 = mlData.from, toData1 = mlData.to, lineData1 = mlData.line; inner$i(mlModel).from = fromData1, inner$i(mlModel).to = toData1, mlModel.setData(lineData1); var symbolType = mlModel.get('symbol'), symbolSize = mlModel.get('symbolSize'), symbolRotate = mlModel.get('symbolRotate'), symbolOffset = mlModel.get('symbolOffset'); function updateDataVisualAndLayout(data, idx, isFrom) { var itemModel = data.getItemModel(idx); updateSingleMarkerEndLayout(data, idx, isFrom, seriesModel, api); var style = itemModel.getModel('itemStyle').getItemStyle(); null == style.fill && (style.fill = getVisualFromData(seriesData, 'color')), data.setItemVisual(idx, { symbolKeepAspect: itemModel.get('symbolKeepAspect'), symbolOffset: retrieve2(itemModel.get('symbolOffset'), symbolOffset[isFrom ? 0 : 1]), symbolRotate: retrieve2(itemModel.get('symbolRotate', !0), symbolRotate[isFrom ? 0 : 1]), symbolSize: retrieve2(itemModel.get('symbolSize'), symbolSize[isFrom ? 0 : 1]), symbol: retrieve2(itemModel.get('symbol', !0), symbolType[isFrom ? 0 : 1]), style: style }); } isArray(symbolType) || (symbolType = [ symbolType, symbolType ]), isArray(symbolSize) || (symbolSize = [ symbolSize, symbolSize ]), isArray(symbolRotate) || (symbolRotate = [ symbolRotate, symbolRotate ]), isArray(symbolOffset) || (symbolOffset = [ symbolOffset, symbolOffset ]), mlData.from.each(function(idx) { updateDataVisualAndLayout(fromData1, idx, !0), updateDataVisualAndLayout(toData1, idx, !1); }), lineData1.each(function(idx) { var lineStyle = lineData1.getItemModel(idx).getModel('lineStyle').getLineStyle(); lineData1.setItemLayout(idx, [ fromData1.getItemLayout(idx), toData1.getItemLayout(idx) ]), null == lineStyle.stroke && (lineStyle.stroke = fromData1.getItemVisual(idx, 'style').fill), lineData1.setItemVisual(idx, { fromSymbolKeepAspect: fromData1.getItemVisual(idx, 'symbolKeepAspect'), fromSymbolOffset: fromData1.getItemVisual(idx, 'symbolOffset'), fromSymbolRotate: fromData1.getItemVisual(idx, 'symbolRotate'), fromSymbolSize: fromData1.getItemVisual(idx, 'symbolSize'), fromSymbol: fromData1.getItemVisual(idx, 'symbol'), toSymbolKeepAspect: toData1.getItemVisual(idx, 'symbolKeepAspect'), toSymbolOffset: toData1.getItemVisual(idx, 'symbolOffset'), toSymbolRotate: toData1.getItemVisual(idx, 'symbolRotate'), toSymbolSize: toData1.getItemVisual(idx, 'symbolSize'), toSymbol: toData1.getItemVisual(idx, 'symbol'), style: lineStyle }); }), lineDraw.updateData(lineData1), mlData.line.eachItemGraphicEl(function(el, idx) { el.traverse(function(child) { getECData(child).dataModel = mlModel; }); }), this.markKeep(lineDraw), lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent'); }, MarkLineView.type = 'markLine', MarkLineView; }(MarkerView), MarkAreaModel = function(_super) { function MarkAreaModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = MarkAreaModel.type, _this; } return __extends(MarkAreaModel, _super), MarkAreaModel.prototype.createMarkerModelFromSeries = function(markerOpt, masterMarkerModel, ecModel) { return new MarkAreaModel(markerOpt, masterMarkerModel, ecModel); }, MarkAreaModel.type = 'markArea', MarkAreaModel.defaultOption = { zlevel: 0, z: 1, tooltip: { trigger: 'item' }, animation: !1, label: { show: !0, position: 'top' }, itemStyle: { borderWidth: 0 }, emphasis: { label: { show: !0, position: 'top' } } }, MarkAreaModel; }(MarkerModel), inner$j = makeInner(), markAreaTransform = function(seriesModel, coordSys, maModel, item) { var lt = dataTransform(seriesModel, item[0]), rb = dataTransform(seriesModel, item[1]), ltCoord = lt.coord, rbCoord = rb.coord; ltCoord[0] = retrieve(ltCoord[0], -1 / 0), ltCoord[1] = retrieve(ltCoord[1], -1 / 0), rbCoord[0] = retrieve(rbCoord[0], 1 / 0), rbCoord[1] = retrieve(rbCoord[1], 1 / 0); var result = mergeAll([ {}, lt, rb ]); return result.coord = [ lt.coord, rb.coord ], result.x0 = lt.x, result.y0 = lt.y, result.x1 = rb.x, result.y1 = rb.y, result; }; function isInifinity$1(val) { return !isNaN(val) && !isFinite(val); } function ifMarkAreaHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) { var otherDimIndex = 1 - dimIndex; return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]); } function markAreaFilter(coordSys, item) { var fromCoord = item.coord[0], toCoord = item.coord[1]; return !!(isCoordinateSystemType(coordSys, 'cartesian2d') && fromCoord && toCoord && (ifMarkAreaHasOnlyDim(1, fromCoord, toCoord) || ifMarkAreaHasOnlyDim(0, fromCoord, toCoord))) || dataFilter$1(coordSys, { coord: fromCoord, x: item.x0, y: item.y0 }) || dataFilter$1(coordSys, { coord: toCoord, x: item.x1, y: item.y1 }); } function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) { var point, coordSys = seriesModel.coordinateSystem, itemModel = data.getItemModel(idx), xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth()), yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight()); if (isNaN(xPx) || isNaN(yPx)) { if (seriesModel.getMarkerPosition) point = seriesModel.getMarkerPosition(data.getValues(dims, idx)); else { var x = data.get(dims[0], idx), y = data.get(dims[1], idx), pt = [ x, y ]; coordSys.clampData && coordSys.clampData(pt, pt), point = coordSys.dataToPoint(pt, !0); } if (isCoordinateSystemType(coordSys, 'cartesian2d')) { var xAxis = coordSys.getAxis('x'), yAxis = coordSys.getAxis('y'), x = data.get(dims[0], idx), y = data.get(dims[1], idx); isInifinity$1(x) ? point[0] = xAxis.toGlobalCoord(xAxis.getExtent()['x0' === dims[0] ? 0 : 1]) : isInifinity$1(y) && (point[1] = yAxis.toGlobalCoord(yAxis.getExtent()['y0' === dims[1] ? 0 : 1])); } isNaN(xPx) || (point[0] = xPx), isNaN(yPx) || (point[1] = yPx); } else point = [ xPx, yPx ]; return point; } var dimPermutations = [ [ 'x0', 'y0' ], [ 'x1', 'y0' ], [ 'x1', 'y1' ], [ 'x0', 'y1' ] ], MarkAreaView = function(_super) { function MarkAreaView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = MarkAreaView.type, _this; } return __extends(MarkAreaView, _super), MarkAreaView.prototype.updateTransform = function(markAreaModel, ecModel, api) { ecModel.eachSeries(function(seriesModel) { var maModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markArea'); if (maModel) { var areaData_1 = maModel.getData(); areaData_1.each(function(idx) { var points = map(dimPermutations, function(dim) { return getSingleMarkerEndPoint(areaData_1, idx, dim, seriesModel, api); }); areaData_1.setItemLayout(idx, points), areaData_1.getItemGraphicEl(idx).setShape('points', points); }); } }, this); }, MarkAreaView.prototype.renderSeries = function(seriesModel, maModel, ecModel, api) { var coordDimsInfos, areaData, optData, coordSys = seriesModel.coordinateSystem, seriesId = seriesModel.id, seriesData = seriesModel.getData(), areaGroupMap = this.markerGroupMap, polygonGroup = areaGroupMap.get(seriesId) || areaGroupMap.set(seriesId, { group: new Group() }); this.group.add(polygonGroup.group), this.markKeep(polygonGroup); var areaData1 = (coordSys ? (coordDimsInfos = map(coordSys && coordSys.dimensions, function(coordDim) { var data = seriesModel.getData(), info = data.getDimensionInfo(data.mapDimension(coordDim)) || {}; return defaults({ name: coordDim }, info); }), areaData = new List(map([ 'x0', 'y0', 'x1', 'y1' ], function(dim, idx) { return { name: dim, type: coordDimsInfos[idx % 2].type }; }), maModel)) : (coordDimsInfos = [ { name: 'value', type: 'float' } ], areaData = new List(coordDimsInfos, maModel)), optData = map(maModel.get('data'), curry(markAreaTransform, seriesModel, coordSys, maModel)), coordSys && (optData = filter(optData, curry(markAreaFilter, coordSys))), areaData.initData(optData, null, coordSys ? function(item, dimName, dataIndex, dimIndex) { return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2]; } : function(item) { return item.value; }), areaData.hasItemOption = !0, areaData); maModel.setData(areaData1), areaData1.each(function(idx) { var points = map(dimPermutations, function(dim) { return getSingleMarkerEndPoint(areaData1, idx, dim, seriesModel, api); }), xAxisScale = coordSys.getAxis('x').scale, yAxisScale = coordSys.getAxis('y').scale, xAxisExtent = xAxisScale.getExtent(), yAxisExtent = yAxisScale.getExtent(), xPointExtent = [ xAxisScale.parse(areaData1.get('x0', idx)), xAxisScale.parse(areaData1.get('x1', idx)) ], yPointExtent = [ yAxisScale.parse(areaData1.get('y0', idx)), yAxisScale.parse(areaData1.get('y1', idx)) ]; asc(xPointExtent), asc(yPointExtent); var overlapped = !(xAxisExtent[0] > xPointExtent[1] || xAxisExtent[1] < xPointExtent[0] || yAxisExtent[0] > yPointExtent[1] || yAxisExtent[1] < yPointExtent[0]); areaData1.setItemLayout(idx, { points: points, allClipped: !overlapped }); var style = areaData1.getItemModel(idx).getModel('itemStyle').getItemStyle(), color$1 = getVisualFromData(seriesData, 'color'); style.fill || (style.fill = color$1, 'string' == typeof style.fill && (style.fill = modifyAlpha(style.fill, 0.4))), style.stroke || (style.stroke = color$1), areaData1.setItemVisual(idx, 'style', style); }), areaData1.diff(inner$j(polygonGroup).data).add(function(idx) { var layout = areaData1.getItemLayout(idx); if (!layout.allClipped) { var polygon = new Polygon({ shape: { points: layout.points } }); areaData1.setItemGraphicEl(idx, polygon), polygonGroup.group.add(polygon); } }).update(function(newIdx, oldIdx) { var polygon = inner$j(polygonGroup).data.getItemGraphicEl(oldIdx), layout = areaData1.getItemLayout(newIdx); layout.allClipped ? polygon && polygonGroup.group.remove(polygon) : (polygon ? updateProps(polygon, { shape: { points: layout.points } }, maModel, newIdx) : polygon = new Polygon({ shape: { points: layout.points } }), areaData1.setItemGraphicEl(newIdx, polygon), polygonGroup.group.add(polygon)); }).remove(function(idx) { var polygon = inner$j(polygonGroup).data.getItemGraphicEl(idx); polygonGroup.group.remove(polygon); }).execute(), areaData1.eachItemGraphicEl(function(polygon, idx) { var itemModel = areaData1.getItemModel(idx), style = areaData1.getItemVisual(idx, 'style'); polygon.useStyle(areaData1.getItemVisual(idx, 'style')), setLabelStyle(polygon, getLabelStatesModels(itemModel), { labelFetcher: maModel, labelDataIndex: idx, defaultText: areaData1.getName(idx) || '', inheritColor: 'string' == typeof style.fill ? modifyAlpha(style.fill, 1) : '#000' }), setStatesStylesFromModel(polygon, itemModel), enableHoverEmphasis(polygon), getECData(polygon).dataModel = maModel; }), inner$j(polygonGroup).data = areaData1, polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent'); }, MarkAreaView.type = 'markArea', MarkAreaView; }(MarkerView), LegendModel = function(_super) { function LegendModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = LegendModel.type, _this.layoutMode = { type: 'box', ignoreSize: !0 }, _this; } return __extends(LegendModel, _super), LegendModel.prototype.init = function(option, parentModel, ecModel) { this.mergeDefaultAndTheme(option, ecModel), option.selected = option.selected || {}, this._updateSelector(option); }, LegendModel.prototype.mergeOption = function(option, ecModel) { _super.prototype.mergeOption.call(this, option, ecModel), this._updateSelector(option); }, LegendModel.prototype._updateSelector = function(option) { var selector = option.selector, ecModel = this.ecModel; !0 === selector && (selector = option.selector = [ 'all', 'inverse' ]), isArray(selector) && each(selector, function(item, index) { var type; isString(item) && (item = { type: item }), selector[index] = merge(item, 'all' === (type = item.type) ? { type: 'all', title: ecModel.getLocale([ 'legend', 'selector', 'all' ]) } : 'inverse' === type ? { type: 'inverse', title: ecModel.getLocale([ 'legend', 'selector', 'inverse' ]) } : void 0); }); }, LegendModel.prototype.optionUpdated = function() { this._updateData(this.ecModel); var legendData = this._data; if (legendData[0] && 'single' === this.get('selectedMode')) { for(var hasSelected = !1, i = 0; i < legendData.length; i++){ var name_1 = legendData[i].get('name'); if (this.isSelected(name_1)) { this.select(name_1), hasSelected = !0; break; } } hasSelected || this.select(legendData[0].get('name')); } }, LegendModel.prototype._updateData = function(ecModel) { var potentialData = [], availableNames = []; ecModel.eachRawSeries(function(seriesModel) { var isPotential, seriesName = seriesModel.name; if (availableNames.push(seriesName), seriesModel.legendVisualProvider) { var names = seriesModel.legendVisualProvider.getAllNames(); ecModel.isSeriesFiltered(seriesModel) || (availableNames = availableNames.concat(names)), names.length ? potentialData = potentialData.concat(names) : isPotential = !0; } else isPotential = !0; isPotential && isNameSpecified(seriesModel) && potentialData.push(seriesModel.name); }), this._availableNames = availableNames; var legendData = map(this.get('data') || potentialData, function(dataItem) { return ('string' == typeof dataItem || 'number' == typeof dataItem) && (dataItem = { name: dataItem }), new Model(dataItem, this, this.ecModel); }, this); this._data = legendData; }, LegendModel.prototype.getData = function() { return this._data; }, LegendModel.prototype.select = function(name) { var selected = this.option.selected; 'single' === this.get('selectedMode') && each(this._data, function(dataItem) { selected[dataItem.get('name')] = !1; }), selected[name] = !0; }, LegendModel.prototype.unSelect = function(name) { 'single' !== this.get('selectedMode') && (this.option.selected[name] = !1); }, LegendModel.prototype.toggleSelected = function(name) { var selected = this.option.selected; selected.hasOwnProperty(name) || (selected[name] = !0), this[selected[name] ? 'unSelect' : 'select'](name); }, LegendModel.prototype.allSelect = function() { var data = this._data, selected = this.option.selected; each(data, function(dataItem) { selected[dataItem.get('name', !0)] = !0; }); }, LegendModel.prototype.inverseSelect = function() { var data = this._data, selected = this.option.selected; each(data, function(dataItem) { var name = dataItem.get('name', !0); selected.hasOwnProperty(name) || (selected[name] = !0), selected[name] = !selected[name]; }); }, LegendModel.prototype.isSelected = function(name) { var selected = this.option.selected; return !(selected.hasOwnProperty(name) && !selected[name]) && indexOf(this._availableNames, name) >= 0; }, LegendModel.prototype.getOrient = function() { return 'vertical' === this.get('orient') ? { index: 1, name: 'vertical' } : { index: 0, name: 'horizontal' }; }, LegendModel.type = 'legend.plain', LegendModel.dependencies = [ 'series' ], LegendModel.defaultOption = { zlevel: 0, z: 4, show: !0, orient: 'horizontal', left: 'center', top: 0, align: 'auto', backgroundColor: 'rgba(0,0,0,0)', borderColor: '#ccc', borderRadius: 0, borderWidth: 0, padding: 5, itemGap: 10, itemWidth: 25, itemHeight: 14, symbolSize: 'auto', inactiveColor: '#ccc', inactiveBorderColor: '#ccc', inactiveBorderWidth: 'auto', itemStyle: { color: 'inherit', opacity: 'inherit', decal: 'inherit', shadowBlur: 0, shadowColor: null, shadowOffsetX: 0, shadowOffsetY: 0, borderColor: 'inherit', borderWidth: 'auto', borderCap: 'inherit', borderJoin: 'inherit', borderDashOffset: 'inherit', borderMiterLimit: 'inherit' }, lineStyle: { width: 'auto', color: 'inherit', inactiveColor: '#ccc', inactiveWidth: 2, opacity: 'inherit', type: 'inherit', cap: 'inherit', join: 'inherit', dashOffset: 'inherit', miterLimit: 'inherit', shadowBlur: 0, shadowColor: null, shadowOffsetX: 0, shadowOffsetY: 0 }, textStyle: { color: '#333' }, selectedMode: !0, selector: !1, selectorLabel: { show: !0, borderRadius: 10, padding: [ 3, 5, 3, 5 ], fontSize: 12, fontFamily: ' sans-serif', color: '#666', borderWidth: 1, borderColor: '#666' }, emphasis: { selectorLabel: { show: !0, color: '#eee', backgroundColor: '#666' } }, selectorPosition: 'auto', selectorItemGap: 7, selectorButtonGap: 10, tooltip: { show: !1 } }, LegendModel; }(ComponentModel), LegendView = function(_super) { function LegendView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = LegendView.type, _this.newlineDisabled = !1, _this; } return __extends(LegendView, _super), LegendView.prototype.init = function() { this.group.add(this._contentGroup = new Group()), this.group.add(this._selectorGroup = new Group()), this._isFirstRender = !0; }, LegendView.prototype.getContentGroup = function() { return this._contentGroup; }, LegendView.prototype.getSelectorGroup = function() { return this._selectorGroup; }, LegendView.prototype.render = function(legendModel, ecModel, api) { var isFirstRender = this._isFirstRender; if (this._isFirstRender = !1, this.resetInner(), legendModel.get('show', !0)) { var itemAlign = legendModel.get('align'), orient = legendModel.get('orient'); itemAlign && 'auto' !== itemAlign || (itemAlign = 'right' === legendModel.get('left') && 'vertical' === orient ? 'right' : 'left'); var selector = legendModel.get('selector', !0), selectorPosition = legendModel.get('selectorPosition', !0); selector && (!selectorPosition || 'auto' === selectorPosition) && (selectorPosition = 'horizontal' === orient ? 'end' : 'start'), this.renderInner(itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition); var positionInfo = legendModel.getBoxLayoutParams(), viewportSize = { width: api.getWidth(), height: api.getHeight() }, padding = legendModel.get('padding'), maxSize = getLayoutRect(positionInfo, viewportSize, padding), mainRect = this.layoutInner(legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition), layoutRect = getLayoutRect(defaults({ width: mainRect.width, height: mainRect.height }, positionInfo), viewportSize, padding); this.group.x = layoutRect.x - mainRect.x, this.group.y = layoutRect.y - mainRect.y, this.group.markRedraw(), this.group.add(this._backgroundEl = makeBackground(mainRect, legendModel)); } }, LegendView.prototype.resetInner = function() { this.getContentGroup().removeAll(), this._backgroundEl && this.group.remove(this._backgroundEl), this.getSelectorGroup().removeAll(); }, LegendView.prototype.renderInner = function(itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) { var contentGroup = this.getContentGroup(), legendDrawnMap = createHashMap(), selectMode = legendModel.get('selectedMode'), excludeSeriesId = []; ecModel.eachRawSeries(function(seriesModel) { seriesModel.get('legendHoverLink') || excludeSeriesId.push(seriesModel.id); }), each(legendModel.getData(), function(legendItemModel, dataIndex) { var name = legendItemModel.get('name'); if (!this.newlineDisabled && ('' === name || '\n' === name)) { var g = new Group(); g.newline = !0, contentGroup.add(g); return; } var seriesModel = ecModel.getSeriesByName(name)[0]; if (!legendDrawnMap.get(name)) { if (seriesModel) { var data = seriesModel.getData(), lineVisualStyle = data.getVisual('legendLineStyle') || {}, symbolType = data.getVisual('legendSymbol'), style = data.getVisual('style'); data.getVisual('symbolSize'), this._createItem(seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, lineVisualStyle, style, symbolType, selectMode).on('click', curry(dispatchSelectAction, name, null, api, excludeSeriesId)).on('mouseover', curry(dispatchHighlightAction, seriesModel.name, null, api, excludeSeriesId)).on('mouseout', curry(dispatchDownplayAction, seriesModel.name, null, api, excludeSeriesId)), legendDrawnMap.set(name, !0); } else ecModel.eachRawSeries(function(seriesModel) { if (!legendDrawnMap.get(name) && seriesModel.legendVisualProvider) { var provider = seriesModel.legendVisualProvider; if (provider.containName(name)) { var idx = provider.indexOfName(name), style = provider.getItemVisual(idx, 'style'), symbolType = provider.getItemVisual(idx, 'legendSymbol'), colorArr = parse(style.fill); colorArr && 0 === colorArr[3] && (colorArr[3] = 0.2, style.fill = stringify(colorArr, 'rgba')), this._createItem(seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, {}, style, symbolType, selectMode).on('click', curry(dispatchSelectAction, null, name, api, excludeSeriesId)).on('mouseover', curry(dispatchHighlightAction, null, name, api, excludeSeriesId)).on('mouseout', curry(dispatchDownplayAction, null, name, api, excludeSeriesId)), legendDrawnMap.set(name, !0); } } }, this); legendDrawnMap.get(name) || console.warn(name + ' series not exists. Legend data should be same with series name or data name.'); } }, this), selector && this._createSelector(selector, legendModel, api, orient, selectorPosition); }, LegendView.prototype._createSelector = function(selector, legendModel, api, orient, selectorPosition) { var selectorGroup = this.getSelectorGroup(); each(selector, function(selectorItem) { var type = selectorItem.type, labelText = new ZRText({ style: { x: 0, y: 0, align: 'center', verticalAlign: 'middle' }, onclick: function() { api.dispatchAction({ type: 'all' === type ? 'legendAllSelect' : 'legendInverseSelect' }); } }); selectorGroup.add(labelText), setLabelStyle(labelText, { normal: legendModel.getModel('selectorLabel'), emphasis: legendModel.getModel([ 'emphasis', 'selectorLabel' ]) }, { defaultText: selectorItem.title }), enableHoverEmphasis(labelText); }); }, LegendView.prototype._createItem = function(seriesModel, name, dataIndex, itemModel, legendModel, itemAlign, lineVisualStyle, itemVisualStyle, symbolType, selectMode) { var opt, symboType, symbol, drawType = seriesModel.visualDrawType, itemWidth = legendModel.get('itemWidth'), itemHeight = legendModel.get('itemHeight'), isSelected = legendModel.isSelected(name), symbolKeepAspect = itemModel.get('symbolKeepAspect'), legendIconType = itemModel.get('icon'), style = function(symbolType, legendModel, legendLineStyle, lineVisualStyle, itemVisualStyle, drawType, isSelected) { for(var legendItemModel = legendModel.getModel('itemStyle'), itemProperties = ITEM_STYLE_KEY_MAP.concat([ [ 'decal' ] ]), itemStyle = {}, i = 0; i < itemProperties.length; ++i){ var propName = itemProperties[i][itemProperties[i].length - 1], visualName = itemProperties[i][0], value = legendItemModel.getShallow(propName); if ('inherit' === value) switch(visualName){ case 'fill': itemStyle.fill = itemVisualStyle[drawType]; break; case 'stroke': itemStyle.stroke = itemVisualStyle[symbolType.startsWith('empty') ? 'fill' : 'stroke']; break; case 'opacity': itemStyle.opacity = ('fill' === drawType ? itemVisualStyle : lineVisualStyle).opacity; break; default: itemStyle[visualName] = itemVisualStyle[visualName]; } else 'auto' === value && 'lineWidth' === visualName ? itemStyle.lineWidth = itemVisualStyle.lineWidth > 0 ? 2 : 0 : itemStyle[visualName] = value; } for(var legendLineModel = legendModel.getModel('lineStyle'), lineProperties = LINE_STYLE_KEY_MAP.concat([ [ 'inactiveColor' ], [ 'inactiveWidth' ] ]), lineStyle = {}, i = 0; i < lineProperties.length; ++i){ var propName = lineProperties[i][1], visualName = lineProperties[i][0], value = legendLineModel.getShallow(propName); 'inherit' === value ? lineStyle[visualName] = lineVisualStyle[visualName] : 'auto' === value && 'lineWidth' === visualName ? lineStyle.lineWidth = lineVisualStyle.lineWidth > 0 ? 2 : 0 : lineStyle[visualName] = value; } if ('auto' === itemStyle.fill && (itemStyle.fill = itemVisualStyle.fill), 'auto' === itemStyle.stroke && (itemStyle.stroke = itemVisualStyle.fill), 'auto' === lineStyle.stroke && (lineStyle.stroke = itemVisualStyle.fill), !isSelected) { var borderWidth = legendModel.get('inactiveBorderWidth'), visualHasBorder = itemStyle[symbolType.indexOf('empty') > -1 ? 'fill' : 'stroke']; itemStyle.lineWidth = 'auto' === borderWidth ? itemVisualStyle.lineWidth > 0 && visualHasBorder ? 2 : 0 : itemStyle.lineWidth, itemStyle.fill = legendModel.get('inactiveColor'), itemStyle.stroke = legendModel.get('inactiveBorderColor'), lineStyle.stroke = legendLineStyle.get('inactiveColor'), lineStyle.lineWidth = legendLineStyle.get('inactiveWidth'); } return { itemStyle: itemStyle, lineStyle: lineStyle }; }(symbolType = legendIconType || symbolType || 'roundRect', itemModel, legendModel.getModel('lineStyle'), lineVisualStyle, itemVisualStyle, drawType, isSelected), itemGroup = new Group(), textStyleModel = itemModel.getModel('textStyle'); 'function' != typeof seriesModel.getLegendIcon || legendIconType ? itemGroup.add(((symbol = createSymbol(symboType = (opt = { itemWidth: itemWidth, itemHeight: itemHeight, symbolType: symbolType, symbolKeepAspect: symbolKeepAspect, itemStyle: style.itemStyle, lineStyle: style.lineStyle }).symbolType || 'roundRect', 0, 0, opt.itemWidth, opt.itemHeight, opt.itemStyle.fill, opt.symbolKeepAspect)).setStyle(opt.itemStyle), symboType.indexOf('empty') > -1 && (symbol.style.stroke = symbol.style.fill, symbol.style.fill = '#fff', symbol.style.lineWidth = 2), symbol)) : itemGroup.add(seriesModel.getLegendIcon({ itemWidth: itemWidth, itemHeight: itemHeight, symbolType: symbolType, symbolKeepAspect: symbolKeepAspect, itemStyle: style.itemStyle, lineStyle: style.lineStyle })); var formatter = legendModel.get('formatter'), content = name; 'string' == typeof formatter && formatter ? content = formatter.replace('{name}', null != name ? name : '') : 'function' == typeof formatter && (content = formatter(name)); var inactiveColor = itemModel.get('inactiveColor'); itemGroup.add(new ZRText({ style: createTextStyle(textStyleModel, { text: content, x: 'left' === itemAlign ? itemWidth + 5 : -5, y: itemHeight / 2, fill: isSelected ? textStyleModel.getTextColor() : inactiveColor, align: itemAlign, verticalAlign: 'middle' }) })); var hitRect = new Rect({ shape: itemGroup.getBoundingRect(), invisible: !0 }), tooltipModel = itemModel.getModel('tooltip'); return tooltipModel.get('show') && setTooltipConfig({ el: hitRect, componentModel: legendModel, itemName: name, itemTooltipOption: tooltipModel.option }), itemGroup.add(hitRect), itemGroup.eachChild(function(child) { child.silent = !0; }), hitRect.silent = !selectMode, this.getContentGroup().add(itemGroup), enableHoverEmphasis(itemGroup), itemGroup.__legendDataIndex = dataIndex, itemGroup; }, LegendView.prototype.layoutInner = function(legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) { var contentGroup = this.getContentGroup(), selectorGroup = this.getSelectorGroup(); boxLayout(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), maxSize.width, maxSize.height); var contentRect = contentGroup.getBoundingRect(), contentPos = [ -contentRect.x, -contentRect.y ]; if (selectorGroup.markRedraw(), contentGroup.markRedraw(), !selector) return contentGroup.x = contentPos[0], contentGroup.y = contentPos[1], this.group.getBoundingRect(); boxLayout('horizontal', selectorGroup, legendModel.get('selectorItemGap', !0)); var selectorRect = selectorGroup.getBoundingRect(), selectorPos = [ -selectorRect.x, -selectorRect.y ], selectorButtonGap = legendModel.get('selectorButtonGap', !0), orientIdx = legendModel.getOrient().index, wh = 0 === orientIdx ? 'width' : 'height', hw = 0 === orientIdx ? 'height' : 'width', yx = 0 === orientIdx ? 'y' : 'x'; 'end' === selectorPosition ? selectorPos[orientIdx] += contentRect[wh] + selectorButtonGap : contentPos[orientIdx] += selectorRect[wh] + selectorButtonGap, selectorPos[1 - orientIdx] += contentRect[hw] / 2 - selectorRect[hw] / 2, selectorGroup.x = selectorPos[0], selectorGroup.y = selectorPos[1], contentGroup.x = contentPos[0], contentGroup.y = contentPos[1]; var mainRect = { x: 0, y: 0 }; return mainRect[wh] = contentRect[wh] + selectorButtonGap + selectorRect[wh], mainRect[hw] = Math.max(contentRect[hw], selectorRect[hw]), mainRect[yx] = Math.min(0, selectorRect[yx] + selectorPos[1 - orientIdx]), mainRect; }, LegendView.prototype.remove = function() { this.getContentGroup().removeAll(), this._isFirstRender = !0; }, LegendView.type = 'legend.plain', LegendView; }(ComponentView); function dispatchSelectAction(seriesName, dataName, api, excludeSeriesId) { dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId), api.dispatchAction({ type: 'legendToggleSelect', name: null != seriesName ? seriesName : dataName }), dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId); } function isUseHoverLayer(api) { for(var emphasisState, list = api.getZr().storage.getDisplayList(), i = 0, len = list.length; i < len && !(emphasisState = list[i].states.emphasis);)i++; return emphasisState && emphasisState.hoverLayer; } function dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId) { isUseHoverLayer(api) || api.dispatchAction({ type: 'highlight', seriesName: seriesName, name: dataName, excludeSeriesId: excludeSeriesId }); } function dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId) { isUseHoverLayer(api) || api.dispatchAction({ type: 'downplay', seriesName: seriesName, name: dataName, excludeSeriesId: excludeSeriesId }); } function legendFilter(ecModel) { var legendModels = ecModel.findComponents({ mainType: 'legend' }); legendModels && legendModels.length && ecModel.filterSeries(function(series) { for(var i = 0; i < legendModels.length; i++)if (!legendModels[i].isSelected(series.name)) return !1; return !0; }); } function legendSelectActionHandler(methodName, payload, ecModel) { var isSelected, selectedMap = {}, isToggleSelect = 'toggleSelected' === methodName; return ecModel.eachComponent('legend', function(legendModel) { isToggleSelect && null != isSelected ? legendModel[isSelected ? 'select' : 'unSelect'](payload.name) : 'allSelect' === methodName || 'inverseSelect' === methodName ? legendModel[methodName]() : (legendModel[methodName](payload.name), isSelected = legendModel.isSelected(payload.name)), each(legendModel.getData(), function(model) { var name = model.get('name'); if ('\n' !== name && '' !== name) { var isItemSelected = legendModel.isSelected(name); selectedMap.hasOwnProperty(name) ? selectedMap[name] = selectedMap[name] && isItemSelected : selectedMap[name] = isItemSelected; } }); }), 'allSelect' === methodName || 'inverseSelect' === methodName ? { selected: selectedMap } : { name: payload.name, selected: selectedMap }; } function install$H(registers) { registers.registerComponentModel(LegendModel), registers.registerComponentView(LegendView), registers.registerProcessor(registers.PRIORITY.PROCESSOR.SERIES_FILTER, legendFilter), registers.registerSubTypeDefaulter('legend', function() { return 'plain'; }), registers.registerAction('legendToggleSelect', 'legendselectchanged', curry(legendSelectActionHandler, 'toggleSelected')), registers.registerAction('legendAllSelect', 'legendselectall', curry(legendSelectActionHandler, 'allSelect')), registers.registerAction('legendInverseSelect', 'legendinverseselect', curry(legendSelectActionHandler, 'inverseSelect')), registers.registerAction('legendSelect', 'legendselected', curry(legendSelectActionHandler, 'select')), registers.registerAction('legendUnSelect', 'legendunselected', curry(legendSelectActionHandler, 'unSelect')); } var ScrollableLegendModel = function(_super) { function ScrollableLegendModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = ScrollableLegendModel.type, _this; } return __extends(ScrollableLegendModel, _super), ScrollableLegendModel.prototype.setScrollDataIndex = function(scrollDataIndex) { this.option.scrollDataIndex = scrollDataIndex; }, ScrollableLegendModel.prototype.init = function(option, parentModel, ecModel) { var inputPositionParams = getLayoutParams(option); _super.prototype.init.call(this, option, parentModel, ecModel), mergeAndNormalizeLayoutParams$1(this, option, inputPositionParams); }, ScrollableLegendModel.prototype.mergeOption = function(option, ecModel) { _super.prototype.mergeOption.call(this, option, ecModel), mergeAndNormalizeLayoutParams$1(this, this.option, option); }, ScrollableLegendModel.type = 'legend.scroll', ScrollableLegendModel.defaultOption = inheritDefaultOption(LegendModel.defaultOption, { scrollDataIndex: 0, pageButtonItemGap: 5, pageButtonGap: null, pageButtonPosition: 'end', pageFormatter: '{current}/{total}', pageIcons: { horizontal: [ 'M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z' ], vertical: [ 'M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z' ] }, pageIconColor: '#2f4554', pageIconInactiveColor: '#aaa', pageIconSize: 15, pageTextStyle: { color: '#333' }, animationDurationUpdate: 800 }), ScrollableLegendModel; }(LegendModel); function mergeAndNormalizeLayoutParams$1(legendModel, target, raw) { var orient = legendModel.getOrient(), ignoreSize = [ 1, 1 ]; ignoreSize[orient.index] = 0, mergeLayoutParam(target, raw, { type: 'box', ignoreSize: !!ignoreSize }); } var WH$1 = [ 'width', 'height' ], XY$1 = [ 'x', 'y' ], ScrollableLegendView = function(_super) { function ScrollableLegendView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = ScrollableLegendView.type, _this.newlineDisabled = !0, _this._currentIndex = 0, _this; } return __extends(ScrollableLegendView, _super), ScrollableLegendView.prototype.init = function() { _super.prototype.init.call(this), this.group.add(this._containerGroup = new Group()), this._containerGroup.add(this.getContentGroup()), this.group.add(this._controllerGroup = new Group()); }, ScrollableLegendView.prototype.resetInner = function() { _super.prototype.resetInner.call(this), this._controllerGroup.removeAll(), this._containerGroup.removeClipPath(), this._containerGroup.__rectSize = null; }, ScrollableLegendView.prototype.renderInner = function(itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) { var self1 = this; _super.prototype.renderInner.call(this, itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition); var controllerGroup = this._controllerGroup, pageIconSize = legendModel.get('pageIconSize', !0), pageIconSizeArr = isArray(pageIconSize) ? pageIconSize : [ pageIconSize, pageIconSize ]; createPageButton('pagePrev', 0); var pageTextStyleModel = legendModel.getModel('pageTextStyle'); function createPageButton(name, iconIdx) { var icon = createIcon(legendModel.get('pageIcons', !0)[legendModel.getOrient().name][iconIdx], { onclick: bind(self1._pageGo, self1, name + 'DataIndex', legendModel, api) }, { x: -pageIconSizeArr[0] / 2, y: -pageIconSizeArr[1] / 2, width: pageIconSizeArr[0], height: pageIconSizeArr[1] }); icon.name = name, controllerGroup.add(icon); } controllerGroup.add(new ZRText({ name: 'pageText', style: { text: 'xx/xx', fill: pageTextStyleModel.getTextColor(), font: pageTextStyleModel.getFont(), verticalAlign: 'middle', align: 'center' }, silent: !0 })), createPageButton('pageNext', 1); }, ScrollableLegendView.prototype.layoutInner = function(legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) { var selectorGroup = this.getSelectorGroup(), orientIdx = legendModel.getOrient().index, wh = WH$1[orientIdx], xy = XY$1[orientIdx], hw = WH$1[1 - orientIdx], yx = XY$1[1 - orientIdx]; selector && boxLayout('horizontal', selectorGroup, legendModel.get('selectorItemGap', !0)); var selectorButtonGap = legendModel.get('selectorButtonGap', !0), selectorRect = selectorGroup.getBoundingRect(), selectorPos = [ -selectorRect.x, -selectorRect.y ], processMaxSize = clone(maxSize); selector && (processMaxSize[wh] = maxSize[wh] - selectorRect[wh] - selectorButtonGap); var mainRect = this._layoutContentAndController(legendModel, isFirstRender, processMaxSize, orientIdx, wh, hw, yx, xy); if (selector) { if ('end' === selectorPosition) selectorPos[orientIdx] += mainRect[wh] + selectorButtonGap; else { var offset = selectorRect[wh] + selectorButtonGap; selectorPos[orientIdx] -= offset, mainRect[xy] -= offset; } mainRect[wh] += selectorRect[wh] + selectorButtonGap, selectorPos[1 - orientIdx] += mainRect[yx] + mainRect[hw] / 2 - selectorRect[hw] / 2, mainRect[hw] = Math.max(mainRect[hw], selectorRect[hw]), mainRect[yx] = Math.min(mainRect[yx], selectorRect[yx] + selectorPos[1 - orientIdx]), selectorGroup.x = selectorPos[0], selectorGroup.y = selectorPos[1], selectorGroup.markRedraw(); } return mainRect; }, ScrollableLegendView.prototype._layoutContentAndController = function(legendModel, isFirstRender, maxSize, orientIdx, wh, hw, yx, xy) { var contentGroup = this.getContentGroup(), containerGroup = this._containerGroup, controllerGroup = this._controllerGroup; boxLayout(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), orientIdx ? maxSize.width : null, orientIdx ? null : maxSize.height), boxLayout('horizontal', controllerGroup, legendModel.get('pageButtonItemGap', !0)); var contentRect = contentGroup.getBoundingRect(), controllerRect = controllerGroup.getBoundingRect(), showController = this._showController = contentRect[wh] > maxSize[wh], contentPos = [ -contentRect.x, -contentRect.y ]; isFirstRender || (contentPos[orientIdx] = contentGroup[xy]); var containerPos = [ 0, 0 ], controllerPos = [ -controllerRect.x, -controllerRect.y ], pageButtonGap = retrieve2(legendModel.get('pageButtonGap', !0), legendModel.get('itemGap', !0)); showController && ('end' === legendModel.get('pageButtonPosition', !0) ? controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh] : containerPos[orientIdx] += controllerRect[wh] + pageButtonGap), controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2, contentGroup.setPosition(contentPos), containerGroup.setPosition(containerPos), controllerGroup.setPosition(controllerPos); var mainRect = { x: 0, y: 0 }; if (mainRect[wh] = showController ? maxSize[wh] : contentRect[wh], mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]), mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]), containerGroup.__rectSize = maxSize[wh], showController) { var clipShape = { x: 0, y: 0 }; clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0), clipShape[hw] = mainRect[hw], containerGroup.setClipPath(new Rect({ shape: clipShape })), containerGroup.__rectSize = clipShape[wh]; } else controllerGroup.eachChild(function(child) { child.attr({ invisible: !0, silent: !0 }); }); var pageInfo = this._getPageInfo(legendModel); return null != pageInfo.pageIndex && updateProps(contentGroup, { x: pageInfo.contentPosition[0], y: pageInfo.contentPosition[1] }, showController ? legendModel : null), this._updatePageInfoView(legendModel, pageInfo), mainRect; }, ScrollableLegendView.prototype._pageGo = function(to, legendModel, api) { var scrollDataIndex = this._getPageInfo(legendModel)[to]; null != scrollDataIndex && api.dispatchAction({ type: 'legendScroll', scrollDataIndex: scrollDataIndex, legendId: legendModel.id }); }, ScrollableLegendView.prototype._updatePageInfoView = function(legendModel, pageInfo) { var controllerGroup = this._controllerGroup; each([ 'pagePrev', 'pageNext' ], function(name) { var canJump = null != pageInfo[name + 'DataIndex'], icon = controllerGroup.childOfName(name); icon && (icon.setStyle('fill', canJump ? legendModel.get('pageIconColor', !0) : legendModel.get('pageIconInactiveColor', !0)), icon.cursor = canJump ? 'pointer' : 'default'); }); var pageText = controllerGroup.childOfName('pageText'), pageFormatter = legendModel.get('pageFormatter'), pageIndex = pageInfo.pageIndex, current = null != pageIndex ? pageIndex + 1 : 0, total = pageInfo.pageCount; pageText && pageFormatter && pageText.setStyle('text', isString(pageFormatter) ? pageFormatter.replace('{current}', null == current ? '' : current + '').replace('{total}', null == total ? '' : total + '') : pageFormatter({ current: current, total: total })); }, ScrollableLegendView.prototype._getPageInfo = function(legendModel) { var scrollDataIndex = legendModel.get('scrollDataIndex', !0), contentGroup = this.getContentGroup(), containerRectSize = this._containerGroup.__rectSize, orientIdx = legendModel.getOrient().index, wh = WH$1[orientIdx], xy = XY$1[orientIdx], targetItemIndex = this._findTargetItemIndex(scrollDataIndex), children = contentGroup.children(), targetItem = children[targetItemIndex], itemCount = children.length, pCount = itemCount ? 1 : 0, result = { contentPosition: [ contentGroup.x, contentGroup.y ], pageCount: pCount, pageIndex: pCount - 1, pagePrevDataIndex: null, pageNextDataIndex: null }; if (!targetItem) return result; var targetItemInfo = getItemInfo(targetItem); result.contentPosition[orientIdx] = -targetItemInfo.s; for(var i = targetItemIndex + 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i <= itemCount; ++i)(!(currItemInfo = getItemInfo(children[i])) && winEndItemInfo.e > winStartItemInfo.s + containerRectSize || currItemInfo && !intersect(currItemInfo, winStartItemInfo.s)) && (winStartItemInfo = winEndItemInfo.i > winStartItemInfo.i ? winEndItemInfo : currItemInfo) && (null == result.pageNextDataIndex && (result.pageNextDataIndex = winStartItemInfo.i), ++result.pageCount), winEndItemInfo = currItemInfo; for(var i = targetItemIndex - 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i >= -1; --i)(!(currItemInfo = getItemInfo(children[i])) || !intersect(winEndItemInfo, currItemInfo.s)) && winStartItemInfo.i < winEndItemInfo.i && (winEndItemInfo = winStartItemInfo, null == result.pagePrevDataIndex && (result.pagePrevDataIndex = winStartItemInfo.i), ++result.pageCount, ++result.pageIndex), winStartItemInfo = currItemInfo; return result; function getItemInfo(el) { if (el) { var itemRect = el.getBoundingRect(), start = itemRect[xy] + el[xy]; return { s: start, e: start + itemRect[wh], i: el.__legendDataIndex }; } } function intersect(itemInfo, winStart) { return itemInfo.e >= winStart && itemInfo.s <= winStart + containerRectSize; } }, ScrollableLegendView.prototype._findTargetItemIndex = function(targetDataIndex) { var index, defaultIndex; return this._showController ? (this.getContentGroup().eachChild(function(child, idx) { var legendDataIdx = child.__legendDataIndex; null == defaultIndex && null != legendDataIdx && (defaultIndex = idx), legendDataIdx === targetDataIndex && (index = idx); }), null != index ? index : defaultIndex) : 0; }, ScrollableLegendView.type = 'legend.scroll', ScrollableLegendView; }(LegendView); function install$I(registers) { use(install$H), registers.registerComponentModel(ScrollableLegendModel), registers.registerComponentView(ScrollableLegendView), function(registers) { registers.registerAction('legendScroll', 'legendscroll', function(payload, ecModel) { var scrollDataIndex = payload.scrollDataIndex; null != scrollDataIndex && ecModel.eachComponent({ mainType: 'legend', subType: 'scroll', query: payload }, function(legendModel) { legendModel.setScrollDataIndex(scrollDataIndex); }); }); }(registers); } var InsideZoomModel = function(_super) { function InsideZoomModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = InsideZoomModel.type, _this; } return __extends(InsideZoomModel, _super), InsideZoomModel.type = 'dataZoom.inside', InsideZoomModel.defaultOption = inheritDefaultOption(DataZoomModel.defaultOption, { disabled: !1, zoomLock: !1, zoomOnMouseWheel: !0, moveOnMouseMove: !0, moveOnMouseWheel: !1, preventDefaultMouseMove: !0 }), InsideZoomModel; }(DataZoomModel), inner$k = makeInner(); function disposeCoordSysRecord(coordSysRecordMap, coordSysRecord) { if (coordSysRecord) { coordSysRecordMap.removeKey(coordSysRecord.model.uid); var controller = coordSysRecord.controller; controller && controller.dispose(); } } function dispatchAction$1(api, batch) { api.dispatchAction({ type: 'dataZoom', animation: { easing: 'cubicOut', duration: 100 }, batch: batch }); } function containsPoint(coordSysModel, e, x, y) { return coordSysModel.coordinateSystem.containPoint([ x, y ]); } var InsideZoomView = function(_super) { function InsideZoomView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = 'dataZoom.inside', _this; } return __extends(InsideZoomView, _super), InsideZoomView.prototype.render = function(dataZoomModel, ecModel, api) { if (_super.prototype.render.apply(this, arguments), dataZoomModel.noTarget()) { this._clear(); return; } this.range = dataZoomModel.getPercentRange(), function(api, dataZoomModel, getRange) { inner$k(api).coordSysRecordMap.each(function(coordSysRecord) { var dzInfo = coordSysRecord.dataZoomInfoMap.get(dataZoomModel.uid); dzInfo && (dzInfo.getRange = getRange); }); }(api, dataZoomModel, { pan: bind(getRangeHandlers.pan, this), zoom: bind(getRangeHandlers.zoom, this), scrollMove: bind(getRangeHandlers.scrollMove, this) }); }, InsideZoomView.prototype.dispose = function() { this._clear(), _super.prototype.dispose.apply(this, arguments); }, InsideZoomView.prototype._clear = function() { (function(api, dataZoomModel) { for(var coordSysRecordMap = inner$k(api).coordSysRecordMap, coordSysKeyArr = coordSysRecordMap.keys(), i = 0; i < coordSysKeyArr.length; i++){ var coordSysKey = coordSysKeyArr[i], coordSysRecord = coordSysRecordMap.get(coordSysKey), dataZoomInfoMap = coordSysRecord.dataZoomInfoMap; if (dataZoomInfoMap) { var dzUid = dataZoomModel.uid; dataZoomInfoMap.get(dzUid) && (dataZoomInfoMap.removeKey(dzUid), dataZoomInfoMap.keys().length || disposeCoordSysRecord(coordSysRecordMap, coordSysRecord)); } } })(this.api, this.dataZoomModel), this.range = null; }, InsideZoomView.type = 'dataZoom.inside', InsideZoomView; }(DataZoomView), getRangeHandlers = { zoom: function(coordSysInfo, coordSysMainType, controller, e) { var lastRange = this.range, range = lastRange.slice(), axisModel = coordSysInfo.axisModels[0]; if (axisModel) { var directionInfo = getDirectionInfo[coordSysMainType](null, [ e.originX, e.originY ], axisModel, controller, coordSysInfo), percentPoint = (directionInfo.signal > 0 ? directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel : directionInfo.pixel - directionInfo.pixelStart) / directionInfo.pixelLength * (range[1] - range[0]) + range[0], scale = Math.max(1 / e.scale, 0); range[0] = (range[0] - percentPoint) * scale + percentPoint, range[1] = (range[1] - percentPoint) * scale + percentPoint; var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan(); if (sliderMove(0, range, [ 0, 100 ], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan), this.range = range, lastRange[0] !== range[0] || lastRange[1] !== range[1]) return range; } }, pan: makeMover(function(range, axisModel, coordSysInfo, coordSysMainType, controller, e) { var directionInfo = getDirectionInfo[coordSysMainType]([ e.oldX, e.oldY ], [ e.newX, e.newY ], axisModel, controller, coordSysInfo); return directionInfo.signal * (range[1] - range[0]) * directionInfo.pixel / directionInfo.pixelLength; }), scrollMove: makeMover(function(range, axisModel, coordSysInfo, coordSysMainType, controller, e) { return getDirectionInfo[coordSysMainType]([ 0, 0 ], [ e.scrollDelta, e.scrollDelta ], axisModel, controller, coordSysInfo).signal * (range[1] - range[0]) * e.scrollDelta; }) }; function makeMover(getPercentDelta) { return function(coordSysInfo, coordSysMainType, controller, e) { var lastRange = this.range, range = lastRange.slice(), axisModel = coordSysInfo.axisModels[0]; if (axisModel && (sliderMove(getPercentDelta(range, axisModel, coordSysInfo, coordSysMainType, controller, e), range, [ 0, 100 ], 'all'), this.range = range, lastRange[0] !== range[0] || lastRange[1] !== range[1])) return range; }; } var getDirectionInfo = { grid: function(oldPoint, newPoint, axisModel, controller, coordSysInfo) { var axis = axisModel.axis, ret = {}, rect = coordSysInfo.model.coordinateSystem.getRect(); return oldPoint = oldPoint || [ 0, 0 ], 'x' === axis.dim ? (ret.pixel = newPoint[0] - oldPoint[0], ret.pixelLength = rect.width, ret.pixelStart = rect.x, ret.signal = axis.inverse ? 1 : -1) : (ret.pixel = newPoint[1] - oldPoint[1], ret.pixelLength = rect.height, ret.pixelStart = rect.y, ret.signal = axis.inverse ? -1 : 1), ret; }, polar: function(oldPoint, newPoint, axisModel, controller, coordSysInfo) { var axis = axisModel.axis, ret = {}, polar = coordSysInfo.model.coordinateSystem, radiusExtent = polar.getRadiusAxis().getExtent(), angleExtent = polar.getAngleAxis().getExtent(); return oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [ 0, 0 ], newPoint = polar.pointToCoord(newPoint), 'radiusAxis' === axisModel.mainType ? (ret.pixel = newPoint[0] - oldPoint[0], ret.pixelLength = radiusExtent[1] - radiusExtent[0], ret.pixelStart = radiusExtent[0], ret.signal = axis.inverse ? 1 : -1) : (ret.pixel = newPoint[1] - oldPoint[1], ret.pixelLength = angleExtent[1] - angleExtent[0], ret.pixelStart = angleExtent[0], ret.signal = axis.inverse ? -1 : 1), ret; }, singleAxis: function(oldPoint, newPoint, axisModel, controller, coordSysInfo) { var axis = axisModel.axis, rect = coordSysInfo.model.coordinateSystem.getRect(), ret = {}; return oldPoint = oldPoint || [ 0, 0 ], 'horizontal' === axis.orient ? (ret.pixel = newPoint[0] - oldPoint[0], ret.pixelLength = rect.width, ret.pixelStart = rect.x, ret.signal = axis.inverse ? 1 : -1) : (ret.pixel = newPoint[1] - oldPoint[1], ret.pixelLength = rect.height, ret.pixelStart = rect.y, ret.signal = axis.inverse ? -1 : 1), ret; } }; function install$K(registers) { installCommon(registers), registers.registerComponentModel(InsideZoomModel), registers.registerComponentView(InsideZoomView), function(registers) { registers.registerProcessor(registers.PRIORITY.PROCESSOR.FILTER, function(ecModel, api) { var apiInner = inner$k(api), coordSysRecordMap = apiInner.coordSysRecordMap || (apiInner.coordSysRecordMap = createHashMap()); coordSysRecordMap.each(function(coordSysRecord) { coordSysRecord.dataZoomInfoMap = null; }), ecModel.eachComponent({ mainType: 'dataZoom', subType: 'inside' }, function(dataZoomModel) { each(collectReferCoordSysModelInfo(dataZoomModel).infoList, function(dzCoordSysInfo) { var coordSysModel, coordSysRecord, controller, coordSysUid = dzCoordSysInfo.model.uid, coordSysRecord1 = coordSysRecordMap.get(coordSysUid) || coordSysRecordMap.set(coordSysUid, (controller = (coordSysRecord = { model: coordSysModel = dzCoordSysInfo.model, containsPoint: curry(containsPoint, coordSysModel), dispatchAction: curry(dispatchAction$1, api), dataZoomInfoMap: null, controller: null }).controller = new RoamController(api.getZr()), each([ 'pan', 'zoom', 'scrollMove' ], function(eventName) { controller.on(eventName, function(event) { var batch = []; coordSysRecord.dataZoomInfoMap.each(function(dzInfo) { if (event.isAvailableBehavior(dzInfo.model.option)) { var method = (dzInfo.getRange || {})[eventName], range = method && method(dzInfo.dzReferCoordSysInfo, coordSysRecord.model.mainType, coordSysRecord.controller, event); !dzInfo.model.get('disabled', !0) && range && batch.push({ dataZoomId: dzInfo.model.id, start: range[0], end: range[1] }); } }), batch.length && coordSysRecord.dispatchAction(batch); }); }), coordSysRecord)); (coordSysRecord1.dataZoomInfoMap || (coordSysRecord1.dataZoomInfoMap = createHashMap())).set(dataZoomModel.uid, { dzReferCoordSysInfo: dzCoordSysInfo, model: dataZoomModel, getRange: null }); }); }), coordSysRecordMap.each(function(coordSysRecord) { var controlType, prefix, typePriority, preventDefaultMouseMove, firstDzInfo, controller = coordSysRecord.controller, dataZoomInfoMap = coordSysRecord.dataZoomInfoMap; if (dataZoomInfoMap) { var firstDzKey = dataZoomInfoMap.keys()[0]; null != firstDzKey && (firstDzInfo = dataZoomInfoMap.get(firstDzKey)); } if (!firstDzInfo) { disposeCoordSysRecord(coordSysRecordMap, coordSysRecord); return; } var controllerParams = (prefix = 'type_', typePriority = { type_true: 2, type_move: 1, type_false: 0, type_undefined: -1 }, preventDefaultMouseMove = !0, dataZoomInfoMap.each(function(dataZoomInfo) { var dataZoomModel = dataZoomInfo.model, oneType = !dataZoomModel.get('disabled', !0) && (!dataZoomModel.get('zoomLock', !0) || 'move'); typePriority[prefix + oneType] > typePriority[prefix + controlType] && (controlType = oneType), preventDefaultMouseMove = preventDefaultMouseMove && dataZoomModel.get('preventDefaultMouseMove', !0); }), { controlType: controlType, opt: { zoomOnMouseWheel: !0, moveOnMouseMove: !0, moveOnMouseWheel: !0, preventDefaultMouseMove: !!preventDefaultMouseMove } }); controller.enable(controllerParams.controlType, controllerParams.opt), controller.setPointerChecker(coordSysRecord.containsPoint), createOrUpdate(coordSysRecord, 'dispatchAction', firstDzInfo.model.get('throttle', !0), 'fixRate'); }); }); }(registers); } var SliderZoomModel = function(_super) { function SliderZoomModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = SliderZoomModel.type, _this; } return __extends(SliderZoomModel, _super), SliderZoomModel.type = 'dataZoom.slider', SliderZoomModel.layoutMode = 'box', SliderZoomModel.defaultOption = inheritDefaultOption(DataZoomModel.defaultOption, { show: !0, right: 'ph', top: 'ph', width: 'ph', height: 'ph', left: null, bottom: null, borderColor: '#d2dbee', borderRadius: 3, backgroundColor: 'rgba(47,69,84,0)', dataBackground: { lineStyle: { color: '#d2dbee', width: 0.5 }, areaStyle: { color: '#d2dbee', opacity: 0.2 } }, selectedDataBackground: { lineStyle: { color: '#8fb0f7', width: 0.5 }, areaStyle: { color: '#8fb0f7', opacity: 0.2 } }, fillerColor: 'rgba(135,175,274,0.2)', handleIcon: 'path://M-9.35,34.56V42m0-40V9.5m-2,0h4a2,2,0,0,1,2,2v21a2,2,0,0,1-2,2h-4a2,2,0,0,1-2-2v-21A2,2,0,0,1-11.35,9.5Z', handleSize: '100%', handleStyle: { color: '#fff', borderColor: '#ACB8D1' }, moveHandleSize: 7, moveHandleIcon: 'path://M-320.9-50L-320.9-50c18.1,0,27.1,9,27.1,27.1V85.7c0,18.1-9,27.1-27.1,27.1l0,0c-18.1,0-27.1-9-27.1-27.1V-22.9C-348-41-339-50-320.9-50z M-212.3-50L-212.3-50c18.1,0,27.1,9,27.1,27.1V85.7c0,18.1-9,27.1-27.1,27.1l0,0c-18.1,0-27.1-9-27.1-27.1V-22.9C-239.4-41-230.4-50-212.3-50z M-103.7-50L-103.7-50c18.1,0,27.1,9,27.1,27.1V85.7c0,18.1-9,27.1-27.1,27.1l0,0c-18.1,0-27.1-9-27.1-27.1V-22.9C-130.9-41-121.8-50-103.7-50z', moveHandleStyle: { color: '#D2DBEE', opacity: 0.7 }, showDetail: !0, showDataShadow: 'auto', realtime: !0, zoomLock: !1, textStyle: { color: '#6E7079' }, brushSelect: !0, brushStyle: { color: 'rgba(135,175,274,0.15)' }, emphasis: { handleStyle: { borderColor: '#8FB0F7' }, moveHandleStyle: { color: '#8FB0F7' } } }), SliderZoomModel; }(DataZoomModel), HORIZONTAL = 'horizontal', VERTICAL = 'vertical', SHOW_DATA_SHADOW_SERIES_TYPE = [ 'line', 'bar', 'candlestick', 'scatter' ], REALTIME_ANIMATION_CONFIG = { easing: 'cubicOut', duration: 100 }, SliderZoomView = function(_super) { function SliderZoomView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = SliderZoomView.type, _this._displayables = {}, _this; } return __extends(SliderZoomView, _super), SliderZoomView.prototype.init = function(ecModel, api) { this.api = api, this._onBrush = bind(this._onBrush, this), this._onBrushEnd = bind(this._onBrushEnd, this); }, SliderZoomView.prototype.render = function(dataZoomModel, ecModel, api, payload) { if (_super.prototype.render.apply(this, arguments), createOrUpdate(this, '_dispatchZoomAction', dataZoomModel.get('throttle'), 'fixRate'), this._orient = dataZoomModel.getOrient(), !1 === dataZoomModel.get('show')) { this.group.removeAll(); return; } if (dataZoomModel.noTarget()) { this._clear(), this.group.removeAll(); return; } payload && 'dataZoom' === payload.type && payload.from === this.uid || this._buildView(), this._updateView(); }, SliderZoomView.prototype.dispose = function() { this._clear(), _super.prototype.dispose.apply(this, arguments); }, SliderZoomView.prototype._clear = function() { obj = this, (fn = obj[fnAttr = '_dispatchZoomAction']) && fn[ORIGIN_METHOD] && (obj[fnAttr] = fn[ORIGIN_METHOD]); var obj, fnAttr, fn, zr = this.api.getZr(); zr.off('mousemove', this._onBrush), zr.off('mouseup', this._onBrushEnd); }, SliderZoomView.prototype._buildView = function() { var thisGroup = this.group; thisGroup.removeAll(), this._brushing = !1, this._displayables.brushRect = null, this._resetLocation(), this._resetInterval(); var barGroup = this._displayables.sliderGroup = new Group(); this._renderBackground(), this._renderHandle(), this._renderDataShadow(), thisGroup.add(barGroup), this._positionGroup(); }, SliderZoomView.prototype._resetLocation = function() { var dataZoomModel = this.dataZoomModel, api = this.api, showMoveHandle = dataZoomModel.get('brushSelect'), coordRect = this._findCoordRect(), ecSize = { width: api.getWidth(), height: api.getHeight() }, positionInfo = this._orient === HORIZONTAL ? { right: ecSize.width - coordRect.x - coordRect.width, top: ecSize.height - 30 - 7 - (showMoveHandle ? 7 : 0), width: coordRect.width, height: 30 } : { right: 7, top: coordRect.y, width: 30, height: coordRect.height }, layoutParams = getLayoutParams(dataZoomModel.option); each([ 'right', 'top', 'width', 'height' ], function(name) { 'ph' === layoutParams[name] && (layoutParams[name] = positionInfo[name]); }); var layoutRect = getLayoutRect(layoutParams, ecSize); this._location = { x: layoutRect.x, y: layoutRect.y }, this._size = [ layoutRect.width, layoutRect.height ], this._orient === VERTICAL && this._size.reverse(); }, SliderZoomView.prototype._positionGroup = function() { var thisGroup = this.group, location = this._location, orient = this._orient, targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel(), inverse = targetAxisModel && targetAxisModel.get('inverse'), sliderGroup = this._displayables.sliderGroup, otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse; sliderGroup.attr(orient !== HORIZONTAL || inverse ? orient === HORIZONTAL && inverse ? { scaleY: otherAxisInverse ? 1 : -1, scaleX: -1 } : orient !== VERTICAL || inverse ? { scaleY: otherAxisInverse ? -1 : 1, scaleX: -1, rotation: Math.PI / 2 } : { scaleY: otherAxisInverse ? -1 : 1, scaleX: 1, rotation: Math.PI / 2 } : { scaleY: otherAxisInverse ? 1 : -1, scaleX: 1 }); var rect = thisGroup.getBoundingRect([ sliderGroup ]); thisGroup.x = location.x - rect.x, thisGroup.y = location.y - rect.y, thisGroup.markRedraw(); }, SliderZoomView.prototype._getViewExtent = function() { return [ 0, this._size[0] ]; }, SliderZoomView.prototype._renderBackground = function() { var dataZoomModel = this.dataZoomModel, size = this._size, barGroup = this._displayables.sliderGroup, brushSelect = dataZoomModel.get('brushSelect'); barGroup.add(new Rect({ silent: !0, shape: { x: 0, y: 0, width: size[0], height: size[1] }, style: { fill: dataZoomModel.get('backgroundColor') }, z2: -40 })); var clickPanel = new Rect({ shape: { x: 0, y: 0, width: size[0], height: size[1] }, style: { fill: 'transparent' }, z2: 0, onclick: bind(this._onClickPanel, this) }), zr = this.api.getZr(); brushSelect ? (clickPanel.on('mousedown', this._onBrushStart, this), clickPanel.cursor = 'crosshair', zr.on('mousemove', this._onBrush), zr.on('mouseup', this._onBrushEnd)) : (zr.off('mousemove', this._onBrush), zr.off('mouseup', this._onBrushEnd)), barGroup.add(clickPanel); }, SliderZoomView.prototype._renderDataShadow = function() { var lastIsEmpty, info = this._dataShadowInfo = this._prepareDataShadowInfo(); if (this._displayables.dataShadowSegs = [], info) { var size = this._size, seriesModel = info.series, data = seriesModel.getRawData(), otherDim = seriesModel.getShadowDim ? seriesModel.getShadowDim() : info.otherDim; if (null != otherDim) { var otherDataExtent = data.getDataExtent(otherDim), otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3; otherDataExtent = [ otherDataExtent[0] - otherOffset, otherDataExtent[1] + otherOffset ]; var otherShadowExtent = [ 0, size[1] ], thisShadowExtent = [ 0, size[0] ], areaPoints = [ [ size[0], 0 ], [ 0, 0 ] ], linePoints = [], step = thisShadowExtent[1] / (data.count() - 1), thisCoord = 0, stride = Math.round(data.count() / size[0]); data.each([ otherDim ], function(value, index) { if (stride > 0 && index % stride) { thisCoord += step; return; } var isEmpty = null == value || isNaN(value) || '' === value, otherCoord = isEmpty ? 0 : linearMap(value, otherDataExtent, otherShadowExtent, !0); isEmpty && !lastIsEmpty && index ? (areaPoints.push([ areaPoints[areaPoints.length - 1][0], 0 ]), linePoints.push([ linePoints[linePoints.length - 1][0], 0 ])) : !isEmpty && lastIsEmpty && (areaPoints.push([ thisCoord, 0 ]), linePoints.push([ thisCoord, 0 ])), areaPoints.push([ thisCoord, otherCoord ]), linePoints.push([ thisCoord, otherCoord ]), thisCoord += step, lastIsEmpty = isEmpty; }); for(var dataZoomModel = this.dataZoomModel, i = 0; i < 3; i++){ var group = function(isSelectedArea) { var model = dataZoomModel.getModel(isSelectedArea ? 'selectedDataBackground' : 'dataBackground'), group = new Group(), polygon = new Polygon({ shape: { points: areaPoints }, segmentIgnoreThreshold: 1, style: model.getModel('areaStyle').getAreaStyle(), silent: !0, z2: -20 }), polyline = new Polyline({ shape: { points: linePoints }, segmentIgnoreThreshold: 1, style: model.getModel('lineStyle').getLineStyle(), silent: !0, z2: -19 }); return group.add(polygon), group.add(polyline), group; }(1 === i); this._displayables.sliderGroup.add(group), this._displayables.dataShadowSegs.push(group); } } } }, SliderZoomView.prototype._prepareDataShadowInfo = function() { var result, dataZoomModel = this.dataZoomModel, showDataShadow = dataZoomModel.get('showDataShadow'); if (!1 !== showDataShadow) { var ecModel = this.ecModel; return dataZoomModel.eachTargetAxis(function(axisDim, axisIndex) { each(dataZoomModel.getAxisProxy(axisDim, axisIndex).getTargetSeriesModels(), function(seriesModel) { if (!(result || !0 !== showDataShadow && 0 > indexOf(SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')))) { var otherAxisInverse, thisAxis = ecModel.getComponent(getAxisMainType(axisDim), axisIndex).axis, otherDim = { x: 'y', y: 'x', radius: 'angle', angle: 'radius' }[axisDim], coordSys = seriesModel.coordinateSystem; null != otherDim && coordSys.getOtherAxis && (otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse), otherDim = seriesModel.getData().mapDimension(otherDim), result = { thisAxis: thisAxis, series: seriesModel, thisDim: axisDim, otherDim: otherDim, otherAxisInverse: otherAxisInverse }; } }, this); }, this), result; } }, SliderZoomView.prototype._renderHandle = function() { var thisGroup = this.group, displayables = this._displayables, handles = displayables.handles = [ null, null ], handleLabels = displayables.handleLabels = [ null, null ], sliderGroup = this._displayables.sliderGroup, size = this._size, dataZoomModel = this.dataZoomModel, api = this.api, borderRadius = dataZoomModel.get('borderRadius') || 0, brushSelect = dataZoomModel.get('brushSelect'), filler = displayables.filler = new Rect({ silent: brushSelect, style: { fill: dataZoomModel.get('fillerColor') }, textConfig: { position: 'inside' } }); sliderGroup.add(filler), sliderGroup.add(new Rect({ silent: !0, subPixelOptimize: !0, shape: { x: 0, y: 0, width: size[0], height: size[1], r: borderRadius }, style: { stroke: dataZoomModel.get('dataBackgroundColor') || dataZoomModel.get('borderColor'), lineWidth: 1, fill: 'rgba(0,0,0,0)' } })), each([ 0, 1 ], function(handleIndex) { var iconStr = dataZoomModel.get('handleIcon'); !symbolBuildProxies[iconStr] && 0 > iconStr.indexOf('path://') && 0 > iconStr.indexOf('image://') && (iconStr = 'path://' + iconStr, deprecateLog('handleIcon now needs \'path://\' prefix when using a path string')); var path = createSymbol(iconStr, -1, 0, 2, 2, null, !0); path.attr({ cursor: getCursor(this._orient), draggable: !0, drift: bind(this._onDragMove, this, handleIndex), ondragend: bind(this._onDragEnd, this), onmouseover: bind(this._showDataInfo, this, !0), onmouseout: bind(this._showDataInfo, this, !1), z2: 5 }); var bRect = path.getBoundingRect(), handleSize = dataZoomModel.get('handleSize'); this._handleHeight = parsePercent$1(handleSize, this._size[1]), this._handleWidth = bRect.width / bRect.height * this._handleHeight, path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle()), path.style.strokeNoScale = !0, path.rectHover = !0, path.ensureState('emphasis').style = dataZoomModel.getModel([ 'emphasis', 'handleStyle' ]).getItemStyle(), enableHoverEmphasis(path); var handleColor = dataZoomModel.get('handleColor'); null != handleColor && (path.style.fill = handleColor), sliderGroup.add(handles[handleIndex] = path); var textStyleModel = dataZoomModel.getModel('textStyle'); thisGroup.add(handleLabels[handleIndex] = new ZRText({ silent: !0, invisible: !0, style: createTextStyle(textStyleModel, { x: 0, y: 0, text: '', verticalAlign: 'middle', align: 'center', fill: textStyleModel.getTextColor(), font: textStyleModel.getFont() }), z2: 10 })); }, this); var actualMoveZone = filler; if (brushSelect) { var moveHandleHeight = parsePercent$1(dataZoomModel.get('moveHandleSize'), size[1]), moveHandle_1 = displayables.moveHandle = new Rect({ style: dataZoomModel.getModel('moveHandleStyle').getItemStyle(), silent: !0, shape: { r: [ 0, 0, 2, 2 ], y: size[1] - 0.5, height: moveHandleHeight } }), iconSize = 0.8 * moveHandleHeight, moveHandleIcon = displayables.moveHandleIcon = createSymbol(dataZoomModel.get('moveHandleIcon'), -iconSize / 2, -iconSize / 2, iconSize, iconSize, '#fff', !0); moveHandleIcon.silent = !0, moveHandleIcon.y = size[1] + moveHandleHeight / 2 - 0.5, moveHandle_1.ensureState('emphasis').style = dataZoomModel.getModel([ 'emphasis', 'moveHandleStyle' ]).getItemStyle(); var moveZoneExpandSize = Math.min(size[1] / 2, Math.max(moveHandleHeight, 10)); (actualMoveZone = displayables.moveZone = new Rect({ invisible: !0, shape: { y: size[1] - moveZoneExpandSize, height: moveHandleHeight + moveZoneExpandSize } })).on('mouseover', function() { api.enterEmphasis(moveHandle_1); }).on('mouseout', function() { api.leaveEmphasis(moveHandle_1); }), sliderGroup.add(moveHandle_1), sliderGroup.add(moveHandleIcon), sliderGroup.add(actualMoveZone); } actualMoveZone.attr({ draggable: !0, cursor: getCursor(this._orient), drift: bind(this._onDragMove, this, 'all'), ondragstart: bind(this._showDataInfo, this, !0), ondragend: bind(this._onDragEnd, this), onmouseover: bind(this._showDataInfo, this, !0), onmouseout: bind(this._showDataInfo, this, !1) }); }, SliderZoomView.prototype._resetInterval = function() { var range = this._range = this.dataZoomModel.getPercentRange(), viewExtent = this._getViewExtent(); this._handleEnds = [ linearMap(range[0], [ 0, 100 ], viewExtent, !0), linearMap(range[1], [ 0, 100 ], viewExtent, !0) ]; }, SliderZoomView.prototype._updateInterval = function(handleIndex, delta) { var dataZoomModel = this.dataZoomModel, handleEnds = this._handleEnds, viewExtend = this._getViewExtent(), minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan(), percentExtent = [ 0, 100 ]; sliderMove(delta, handleEnds, viewExtend, dataZoomModel.get('zoomLock') ? 'all' : handleIndex, null != minMaxSpan.minSpan ? linearMap(minMaxSpan.minSpan, percentExtent, viewExtend, !0) : null, null != minMaxSpan.maxSpan ? linearMap(minMaxSpan.maxSpan, percentExtent, viewExtend, !0) : null); var lastRange = this._range, range = this._range = asc([ linearMap(handleEnds[0], viewExtend, percentExtent, !0), linearMap(handleEnds[1], viewExtend, percentExtent, !0) ]); return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1]; }, SliderZoomView.prototype._updateView = function(nonRealtime) { var displaybles = this._displayables, handleEnds = this._handleEnds, handleInterval = asc(handleEnds.slice()), size = this._size; each([ 0, 1 ], function(handleIndex) { var handle = displaybles.handles[handleIndex], handleHeight = this._handleHeight; handle.attr({ scaleX: handleHeight / 2, scaleY: handleHeight / 2, x: handleEnds[handleIndex] + (handleIndex ? -1 : 1), y: size[1] / 2 - handleHeight / 2 }); }, this), displaybles.filler.setShape({ x: handleInterval[0], y: 0, width: handleInterval[1] - handleInterval[0], height: size[1] }); var viewExtent = { x: handleInterval[0], width: handleInterval[1] - handleInterval[0] }; displaybles.moveHandle && (displaybles.moveHandle.setShape(viewExtent), displaybles.moveZone.setShape(viewExtent), displaybles.moveZone.getBoundingRect(), displaybles.moveHandleIcon && displaybles.moveHandleIcon.attr('x', viewExtent.x + viewExtent.width / 2)); for(var dataShadowSegs = displaybles.dataShadowSegs, segIntervals = [ 0, handleInterval[0], handleInterval[1], size[0] ], i = 0; i < dataShadowSegs.length; i++){ var segGroup = dataShadowSegs[i], clipPath = segGroup.getClipPath(); clipPath || (clipPath = new Rect(), segGroup.setClipPath(clipPath)), clipPath.setShape({ x: segIntervals[i], y: 0, width: segIntervals[i + 1] - segIntervals[i], height: size[1] }); } this._updateDataInfo(nonRealtime); }, SliderZoomView.prototype._updateDataInfo = function(nonRealtime) { var dataZoomModel = this.dataZoomModel, displaybles = this._displayables, handleLabels = displaybles.handleLabels, orient = this._orient, labelTexts = [ '', '' ]; if (dataZoomModel.get('showDetail')) { var axisProxy = dataZoomModel.findRepresentativeAxisProxy(); if (axisProxy) { var axis = axisProxy.getAxisModel().axis, range = this._range, dataInterval = nonRealtime ? axisProxy.calculateDataWindow({ start: range[0], end: range[1] }).valueWindow : axisProxy.getDataValueWindow(); labelTexts = [ this._formatLabel(dataInterval[0], axis), this._formatLabel(dataInterval[1], axis) ]; } } var orderedHandleEnds = asc(this._handleEnds.slice()); function setLabel(handleIndex) { var barTransform = getTransform(displaybles.handles[handleIndex].parent, this.group), direction = transformDirection(0 === handleIndex ? 'right' : 'left', barTransform), offset = this._handleWidth / 2 + 5, textPoint = applyTransform$1([ orderedHandleEnds[handleIndex] + (0 === handleIndex ? -offset : offset), this._size[1] / 2 ], barTransform); handleLabels[handleIndex].setStyle({ x: textPoint[0], y: textPoint[1], verticalAlign: orient === HORIZONTAL ? 'middle' : direction, align: orient === HORIZONTAL ? direction : 'center', text: labelTexts[handleIndex] }); } setLabel.call(this, 0), setLabel.call(this, 1); }, SliderZoomView.prototype._formatLabel = function(value, axis) { var dataZoomModel = this.dataZoomModel, labelFormatter = dataZoomModel.get('labelFormatter'), labelPrecision = dataZoomModel.get('labelPrecision'); (null == labelPrecision || 'auto' === labelPrecision) && (labelPrecision = axis.getPixelPrecision()); var valueStr = null == value || isNaN(value) ? '' : 'category' === axis.type || 'time' === axis.type ? axis.scale.getLabel({ value: Math.round(value) }) : value.toFixed(Math.min(labelPrecision, 20)); return isFunction(labelFormatter) ? labelFormatter(value, valueStr) : isString(labelFormatter) ? labelFormatter.replace('{value}', valueStr) : valueStr; }, SliderZoomView.prototype._showDataInfo = function(showOrHide) { showOrHide = this._dragging || showOrHide; var displayables = this._displayables, handleLabels = displayables.handleLabels; handleLabels[0].attr('invisible', !showOrHide), handleLabels[1].attr('invisible', !showOrHide), displayables.moveHandle && this.api[showOrHide ? 'enterEmphasis' : 'leaveEmphasis'](displayables.moveHandle, 1); }, SliderZoomView.prototype._onDragMove = function(handleIndex, dx, dy, event) { this._dragging = !0, stop(event.event); var vertex = applyTransform$1([ dx, dy ], this._displayables.sliderGroup.getLocalTransform(), !0), changed = this._updateInterval(handleIndex, vertex[0]), realtime = this.dataZoomModel.get('realtime'); this._updateView(!realtime), changed && realtime && this._dispatchZoomAction(!0); }, SliderZoomView.prototype._onDragEnd = function() { this._dragging = !1, this._showDataInfo(!1), this.dataZoomModel.get('realtime') || this._dispatchZoomAction(!1); }, SliderZoomView.prototype._onClickPanel = function(e) { var size = this._size, localPoint = this._displayables.sliderGroup.transformCoordToLocal(e.offsetX, e.offsetY); if (!(localPoint[0] < 0) && !(localPoint[0] > size[0]) && !(localPoint[1] < 0) && !(localPoint[1] > size[1])) { var handleEnds = this._handleEnds, center = (handleEnds[0] + handleEnds[1]) / 2, changed = this._updateInterval('all', localPoint[0] - center); this._updateView(), changed && this._dispatchZoomAction(!1); } }, SliderZoomView.prototype._onBrushStart = function(e) { var x = e.offsetX, y = e.offsetY; this._brushStart = new Point(x, y), this._brushing = !0, this._brushStartTime = +new Date(); }, SliderZoomView.prototype._onBrushEnd = function(e) { if (this._brushing) { var brushRect = this._displayables.brushRect; if (this._brushing = !1, brushRect) { brushRect.attr('ignore', !0); var brushShape = brushRect.shape; if (!(+new Date() - this._brushStartTime < 200 && 5 > Math.abs(brushShape.width))) { var viewExtend = this._getViewExtent(), percentExtent = [ 0, 100 ]; this._range = asc([ linearMap(brushShape.x, viewExtend, percentExtent, !0), linearMap(brushShape.x + brushShape.width, viewExtend, percentExtent, !0) ]), this._handleEnds = [ brushShape.x, brushShape.x + brushShape.width ], this._updateView(), this._dispatchZoomAction(!1); } } } }, SliderZoomView.prototype._onBrush = function(e) { this._brushing && (stop(e.event), this._updateBrushRect(e.offsetX, e.offsetY)); }, SliderZoomView.prototype._updateBrushRect = function(mouseX, mouseY) { var displayables = this._displayables, dataZoomModel = this.dataZoomModel, brushRect = displayables.brushRect; brushRect || (brushRect = displayables.brushRect = new Rect({ silent: !0, style: dataZoomModel.getModel('brushStyle').getItemStyle() }), displayables.sliderGroup.add(brushRect)), brushRect.attr('ignore', !1); var brushStart = this._brushStart, sliderGroup = this._displayables.sliderGroup, endPoint = sliderGroup.transformCoordToLocal(mouseX, mouseY), startPoint = sliderGroup.transformCoordToLocal(brushStart.x, brushStart.y), size = this._size; endPoint[0] = Math.max(Math.min(size[0], endPoint[0]), 0), brushRect.setShape({ x: startPoint[0], y: 0, width: endPoint[0] - startPoint[0], height: size[1] }); }, SliderZoomView.prototype._dispatchZoomAction = function(realtime) { var range = this._range; this.api.dispatchAction({ type: 'dataZoom', from: this.uid, dataZoomId: this.dataZoomModel.id, animation: realtime ? REALTIME_ANIMATION_CONFIG : null, start: range[0], end: range[1] }); }, SliderZoomView.prototype._findCoordRect = function() { var rect, coordSysInfoList = collectReferCoordSysModelInfo(this.dataZoomModel).infoList; if (!rect && coordSysInfoList.length) { var coordSys = coordSysInfoList[0].model.coordinateSystem; rect = coordSys.getRect && coordSys.getRect(); } if (!rect) { var width = this.api.getWidth(), height = this.api.getHeight(); rect = { x: 0.2 * width, y: 0.2 * height, width: 0.6 * width, height: 0.6 * height }; } return rect; }, SliderZoomView.type = 'dataZoom.slider', SliderZoomView; }(DataZoomView); function getCursor(orient) { return 'vertical' === orient ? 'ns-resize' : 'ew-resize'; } function install$L(registers) { registers.registerComponentModel(SliderZoomModel), registers.registerComponentView(SliderZoomView), installCommon(registers); } var visualDefault = { get: function(visualType, key, isCategory) { var value = clone((defaultOption$1[visualType] || {})[key]); return isCategory && isArray(value) ? value[value.length - 1] : value; } }, defaultOption$1 = { color: { active: [ '#006edd', '#e0ffff' ], inactive: [ 'rgba(0,0,0,0)' ] }, colorHue: { active: [ 0, 360 ], inactive: [ 0, 0 ] }, colorSaturation: { active: [ 0.3, 1 ], inactive: [ 0, 0 ] }, colorLightness: { active: [ 0.9, 0.5 ], inactive: [ 0, 0 ] }, colorAlpha: { active: [ 0.3, 1 ], inactive: [ 0, 0 ] }, opacity: { active: [ 0.3, 1 ], inactive: [ 0, 0 ] }, symbol: { active: [ 'circle', 'roundRect', 'diamond' ], inactive: [ 'none' ] }, symbolSize: { active: [ 10, 50 ], inactive: [ 0, 0 ] } }, mapVisual$1 = VisualMapping.mapVisual, eachVisual = VisualMapping.eachVisual, VisualMapModel = function(_super) { function VisualMapModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = VisualMapModel.type, _this.stateList = [ 'inRange', 'outOfRange' ], _this.replacableOptionKeys = [ 'inRange', 'outOfRange', 'target', 'controller', 'color' ], _this.layoutMode = { type: 'box', ignoreSize: !0 }, _this.dataBound = [ -1 / 0, 1 / 0 ], _this.targetVisuals = {}, _this.controllerVisuals = {}, _this; } return __extends(VisualMapModel, _super), VisualMapModel.prototype.init = function(option, parentModel, ecModel) { this.mergeDefaultAndTheme(option, ecModel); }, VisualMapModel.prototype.optionUpdated = function(newOption, isInit) { var thisOption = this.option; env1.canvasSupported || (thisOption.realtime = !1), isInit || replaceVisualOption(thisOption, newOption, this.replacableOptionKeys), this.textStyleModel = this.getModel('textStyle'), this.resetItemSize(), this.completeVisualOption(); }, VisualMapModel.prototype.resetVisual = function(supplementVisualOption) { var stateList = this.stateList; supplementVisualOption = bind(supplementVisualOption, this), this.controllerVisuals = createVisualMappings(this.option.controller, stateList, supplementVisualOption), this.targetVisuals = createVisualMappings(this.option.target, stateList, supplementVisualOption); }, VisualMapModel.prototype.getItemSymbol = function() { return null; }, VisualMapModel.prototype.getTargetSeriesIndices = function() { var optionSeriesIndex = this.option.seriesIndex, seriesIndices = []; return null == optionSeriesIndex || 'all' === optionSeriesIndex ? this.ecModel.eachSeries(function(seriesModel, index) { seriesIndices.push(index); }) : seriesIndices = normalizeToArray(optionSeriesIndex), seriesIndices; }, VisualMapModel.prototype.eachTargetSeries = function(callback, context) { each(this.getTargetSeriesIndices(), function(seriesIndex) { var seriesModel = this.ecModel.getSeriesByIndex(seriesIndex); seriesModel && callback.call(context, seriesModel); }, this); }, VisualMapModel.prototype.isTargetSeries = function(seriesModel) { var is = !1; return this.eachTargetSeries(function(model) { model === seriesModel && (is = !0); }), is; }, VisualMapModel.prototype.formatValueText = function(value, isCategory, edgeSymbols) { var isMinMax, option = this.option, precision = option.precision, dataBound = this.dataBound, formatter = option.formatter; edgeSymbols = edgeSymbols || [ '<', '>' ], isArray(value) && (value = value.slice(), isMinMax = !0); var textValue = isCategory ? value : isMinMax ? [ toFixed(value[0]), toFixed(value[1]) ] : toFixed(value); if (isString(formatter)) return formatter.replace('{value}', isMinMax ? textValue[0] : textValue).replace('{value2}', isMinMax ? textValue[1] : textValue); if (isFunction(formatter)) return isMinMax ? formatter(value[0], value[1]) : formatter(value); if (!isMinMax) return textValue; return value[0] === dataBound[0] ? edgeSymbols[0] + ' ' + textValue[1] : value[1] === dataBound[1] ? edgeSymbols[1] + ' ' + textValue[0] : textValue[0] + ' - ' + textValue[1]; function toFixed(val) { return val === dataBound[0] ? 'min' : val === dataBound[1] ? 'max' : (+val).toFixed(Math.min(precision, 20)); } }, VisualMapModel.prototype.resetExtent = function() { var thisOption = this.option, extent = asc([ thisOption.min, thisOption.max ]); this._dataExtent = extent; }, VisualMapModel.prototype.getDataDimension = function(list) { var optDim = this.option.dimension, listDimensions = list.dimensions; if (null != optDim || listDimensions.length) { if (null != optDim) return list.getDimension(optDim); for(var dimNames = list.dimensions, i = dimNames.length - 1; i >= 0; i--){ var dimName = dimNames[i]; if (!list.getDimensionInfo(dimName).isCalculationCoord) return dimName; } } }, VisualMapModel.prototype.getExtent = function() { return this._dataExtent.slice(); }, VisualMapModel.prototype.completeVisualOption = function() { var ecModel = this.ecModel, thisOption = this.option, base = { inRange: thisOption.inRange, outOfRange: thisOption.outOfRange }, target = thisOption.target || (thisOption.target = {}), controller = thisOption.controller || (thisOption.controller = {}); merge(target, base), merge(controller, base); var isCategory = this.isCategory(); function completeSingle(base) { isArray(thisOption.color) && !base.inRange && (base.inRange = { color: thisOption.color.slice().reverse() }), base.inRange = base.inRange || { color: ecModel.get('gradientColor') }; } completeSingle.call(this, target), completeSingle.call(this, controller), (function(base, stateExist, stateAbsent) { var optExist = base[stateExist], optAbsent = base[stateAbsent]; optExist && !optAbsent && (optAbsent = base[stateAbsent] = {}, each(optExist, function(visualData, visualType) { if (VisualMapping.isValidType(visualType)) { var defa = visualDefault.get(visualType, 'inactive', isCategory); null == defa || (optAbsent[visualType] = defa, 'color' !== visualType || optAbsent.hasOwnProperty('opacity') || optAbsent.hasOwnProperty('colorAlpha') || (optAbsent.opacity = [ 0, 0 ])); } })); }).call(this, target, 'inRange', 'outOfRange'), (function(controller) { var symbolExists = (controller.inRange || {}).symbol || (controller.outOfRange || {}).symbol, symbolSizeExists = (controller.inRange || {}).symbolSize || (controller.outOfRange || {}).symbolSize, inactiveColor = this.get('inactiveColor'), defaultSymbol = this.getItemSymbol() || 'roundRect'; each(this.stateList, function(state) { var itemSize = this.itemSize, visuals = controller[state]; visuals || (visuals = controller[state] = { color: isCategory ? inactiveColor : [ inactiveColor ] }), null == visuals.symbol && (visuals.symbol = symbolExists && clone(symbolExists) || (isCategory ? defaultSymbol : [ defaultSymbol ])), null == visuals.symbolSize && (visuals.symbolSize = symbolSizeExists && clone(symbolSizeExists) || (isCategory ? itemSize[0] : [ itemSize[0], itemSize[0] ])), visuals.symbol = mapVisual$1(visuals.symbol, function(symbol) { return 'none' === symbol ? defaultSymbol : symbol; }); var symbolSize = visuals.symbolSize; if (null != symbolSize) { var max_1 = -1 / 0; eachVisual(symbolSize, function(value) { value > max_1 && (max_1 = value); }), visuals.symbolSize = mapVisual$1(symbolSize, function(value) { return linearMap(value, [ 0, max_1 ], [ 0, itemSize[0] ], !0); }); } }, this); }).call(this, controller); }, VisualMapModel.prototype.resetItemSize = function() { this.itemSize = [ parseFloat(this.get('itemWidth')), parseFloat(this.get('itemHeight')) ]; }, VisualMapModel.prototype.isCategory = function() { return !!this.option.categories; }, VisualMapModel.prototype.setSelected = function(selected) {}, VisualMapModel.prototype.getSelected = function() { return null; }, VisualMapModel.prototype.getValueState = function(value) { return null; }, VisualMapModel.prototype.getVisualMeta = function(getColorVisual) { return null; }, VisualMapModel.type = 'visualMap', VisualMapModel.dependencies = [ 'series' ], VisualMapModel.defaultOption = { show: !0, zlevel: 0, z: 4, seriesIndex: 'all', min: 0, max: 200, left: 0, right: null, top: null, bottom: 0, itemWidth: null, itemHeight: null, inverse: !1, orient: 'vertical', backgroundColor: 'rgba(0,0,0,0)', borderColor: '#ccc', contentColor: '#5793f3', inactiveColor: '#aaa', borderWidth: 0, padding: 5, textGap: 10, precision: 0, textStyle: { color: '#333' } }, VisualMapModel; }(ComponentModel), ContinuousModel = function(_super) { function ContinuousModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = ContinuousModel.type, _this; } return __extends(ContinuousModel, _super), ContinuousModel.prototype.optionUpdated = function(newOption, isInit) { _super.prototype.optionUpdated.apply(this, arguments), this.resetExtent(), this.resetVisual(function(mappingOption) { mappingOption.mappingMethod = 'linear', mappingOption.dataExtent = this.getExtent(); }), this._resetRange(); }, ContinuousModel.prototype.resetItemSize = function() { _super.prototype.resetItemSize.apply(this, arguments); var itemSize = this.itemSize; (null == itemSize[0] || isNaN(itemSize[0])) && (itemSize[0] = 20), (null == itemSize[1] || isNaN(itemSize[1])) && (itemSize[1] = 140); }, ContinuousModel.prototype._resetRange = function() { var dataExtent = this.getExtent(), range = this.option.range; !range || range.auto ? (dataExtent.auto = 1, this.option.range = dataExtent) : isArray(range) && (range[0] > range[1] && range.reverse(), range[0] = Math.max(range[0], dataExtent[0]), range[1] = Math.min(range[1], dataExtent[1])); }, ContinuousModel.prototype.completeVisualOption = function() { _super.prototype.completeVisualOption.apply(this, arguments), each(this.stateList, function(state) { var symbolSize = this.option.controller[state].symbolSize; symbolSize && symbolSize[0] !== symbolSize[1] && (symbolSize[0] = symbolSize[1] / 3); }, this); }, ContinuousModel.prototype.setSelected = function(selected) { this.option.range = selected.slice(), this._resetRange(); }, ContinuousModel.prototype.getSelected = function() { var dataExtent = this.getExtent(), dataInterval = asc((this.get('range') || []).slice()); return dataInterval[0] > dataExtent[1] && (dataInterval[0] = dataExtent[1]), dataInterval[1] > dataExtent[1] && (dataInterval[1] = dataExtent[1]), dataInterval[0] < dataExtent[0] && (dataInterval[0] = dataExtent[0]), dataInterval[1] < dataExtent[0] && (dataInterval[1] = dataExtent[0]), dataInterval; }, ContinuousModel.prototype.getValueState = function(value) { var range = this.option.range, dataExtent = this.getExtent(); return (range[0] <= dataExtent[0] || range[0] <= value) && (range[1] >= dataExtent[1] || value <= range[1]) ? 'inRange' : 'outOfRange'; }, ContinuousModel.prototype.findTargetDataIndices = function(range) { var result = []; return this.eachTargetSeries(function(seriesModel) { var dataIndices = [], data = seriesModel.getData(); data.each(this.getDataDimension(data), function(value, dataIndex) { range[0] <= value && value <= range[1] && dataIndices.push(dataIndex); }, this), result.push({ seriesId: seriesModel.id, dataIndex: dataIndices }); }, this), result; }, ContinuousModel.prototype.getVisualMeta = function(getColorVisual) { var oVals = getColorStopValues(this, 'outOfRange', this.getExtent()), iVals = getColorStopValues(this, 'inRange', this.option.range.slice()), stops = []; function setStop(value, valueState) { stops.push({ value: value, color: getColorVisual(value, valueState) }); } for(var iIdx = 0, oIdx = 0, iLen = iVals.length, oLen = oVals.length; oIdx < oLen && (!iVals.length || oVals[oIdx] <= iVals[0]); oIdx++)oVals[oIdx] < iVals[iIdx] && setStop(oVals[oIdx], 'outOfRange'); for(var first = 1; iIdx < iLen; iIdx++, first = 0)first && stops.length && setStop(iVals[iIdx], 'outOfRange'), setStop(iVals[iIdx], 'inRange'); for(var first = 1; oIdx < oLen; oIdx++)(!iVals.length || iVals[iVals.length - 1] < oVals[oIdx]) && (first && (stops.length && setStop(stops[stops.length - 1].value, 'outOfRange'), first = 0), setStop(oVals[oIdx], 'outOfRange')); var stopsLen = stops.length; return { stops: stops, outerColors: [ stopsLen ? stops[0].color : 'transparent', stopsLen ? stops[stopsLen - 1].color : 'transparent' ] }; }, ContinuousModel.type = 'visualMap.continuous', ContinuousModel.defaultOption = inheritDefaultOption(VisualMapModel.defaultOption, { align: 'auto', calculable: !1, hoverLink: !0, realtime: !0, handleIcon: 'path://M-11.39,9.77h0a3.5,3.5,0,0,1-3.5,3.5h-22a3.5,3.5,0,0,1-3.5-3.5h0a3.5,3.5,0,0,1,3.5-3.5h22A3.5,3.5,0,0,1-11.39,9.77Z', handleSize: '120%', handleStyle: { borderColor: '#fff', borderWidth: 1 }, indicatorIcon: 'circle', indicatorSize: '50%', indicatorStyle: { borderColor: '#fff', borderWidth: 2, shadowBlur: 2, shadowOffsetX: 1, shadowOffsetY: 1, shadowColor: 'rgba(0,0,0,0.2)' } }), ContinuousModel; }(VisualMapModel); function getColorStopValues(visualMapModel, valueState, dataExtent) { if (dataExtent[0] === dataExtent[1]) return dataExtent.slice(); for(var step = (dataExtent[1] - dataExtent[0]) / 200, value = dataExtent[0], stopValues = [], i = 0; i <= 200 && value < dataExtent[1]; i++)stopValues.push(value), value += step; return stopValues.push(dataExtent[1]), stopValues; } var VisualMapView = function(_super) { function VisualMapView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = VisualMapView.type, _this.autoPositionValues = { left: 1, right: 1, top: 1, bottom: 1 }, _this; } return __extends(VisualMapView, _super), VisualMapView.prototype.init = function(ecModel, api) { this.ecModel = ecModel, this.api = api; }, VisualMapView.prototype.render = function(visualMapModel, ecModel, api, payload) { if (this.visualMapModel = visualMapModel, !1 === visualMapModel.get('show')) { this.group.removeAll(); return; } this.doRender(visualMapModel, ecModel, api, payload); }, VisualMapView.prototype.renderBackground = function(group) { var visualMapModel = this.visualMapModel, padding = normalizeCssArray(visualMapModel.get('padding') || 0), rect = group.getBoundingRect(); group.add(new Rect({ z2: -1, silent: !0, shape: { x: rect.x - padding[3], y: rect.y - padding[0], width: rect.width + padding[3] + padding[1], height: rect.height + padding[0] + padding[2] }, style: { fill: visualMapModel.get('backgroundColor'), stroke: visualMapModel.get('borderColor'), lineWidth: visualMapModel.get('borderWidth') } })); }, VisualMapView.prototype.getControllerVisual = function(targetValue, visualCluster, opts) { var forceState = (opts = opts || {}).forceState, visualMapModel = this.visualMapModel, visualObj = {}; if ('color' === visualCluster) { var defaultColor = visualMapModel.get('contentColor'); visualObj.color = defaultColor; } function getter(key) { return visualObj[key]; } function setter(key, value) { visualObj[key] = value; } var mappings = visualMapModel.controllerVisuals[forceState || visualMapModel.getValueState(targetValue)], visualTypes = VisualMapping.prepareVisualTypes(mappings); return each(visualTypes, function(type) { var visualMapping = mappings[type]; opts.convertOpacityToAlpha && 'opacity' === type && (type = 'colorAlpha', visualMapping = mappings.__alphaForOpacity), VisualMapping.dependsOn(type, visualCluster) && visualMapping && visualMapping.applyVisual(targetValue, getter, setter); }), visualObj[visualCluster]; }, VisualMapView.prototype.positionGroup = function(group) { var model = this.visualMapModel, api = this.api; positionElement(group, model.getBoxLayoutParams(), { width: api.getWidth(), height: api.getHeight() }); }, VisualMapView.prototype.doRender = function(visualMapModel, ecModel, api, payload) {}, VisualMapView.type = 'visualMap', VisualMapView; }(ComponentView), paramsSet = [ [ 'left', 'right', 'width' ], [ 'top', 'bottom', 'height' ] ]; function getItemAlign(visualMapModel, api, itemSize) { var modelOption = visualMapModel.option, itemAlign = modelOption.align; if (null != itemAlign && 'auto' !== itemAlign) return itemAlign; for(var ecSize = { width: api.getWidth(), height: api.getHeight() }, realIndex = 'horizontal' === modelOption.orient ? 1 : 0, reals = paramsSet[realIndex], fakeValue = [ 0, null, 10 ], layoutInput = {}, i = 0; i < 3; i++)layoutInput[paramsSet[1 - realIndex][i]] = fakeValue[i], layoutInput[reals[i]] = 2 === i ? itemSize[0] : modelOption[reals[i]]; var rParam = [ [ 'x', 'width', 3 ], [ 'y', 'height', 0 ] ][realIndex], rect = getLayoutRect(layoutInput, ecSize, modelOption.padding); return reals[(rect.margin[rParam[2]] || 0) + rect[rParam[0]] + 0.5 * rect[rParam[1]] < 0.5 * ecSize[rParam[1]] ? 0 : 1]; } function makeHighDownBatch(batch, visualMapModel) { return each(batch || [], function(batchItem) { null != batchItem.dataIndex && (batchItem.dataIndexInside = batchItem.dataIndex, batchItem.dataIndex = null), batchItem.highlightKey = 'visualMap' + (visualMapModel ? visualMapModel.componentIndex : ''); }), batch; } var mathMin$a = Math.min, mathMax$a = Math.max, ContinuousView = function(_super) { function ContinuousView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = ContinuousView.type, _this._shapes = {}, _this._dataInterval = [], _this._handleEnds = [], _this._hoverLinkDataIndices = [], _this; } return __extends(ContinuousView, _super), ContinuousView.prototype.doRender = function(visualMapModel, ecModel, api, payload) { this._api = api, payload && 'selectDataRange' === payload.type && payload.from === this.uid || this._buildView(); }, ContinuousView.prototype._buildView = function() { this.group.removeAll(); var visualMapModel = this.visualMapModel, thisGroup = this.group; this._orient = visualMapModel.get('orient'), this._useHandle = visualMapModel.get('calculable'), this._resetInterval(), this._renderBar(thisGroup); var dataRangeText = visualMapModel.get('text'); this._renderEndsText(thisGroup, dataRangeText, 0), this._renderEndsText(thisGroup, dataRangeText, 1), this._updateView(!0), this.renderBackground(thisGroup), this._updateView(), this._enableHoverLinkToSeries(), this._enableHoverLinkFromSeries(), this.positionGroup(thisGroup); }, ContinuousView.prototype._renderEndsText = function(group, dataRangeText, endsIndex) { if (dataRangeText) { var text = dataRangeText[1 - endsIndex]; text = null != text ? text + '' : ''; var visualMapModel = this.visualMapModel, textGap = visualMapModel.get('textGap'), itemSize = visualMapModel.itemSize, barGroup = this._shapes.mainGroup, position = this._applyTransform([ itemSize[0] / 2, 0 === endsIndex ? -textGap : itemSize[1] + textGap ], barGroup), align = this._applyTransform(0 === endsIndex ? 'bottom' : 'top', barGroup), orient = this._orient, textStyleModel = this.visualMapModel.textStyleModel; this.group.add(new ZRText({ style: { x: position[0], y: position[1], verticalAlign: 'horizontal' === orient ? 'middle' : align, align: 'horizontal' === orient ? align : 'center', text: text, font: textStyleModel.getFont(), fill: textStyleModel.getTextColor() } })); } }, ContinuousView.prototype._renderBar = function(targetGroup) { var visualMapModel = this.visualMapModel, shapes = this._shapes, itemSize = visualMapModel.itemSize, orient = this._orient, useHandle = this._useHandle, itemAlign = getItemAlign(visualMapModel, this.api, itemSize), mainGroup = shapes.mainGroup = this._createBarGroup(itemAlign), gradientBarGroup = new Group(); mainGroup.add(gradientBarGroup), gradientBarGroup.add(shapes.outOfRange = createPolygon()), gradientBarGroup.add(shapes.inRange = createPolygon(null, useHandle ? getCursor$1(this._orient) : null, bind(this._dragHandle, this, 'all', !1), bind(this._dragHandle, this, 'all', !0))), gradientBarGroup.setClipPath(new Rect({ shape: { x: 0, y: 0, width: itemSize[0], height: itemSize[1], r: 3 } })); var textRect = visualMapModel.textStyleModel.getTextRect('国'), textSize = mathMax$a(textRect.width, textRect.height); useHandle && (shapes.handleThumbs = [], shapes.handleLabels = [], shapes.handleLabelPoints = [], this._createHandle(visualMapModel, mainGroup, 0, itemSize, textSize, orient), this._createHandle(visualMapModel, mainGroup, 1, itemSize, textSize, orient)), this._createIndicator(visualMapModel, mainGroup, itemSize, textSize, orient), targetGroup.add(mainGroup); }, ContinuousView.prototype._createHandle = function(visualMapModel, mainGroup, handleIndex, itemSize, textSize, orient) { var onDrift = bind(this._dragHandle, this, handleIndex, !1), onDragEnd = bind(this._dragHandle, this, handleIndex, !0), handleSize = parsePercent(visualMapModel.get('handleSize'), itemSize[0]), handleThumb = createSymbol(visualMapModel.get('handleIcon'), -handleSize / 2, -handleSize / 2, handleSize, handleSize, null, !0), cursor = getCursor$1(this._orient); handleThumb.attr({ cursor: cursor, draggable: !0, drift: onDrift, ondragend: onDragEnd, onmousemove: function(e) { stop(e.event); } }), handleThumb.x = itemSize[0] / 2, handleThumb.useStyle(visualMapModel.getModel('handleStyle').getItemStyle()), handleThumb.setStyle({ strokeNoScale: !0, strokeFirst: !0 }), handleThumb.style.lineWidth *= 2, handleThumb.ensureState('emphasis').style = visualMapModel.getModel([ 'emphasis', 'handleStyle' ]).getItemStyle(), setAsHighDownDispatcher(handleThumb, !0), mainGroup.add(handleThumb); var textStyleModel = this.visualMapModel.textStyleModel, handleLabel = new ZRText({ cursor: cursor, draggable: !0, drift: onDrift, onmousemove: function(e) { stop(e.event); }, ondragend: onDragEnd, style: { x: 0, y: 0, text: '', font: textStyleModel.getFont(), fill: textStyleModel.getTextColor() } }); handleLabel.ensureState('blur').style = { opacity: 0.1 }, handleLabel.stateTransition = { duration: 200 }, this.group.add(handleLabel); var shapes = this._shapes; shapes.handleThumbs[handleIndex] = handleThumb, shapes.handleLabelPoints[handleIndex] = [ handleSize, 0 ], shapes.handleLabels[handleIndex] = handleLabel; }, ContinuousView.prototype._createIndicator = function(visualMapModel, mainGroup, itemSize, textSize, orient) { var scale = parsePercent(visualMapModel.get('indicatorSize'), itemSize[0]), indicator = createSymbol(visualMapModel.get('indicatorIcon'), -scale / 2, -scale / 2, scale, scale, null, !0); indicator.attr({ cursor: 'move', invisible: !0, silent: !0, x: itemSize[0] / 2 }); var indicatorStyle = visualMapModel.getModel('indicatorStyle').getItemStyle(); if (indicator instanceof ZRImage) { var pathStyle = indicator.style; indicator.useStyle(extend({ image: pathStyle.image, x: pathStyle.x, y: pathStyle.y, width: pathStyle.width, height: pathStyle.height }, indicatorStyle)); } else indicator.useStyle(indicatorStyle); mainGroup.add(indicator); var textStyleModel = this.visualMapModel.textStyleModel, indicatorLabel = new ZRText({ silent: !0, invisible: !0, style: { x: 0, y: 0, text: '', font: textStyleModel.getFont(), fill: textStyleModel.getTextColor() } }); this.group.add(indicatorLabel); var indicatorLabelPoint = [ ('horizontal' === orient ? textSize / 2 : 6) + itemSize[0] / 2, 0 ], shapes = this._shapes; shapes.indicator = indicator, shapes.indicatorLabel = indicatorLabel, shapes.indicatorLabelPoint = indicatorLabelPoint, this._firstShowIndicator = !0; }, ContinuousView.prototype._dragHandle = function(handleIndex, isEnd, dx, dy) { if (this._useHandle) { if (this._dragging = !isEnd, !isEnd) { var vertex = this._applyTransform([ dx, dy ], this._shapes.mainGroup, !0); this._updateInterval(handleIndex, vertex[1]), this._hideIndicator(), this._updateView(); } !this.visualMapModel.get('realtime') === isEnd && this.api.dispatchAction({ type: 'selectDataRange', from: this.uid, visualMapId: this.visualMapModel.id, selected: this._dataInterval.slice() }), isEnd ? this._hovering || this._clearHoverLinkToSeries() : useHoverLinkOnHandle(this.visualMapModel) && this._doHoverLinkToSeries(this._handleEnds[handleIndex], !1); } }, ContinuousView.prototype._resetInterval = function() { var visualMapModel = this.visualMapModel, dataInterval = this._dataInterval = visualMapModel.getSelected(), dataExtent = visualMapModel.getExtent(), sizeExtent = [ 0, visualMapModel.itemSize[1] ]; this._handleEnds = [ linearMap(dataInterval[0], dataExtent, sizeExtent, !0), linearMap(dataInterval[1], dataExtent, sizeExtent, !0) ]; }, ContinuousView.prototype._updateInterval = function(handleIndex, delta) { delta = delta || 0; var visualMapModel = this.visualMapModel, handleEnds = this._handleEnds, sizeExtent = [ 0, visualMapModel.itemSize[1] ]; sliderMove(delta, handleEnds, sizeExtent, handleIndex, 0); var dataExtent = visualMapModel.getExtent(); this._dataInterval = [ linearMap(handleEnds[0], sizeExtent, dataExtent, !0), linearMap(handleEnds[1], sizeExtent, dataExtent, !0) ]; }, ContinuousView.prototype._updateView = function(forSketch) { var visualMapModel = this.visualMapModel, dataExtent = visualMapModel.getExtent(), shapes = this._shapes, outOfRangeHandleEnds = [ 0, visualMapModel.itemSize[1] ], inRangeHandleEnds = forSketch ? outOfRangeHandleEnds : this._handleEnds, visualInRange = this._createBarVisual(this._dataInterval, dataExtent, inRangeHandleEnds, 'inRange'), visualOutOfRange = this._createBarVisual(dataExtent, dataExtent, outOfRangeHandleEnds, 'outOfRange'); shapes.inRange.setStyle({ fill: visualInRange.barColor }).setShape('points', visualInRange.barPoints), shapes.outOfRange.setStyle({ fill: visualOutOfRange.barColor }).setShape('points', visualOutOfRange.barPoints), this._updateHandle(inRangeHandleEnds, visualInRange); }, ContinuousView.prototype._createBarVisual = function(dataInterval, dataExtent, handleEnds, forceState) { var opts = { forceState: forceState, convertOpacityToAlpha: !0 }, colorStops = this._makeColorGradient(dataInterval, opts), symbolSizes = [ this.getControllerVisual(dataInterval[0], 'symbolSize', opts), this.getControllerVisual(dataInterval[1], 'symbolSize', opts) ], barPoints = this._createBarPoints(handleEnds, symbolSizes); return { barColor: new LinearGradient(0, 0, 0, 1, colorStops), barPoints: barPoints, handlesColor: [ colorStops[0].color, colorStops[colorStops.length - 1].color ] }; }, ContinuousView.prototype._makeColorGradient = function(dataInterval, opts) { var colorStops = [], step = (dataInterval[1] - dataInterval[0]) / 100; colorStops.push({ color: this.getControllerVisual(dataInterval[0], 'color', opts), offset: 0 }); for(var i = 1; i < 100; i++){ var currValue = dataInterval[0] + step * i; if (currValue > dataInterval[1]) break; colorStops.push({ color: this.getControllerVisual(currValue, 'color', opts), offset: i / 100 }); } return colorStops.push({ color: this.getControllerVisual(dataInterval[1], 'color', opts), offset: 1 }), colorStops; }, ContinuousView.prototype._createBarPoints = function(handleEnds, symbolSizes) { var itemSize = this.visualMapModel.itemSize; return [ [ itemSize[0] - symbolSizes[0], handleEnds[0] ], [ itemSize[0], handleEnds[0] ], [ itemSize[0], handleEnds[1] ], [ itemSize[0] - symbolSizes[1], handleEnds[1] ] ]; }, ContinuousView.prototype._createBarGroup = function(itemAlign) { var orient = this._orient, inverse = this.visualMapModel.get('inverse'); return new Group('horizontal' !== orient || inverse ? 'horizontal' === orient && inverse ? { scaleX: 'bottom' === itemAlign ? -1 : 1, rotation: -Math.PI / 2 } : 'vertical' !== orient || inverse ? { scaleX: 'left' === itemAlign ? 1 : -1 } : { scaleX: 'left' === itemAlign ? 1 : -1, scaleY: -1 } : { scaleX: 'bottom' === itemAlign ? 1 : -1, rotation: Math.PI / 2 }); }, ContinuousView.prototype._updateHandle = function(handleEnds, visualInRange) { if (this._useHandle) { var shapes = this._shapes, visualMapModel = this.visualMapModel, handleThumbs = shapes.handleThumbs, handleLabels = shapes.handleLabels, itemSize = visualMapModel.itemSize, dataExtent = visualMapModel.getExtent(); each([ 0, 1 ], function(handleIndex) { var handleThumb = handleThumbs[handleIndex]; handleThumb.setStyle('fill', visualInRange.handlesColor[handleIndex]), handleThumb.y = handleEnds[handleIndex]; var val = linearMap(handleEnds[handleIndex], [ 0, itemSize[1] ], dataExtent, !0), symbolSize = this.getControllerVisual(val, 'symbolSize'); handleThumb.scaleX = handleThumb.scaleY = symbolSize / itemSize[0], handleThumb.x = itemSize[0] - symbolSize / 2; var textPoint = applyTransform$1(shapes.handleLabelPoints[handleIndex], getTransform(handleThumb, this.group)); handleLabels[handleIndex].setStyle({ x: textPoint[0], y: textPoint[1], text: visualMapModel.formatValueText(this._dataInterval[handleIndex]), verticalAlign: 'middle', align: 'vertical' === this._orient ? this._applyTransform('left', shapes.mainGroup) : 'center' }); }, this); } }, ContinuousView.prototype._showIndicator = function(cursorValue, textValue, rangeSymbol, halfHoverLinkSize) { var visualMapModel = this.visualMapModel, dataExtent = visualMapModel.getExtent(), itemSize = visualMapModel.itemSize, sizeExtent = [ 0, itemSize[1] ], shapes = this._shapes, indicator = shapes.indicator; if (indicator) { indicator.attr('invisible', !1); var color = this.getControllerVisual(cursorValue, 'color', { convertOpacityToAlpha: !0 }), symbolSize = this.getControllerVisual(cursorValue, 'symbolSize'), y = linearMap(cursorValue, dataExtent, sizeExtent, !0), x = itemSize[0] - symbolSize / 2, oldIndicatorPos = { x: indicator.x, y: indicator.y }; indicator.y = y, indicator.x = x; var textPoint = applyTransform$1(shapes.indicatorLabelPoint, getTransform(indicator, this.group)), indicatorLabel = shapes.indicatorLabel; indicatorLabel.attr('invisible', !1); var align = this._applyTransform('left', shapes.mainGroup), isHorizontal = 'horizontal' === this._orient; indicatorLabel.setStyle({ text: (rangeSymbol || '') + visualMapModel.formatValueText(textValue), verticalAlign: isHorizontal ? align : 'middle', align: isHorizontal ? 'center' : align }); var indicatorNewProps = { x: x, y: y, style: { fill: color } }, labelNewProps = { style: { x: textPoint[0], y: textPoint[1] } }; if (visualMapModel.ecModel.isAnimationEnabled() && !this._firstShowIndicator) { var animationCfg = { duration: 100, easing: 'cubicInOut', additive: !0 }; indicator.x = oldIndicatorPos.x, indicator.y = oldIndicatorPos.y, indicator.animateTo(indicatorNewProps, animationCfg), indicatorLabel.animateTo(labelNewProps, animationCfg); } else indicator.attr(indicatorNewProps), indicatorLabel.attr(labelNewProps); this._firstShowIndicator = !1; var handleLabels = this._shapes.handleLabels; if (handleLabels) for(var i = 0; i < handleLabels.length; i++)this._api.enterBlur(handleLabels[i]); } }, ContinuousView.prototype._enableHoverLinkToSeries = function() { var self1 = this; this._shapes.mainGroup.on('mousemove', function(e) { if (self1._hovering = !0, !self1._dragging) { var itemSize = self1.visualMapModel.itemSize, pos = self1._applyTransform([ e.offsetX, e.offsetY ], self1._shapes.mainGroup, !0, !0); pos[1] = mathMin$a(mathMax$a(0, pos[1]), itemSize[1]), self1._doHoverLinkToSeries(pos[1], 0 <= pos[0] && pos[0] <= itemSize[0]); } }).on('mouseout', function() { self1._hovering = !1, self1._dragging || self1._clearHoverLinkToSeries(); }); }, ContinuousView.prototype._enableHoverLinkFromSeries = function() { var zr = this.api.getZr(); this.visualMapModel.option.hoverLink ? (zr.on('mouseover', this._hoverLinkFromSeriesMouseOver, this), zr.on('mouseout', this._hideIndicator, this)) : this._clearHoverLinkFromSeries(); }, ContinuousView.prototype._doHoverLinkToSeries = function(cursorPos, hoverOnBar) { var visualMapModel = this.visualMapModel, itemSize = visualMapModel.itemSize; if (visualMapModel.option.hoverLink) { var halfHoverLinkSize, hoverLinkDataSize, sizeExtent = [ 0, itemSize[1] ], dataExtent = visualMapModel.getExtent(); cursorPos = mathMin$a(mathMax$a(sizeExtent[0], cursorPos), sizeExtent[1]); var halfHoverLinkSize1 = (halfHoverLinkSize = 6, (hoverLinkDataSize = visualMapModel.get('hoverLinkDataSize')) && (halfHoverLinkSize = linearMap(hoverLinkDataSize, dataExtent, sizeExtent, !0) / 2), halfHoverLinkSize), hoverRange = [ cursorPos - halfHoverLinkSize1, cursorPos + halfHoverLinkSize1 ], cursorValue = linearMap(cursorPos, sizeExtent, dataExtent, !0), valueRange = [ linearMap(hoverRange[0], sizeExtent, dataExtent, !0), linearMap(hoverRange[1], sizeExtent, dataExtent, !0) ]; hoverRange[0] < sizeExtent[0] && (valueRange[0] = -1 / 0), hoverRange[1] > sizeExtent[1] && (valueRange[1] = 1 / 0), hoverOnBar && (valueRange[0] === -1 / 0 ? this._showIndicator(cursorValue, valueRange[1], '< ', halfHoverLinkSize1) : valueRange[1] === 1 / 0 ? this._showIndicator(cursorValue, valueRange[0], '> ', halfHoverLinkSize1) : this._showIndicator(cursorValue, cursorValue, '≈ ', halfHoverLinkSize1)); var oldBatch = this._hoverLinkDataIndices, newBatch = []; (hoverOnBar || useHoverLinkOnHandle(visualMapModel)) && (newBatch = this._hoverLinkDataIndices = visualMapModel.findTargetDataIndices(valueRange)); var resultBatches = function(batchA, batchB) { var mapA = {}, mapB = {}; return makeMap(batchA || [], mapA), makeMap(batchB || [], mapB, mapA), [ mapToArray(mapA), mapToArray(mapB) ]; function makeMap(sourceBatch, map, otherMap) { for(var i = 0, len = sourceBatch.length; i < len; i++){ var seriesId = convertOptionIdName(sourceBatch[i].seriesId, null); if (null == seriesId) return; for(var dataIndices = normalizeToArray(sourceBatch[i].dataIndex), otherDataIndices = otherMap && otherMap[seriesId], j = 0, lenj = dataIndices.length; j < lenj; j++){ var dataIndex = dataIndices[j]; otherDataIndices && otherDataIndices[dataIndex] ? otherDataIndices[dataIndex] = null : (map[seriesId] || (map[seriesId] = {}))[dataIndex] = 1; } } } function mapToArray(map, isData) { var result = []; for(var i in map)if (map.hasOwnProperty(i) && null != map[i]) { if (isData) result.push(+i); else { var dataIndices = mapToArray(map[i], !0); dataIndices.length && result.push({ seriesId: i, dataIndex: dataIndices }); } } return result; } }(oldBatch, newBatch); this._dispatchHighDown('downplay', makeHighDownBatch(resultBatches[0], visualMapModel)), this._dispatchHighDown('highlight', makeHighDownBatch(resultBatches[1], visualMapModel)); } }, ContinuousView.prototype._hoverLinkFromSeriesMouseOver = function(e) { var el = e.target, visualMapModel = this.visualMapModel; if (el && null != getECData(el).dataIndex) { var ecData = getECData(el), dataModel = this.ecModel.getSeriesByIndex(ecData.seriesIndex); if (visualMapModel.isTargetSeries(dataModel)) { var data = dataModel.getData(ecData.dataType), value = data.get(visualMapModel.getDataDimension(data), ecData.dataIndex); isNaN(value) || this._showIndicator(value, value); } } }, ContinuousView.prototype._hideIndicator = function() { var shapes = this._shapes; shapes.indicator && shapes.indicator.attr('invisible', !0), shapes.indicatorLabel && shapes.indicatorLabel.attr('invisible', !0); var handleLabels = this._shapes.handleLabels; if (handleLabels) for(var i = 0; i < handleLabels.length; i++)this._api.leaveBlur(handleLabels[i]); }, ContinuousView.prototype._clearHoverLinkToSeries = function() { this._hideIndicator(); var indices = this._hoverLinkDataIndices; this._dispatchHighDown('downplay', makeHighDownBatch(indices, this.visualMapModel)), indices.length = 0; }, ContinuousView.prototype._clearHoverLinkFromSeries = function() { this._hideIndicator(); var zr = this.api.getZr(); zr.off('mouseover', this._hoverLinkFromSeriesMouseOver), zr.off('mouseout', this._hideIndicator); }, ContinuousView.prototype._applyTransform = function(vertex, element, inverse, global1) { var transform = getTransform(element, global1 ? null : this.group); return isArray(vertex) ? applyTransform$1(vertex, transform, inverse) : transformDirection(vertex, transform, inverse); }, ContinuousView.prototype._dispatchHighDown = function(type, batch) { batch && batch.length && this.api.dispatchAction({ type: type, batch: batch }); }, ContinuousView.prototype.dispose = function() { this._clearHoverLinkFromSeries(), this._clearHoverLinkToSeries(); }, ContinuousView.prototype.remove = function() { this._clearHoverLinkFromSeries(), this._clearHoverLinkToSeries(); }, ContinuousView.type = 'visualMap.continuous', ContinuousView; }(VisualMapView); function createPolygon(points, cursor, onDrift, onDragEnd) { return new Polygon({ shape: { points: points }, draggable: !!onDrift, cursor: cursor, drift: onDrift, onmousemove: function(e) { stop(e.event); }, ondragend: onDragEnd }); } function useHoverLinkOnHandle(visualMapModel) { var hoverLinkOnHandle = visualMapModel.get('hoverLinkOnHandle'); return !!(null == hoverLinkOnHandle ? visualMapModel.get('realtime') : hoverLinkOnHandle); } function getCursor$1(orient) { return 'vertical' === orient ? 'ns-resize' : 'ew-resize'; } var visualMapActionInfo = { type: 'selectDataRange', event: 'dataRangeSelected', update: 'update' }, visualMapActionHander = function(payload, ecModel) { ecModel.eachComponent({ mainType: 'visualMap', query: payload }, function(model) { model.setSelected(payload.selected); }); }, visualMapEncodingHandlers = [ { createOnAllSeries: !0, reset: function(seriesModel, ecModel) { var resetDefines = []; return ecModel.eachComponent('visualMap', function(visualMapModel) { var stateList, visualMappings, getValueState, dim, visualTypesMap, pipelineContext = seriesModel.pipelineContext; !visualMapModel.isTargetSeries(seriesModel) || pipelineContext && pipelineContext.large || resetDefines.push((stateList = visualMapModel.stateList, visualMappings = visualMapModel.targetVisuals, getValueState = bind(visualMapModel.getValueState, visualMapModel), dim = visualMapModel.getDataDimension(seriesModel.getData()), visualTypesMap = {}, each(stateList, function(state) { var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]); visualTypesMap[state] = visualTypes; }), { progress: function(params, data) { function getVisual(key) { return getItemVisualFromData(data, dataIndex, key); } function setVisual(key, value) { setItemVisualFromData(data, dataIndex, key, value); } for(null != dim && (dimName = data.getDimension(dim)); null != (dataIndex = params.next());){ var dimName, dataIndex, rawDataItem = data.getRawDataItem(dataIndex); if (!rawDataItem || !1 !== rawDataItem.visualMap) for(var value = null != dim ? data.get(dimName, dataIndex) : dataIndex, valueState = getValueState(value), mappings = visualMappings[valueState], visualTypes = visualTypesMap[valueState], i = 0, len = visualTypes.length; i < len; i++){ var type = visualTypes[i]; mappings[type] && mappings[type].applyVisual(value, getVisual, setVisual); } } } })); }), resetDefines; } }, { createOnAllSeries: !0, reset: function(seriesModel, ecModel) { var data = seriesModel.getData(), visualMetaList = []; ecModel.eachComponent('visualMap', function(visualMapModel) { if (visualMapModel.isTargetSeries(seriesModel)) { var visualMeta = visualMapModel.getVisualMeta(bind(getColorVisual, null, seriesModel, visualMapModel)) || { stops: [], outerColors: [] }, concreteDim = visualMapModel.getDataDimension(data), dimInfo = data.getDimensionInfo(concreteDim); null != dimInfo && (visualMeta.dimension = dimInfo.index, visualMetaList.push(visualMeta)); } }), seriesModel.getData().setVisual('visualMeta', visualMetaList); } } ]; function getColorVisual(seriesModel, visualMapModel, value, valueState) { for(var mappings = visualMapModel.targetVisuals[valueState], visualTypes = VisualMapping.prepareVisualTypes(mappings), resultVisual = { color: getVisualFromData(seriesModel.getData(), 'color') }, i = 0, len = visualTypes.length; i < len; i++){ var type = visualTypes[i], mapping = mappings['opacity' === type ? '__alphaForOpacity' : type]; mapping && mapping.applyVisual(value, getVisual, setVisual); } return resultVisual.color; function getVisual(key) { return resultVisual[key]; } function setVisual(key, value) { resultVisual[key] = value; } } function visualMapPreprocessor(option) { var visualMap = option && option.visualMap; isArray(visualMap) || (visualMap = visualMap ? [ visualMap ] : []), each(visualMap, function(opt) { if (opt) { has$1(opt, 'splitList') && !has$1(opt, 'pieces') && (opt.pieces = opt.splitList, delete opt.splitList); var pieces = opt.pieces; pieces && isArray(pieces) && each(pieces, function(piece) { isObject(piece) && (has$1(piece, 'start') && !has$1(piece, 'min') && (piece.min = piece.start), has$1(piece, 'end') && !has$1(piece, 'max') && (piece.max = piece.end)); }); } }); } function has$1(obj, name) { return obj && obj.hasOwnProperty && obj.hasOwnProperty(name); } var installed$1 = !1; function installCommon$1(registers) { installed$1 || (installed$1 = !0, registers.registerSubTypeDefaulter('visualMap', function(option) { return option.categories || (option.pieces ? option.pieces.length > 0 : option.splitNumber > 0) && !option.calculable ? 'piecewise' : 'continuous'; }), registers.registerAction(visualMapActionInfo, visualMapActionHander), each(visualMapEncodingHandlers, function(handler) { registers.registerVisual(registers.PRIORITY.VISUAL.COMPONENT, handler); }), registers.registerPreprocessor(visualMapPreprocessor)); } function install$N(registers) { registers.registerComponentModel(ContinuousModel), registers.registerComponentView(ContinuousView), installCommon$1(registers); } var PiecewiseModel = function(_super) { function PiecewiseModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = PiecewiseModel.type, _this._pieceList = [], _this; } return __extends(PiecewiseModel, _super), PiecewiseModel.prototype.optionUpdated = function(newOption, isInit) { _super.prototype.optionUpdated.apply(this, arguments), this.resetExtent(); var mode = this._mode = this._determineMode(); this._pieceList = [], resetMethods[this._mode].call(this, this._pieceList), this._resetSelected(newOption, isInit); var categories = this.option.categories; this.resetVisual(function(mappingOption, state) { 'categories' === mode ? (mappingOption.mappingMethod = 'category', mappingOption.categories = clone(categories)) : (mappingOption.dataExtent = this.getExtent(), mappingOption.mappingMethod = 'piecewise', mappingOption.pieceList = map(this._pieceList, function(piece) { return piece = clone(piece), 'inRange' !== state && (piece.visual = null), piece; })); }); }, PiecewiseModel.prototype.completeVisualOption = function() { var option = this.option, visualTypesInPieces = {}, visualTypes = VisualMapping.listVisualTypes(), isCategory = this.isCategory(); function has(obj, state, visualType) { return obj && obj[state] && obj[state].hasOwnProperty(visualType); } each(option.pieces, function(piece) { each(visualTypes, function(visualType) { piece.hasOwnProperty(visualType) && (visualTypesInPieces[visualType] = 1); }); }), each(visualTypesInPieces, function(v, visualType) { var exists = !1; each(this.stateList, function(state) { exists = exists || has(option, state, visualType) || has(option.target, state, visualType); }, this), exists || each(this.stateList, function(state) { (option[state] || (option[state] = {}))[visualType] = visualDefault.get(visualType, 'inRange' === state ? 'active' : 'inactive', isCategory); }); }, this), _super.prototype.completeVisualOption.apply(this, arguments); }, PiecewiseModel.prototype._resetSelected = function(newOption, isInit) { var thisOption = this.option, pieceList = this._pieceList, selected = (isInit ? thisOption : newOption).selected || {}; if (thisOption.selected = selected, each(pieceList, function(piece, index) { var key = this.getSelectedMapKey(piece); selected.hasOwnProperty(key) || (selected[key] = !0); }, this), 'single' === thisOption.selectedMode) { var hasSel_1 = !1; each(pieceList, function(piece, index) { var key = this.getSelectedMapKey(piece); selected[key] && (hasSel_1 ? selected[key] = !1 : hasSel_1 = !0); }, this); } }, PiecewiseModel.prototype.getItemSymbol = function() { return this.get('itemSymbol'); }, PiecewiseModel.prototype.getSelectedMapKey = function(piece) { return 'categories' === this._mode ? piece.value + '' : piece.index + ''; }, PiecewiseModel.prototype.getPieceList = function() { return this._pieceList; }, PiecewiseModel.prototype._determineMode = function() { var option = this.option; return option.pieces && option.pieces.length > 0 ? 'pieces' : this.option.categories ? 'categories' : 'splitNumber'; }, PiecewiseModel.prototype.setSelected = function(selected) { this.option.selected = clone(selected); }, PiecewiseModel.prototype.getValueState = function(value) { var index = VisualMapping.findPieceIndex(value, this._pieceList); return null != index && this.option.selected[this.getSelectedMapKey(this._pieceList[index])] ? 'inRange' : 'outOfRange'; }, PiecewiseModel.prototype.findTargetDataIndices = function(pieceIndex) { var result = [], pieceList = this._pieceList; return this.eachTargetSeries(function(seriesModel) { var dataIndices = [], data = seriesModel.getData(); data.each(this.getDataDimension(data), function(value, dataIndex) { VisualMapping.findPieceIndex(value, pieceList) === pieceIndex && dataIndices.push(dataIndex); }, this), result.push({ seriesId: seriesModel.id, dataIndex: dataIndices }); }, this), result; }, PiecewiseModel.prototype.getRepresentValue = function(piece) { var representValue; if (this.isCategory()) representValue = piece.value; else if (null != piece.value) representValue = piece.value; else { var pieceInterval = piece.interval || []; representValue = pieceInterval[0] === -1 / 0 && pieceInterval[1] === 1 / 0 ? 0 : (pieceInterval[0] + pieceInterval[1]) / 2; } return representValue; }, PiecewiseModel.prototype.getVisualMeta = function(getColorVisual) { if (!this.isCategory()) { var stops = [], outerColors = [ '', '' ], visualMapModel = this, pieceList = this._pieceList.slice(); if (pieceList.length) { var edge = pieceList[0].interval[0]; edge !== -1 / 0 && pieceList.unshift({ interval: [ -1 / 0, edge ] }), (edge = pieceList[pieceList.length - 1].interval[1]) !== 1 / 0 && pieceList.push({ interval: [ edge, 1 / 0 ] }); } else pieceList.push({ interval: [ -1 / 0, 1 / 0 ] }); var curr = -1 / 0; return each(pieceList, function(piece) { var interval = piece.interval; interval && (interval[0] > curr && setStop([ curr, interval[0] ], 'outOfRange'), setStop(interval.slice()), curr = interval[1]); }, this), { stops: stops, outerColors: outerColors }; } function setStop(interval, valueState) { var representValue = visualMapModel.getRepresentValue({ interval: interval }); valueState || (valueState = visualMapModel.getValueState(representValue)); var color = getColorVisual(representValue, valueState); interval[0] === -1 / 0 ? outerColors[0] = color : interval[1] === 1 / 0 ? outerColors[1] = color : stops.push({ value: interval[0], color: color }, { value: interval[1], color: color }); } }, PiecewiseModel.type = 'visualMap.piecewise', PiecewiseModel.defaultOption = inheritDefaultOption(VisualMapModel.defaultOption, { selected: null, minOpen: !1, maxOpen: !1, align: 'auto', itemWidth: 20, itemHeight: 14, itemSymbol: 'roundRect', pieces: null, categories: null, splitNumber: 5, selectedMode: 'multiple', itemGap: 10, hoverLink: !0 }), PiecewiseModel; }(VisualMapModel), resetMethods = { splitNumber: function(outPieceList) { var thisOption = this.option, precision = Math.min(thisOption.precision, 20), dataExtent = this.getExtent(), splitNumber = thisOption.splitNumber; splitNumber = Math.max(parseInt(splitNumber, 10), 1), thisOption.splitNumber = splitNumber; for(var splitStep = (dataExtent[1] - dataExtent[0]) / splitNumber; +splitStep.toFixed(precision) !== splitStep && precision < 5;)precision++; thisOption.precision = precision, splitStep = +splitStep.toFixed(precision), thisOption.minOpen && outPieceList.push({ interval: [ -1 / 0, dataExtent[0] ], close: [ 0, 0 ] }); for(var index = 0, curr = dataExtent[0]; index < splitNumber; curr += splitStep, index++){ var max = index === splitNumber - 1 ? dataExtent[1] : curr + splitStep; outPieceList.push({ interval: [ curr, max ], close: [ 1, 1 ] }); } thisOption.maxOpen && outPieceList.push({ interval: [ dataExtent[1], 1 / 0 ], close: [ 0, 0 ] }), reformIntervals(outPieceList), each(outPieceList, function(piece, index) { piece.index = index, piece.text = this.formatValueText(piece.interval); }, this); }, categories: function(outPieceList) { var thisOption = this.option; each(thisOption.categories, function(cate) { outPieceList.push({ text: this.formatValueText(cate, !0), value: cate }); }, this), normalizeReverse(thisOption, outPieceList); }, pieces: function(outPieceList) { var thisOption = this.option; each(thisOption.pieces, function(pieceListItem, index) { isObject(pieceListItem) || (pieceListItem = { value: pieceListItem }); var item = { text: '', index: index }; if (null != pieceListItem.label && (item.text = pieceListItem.label), pieceListItem.hasOwnProperty('value')) { var value = item.value = pieceListItem.value; item.interval = [ value, value ], item.close = [ 1, 1 ]; } else { for(var interval = item.interval = [], close_1 = item.close = [ 0, 0 ], closeList = [ 1, 0, 1 ], infinityList = [ -1 / 0, 1 / 0 ], useMinMax = [], lg = 0; lg < 2; lg++){ for(var names = [ [ 'gte', 'gt', 'min' ], [ 'lte', 'lt', 'max' ] ][lg], i = 0; i < 3 && null == interval[lg]; i++)interval[lg] = pieceListItem[names[i]], close_1[lg] = closeList[i], useMinMax[lg] = 2 === i; null == interval[lg] && (interval[lg] = infinityList[lg]); } useMinMax[0] && interval[1] === 1 / 0 && (close_1[0] = 0), useMinMax[1] && interval[0] === -1 / 0 && (close_1[1] = 0), interval[0] > interval[1] && console.warn('Piece ' + index + 'is illegal: ' + interval + ' lower bound should not greater then uppper bound.'), interval[0] === interval[1] && close_1[0] && close_1[1] && (item.value = interval[0]); } item.visual = VisualMapping.retrieveVisuals(pieceListItem), outPieceList.push(item); }, this), normalizeReverse(thisOption, outPieceList), reformIntervals(outPieceList), each(outPieceList, function(piece) { var close = piece.close, edgeSymbols = [ [ '<', '≤' ][close[1]], [ '>', '≥' ][close[0]] ]; piece.text = piece.text || this.formatValueText(null != piece.value ? piece.value : piece.interval, !1, edgeSymbols); }, this); } }; function normalizeReverse(thisOption, pieceList) { var inverse = thisOption.inverse; ('vertical' === thisOption.orient ? !inverse : inverse) && pieceList.reverse(); } var PiecewiseVisualMapView = function(_super) { function PiecewiseVisualMapView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = PiecewiseVisualMapView.type, _this; } return __extends(PiecewiseVisualMapView, _super), PiecewiseVisualMapView.prototype.doRender = function() { var thisGroup = this.group; thisGroup.removeAll(); var visualMapModel = this.visualMapModel, textGap = visualMapModel.get('textGap'), textStyleModel = visualMapModel.textStyleModel, textFont = textStyleModel.getFont(), textFill = textStyleModel.getTextColor(), itemAlign = this._getItemAlign(), itemSize = visualMapModel.itemSize, viewData = this._getViewData(), endsText = viewData.endsText, showLabel = retrieve(visualMapModel.get('showLabel', !0), !endsText); endsText && this._renderEndsText(thisGroup, endsText[0], itemSize, showLabel, itemAlign), each(viewData.viewPieceList, function(item) { var piece = item.piece, itemGroup = new Group(); itemGroup.onclick = bind(this._onItemClick, this, piece), this._enableHoverLink(itemGroup, item.indexInModelPieceList); var representValue = visualMapModel.getRepresentValue(piece); if (this._createItemSymbol(itemGroup, representValue, [ 0, 0, itemSize[0], itemSize[1] ]), showLabel) { var visualState = this.visualMapModel.getValueState(representValue); itemGroup.add(new ZRText({ style: { x: 'right' === itemAlign ? -textGap : itemSize[0] + textGap, y: itemSize[1] / 2, text: piece.text, verticalAlign: 'middle', align: itemAlign, font: textFont, fill: textFill, opacity: 'outOfRange' === visualState ? 0.5 : 1 } })); } thisGroup.add(itemGroup); }, this), endsText && this._renderEndsText(thisGroup, endsText[1], itemSize, showLabel, itemAlign), boxLayout(visualMapModel.get('orient'), thisGroup, visualMapModel.get('itemGap')), this.renderBackground(thisGroup), this.positionGroup(thisGroup); }, PiecewiseVisualMapView.prototype._enableHoverLink = function(itemGroup, pieceIndex) { var _this = this; itemGroup.on('mouseover', function() { return onHoverLink('highlight'); }).on('mouseout', function() { return onHoverLink('downplay'); }); var onHoverLink = function(method) { var visualMapModel = _this.visualMapModel; visualMapModel.option.hoverLink && _this.api.dispatchAction({ type: method, batch: makeHighDownBatch(visualMapModel.findTargetDataIndices(pieceIndex), visualMapModel) }); }; }, PiecewiseVisualMapView.prototype._getItemAlign = function() { var visualMapModel = this.visualMapModel, modelOption = visualMapModel.option; if ('vertical' === modelOption.orient) return getItemAlign(visualMapModel, this.api, visualMapModel.itemSize); var align = modelOption.align; return align && 'auto' !== align || (align = 'left'), align; }, PiecewiseVisualMapView.prototype._renderEndsText = function(group, text, itemSize, showLabel, itemAlign) { if (text) { var itemGroup = new Group(), textStyleModel = this.visualMapModel.textStyleModel; itemGroup.add(new ZRText({ style: { x: showLabel ? 'right' === itemAlign ? itemSize[0] : 0 : itemSize[0] / 2, y: itemSize[1] / 2, verticalAlign: 'middle', align: showLabel ? itemAlign : 'center', text: text, font: textStyleModel.getFont(), fill: textStyleModel.getTextColor() } })), group.add(itemGroup); } }, PiecewiseVisualMapView.prototype._getViewData = function() { var visualMapModel = this.visualMapModel, viewPieceList = map(visualMapModel.getPieceList(), function(piece, index) { return { piece: piece, indexInModelPieceList: index }; }), endsText = visualMapModel.get('text'), orient = visualMapModel.get('orient'), inverse = visualMapModel.get('inverse'); return ('horizontal' === orient ? inverse : !inverse) ? viewPieceList.reverse() : endsText && (endsText = endsText.slice().reverse()), { viewPieceList: viewPieceList, endsText: endsText }; }, PiecewiseVisualMapView.prototype._createItemSymbol = function(group, representValue, shapeParam) { group.add(createSymbol(this.getControllerVisual(representValue, 'symbol'), shapeParam[0], shapeParam[1], shapeParam[2], shapeParam[3], this.getControllerVisual(representValue, 'color'))); }, PiecewiseVisualMapView.prototype._onItemClick = function(piece) { var visualMapModel = this.visualMapModel, option = visualMapModel.option, selected = clone(option.selected), newKey = visualMapModel.getSelectedMapKey(piece); 'single' === option.selectedMode ? (selected[newKey] = !0, each(selected, function(o, key) { selected[key] = key === newKey; })) : selected[newKey] = !selected[newKey], this.api.dispatchAction({ type: 'selectDataRange', from: this.uid, visualMapId: this.visualMapModel.id, selected: selected }); }, PiecewiseVisualMapView.type = 'visualMap.piecewise', PiecewiseVisualMapView; }(VisualMapView); function install$O(registers) { registers.registerComponentModel(PiecewiseModel), registers.registerComponentView(PiecewiseVisualMapView), installCommon$1(registers); } var DEFAULT_OPTION = { label: { enabled: !0 }, decal: { show: !1 } }, inner$l = makeInner(), decalPaletteScope = {}; function ariaVisual(ecModel, api) { var ariaModel = ecModel.getModel('aria'); if (ariaModel.get('enabled')) { var defaultOption = clone(DEFAULT_OPTION); merge(defaultOption.label, ecModel.getLocaleModel().get('aria'), !1), merge(ariaModel.option, defaultOption, !1), function() { if (ariaModel.getModel('decal').get('show')) { var paletteScopeGroupByType_1 = createHashMap(); ecModel.eachSeries(function(seriesModel) { if (seriesModel.useColorPaletteOnData) { var decalScope = paletteScopeGroupByType_1.get(seriesModel.type); decalScope || (decalScope = {}, paletteScopeGroupByType_1.set(seriesModel.type, decalScope)), inner$l(seriesModel).scope = decalScope; } }), ecModel.eachRawSeries(function(seriesModel) { if (!ecModel.isSeriesFiltered(seriesModel)) { if ('function' == typeof seriesModel.enableAriaDecal) { seriesModel.enableAriaDecal(); return; } var data = seriesModel.getData(); if (seriesModel.useColorPaletteOnData) { var dataAll_1 = seriesModel.getRawData(), idxMap_1 = {}, decalScope_1 = inner$l(seriesModel).scope; data.each(function(idx) { idxMap_1[data.getRawIndex(idx)] = idx; }); var dataCount_1 = dataAll_1.count(); dataAll_1.each(function(rawIdx) { var idx = idxMap_1[rawIdx], name = dataAll_1.getName(rawIdx) || rawIdx + '', paletteDecal = getDecalFromPalette(seriesModel.ecModel, name, decalScope_1, dataCount_1), specifiedDecal = data.getItemVisual(idx, 'decal'); data.setItemVisual(idx, 'decal', mergeDecal(specifiedDecal, paletteDecal)); }); } else { var paletteDecal = getDecalFromPalette(seriesModel.ecModel, seriesModel.name, decalPaletteScope, ecModel.getSeriesCount()), specifiedDecal = data.getVisual('decal'); data.setVisual('decal', mergeDecal(specifiedDecal, paletteDecal)); } } function mergeDecal(specifiedDecal, paletteDecal) { var resultDecal = specifiedDecal ? extend(extend({}, paletteDecal), specifiedDecal) : paletteDecal; return resultDecal.dirty = !0, resultDecal; } }); } }(), function() { var ariaLabel, labelLocale = ecModel.getLocaleModel().get('aria'), labelModel = ariaModel.getModel('label'); if (labelModel.option = defaults(labelModel.option, labelLocale), labelModel.get('enabled')) { var dom = api.getZr().dom; if (labelModel.get('description')) { dom.setAttribute('aria-label', labelModel.get('description')); return; } var seriesCnt = ecModel.getSeriesCount(), maxDataCnt = labelModel.get([ 'data', 'maxCount' ]) || 10, displaySeriesCnt = Math.min(seriesCnt, labelModel.get([ 'series', 'maxCount' ]) || 10); if (!(seriesCnt < 1)) { var title, title1 = ((title = ecModel.get('title')) && title.length && (title = title[0]), title && title.text); ariaLabel = title1 ? replace(labelModel.get([ 'general', 'withTitle' ]), { title: title1 }) : labelModel.get([ 'general', 'withoutTitle' ]); var seriesLabels_1 = []; ariaLabel += replace(seriesCnt > 1 ? labelModel.get([ 'series', 'multiple', 'prefix' ]) : labelModel.get([ 'series', 'single', 'prefix' ]), { seriesCount: seriesCnt }), ecModel.eachSeries(function(seriesModel, idx) { if (idx < displaySeriesCnt) { var type, seriesLabel = void 0, withName = seriesModel.get('name') ? 'withName' : 'withoutName'; seriesLabel = replace(seriesLabel = seriesCnt > 1 ? labelModel.get([ 'series', 'multiple', withName ]) : labelModel.get([ 'series', 'single', withName ]), { seriesId: seriesModel.seriesIndex, seriesName: seriesModel.get('name'), seriesType: (type = seriesModel.subType, ecModel.getLocaleModel().get([ 'series', 'typeNames' ])[type] || '自定义图') }); var data = seriesModel.getData(); data.count() > maxDataCnt ? seriesLabel += replace(labelModel.get([ 'data', 'partialData' ]), { displayCnt: maxDataCnt }) : seriesLabel += labelModel.get([ 'data', 'allData' ]); for(var dataLabels = [], i = 0; i < data.count(); i++)if (i < maxDataCnt) { var name_1 = data.getName(i), value = retrieveRawValue(data, i), dataLabel = labelModel.get([ 'data', name_1 ? 'withName' : 'withoutName' ]); dataLabels.push(replace(dataLabel, { name: name_1, value: value })); } var middleSeparator_1 = labelModel.get([ 'data', 'separator', 'middle' ]), endSeparator_1 = labelModel.get([ 'data', 'separator', 'end' ]); seriesLabel += dataLabels.join(middleSeparator_1) + endSeparator_1, seriesLabels_1.push(seriesLabel); } }); var separatorModel = labelModel.getModel([ 'series', 'multiple', 'separator' ]), middleSeparator = separatorModel.get('middle'), endSeparator = separatorModel.get('end'); ariaLabel += seriesLabels_1.join(middleSeparator) + endSeparator, dom.setAttribute('aria-label', ariaLabel); } } }(); } function replace(str, keyValues) { if ('string' != typeof str) return str; var result = str; return each(keyValues, function(value, key) { result = result.replace(RegExp('\\{\\s*' + key + '\\s*\\}', 'g'), value); }), result; } } function ariaPreprocessor(option) { if (option && option.aria) { var aria = option.aria; null != aria.show && (aria.enabled = aria.show), aria.label = aria.label || {}, each([ 'description', 'general', 'series', 'data' ], function(name) { null != aria[name] && (aria.label[name] = aria[name]); }); } } var RELATIONAL_EXPRESSION_OP_ALIAS_MAP = { value: 'eq', '<': 'lt', '<=': 'lte', '>': 'gt', '>=': 'gte', '=': 'eq', '!=': 'ne', '<>': 'ne' }, RegExpEvaluator = function() { function RegExpEvaluator(rVal) { null == (this._condVal = isString(rVal) ? RegExp(rVal) : isRegExp(rVal) ? rVal : null) && throwError(makePrintable('Illegal regexp', rVal, 'in')); } return RegExpEvaluator.prototype.evaluate = function(lVal) { var type = typeof lVal; return 'string' === type ? this._condVal.test(lVal) : 'number' === type && this._condVal.test(lVal + ''); }, RegExpEvaluator; }(), ConstConditionInternal = function() { function ConstConditionInternal() {} return ConstConditionInternal.prototype.evaluate = function() { return this.value; }, ConstConditionInternal; }(), AndConditionInternal = function() { function AndConditionInternal() {} return AndConditionInternal.prototype.evaluate = function() { for(var children = this.children, i = 0; i < children.length; i++)if (!children[i].evaluate()) return !1; return !0; }, AndConditionInternal; }(), OrConditionInternal = function() { function OrConditionInternal() {} return OrConditionInternal.prototype.evaluate = function() { for(var children = this.children, i = 0; i < children.length; i++)if (children[i].evaluate()) return !0; return !1; }, OrConditionInternal; }(), NotConditionInternal = function() { function NotConditionInternal() {} return NotConditionInternal.prototype.evaluate = function() { return !this.child.evaluate(); }, NotConditionInternal; }(), RelationalConditionInternal = function() { function RelationalConditionInternal() {} return RelationalConditionInternal.prototype.evaluate = function() { for(var needParse = !!this.valueParser, tarValRaw = (0, this.getValue)(this.valueGetterParam), tarValParsed = needParse ? this.valueParser(tarValRaw) : null, i = 0; i < this.subCondList.length; i++)if (!this.subCondList[i].evaluate(needParse ? tarValParsed : tarValRaw)) return !1; return !0; }, RelationalConditionInternal; }(); function parseOption(exprOption, getters) { if (!0 === exprOption || !1 === exprOption) { var val, subOption, errMsg, cond, cond1 = new ConstConditionInternal(); return cond1.value = exprOption, cond1; } if (isObject(exprOption) && !isArrayLike(exprOption) || throwError(makePrintable('Illegal config. Expect a plain object but actually', exprOption)), exprOption.and) return parseAndOrOption('and', exprOption, getters); if (exprOption.or) return parseAndOrOption('or', exprOption, getters); if (exprOption.not) { return subOption = exprOption.not, errMsg = '', errMsg = makePrintable('"not" condition should only be `not: {}`.', 'Illegal condition:', exprOption), isObject(val = subOption) && !isArrayLike(val) || throwError(errMsg), (cond = new NotConditionInternal()).child = parseOption(subOption, getters), cond.child || throwError(errMsg), cond; } return function(exprOption, getters) { for(var valueGetterParam = getters.prepareGetValue(exprOption), subCondList = [], exprKeys = keys(exprOption), parserName = exprOption.parser, valueParser = parserName ? (type = parserName, valueParserMap.get(type)) : null, i = 0; i < exprKeys.length; i++){ var type, keyRaw = exprKeys[i]; if (!('parser' === keyRaw || getters.valueGetterAttrMap.get(keyRaw))) { var op = hasOwn(RELATIONAL_EXPRESSION_OP_ALIAS_MAP, keyRaw) ? RELATIONAL_EXPRESSION_OP_ALIAS_MAP[keyRaw] : keyRaw, condValueRaw = exprOption[keyRaw], condValueParsed = valueParser ? valueParser(condValueRaw) : condValueRaw, evaluator = ('eq' === op || 'ne' === op ? new FilterEqualityComparator('eq' === op, condValueParsed) : hasOwn(ORDER_COMPARISON_OP_MAP, op) ? new FilterOrderComparator(op, condValueParsed) : null) || 'reg' === op && new RegExpEvaluator(condValueParsed); evaluator || throwError(makePrintable('Illegal relational operation: "' + keyRaw + '" in condition:', exprOption)), subCondList.push(evaluator); } } subCondList.length || throwError(makePrintable('Relational condition must have at least one operator.', 'Illegal condition:', exprOption)); var cond = new RelationalConditionInternal(); return cond.valueGetterParam = valueGetterParam, cond.valueParser = valueParser, cond.getValue = getters.getValue, cond.subCondList = subCondList, cond; }(exprOption, getters); } function parseAndOrOption(op, exprOption, getters) { var subOptionArr = exprOption[op], errMsg = ''; errMsg = makePrintable('"and"/"or" condition should only be `' + op + ': [...]` and must not be empty array.', 'Illegal condition:', exprOption), isArray(subOptionArr) || throwError(errMsg), subOptionArr.length || throwError(errMsg); var cond = 'and' === op ? new AndConditionInternal() : new OrConditionInternal(); return cond.children = map(subOptionArr, function(subOption) { return parseOption(subOption, getters); }), cond.children.length || throwError(errMsg), cond; } var ConditionalExpressionParsed = function() { function ConditionalExpressionParsed(exprOption, getters) { this._cond = parseOption(exprOption, getters); } return ConditionalExpressionParsed.prototype.evaluate = function() { return this._cond.evaluate(); }, ConditionalExpressionParsed; }(), filterTransform = { type: 'echarts:filter', transform: function(params) { for(var exprOption, getters, rawItem, upstream = params.upstream, condition = (exprOption = params.config, getters = { valueGetterAttrMap: createHashMap({ dimension: !0 }), prepareGetValue: function(exprOption) { var dimLoose = exprOption.dimension; hasOwn(exprOption, 'dimension') || throwError(makePrintable('Relation condition must has prop "dimension" specified.', 'Illegal condition:', exprOption)); var dimInfo = upstream.getDimensionInfo(dimLoose); return dimInfo || throwError(makePrintable('Can not find dimension info via: ' + dimLoose + '.\n', 'Existing dimensions: ', upstream.cloneAllDimensionInfo(), '.\n', 'Illegal condition:', exprOption, '.\n')), { dimIdx: dimInfo.index }; }, getValue: function(param) { return upstream.retrieveValueFromItem(rawItem, param.dimIdx); } }, new ConditionalExpressionParsed(exprOption, getters)), resultData = [], i = 0, len = upstream.count(); i < len; i++)rawItem = upstream.getRawDataItem(i), condition.evaluate() && resultData.push(rawItem); return { data: resultData }; } }, sampleLog = ''; sampleLog = 'Valid config is like: { dimension: "age", order: "asc" } or [{ dimension: "age", order: "asc"], { dimension: "date", order: "desc" }]'; var sortTransform = { type: 'echarts:sort', transform: function(params) { var upstream = params.upstream, orderExprList = normalizeToArray(params.config); orderExprList.length || throwError('Empty `config` in sort transform.'); var orderDefList = []; each(orderExprList, function(orderExpr) { var dimLoose = orderExpr.dimension, order = orderExpr.order, parserName = orderExpr.parser, incomparable = orderExpr.incomparable; null == dimLoose && throwError('Sort transform config must has "dimension" specified.' + sampleLog), 'asc' !== order && 'desc' !== order && throwError('Sort transform config must has "order" specified.' + sampleLog), incomparable && 'min' !== incomparable && 'max' !== incomparable && throwError('incomparable must be "min" or "max" rather than "' + incomparable + '".'), 'asc' !== order && 'desc' !== order && throwError('order must be "asc" or "desc" rather than "' + order + '".'); var dimInfo = upstream.getDimensionInfo(dimLoose); dimInfo || throwError(makePrintable('Can not find dimension info via: ' + dimLoose + '.\n', 'Existing dimensions: ', upstream.cloneAllDimensionInfo(), '.\n', 'Illegal config:', orderExpr, '.\n')); var parser = parserName ? valueParserMap.get(parserName) : null; parserName && !parser && throwError(makePrintable('Invalid parser name ' + parserName + '.\n', 'Illegal config:', orderExpr, '.\n')), orderDefList.push({ dimIdx: dimInfo.index, parser: parser, comparator: new SortOrderComparator(order, incomparable) }); }); var sourceFormat = upstream.sourceFormat; sourceFormat !== SOURCE_FORMAT_ARRAY_ROWS && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS && throwError('sourceFormat "' + sourceFormat + '" is not supported yet'); for(var resultData = [], i = 0, len = upstream.count(); i < len; i++)resultData.push(upstream.getRawDataItem(i)); return resultData.sort(function(item0, item1) { for(var i = 0; i < orderDefList.length; i++){ var orderDef = orderDefList[i], val0 = upstream.retrieveValueFromItem(item0, orderDef.dimIdx), val1 = upstream.retrieveValueFromItem(item1, orderDef.dimIdx); orderDef.parser && (val0 = orderDef.parser(val0), val1 = orderDef.parser(val1)); var result = orderDef.comparator.evaluate(val0, val1); if (0 !== result) return result; } return 0; }), { data: resultData }; } }, DatasetModel = function(_super) { function DatasetModel() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = 'dataset', _this; } return __extends(DatasetModel, _super), DatasetModel.prototype.init = function(option, parentModel, ecModel) { _super.prototype.init.call(this, option, parentModel, ecModel), this._sourceManager = new SourceManager(this), disableTransformOptionMerge(this); }, DatasetModel.prototype.mergeOption = function(newOption, ecModel) { _super.prototype.mergeOption.call(this, newOption, ecModel), disableTransformOptionMerge(this); }, DatasetModel.prototype.optionUpdated = function() { this._sourceManager.dirty(); }, DatasetModel.prototype.getSourceManager = function() { return this._sourceManager; }, DatasetModel.type = 'dataset', DatasetModel.defaultOption = { seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN }, DatasetModel; }(ComponentModel), DatasetView = function(_super) { function DatasetView() { var _this = null !== _super && _super.apply(this, arguments) || this; return _this.type = 'dataset', _this; } return __extends(DatasetView, _super), DatasetView.type = 'dataset', DatasetView; }(ComponentView); use([ function(registers) { registers.registerPainter('canvas', CanvasPainter); } ]), use([ function(registers) { registers.registerPainter('svg', SVGPainter); } ]), use([ function(registers) { registers.registerChartView(LineView), registers.registerSeriesModel(LineSeriesModel), registers.registerLayout(pointsLayout('line', !0)), registers.registerVisual({ seriesType: 'line', reset: function(seriesModel) { var data = seriesModel.getData(), lineStyle = seriesModel.getModel('lineStyle').getLineStyle(); lineStyle && !lineStyle.stroke && (lineStyle.stroke = data.getVisual('style').fill), data.setVisual('legendLineStyle', lineStyle); } }), registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('line')); }, function(registers) { registers.registerChartView(BarView), registers.registerSeriesModel(BarSeriesModel), registers.registerLayout(registers.PRIORITY.VISUAL.LAYOUT, curry(layout, 'bar')), registers.registerLayout(registers.PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, largeLayout), registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('bar')), registers.registerAction({ type: 'changeAxisOrder', event: 'changeAxisOrder', update: 'update' }, function(payload, ecModel) { var componentType = payload.componentType || 'series'; ecModel.eachComponent({ mainType: componentType, query: payload }, function(componentModel) { payload.sortInfo && componentModel.axis.setCategorySortInfo(payload.sortInfo); }); }); }, function(registers) { registers.registerChartView(PieView), registers.registerSeriesModel(PieSeriesModel), createLegacyDataSelectAction('pie', registers.registerAction), registers.registerLayout(curry(pieLayout, 'pie')), registers.registerProcessor(dataFilter('pie')); }, function(registers) { use(install$5), registers.registerSeriesModel(ScatterSeriesModel), registers.registerChartView(ScatterView), registers.registerLayout(pointsLayout('scatter')); }, function(registers) { use(install$7), registers.registerChartView(RadarView), registers.registerSeriesModel(RadarSeriesModel), registers.registerLayout(radarLayout), registers.registerProcessor(dataFilter('radar')), registers.registerPreprocessor(radarBackwardCompat); }, function(registers) { use(install$9), registers.registerChartView(MapView), registers.registerSeriesModel(MapSeries), registers.registerLayout(mapSymbolLayout), registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, mapDataStatistic), createLegacyDataSelectAction('map', registers.registerAction); }, function(registers) { registers.registerChartView(TreeView), registers.registerSeriesModel(TreeSeriesModel), registers.registerLayout(treeLayout), registers.registerVisual(treeVisual), registers.registerAction({ type: 'treeExpandAndCollapse', event: 'treeExpandAndCollapse', update: 'update' }, function(payload, ecModel) { ecModel.eachComponent({ mainType: 'series', subType: 'tree', query: payload }, function(seriesModel) { var dataIndex = payload.dataIndex, node = seriesModel.getData().tree.getNodeByDataIndex(dataIndex); node.isExpand = !node.isExpand; }); }), registers.registerAction({ type: 'treeRoam', event: 'treeRoam', update: 'none' }, function(payload, ecModel) { ecModel.eachComponent({ mainType: 'series', subType: 'tree', query: payload }, function(seriesModel) { var res = updateCenterAndZoom(seriesModel.coordinateSystem, payload); seriesModel.setCenter && seriesModel.setCenter(res.center), seriesModel.setZoom && seriesModel.setZoom(res.zoom); }); }); }, function(registers) { registers.registerSeriesModel(TreemapSeriesModel), registers.registerChartView(TreemapView), registers.registerVisual(treemapVisual), registers.registerLayout(treemapLayout), function(registers) { for(var i = 0; i < actionTypes.length; i++)registers.registerAction({ type: actionTypes[i], update: 'updateView' }, noop$1); registers.registerAction({ type: 'treemapRootToNode', update: 'updateView' }, function(payload, ecModel) { ecModel.eachComponent({ mainType: 'series', subType: 'treemap', query: payload }, function(model, index) { var targetInfo = retrieveTargetInfo(payload, [ 'treemapZoomToNode', 'treemapRootToNode' ], model); if (targetInfo) { var originViewRoot = model.getViewRoot(); originViewRoot && (payload.direction = aboveViewRoot(originViewRoot, targetInfo.node) ? 'rollUp' : 'drillDown'), model.resetViewRoot(targetInfo.node); } }); }); }(registers); }, function(registers) { registers.registerChartView(GraphView), registers.registerSeriesModel(GraphSeriesModel), registers.registerProcessor(categoryFilter), registers.registerVisual(categoryVisual), registers.registerVisual(graphEdgeVisual), registers.registerLayout(graphSimpleLayout), registers.registerLayout(registers.PRIORITY.VISUAL.POST_CHART_LAYOUT, graphCircularLayout), registers.registerLayout(graphForceLayout), registers.registerCoordinateSystem('graphView', { dimensions: View.dimensions, create: createViewCoordSys }), registers.registerAction({ type: 'focusNodeAdjacency', event: 'focusNodeAdjacency', update: 'series:focusNodeAdjacency' }, function() {}), registers.registerAction({ type: 'unfocusNodeAdjacency', event: 'unfocusNodeAdjacency', update: 'series:unfocusNodeAdjacency' }, function() {}), registers.registerAction(actionInfo, function(payload, ecModel) { ecModel.eachComponent({ mainType: 'series', query: payload }, function(seriesModel) { var res = updateCenterAndZoom(seriesModel.coordinateSystem, payload); seriesModel.setCenter && seriesModel.setCenter(res.center), seriesModel.setZoom && seriesModel.setZoom(res.zoom); }); }); }, function(registers) { registers.registerChartView(GaugeView), registers.registerSeriesModel(GaugeSeriesModel); }, function(registers) { registers.registerChartView(FunnelView), registers.registerSeriesModel(FunnelSeriesModel), registers.registerLayout(funnelLayout), registers.registerProcessor(dataFilter('funnel')); }, function(registers) { use(install$g), registers.registerChartView(ParallelView), registers.registerSeriesModel(ParallelSeriesModel), registers.registerVisual(registers.PRIORITY.VISUAL.BRUSH, parallelVisual); }, function(registers) { registers.registerChartView(SankeyView), registers.registerSeriesModel(SankeySeriesModel), registers.registerLayout(sankeyLayout), registers.registerVisual(sankeyVisual), registers.registerAction({ type: 'dragNode', event: 'dragnode', update: 'update' }, function(payload, ecModel) { ecModel.eachComponent({ mainType: 'series', subType: 'sankey', query: payload }, function(seriesModel) { seriesModel.setNodePosition(payload.dataIndex, [ payload.localX, payload.localY ]); }); }); }, function(registers) { registers.registerSeriesModel(BoxplotSeriesModel), registers.registerChartView(BoxplotView), registers.registerVisual(boxplotVisual), registers.registerLayout(boxplotLayout), registers.registerTransform(boxplotTransform); }, function(registers) { registers.registerChartView(CandlestickView), registers.registerSeriesModel(CandlestickSeriesModel), registers.registerPreprocessor(candlestickPreprocessor), registers.registerVisual(candlestickVisual), registers.registerLayout(candlestickLayout); }, function(registers) { registers.registerChartView(EffectScatterView), registers.registerSeriesModel(EffectScatterSeriesModel), registers.registerLayout(pointsLayout('effectScatter')); }, function(registers) { registers.registerChartView(LinesView), registers.registerSeriesModel(LinesSeriesModel), registers.registerLayout(linesLayout), registers.registerVisual(linesVisual); }, function(registers) { registers.registerChartView(HeatmapView), registers.registerSeriesModel(HeatmapSeriesModel); }, function(registers) { registers.registerChartView(PictorialBarView), registers.registerSeriesModel(PictorialBarSeriesModel), registers.registerLayout(curry(layout, 'pictorialBar')); }, function(registers) { registers.registerChartView(ThemeRiverView), registers.registerSeriesModel(ThemeRiverSeriesModel), registers.registerLayout(themeRiverLayout), registers.registerProcessor(dataFilter('themeRiver')); }, function(registers) { registers.registerChartView(SunburstView), registers.registerSeriesModel(SunburstSeriesModel), registers.registerLayout(curry(sunburstLayout, 'sunburst')), registers.registerProcessor(curry(dataFilter, 'sunburst')), registers.registerVisual(sunburstVisual), registers.registerAction({ type: ROOT_TO_NODE_ACTION, update: 'updateView' }, function(payload, ecModel) { ecModel.eachComponent({ mainType: 'series', subType: 'sunburst', query: payload }, function(model, index) { var targetInfo = retrieveTargetInfo(payload, [ ROOT_TO_NODE_ACTION ], model); if (targetInfo) { var originViewRoot = model.getViewRoot(); originViewRoot && (payload.direction = aboveViewRoot(originViewRoot, targetInfo.node) ? 'rollUp' : 'drillDown'), model.resetViewRoot(targetInfo.node); } }); }), registers.registerAction({ type: HIGHLIGHT_ACTION, update: 'none' }, function(payload, ecModel, api) { payload = extend({}, payload), ecModel.eachComponent({ mainType: 'series', subType: 'sunburst', query: payload }, function(model) { var targetInfo = retrieveTargetInfo(payload, [ HIGHLIGHT_ACTION ], model); targetInfo && (payload.dataIndex = targetInfo.node.dataIndex); }), deprecateReplaceLog('highlight', 'sunburstHighlight'), api.dispatchAction(extend(payload, { type: 'highlight' })); }), registers.registerAction({ type: 'sunburstUnhighlight', update: 'updateView' }, function(payload, ecModel, api) { payload = extend({}, payload), deprecateReplaceLog('downplay', 'sunburstUnhighlight'), api.dispatchAction(extend(payload, { type: 'downplay' })); }); }, function(registers) { registers.registerChartView(CustomSeriesView), registers.registerSeriesModel(CustomSeriesModel); } ]), use(function(registers) { use(install$5), use(install$s); }), use(function(registers) { use(install$s), AxisView.registerAxisPointerClass('PolarAxisPointer', PolarAxisPointer), registers.registerCoordinateSystem('polar', polarCreator), registers.registerComponentModel(PolarModel), registers.registerComponentView(PolarView), axisModelCreator(registers, 'angle', AngleAxisModel, angleAxisExtraOption), axisModelCreator(registers, 'radius', RadiusAxisModel, radiusAxisExtraOption), registers.registerComponentView(AngleAxisView), registers.registerComponentView(RadiusAxisView), registers.registerLayout(curry(barLayoutPolar, 'bar')); }), use(install$9), use(function(registers) { use(install$s), AxisView.registerAxisPointerClass('SingleAxisPointer', SingleAxisPointer), registers.registerComponentView(SingleView), registers.registerComponentView(SingleAxisView), registers.registerComponentModel(SingleAxisModel), axisModelCreator(registers, 'single', SingleAxisModel, SingleAxisModel.defaultOption), registers.registerCoordinateSystem('single', singleCreator); }), use(install$g), use(function(registers) { registers.registerComponentModel(CalendarModel), registers.registerComponentView(CalendarView), registers.registerCoordinateSystem('calendar', Calendar); }), use(function(registers) { registers.registerComponentModel(GraphicComponentModel), registers.registerComponentView(GraphicComponentView), registers.registerPreprocessor(preprocessor); }), use(function(registers) { registers.registerComponentModel(ToolboxModel), registers.registerComponentView(ToolboxView), features.saveAsImage = SaveAsImage, features.magicType = MagicType, features.dataView = DataView, features.dataZoom = DataZoomFeature, features.restore = RestoreOption, use(install$y); }), use(function(registers) { use(install$s), registers.registerComponentModel(TooltipModel), registers.registerComponentView(TooltipView), registers.registerAction({ type: 'showTip', event: 'showTip', update: 'tooltip:manuallyShowTip' }, function() {}), registers.registerAction({ type: 'hideTip', event: 'hideTip', update: 'tooltip:manuallyHideTip' }, function() {}); }), use(install$s), use(function(registers) { registers.registerComponentView(BrushView), registers.registerComponentModel(BrushModel), registers.registerPreprocessor(brushPreprocessor), registers.registerVisual(registers.PRIORITY.VISUAL.BRUSH, brushVisual), registers.registerAction({ type: 'brush', event: 'brush', update: 'updateVisual' }, function(payload, ecModel) { ecModel.eachComponent({ mainType: 'brush', query: payload }, function(brushModel) { brushModel.setAreas(payload.areas); }); }), registers.registerAction({ type: 'brushSelect', event: 'brushSelected', update: 'none' }, function() {}), registers.registerAction({ type: 'brushEnd', event: 'brushEnd', update: 'none' }, function() {}), features.brush = BrushFeature; }), use(function(registers) { registers.registerComponentModel(TitleModel), registers.registerComponentView(TitleView); }), use(function(registers) { registers.registerComponentModel(SliderTimelineModel), registers.registerComponentView(SliderTimelineView), registers.registerSubTypeDefaulter('timeline', function() { return 'slider'; }), registers.registerAction({ type: 'timelineChange', event: 'timelineChanged', update: 'prepareAndUpdate' }, function(payload, ecModel) { var timelineModel = ecModel.getComponent('timeline'); return timelineModel && null != payload.currentIndex && (timelineModel.setCurrentIndex(payload.currentIndex), !timelineModel.get('loop', !0) && timelineModel.isIndexMax() && timelineModel.setPlayState(!1)), ecModel.resetOption('timeline', { replaceMerge: timelineModel.get('replaceMerge', !0) }), defaults({ currentIndex: timelineModel.option.currentIndex }, payload); }), registers.registerAction({ type: 'timelinePlayChange', event: 'timelinePlayChanged', update: 'update' }, function(payload, ecModel) { var timelineModel = ecModel.getComponent('timeline'); timelineModel && null != payload.playState && timelineModel.setPlayState(payload.playState); }), registers.registerPreprocessor(timelinePreprocessor); }), use(function(registers) { registers.registerComponentModel(MarkPointModel), registers.registerComponentView(MarkPointView), registers.registerPreprocessor(function(opt) { checkMarkerInSeries(opt.series, 'markPoint') && (opt.markPoint = opt.markPoint || {}); }); }), use(function(registers) { registers.registerComponentModel(MarkLineModel), registers.registerComponentView(MarkLineView), registers.registerPreprocessor(function(opt) { checkMarkerInSeries(opt.series, 'markLine') && (opt.markLine = opt.markLine || {}); }); }), use(function(registers) { registers.registerComponentModel(MarkAreaModel), registers.registerComponentView(MarkAreaView), registers.registerPreprocessor(function(opt) { checkMarkerInSeries(opt.series, 'markArea') && (opt.markArea = opt.markArea || {}); }); }), use(function(registers) { use(install$H), use(install$I); }), use(function(registers) { use(install$K), use(install$L); }), use(install$K), use(install$L), use(function(registers) { use(install$N), use(install$O); }), use(install$N), use(install$O), use(function(registers) { registers.registerPreprocessor(ariaPreprocessor), registers.registerVisual(registers.PRIORITY.VISUAL.ARIA, ariaVisual); }), use(function(registers) { registers.registerTransform(filterTransform), registers.registerTransform(sortTransform); }), use(function(registers) { registers.registerComponentModel(DatasetModel), registers.registerComponentView(DatasetView); }), exports1.Axis = Axis, exports1.ChartView = ChartView, exports1.ComponentModel = ComponentModel, exports1.ComponentView = ComponentView, exports1.List = List, exports1.Model = Model, exports1.PRIORITY = PRIORITY, exports1.SeriesModel = SeriesModel, exports1.color = color, exports1.connect = function(groupId) { if (isArray(groupId)) { var charts = groupId; groupId = null, each(charts, function(chart) { null != chart.group && (groupId = chart.group); }), groupId = groupId || 'g_' + groupIdBase++, each(charts, function(chart) { chart.group = groupId; }); } return connectedGroups[groupId] = !0, groupId; }, exports1.dataTool = {}, exports1.dependencies = { zrender: '5.1.0' }, exports1.disConnect = disConnect, exports1.disconnect = disConnect, exports1.dispose = function(chart) { 'string' == typeof chart ? chart = instances$1[chart] : chart instanceof ECharts || (chart = getInstanceByDom(chart)), chart instanceof ECharts && !chart.isDisposed() && chart.dispose(); }, exports1.env = env1, exports1.extendChartView = function(proto) { var View = ChartView.extend(proto); return ChartView.registerClass(View), View; }, exports1.extendComponentModel = function(proto) { var Model = ComponentModel.extend(proto); return ComponentModel.registerClass(Model), Model; }, exports1.extendComponentView = function(proto) { var View = ComponentView.extend(proto); return ComponentView.registerClass(View), View; }, exports1.extendSeriesModel = function(proto) { var Model = SeriesModel.extend(proto); return SeriesModel.registerClass(Model), Model; }, exports1.format = format$1, exports1.getCoordinateSystemDimensions = function(type) { var coordSysCreator = CoordinateSystemManager.get(type); if (coordSysCreator) return coordSysCreator.getDimensionsInfo ? coordSysCreator.getDimensionsInfo() : coordSysCreator.dimensions.slice(); }, exports1.getInstanceByDom = getInstanceByDom, exports1.getInstanceById = function(key) { return instances$1[key]; }, exports1.getMap = function(mapName) { return geoSourceManager.getMapForUser(mapName); }, exports1.graphic = graphic$1, exports1.helper = helper, exports1.init = function(dom, theme, opts) { if (!dom) throw Error('Initialize failed: invalid dom.'); var existInstance = getInstanceByDom(dom); if (existInstance) return console.warn('There is a chart instance already initialized on the dom.'), existInstance; !isDom(dom) || 'CANVAS' === dom.nodeName.toUpperCase() || (dom.clientWidth || opts && null != opts.width) && (dom.clientHeight || opts && null != opts.height) || console.warn("Can't get DOM width or height. Please check dom.clientWidth and dom.clientHeight. They should not be 0.For example, you may need to call this in the callback of window.onload."); var chart = new ECharts(dom, theme, opts); return chart.id = 'ec_' + idBase++, instances$1[chart.id] = chart, setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id), enableConnect(chart), each(postInitFuncs, function(postInitFunc) { postInitFunc(chart); }), chart; }, exports1.innerDrawElementOnCanvas = brushSingle, exports1.matrix = matrix, exports1.number = number, exports1.parseGeoJSON = parseGeoJSON, exports1.parseGeoJson = parseGeoJSON, exports1.registerAction = registerAction, exports1.registerCoordinateSystem = registerCoordinateSystem, exports1.registerLayout = registerLayout, exports1.registerLoading = registerLoading, exports1.registerLocale = registerLocale, exports1.registerMap = registerMap, exports1.registerPostInit = registerPostInit, exports1.registerPostUpdate = registerPostUpdate, exports1.registerPreprocessor = registerPreprocessor, exports1.registerProcessor = registerProcessor, exports1.registerTheme = function(name, theme) { themeStorage[name] = theme; }, exports1.registerTransform = registerTransform, exports1.registerVisual = registerVisual, exports1.setCanvasCreator = function(creator) { methods.createCanvas = creator; }, exports1.throttle = throttle, exports1.time = time, exports1.use = use, exports1.util = util$1, exports1.vector = vector, exports1.version = '5.1.1', exports1.zrUtil = util, exports1.zrender = zrender, Object.defineProperty(exports1, '__esModule', { value: !0 }); });