;(function(){function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}function _typeof(obj){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj;}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;},_typeof(obj);}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}var __vite_style__=document.createElement('style');__vite_style__.innerHTML="._incomeConsus_1rx47_1{margin:.37333rem;border-radius:.26667rem;background-color:#fff;overflow:hidden}._income_1rx47_1{padding-top:.48rem}._income_1rx47_1 ._countPrice_1rx47_10{font-size:.69333rem;font-weight:700;color:#ff4e19;line-height:.82667rem}._income_1rx47_1 .van-cell__title{font-size:.42667rem;color:#000}._income_1rx47_1 ._searchTime_1rx47_20{position:relative;box-sizing:border-box;max-width:100%;margin-right:.32rem;color:#333}._income_1rx47_1 ._searchTime_1rx47_20:after{position:absolute;top:50%;right:-.26667rem;margin-top:-.13333rem;border:.08rem solid;border-color:transparent transparent #999999 #999999;transform:rotate(-45deg);content:\" \"}._section_1rx47_37{overflow-x:auto;overflow-y:hidden;margin:0 .32rem}._section_1rx47_37::-webkit-scrollbar{display:none}._numberCount_1rx47_45{font-size:.34667rem;color:gray;line-height:.64rem;flex-wrap:nowrap!important;padding:.53333rem 0}._numberCount_1rx47_45 i{display:inline-block;width:.05333rem;height:1.12rem;border-radius:.05333rem;background:linear-gradient(180deg,#b5c4ff 0%,#5b85f9 100%);margin-right:.16rem}._numberCount_1rx47_45 ._color1_1rx47_60{background:linear-gradient(166deg,#59e5d5 0%,#2dc7aa 100%)}._numberCount_1rx47_45 ._color2_1rx47_63{background:linear-gradient(163deg,#b9ff4b 0%,#91dd1c 100%)}._numberCount_1rx47_45 ._color3_1rx47_66{background:linear-gradient(180deg,#ffc979 0%,#ffa92c 100%)}._numberCount_1rx47_45 ._color4_1rx47_69{background:linear-gradient(180deg,#e6c474 0%,#be7e2e 100%)}._numberCount_1rx47_45 ._color5_1rx47_72{background:linear-gradient(180deg,#4bcdff 0%,#1c96dd 100%)}._numberCount_1rx47_45 ._color6_1rx47_75{background:linear-gradient(180deg,#ee90ff 0%,#d22cff 100%)}._numberCount_1rx47_45 ._color7_1rx47_78{background:linear-gradient(180deg,#ff6f6f 0%,#ff3c3c 100%)}._numberCount_1rx47_45 ._color8_1rx47_81{background:#1aee3e}._numberCount_1rx47_45 ._type_1rx47_84 span{display:block}._numberCount_1rx47_45 ._type_1rx47_84 ._price_1rx47_87{font-size:.42667rem;font-weight:500;color:#000;line-height:.58667rem}._numberCount_1rx47_45 .van-col{display:flex;align-items:center;background-color:#f7f7f7;margin-left:.32rem}._numberCount_1rx47_45 .van-col:first-child{margin-left:0}._incomeTitle_1rx47_102{display:flex;align-items:center;padding:0 .32rem;font-size:.37333rem;font-weight:500;color:#333;line-height:.53333rem}._incomeTitle_1rx47_102 i{margin-right:.13333rem;border-radius:.05333rem;display:inline-block;width:.10667rem;height:.37333rem;background:linear-gradient(166deg,#59e5d5 0%,#2dc7aa 100%)}._incomeLine_1rx47_119{height:5.33333rem;padding:0 .26667rem .8rem}._pieSection_1rx47_123{padding:.48rem 0 0;margin:0 .26667rem .53333rem;display:flex;align-items:center}._pieIncome_1rx47_129{width:4.26667rem;height:4.26667rem}._rateAll_1rx47_133{font-size:.32rem;color:#666;line-height:1;display:flex;align-items:flex-start;flex-direction:column}._rateAll_1rx47_133 img{width:.53333rem;height:.53333rem;margin-right:.10667rem}._rateAll_1rx47_133>div{padding-bottom:.32rem;display:flex;align-items:center}._rateAll_1rx47_133 ._rate_1rx47_133{padding-left:.10667rem;font-size:.37333rem;font-weight:600;color:#333;line-height:.53333rem}._pieData_1rx47_158{font-size:.37333rem;color:gray;line-height:1;padding-left:.53333rem;display:flex;align-items:flex-start;flex-wrap:wrap;padding-bottom:.32rem}._pieData_1rx47_158>div{padding-bottom:.32rem;flex-basis:45%}._pieData_1rx47_158>div:nth-child(2n + 2){flex-basis:55%}._pieData_1rx47_158>div:nth-child(2n + 2) ._pieTitle_1rx47_175{min-width:2.4rem}._pieData_1rx47_158>div:last-child{padding-bottom:0}._pieData_1rx47_158 i{display:inline-block;width:.29333rem;height:.29333rem;border-radius:50%;background:#5b8ff9}._pieData_1rx47_158 ._pieLive_1rx47_188{background:#2dc7aa}._pieData_1rx47_158 ._pieVideo_1rx47_191{background:#91dd1c}._pieData_1rx47_158 ._pieMusic_1rx47_194{background:#ffa92c}._pieData_1rx47_158 ._pie1_1rx47_197{background:#be7e2e}._pieData_1rx47_158 ._pie2_1rx47_200{background:#1c96dd}._pieData_1rx47_158 ._pie3_1rx47_203{background:#d22cff}._pieData_1rx47_158 ._pie4_1rx47_206{background:#ff3c3c}._pieData_1rx47_158 ._pie5_1rx47_209{background:#1aee3e}._pieData_1rx47_158 ._pieTitle_1rx47_175{display:inline-block;padding-left:.24rem;margin-right:.26667rem;min-width:1.6rem;color:#1a1a1a;border-right:.02667rem solid #808080}._timePopup_1rx47_220{display:flex;align-items:center;justify-content:center;padding:.26667rem 0}._timeMonth_1rx47_226,._timeYear_1rx47_227{padding:0 .74667rem;margin-left:0!important}._timeMonth_1rx47_226{border-radius:var(--van-button-border-radius) 0 0 var(--van-button-border-radius)}._timeYear_1rx47_227{border-radius:0 var(--van-button-border-radius) var(--van-button-border-radius) 0}\n";document.head.appendChild(__vite_style__);System.register(['./vendor-legacy.85605a93.js','./index-legacy.f25f109a2.js','./index-legacy.637f3556.js','./index-legacy.f25f109a11.js','./index-legacy.a46cdcf2.js'],function(exports){'use strict';var defineComponent,markRaw,dayjs,createVNode,Cell,Row,Col,createTextVNode,Popup,DatetimePicker,Button,Picker,request,moneyFormat,formatterDate;return{setters:[function(module){defineComponent=module.d;markRaw=module.aE;dayjs=module.g;createVNode=module.a;Cell=module.q;Row=module.k;Col=module.l;createTextVNode=module.j;Popup=module.P;DatetimePicker=module.J;Button=module.B;Picker=module.a9;},function(){},function(){},function(){},function(module){request=module.r;moneyFormat=module.n;formatterDate=module.j;}],execute:function execute(){var _Object$freeze,_Object$freeze2,_Object$freeze3;var icon_fly="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAAAXNSR0IArs4c6QAAA2JJREFUWEftl9tLFHEUxz9n1FoqS4IkpNtDQaYlGd3snlYrhgTdifoT6jGqh9CgepCgx3qIHopKuqA+lElZDyph1ENUpoHQhei5pDJ3Tszorjuzl5ndVZHYeZv5nd+cz3zP+Z7frjDJL5nkfGQBM61QVsGsgpkqEG+/tpNLEeswqUIoRHkixdyLFzthPag9FBEiiEEQZQdQ4AAS6qWYs27IcQPUl+QxhQpyCALVwAo06Vj7xTvy5QChaMgxBdQ+5vGLasSGqkKZaSeLzqJR6a3n4XvhDwFmyRL+jBmgvmUKQ2y0y2baYCUeKiVr6dtSxuGMS6yvWDjSRxbQdpT8yEujFXHLEK1ceG00fgCDpVLGl5QBtY+p/GDTSB9ZpVs2Ds4+JeVcTMnF+poKTE4ClSjTI70UT4l4n50sztl7PQQokxIGfQNqN8eA66729hbOgkrddjtlNW2JXh7zOm1nBtP4BszwJooTIbxByfHZCndlLfuT5YkF7GYNIV5E2d+5f3QsjD4fVu4tQh0m3UALUGqrmTjeMkaxrOFzaoAdtkv7HeMiWemE9wj1PKKRKrZgcAeY40P901LBBa+4uB2jHTSh1DoUcA9c6EE4x3pui2BqJycwaQByPQez8IECViQyhueg1k5mY9KBsjTOF/ZicI6v3LKOJW0nQC5XgaNeakTWDXbJBh77iU/oOe1iEYN0AXNHFPloK/aNm+HzUttYwFTuo6xyJEs0sIercE82s88PXGzRXLv0OStRrmFwmRA3ZBtD4RBtZytCo89+C28bQCiWLcmN4Vlir6/TZxxHaUDJSxrrVtLgtGz1NkbagHa/hbiCcCzhGIpIHJVmuJF6mctyP8ZIC1CfM5+/PIjpNy+5w+uWMSr9GSNlQH1KCUM8BQodPO75GG8oD2+4LzvZ6/dbUgds5RDKrXQSIFgnxjLZwad09vs62vXhCKC76f3cC2ckyPl04DzHTKTfLUAzDQWFXhambozUS9zMboSWmKMP+w+O9cvFeYWVzSUo1bSmq55/BRuZRYBel0m+Y1CDUodSY0M4TdMotRzMBM43oJ27mXKUSyilQCcGJ6SWfm1lOr+5gnIkCuYJg+yRA/ycMECvRNrEYkzKyKFfannlFe933ZeL/b5sPOKygJmqmlXwv1fwH9at6ylMGY7gAAAAAElFTkSuQmCC";var __glob_21_0=/*#__PURE__*/Object.freeze((_Object$freeze={__proto__:null},_defineProperty(_Object$freeze,Symbol.toStringTag,'Module'),_defineProperty(_Object$freeze,'default',icon_fly),_Object$freeze));var icon_user="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAAAXNSR0IArs4c6QAABDFJREFUWEftmF9oW3UUx7/n3mTt/INaxUEiU1zrHKnaJsW0nVazFbWbxYW6TREEEWT6sBdBfPDNB/Ft4ItTEMZAtKFUzdSuLbVOu3Zp1jSldWPWP3OzdXSCUu1s19wjN7lpbm7u3f3d22UUNA+BXM7vez58z+93fueGsMY/tMb58N8BbJ9JXleZWe/zyBnPcuXSbKyq4c+rUZ1VObibO2VpNvAMMe8DIwywl3NUTEQTIBz6G1UH4z7fgltY14C7z437iaQYGE02yX+SJLnjI38g5QbSFWD0/KlbvXz5BDNvsk/KANG8xGj+eOMDk/bxxRGuADvOjn9G4PaslKbAWm2NgtpjEGGa5tcFYoHAkhNIx4DRn8eaiHB8JUmeIP8gr2jynAgvd20MvltmwJMfAHihJMkKkIGMdBZLNNZ9ZyhUVsBdP46eY8IdBcOsLNOOs46GQEqmAhvivoaLopCOShydTt+ekRYviIrnGo4WrWVSoDx+5O7GXlENR4DtZxMBLPMVTyJrp4XypdVIWCMlmZ6L3xX+sCyAO84MtRBJX+tPr2giXdz+z6ub3hFd58jBtu9HGgnKsKi4aRzJ+76oDh8U1XAE+OQPIzXLmcwZXfsrdBvL0hpQiPb01DTHygIYSia9t914Sb1XPaIJjHEKSfV992wdF13vyEFV9LHTx5IAHPWygs20cF6ZveW7wB7h28Q54Klv3lKgvG68OKwcKW7b1NO/paVN1D2zrWS7dvvpY/dDyaRtA00CJJme79v86GEnax07qIpvm/pqAOCIWSJDXy6EEGaUC7RpMBL5p+yAkakBdTgdYoYsmkwCXhqo3f6+aLzoFrLUe2Sy/20wvyaSkIiODgZa20ArF5/IsmyMqxJnVzJLLZP9nQB35H7mcpYISpSSLv+1bbA++ocwlS7QPaAq0tkpP7z5pgQDQdPkhHled71/6N6H5t3Arc5BzcWtE72/AOxfsVBPQsReT4VvMBD57ZoDqrdKhXfuAJhfKUpeOkn3LvDi3vFrVeK6VPfN66lyL7PyKoAaS2eKJmyag0wHiDOHhuvaf3Xipu0ebBg9Uit5lEYwbSGiB7Pvv8ze0tOQkyrMgwYMFZhI/U4zMAyJ0sw4MVq/84r3siVgOBWvYYUPM9QXct1kvOoGpQnkTz3Rt1iWXkyEd2anJOPHFLBpqqdq6dLiBAGFzW+YkJ2USSD2d4XQOBZ6aloIMJT89E0wv6EPzo/spQbalNaSzuAN4ejJhl1PCAEGE93HGWz3l4aAMQ5C1P0pV2xIBXfMFXUqM4m6ka4+EFodyOtCLccFk1NTjELeJX8q+OyMLeB9o12tksJfMrPt5Ew2t6Vxa1iWkOiTdPjpqFCJ1aDaRKxZUmg/g6vVe9fKTStAezACiJkVXISMeOYGvGc2adv2QXdlvnqr/gdcrZdr3sF/AWQ0XDiCWwUIAAAAAElFTkSuQmCC";var __glob_21_1=/*#__PURE__*/Object.freeze((_Object$freeze2={__proto__:null},_defineProperty(_Object$freeze2,Symbol.toStringTag,'Module'),_defineProperty(_Object$freeze2,'default',icon_user),_Object$freeze2));var incomeConsus="_incomeConsus_1rx47_1";var income="_income_1rx47_1";var countPrice="_countPrice_1rx47_10";var searchTime="_searchTime_1rx47_20";var section="_section_1rx47_37";var numberCount="_numberCount_1rx47_45";var color1="_color1_1rx47_60";var color2="_color2_1rx47_63";var color3="_color3_1rx47_66";var color4="_color4_1rx47_69";var color5="_color5_1rx47_72";var color6="_color6_1rx47_75";var color7="_color7_1rx47_78";var color8="_color8_1rx47_81";var type="_type_1rx47_84";var price="_price_1rx47_87";var incomeTitle="_incomeTitle_1rx47_102";var incomeLine="_incomeLine_1rx47_119";var pieSection="_pieSection_1rx47_123";var pieIncome="_pieIncome_1rx47_129";var rateAll="_rateAll_1rx47_133";var rate="_rate_1rx47_133";var pieData="_pieData_1rx47_158";var pieTitle="_pieTitle_1rx47_175";var pieLive="_pieLive_1rx47_188";var pieVideo="_pieVideo_1rx47_191";var pieMusic="_pieMusic_1rx47_194";var pie1="_pie1_1rx47_197";var pie2="_pie2_1rx47_200";var pie3="_pie3_1rx47_203";var pie4="_pie4_1rx47_206";var pie5="_pie5_1rx47_209";var timePopup="_timePopup_1rx47_220";var timeMonth="_timeMonth_1rx47_226";var timeYear="_timeYear_1rx47_227";var styles={incomeConsus:incomeConsus,income:income,countPrice:countPrice,searchTime:searchTime,section:section,numberCount:numberCount,color1:color1,color2:color2,color3:color3,color4:color4,color5:color5,color6:color6,color7:color7,color8:color8,type:type,price:price,incomeTitle:incomeTitle,incomeLine:incomeLine,pieSection:pieSection,pieIncome:pieIncome,rateAll:rateAll,rate:rate,pieData:pieData,pieTitle:pieTitle,pieLive:pieLive,pieVideo:pieVideo,pieMusic:pieMusic,pie1:pie1,pie2:pie2,pie3:pie3,pie4:pie4,pie5:pie5,timePopup:timePopup,timeMonth:timeMonth,timeYear:timeYear};/*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise */var _extendStatics$=function extendStatics$1(d,b){_extendStatics$=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b;}||function(d,b){for(var p in b){if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p];}};return _extendStatics$(d,b);};function __extends$1(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");_extendStatics$(d,b);function __(){this.constructor=d;}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __());}var Browser=function(){function Browser(){this.firefox=false;this.ie=false;this.edge=false;this.newEdge=false;this.weChat=false;}return Browser;}();var Env=function(){function Env(){this.browser=new Browser();this.node=false;this.wxa=false;this.worker=false;this.svgSupported=false;this.touchEventsSupported=false;this.pointerEventsSupported=false;this.domSupported=false;this.transformSupported=false;this.transform3dSupported=false;this.hasGlobalWindow=typeof window!=='undefined';}return Env;}();var env=new Env();if((typeof wx==="undefined"?"undefined":_typeof(wx))==='object'&&typeof wx.getSystemInfoSync==='function'){env.wxa=true;env.touchEventsSupported=true;}else if(typeof document==='undefined'&&typeof self!=='undefined'){env.worker=true;}else if(typeof navigator==='undefined'){env.node=true;env.svgSupported=true;}else{detect(navigator.userAgent,env);}function detect(ua,env){var browser=env.browser;var firefox=ua.match(/Firefox\/([\d.]+)/);var ie=ua.match(/MSIE\s([\d.]+)/)||ua.match(/Trident\/.+?rv:(([\d.]+))/);var edge=ua.match(/Edge?\/([\d.]+)/);var weChat=/micromessenger/i.test(ua);if(firefox){browser.firefox=true;browser.version=firefox[1];}if(ie){browser.ie=true;browser.version=ie[1];}if(edge){browser.edge=true;browser.version=edge[1];browser.newEdge=+edge[1].split('.')[0]>18;}if(weChat){browser.weChat=true;}env.svgSupported=typeof SVGRect!=='undefined';env.touchEventsSupported='ontouchstart'in window&&!browser.ie&&!browser.edge;env.pointerEventsSupported='onpointerdown'in window&&(browser.edge||browser.ie&&+browser.version>=11);env.domSupported=typeof document!=='undefined';var 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 env$1=env;var DEFAULT_FONT_SIZE=12;var DEFAULT_FONT_FAMILY='sans-serif';var DEFAULT_FONT=DEFAULT_FONT_SIZE+"px "+DEFAULT_FONT_FAMILY;var OFFSET=20;var SCALE=100;var defaultWidthMapStr="007LLmW'55;N0500LLLLLLLLLL00NNNLzWW\\\\WQb\\0FWLg\\bWb\\WQ\\WrWWQ000CL5LLFLL0LL**F*gLLLL5F0LF\\FFF5.5N";function getTextWidthMap(mapStr){var map={};if(typeof JSON==='undefined'){return map;}for(var i=0;i=0){width=fontSize*text.length;}else{for(var i=0;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;}function preparePointerTransformer(markers,saved,inverse){var transformerName=inverse?'invTrans':'trans';var transformer=saved[transformerName];var oldSrcCoords=saved.srcCoords;var srcCoords=[];var destCoords=[];var oldCoordTheSame=true;for(var i=0;i<4;i++){var rect=markers[i].getBoundingClientRect();var ii=2*i;var x=rect.left;var 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 isCanvasEl(el){return el.nodeName.toUpperCase()==='CANVAS';}var MOUSE_EVENT_REG=/^(?:mouse|pointer|contextmenu|drag|drop)|click/;var _calcOut=[];var firefoxNotSupportOffsetXY=env$1.browser.firefox&&+env$1.browser.version.split('.')[0]<39;function clientToLocal(el,e,out,calculate){out=out||{};if(calculate){calculateZrXY(el,e,out);}else if(firefoxNotSupportOffsetXY&&e.layerX!=null&&e.layerX!==e.offsetX){out.zrX=e.layerX;out.zrY=e.layerY;}else if(e.offsetX!=null){out.zrX=e.offsetX;out.zrY=e.offsetY;}else{calculateZrXY(el,e,out);}return out;}function calculateZrXY(el,e,out){if(env$1.domSupported&&el.getBoundingClientRect){var ex=e.clientX;var ey=e.clientY;if(isCanvasEl(el)){var box=el.getBoundingClientRect();out.zrX=ex-box.left;out.zrY=ey-box.top;return;}else{if(transformCoordWithViewport(_calcOut,el,ex,ey)){out.zrX=_calcOut[0];out.zrY=_calcOut[1];return;}}}out.zrX=out.zrY=0;}function getNativeEvent(e){return e||window.event;}function normalizeEvent(el,e,calculate){e=getNativeEvent(e);if(e.zrX!=null){return e;}var eventType=e.type;var isTouch=eventType&&eventType.indexOf('touch')>=0;if(!isTouch){clientToLocal(el,e,e,calculate);var wheelDelta=getWheelDeltaMayPolyfill(e);e.zrDelta=wheelDelta?wheelDelta/120:-(e.detail||0)/3;}else{var touch=eventType!=='touchend'?e.targetTouches[0]:e.changedTouches[0];touch&&clientToLocal(el,touch,e,calculate);}var button=e.button;if(e.which==null&&button!==undefined&&MOUSE_EVENT_REG.test(e.type)){e.which=button&1?1:button&2?3:button&4?2:0;}return e;}function getWheelDeltaMayPolyfill(e){var rawWheelDelta=e.wheelDelta;if(rawWheelDelta){return rawWheelDelta;}var deltaX=e.deltaX;var deltaY=e.deltaY;if(deltaX==null||deltaY==null){return rawWheelDelta;}var delta=deltaY!==0?Math.abs(deltaY):Math.abs(deltaX);var sign=deltaY>0?-1:deltaY<0?1:deltaX>0?-1:1;return 3*delta*sign;}function addEventListener(el,name,handler,opt){el.addEventListener(name,handler,opt);}function removeEventListener(el,name,handler,opt){el.removeEventListener(name,handler,opt);}var stop=function stop(e){e.preventDefault();e.stopPropagation();e.cancelBubble=true;};function isMiddleOrRightButtonOnMouseUpDown(e){return e.which===2||e.which===3;}var GestureMgr=function(){function GestureMgr(){this._track=[];}GestureMgr.prototype.recognize=function(event,target,root){this._doTrack(event,target,root);return this._recognize(event);};GestureMgr.prototype.clear=function(){this._track.length=0;return this;};GestureMgr.prototype._doTrack=function(event,target,root){var touches=event.touches;if(!touches){return;}var trackItem={points:[],touches:[],target:target,event:event};for(var i=0,len=touches.length;i1&&pinchEnd&&pinchEnd.length>1){var pinchScale=dist(pinchEnd)/dist(pinchPre);!isFinite(pinchScale)&&(pinchScale=1);event.pinchScale=pinchScale;var pinchCenter=center(pinchEnd);event.pinchX=pinchCenter[0];event.pinchY=pinchCenter[1];return{type:'pinch',target:tracks[0].target,event:event};}}};var SILENT='silent';function makeEventPacket(eveType,targetInfo,event){return{type:eveType,event:event,target:targetInfo.target,topTarget:targetInfo.topTarget,cancelBubble:false,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};}function stopEvent(){stop(this.event);}var EmptyProxy=function(_super){__extends(EmptyProxy,_super);function EmptyProxy(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.handler=null;return _this;}EmptyProxy.prototype.dispose=function(){};EmptyProxy.prototype.setCursor=function(){};return EmptyProxy;}(Eventful$1);var HoveredResult=function(){function HoveredResult(x,y){this.x=x;this.y=y;}return HoveredResult;}();var handlerNames=['click','dblclick','mousewheel','mouseout','mouseup','mousedown','mousemove','contextmenu'];var Handler=function(_super){__extends(Handler,_super);function Handler(storage,painter,proxy,painterRoot){var _this=_super.call(this)||this;_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$1(_this);return _this;}Handler.prototype.setHandlerProxy=function(proxy){if(this.proxy){this.proxy.dispose();}if(proxy){each$7(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;var y=event.zrY;var isOutside=isOutsideBoundary(this,x,y);var lastHovered=this._hovered;var lastHoveredTarget=lastHovered.target;if(lastHoveredTarget&&!lastHoveredTarget.__zr){lastHovered=this.findHover(lastHovered.x,lastHovered.y);lastHoveredTarget=lastHovered.target;}var hovered=this._hovered=isOutside?new HoveredResult(x,y):this.findHover(x,y);var hoveredTarget=hovered.target;var proxy=this.proxy;proxy.setCursor&&proxy.setCursor(hoveredTarget?hoveredTarget.cursor:'default');if(lastHoveredTarget&&hoveredTarget!==lastHoveredTarget){this.dispatchToElement(lastHovered,'mouseout',event);}this.dispatchToElement(hovered,'mousemove',event);if(hoveredTarget&&hoveredTarget!==lastHoveredTarget){this.dispatchToElement(hovered,'mouseover',event);}};Handler.prototype.mouseout=function(event){var eventControl=event.zrEventControl;if(eventControl!=='only_globalout'){this.dispatchToElement(this._hovered,'mouseout',event);}if(eventControl!=='no_globalout'){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){targetInfo=targetInfo||{};var el=targetInfo.target;if(el&&el.silent){return;}var eventKey='on'+eventName;var eventPacket=makeEventPacket(eventName,targetInfo,event);while(el){el[eventKey]&&(eventPacket.cancelBubble=!!el[eventKey].call(el,eventPacket));el.trigger(eventName,eventPacket);el=el.__hostTarget?el.__hostTarget:el.parent;if(eventPacket.cancelBubble){break;}}if(!eventPacket.cancelBubble){this.trigger(eventName,eventPacket);if(this.painter&&this.painter.eachOtherLayer){this.painter.eachOtherLayer(function(layer){if(typeof layer[eventKey]==='function'){layer[eventKey].call(layer,eventPacket);}if(layer.trigger){layer.trigger(eventName,eventPacket);}});}}};Handler.prototype.findHover=function(x,y,exclude){var list=this.storage.getDisplayList();var out=new HoveredResult(x,y);for(var i=list.length-1;i>=0;i--){var hoverCheckResult=void 0;if(list[i]!==exclude&&!list[i].ignore&&(hoverCheckResult=isHover(list[i],x,y))){!out.topTarget&&(out.topTarget=list[i]);if(hoverCheckResult!==SILENT){out.target=list[i];break;}}}return out;};Handler.prototype.processGesture=function(event,stage){if(!this._gestureMgr){this._gestureMgr=new GestureMgr();}var gestureMgr=this._gestureMgr;stage==='start'&&gestureMgr.clear();var gestureInfo=gestureMgr.recognize(event,this.findHover(event.zrX,event.zrY,null).target,this.proxy.dom);stage==='end'&&gestureMgr.clear();if(gestureInfo){var type=gestureInfo.type;event.gestureEvent=type;var res=new HoveredResult();res.target=gestureInfo.target;this.dispatchToElement(res,type,gestureInfo.event);}};return Handler;}(Eventful$1);each$7(['click','mousedown','mouseup','mousewheel','dblclick','contextmenu'],function(name){Handler.prototype[name]=function(event){var x=event.zrX;var y=event.zrY;var isOutside=isOutsideBoundary(this,x,y);var hovered;var hoveredTarget;if(name!=='mouseup'||!isOutside){hovered=this.findHover(x,y);hoveredTarget=hovered.target;}if(name==='mousedown'){this._downEl=hoveredTarget;this._downPoint=[event.zrX,event.zrY];this._upEl=hoveredTarget;}else if(name==='mouseup'){this._upEl=hoveredTarget;}else if(name==='click'){if(this._downEl!==this._upEl||!this._downPoint||dist$1(this._downPoint,[event.zrX,event.zrY])>4){return;}this._downPoint=null;}this.dispatchToElement(hovered,name,event);};});function isHover(displayable,x,y){if(displayable[displayable.rectHover?'rectContain':'contain'](x,y)){var el=displayable;var isSilent=void 0;var ignoreClip=false;while(el){if(el.ignoreClip){ignoreClip=true;}if(!ignoreClip){var clipPath=el.getClipPath();if(clipPath&&!clipPath.contain(x,y)){return false;}if(el.silent){isSilent=true;}}var hostEl=el.__hostTarget;el=hostEl?hostEl:el.parent;}return isSilent?SILENT:true;}return false;}function isOutsideBoundary(handlerInstance,x,y){var painter=handlerInstance.painter;return x<0||x>painter.getWidth()||y<0||y>painter.getHeight();}var Handler$1=Handler;var DEFAULT_MIN_MERGE=32;var DEFAULT_MIN_GALLOPING=7;function minRunLength(n){var r=0;while(n>=DEFAULT_MIN_MERGE){r|=n&1;n>>=1;}return n+r;}function makeAscendingRun(array,lo,hi,compare){var runHi=lo+1;if(runHi===hi){return 1;}if(compare(array[runHi++],array[lo])<0){while(runHi=0){runHi++;}}return runHi-lo;}function reverseRun(array,lo,hi){hi--;while(lo>>1;if(compare(pivot,array[mid])<0){right=mid;}else{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:while(n>0){array[left+n]=array[left+n-1];n--;}}array[left]=pivot;}}function gallopLeft(value,array,start,length,hint,compare){var lastOffset=0;var maxOffset=0;var offset=1;if(compare(value,array[start+hint])>0){maxOffset=length-hint;while(offset0){lastOffset=offset;offset=(offset<<1)+1;if(offset<=0){offset=maxOffset;}}if(offset>maxOffset){offset=maxOffset;}lastOffset+=hint;offset+=hint;}else{maxOffset=hint+1;while(offsetmaxOffset){offset=maxOffset;}var tmp=lastOffset;lastOffset=hint-offset;offset=hint-tmp;}lastOffset++;while(lastOffset>>1);if(compare(value,array[start+m])>0){lastOffset=m+1;}else{offset=m;}}return offset;}function gallopRight(value,array,start,length,hint,compare){var lastOffset=0;var maxOffset=0;var offset=1;if(compare(value,array[start+hint])<0){maxOffset=hint+1;while(offsetmaxOffset){offset=maxOffset;}var tmp=lastOffset;lastOffset=hint-offset;offset=hint-tmp;}else{maxOffset=length-hint;while(offset=0){lastOffset=offset;offset=(offset<<1)+1;if(offset<=0){offset=maxOffset;}}if(offset>maxOffset){offset=maxOffset;}lastOffset+=hint;offset+=hint;}lastOffset++;while(lastOffset>>1);if(compare(value,array[start+m])<0){offset=m;}else{lastOffset=m+1;}}return offset;}function TimSort(array,compare){var minGallop=DEFAULT_MIN_GALLOPING;var runStart;var runLength;var stackSize=0;var tmp=[];runStart=[];runLength=[];function pushRun(_runStart,_runLength){runStart[stackSize]=_runStart;runLength[stackSize]=_runLength;stackSize+=1;}function mergeRuns(){while(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]){if(runLength[n-1]runLength[n+1]){break;}mergeAt(n);}}function forceMergeRuns(){while(stackSize>1){var n=stackSize-2;if(n>0&&runLength[n-1]=DEFAULT_MIN_GALLOPING||count2>=DEFAULT_MIN_GALLOPING);if(exit){break;}if(_minGallop<0){_minGallop=0;}_minGallop+=2;}minGallop=_minGallop;minGallop<1&&(minGallop=1);if(length1===1){for(i=0;i=0;i--){array[customDest+i]=array[customCursor+i];}array[dest]=tmp[cursor2];return;}var _minGallop=minGallop;while(true){var count1=0;var count2=0;var exit=false;do{if(compare(tmp[cursor2],array[cursor1])<0){array[dest--]=array[cursor1--];count1++;count2=0;if(--length1===0){exit=true;break;}}else{array[dest--]=tmp[cursor2--];count2++;count1=0;if(--length2===1){exit=true;break;}}}while((count1|count2)<_minGallop);if(exit){break;}do{count1=length1-gallopRight(tmp[cursor2],array,start1,length1,length1-1,compare);if(count1!==0){dest-=count1;cursor1-=count1;length1-=count1;customDest=dest+1;customCursor=cursor1+1;for(i=count1-1;i>=0;i--){array[customDest+i]=array[customCursor+i];}if(length1===0){exit=true;break;}}array[dest--]=tmp[cursor2--];if(--length2===1){exit=true;break;}count2=length2-gallopLeft(array[cursor1],tmp,0,length2,length2-1,compare);if(count2!==0){dest-=count2;cursor2-=count2;length2-=count2;customDest=dest+1;customCursor=cursor2+1;for(i=0;i=DEFAULT_MIN_GALLOPING||count2>=DEFAULT_MIN_GALLOPING);if(exit){break;}if(_minGallop<0){_minGallop=0;}_minGallop+=2;}minGallop=_minGallop;if(minGallop<1){minGallop=1;}if(length2===1){dest-=length1;cursor1-=length1;customDest=dest+1;customCursor=cursor1+1;for(i=length1-1;i>=0;i--){array[customDest+i]=array[customCursor+i];}array[dest]=tmp[cursor2];}else if(length2===0){throw new Error();}else{customCursor=dest-(length2-1);for(i=0;iminRun){force=minRun;}binaryInsertionSort(array,lo,lo+force,lo+runLength,compare);runLength=force;}ts.pushRun(lo,runLength);ts.mergeRuns();remaining-=runLength;lo+=runLength;}while(remaining!==0);ts.forceMergeRuns();}var REDRAW_BIT=1;var STYLE_CHANGED_BIT=2;var SHAPE_CHANGED_BIT=4;var invalidZErrorLogged=false;function logInvalidZError(){if(invalidZErrorLogged){return;}invalidZErrorLogged=true;console.warn('z / z2 / zlevel of displayable is invalid, which may cause unexpected errors');}function shapeCompareFunc(a,b){if(a.zlevel===b.zlevel){if(a.z===b.z){return a.z2-b.z2;}return a.z-b.z;}return a.zlevel-b.zlevel;}var Storage=function(){function Storage(){this._roots=[];this._displayList=[];this._displayListLen=0;this.displayableSortFunc=shapeCompareFunc;}Storage.prototype.traverse=function(cb,context){for(var i=0;i0){disp.__clipPaths=[];}if(isNaN(disp.z)){logInvalidZError();disp.z=0;}if(isNaN(disp.z2)){logInvalidZError();disp.z2=0;}if(isNaN(disp.zlevel)){logInvalidZError();disp.zlevel=0;}this._displayList[this._displayListLen++]=disp;}var decalEl=el.getDecalElement&&el.getDecalElement();if(decalEl){this._updateAndAddDisplayable(decalEl,clipPaths,includeIgnore);}var textGuide=el.getTextGuideLine();if(textGuide){this._updateAndAddDisplayable(textGuide,clipPaths,includeIgnore);}var textEl=el.getTextContent();if(textEl){this._updateAndAddDisplayable(textEl,clipPaths,includeIgnore);}};Storage.prototype.addRoot=function(el){if(el.__zr&&el.__zr.storage===this){return;}this._roots.push(el);};Storage.prototype.delRoot=function(el){if(el instanceof Array){for(var i=0,l=el.length;i=0){this._roots.splice(idx,1);}};Storage.prototype.delAllRoots=function(){this._roots=[];this._displayList=[];this._displayListLen=0;return;};Storage.prototype.getRoots=function(){return this._roots;};Storage.prototype.dispose=function(){this._displayList=null;this._roots=null;};return Storage;}();var Storage$1=Storage;var requestAnimationFrame;requestAnimationFrame=env$1.hasGlobalWindow&&(window.requestAnimationFrame&&window.requestAnimationFrame.bind(window)||window.msRequestAnimationFrame&&window.msRequestAnimationFrame.bind(window)||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame)||function(func){return setTimeout(func,16);};var requestAnimationFrame$1=requestAnimationFrame;var easingFuncs={linear:function linear(k){return k;},quadraticIn:function quadraticIn(k){return k*k;},quadraticOut:function quadraticOut(k){return k*(2-k);},quadraticInOut:function quadraticInOut(k){if((k*=2)<1){return 0.5*k*k;}return-0.5*(--k*(k-2)-1);},cubicIn:function cubicIn(k){return k*k*k;},cubicOut:function cubicOut(k){return--k*k*k+1;},cubicInOut:function cubicInOut(k){if((k*=2)<1){return 0.5*k*k*k;}return 0.5*((k-=2)*k*k+2);},quarticIn:function quarticIn(k){return k*k*k*k;},quarticOut:function quarticOut(k){return 1- --k*k*k*k;},quarticInOut:function quarticInOut(k){if((k*=2)<1){return 0.5*k*k*k*k;}return-0.5*((k-=2)*k*k*k-2);},quinticIn:function quinticIn(k){return k*k*k*k*k;},quinticOut:function quinticOut(k){return--k*k*k*k*k+1;},quinticInOut:function quinticInOut(k){if((k*=2)<1){return 0.5*k*k*k*k*k;}return 0.5*((k-=2)*k*k*k*k+2);},sinusoidalIn:function sinusoidalIn(k){return 1-Math.cos(k*Math.PI/2);},sinusoidalOut:function sinusoidalOut(k){return Math.sin(k*Math.PI/2);},sinusoidalInOut:function sinusoidalInOut(k){return 0.5*(1-Math.cos(Math.PI*k));},exponentialIn:function exponentialIn(k){return k===0?0:Math.pow(1024,k-1);},exponentialOut:function exponentialOut(k){return k===1?1:1-Math.pow(2,-10*k);},exponentialInOut:function exponentialInOut(k){if(k===0){return 0;}if(k===1){return 1;}if((k*=2)<1){return 0.5*Math.pow(1024,k-1);}return 0.5*(-Math.pow(2,-10*(k-1))+2);},circularIn:function circularIn(k){return 1-Math.sqrt(1-k*k);},circularOut:function circularOut(k){return Math.sqrt(1- --k*k);},circularInOut:function circularInOut(k){if((k*=2)<1){return-0.5*(Math.sqrt(1-k*k)-1);}return 0.5*(Math.sqrt(1-(k-=2)*k)+1);},elasticIn:function elasticIn(k){var s;var a=0.1;var p=0.4;if(k===0){return 0;}if(k===1){return 1;}if(!a||a<1){a=1;s=p/4;}else{s=p*Math.asin(1/a)/(2*Math.PI);}return-(a*Math.pow(2,10*(k-=1))*Math.sin((k-s)*(2*Math.PI)/p));},elasticOut:function elasticOut(k){var s;var a=0.1;var p=0.4;if(k===0){return 0;}if(k===1){return 1;}if(!a||a<1){a=1;s=p/4;}else{s=p*Math.asin(1/a)/(2*Math.PI);}return a*Math.pow(2,-10*k)*Math.sin((k-s)*(2*Math.PI)/p)+1;},elasticInOut:function elasticInOut(k){var s;var a=0.1;var p=0.4;if(k===0){return 0;}if(k===1){return 1;}if(!a||a<1){a=1;s=p/4;}else{s=p*Math.asin(1/a)/(2*Math.PI);}if((k*=2)<1){return-0.5*(a*Math.pow(2,10*(k-=1))*Math.sin((k-s)*(2*Math.PI)/p));}return a*Math.pow(2,-10*(k-=1))*Math.sin((k-s)*(2*Math.PI)/p)*0.5+1;},backIn:function backIn(k){var s=1.70158;return k*k*((s+1)*k-s);},backOut:function backOut(k){var s=1.70158;return--k*k*((s+1)*k+s)+1;},backInOut:function backInOut(k){var s=1.70158*1.525;if((k*=2)<1){return 0.5*(k*k*((s+1)*k-s));}return 0.5*((k-=2)*k*((s+1)*k+s)+2);},bounceIn:function bounceIn(k){return 1-easingFuncs.bounceOut(1-k);},bounceOut:function bounceOut(k){if(k<1/2.75){return 7.5625*k*k;}else if(k<2/2.75){return 7.5625*(k-=1.5/2.75)*k+0.75;}else if(k<2.5/2.75){return 7.5625*(k-=2.25/2.75)*k+0.9375;}else{return 7.5625*(k-=2.625/2.75)*k+0.984375;}},bounceInOut:function bounceInOut(k){if(k<0.5){return easingFuncs.bounceIn(k*2)*0.5;}return easingFuncs.bounceOut(k*2-1)*0.5+0.5;}};var easingFuncs$1=easingFuncs;var mathPow$2=Math.pow;var mathSqrt$3=Math.sqrt;var EPSILON$2=1e-8;var EPSILON_NUMERIC=1e-4;var THREE_SQRT=mathSqrt$3(3);var ONE_THIRD=1/3;var _v0=create$1();var _v1=create$1();var _v2=create$1();function isAroundZero(val){return val>-EPSILON$2&&valEPSILON$2||val<-EPSILON$2;}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;var b=3*(p2-p1*2+p0);var c=3*(p1-p0);var d=p0-val;var A=b*b-3*a*c;var B=b*c-9*a*d;var C=c*c-3*b*d;var n=0;if(isAroundZero(A)&&isAroundZero(B)){if(isAroundZero(b)){roots[0]=0;}else{var t1=-c/b;if(t1>=0&&t1<=1){roots[n++]=t1;}}}else{var disc=B*B-4*A*C;if(isAroundZero(disc)){var K=B/A;var t1=-b/a+K;var t2=-K/2;if(t1>=0&&t1<=1){roots[n++]=t1;}if(t2>=0&&t2<=1){roots[n++]=t2;}}else if(disc>0){var discSqrt=mathSqrt$3(disc);var Y1=A*b+1.5*a*(-B+discSqrt);var Y2=A*b+1.5*a*(-B-discSqrt);if(Y1<0){Y1=-mathPow$2(-Y1,ONE_THIRD);}else{Y1=mathPow$2(Y1,ONE_THIRD);}if(Y2<0){Y2=-mathPow$2(-Y2,ONE_THIRD);}else{Y2=mathPow$2(Y2,ONE_THIRD);}var t1=(-b-(Y1+Y2))/(3*a);if(t1>=0&&t1<=1){roots[n++]=t1;}}else{var T=(2*A*b-3*a*B)/(2*mathSqrt$3(A*A*A));var theta=Math.acos(T)/3;var ASqrt=mathSqrt$3(A);var tmp=Math.cos(theta);var t1=(-b-2*ASqrt*tmp)/(3*a);var t2=(-b+ASqrt*(tmp+THREE_SQRT*Math.sin(theta)))/(3*a);var t3=(-b+ASqrt*(tmp-THREE_SQRT*Math.sin(theta)))/(3*a);if(t1>=0&&t1<=1){roots[n++]=t1;}if(t2>=0&&t2<=1){roots[n++]=t2;}if(t3>=0&&t3<=1){roots[n++]=t3;}}}return n;}function cubicExtrema(p0,p1,p2,p3,extrema){var b=6*p2-12*p1+6*p0;var a=9*p1+3*p3-3*p0-9*p2;var c=3*p1-3*p0;var n=0;if(isAroundZero(a)){if(isNotAroundZero$1(b)){var t1=-c/b;if(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$3(disc);var t1=(-b+discSqrt)/(2*a);var t2=(-b-discSqrt)/(2*a);if(t1>=0&&t1<=1){extrema[n++]=t1;}if(t2>=0&&t2<=1){extrema[n++]=t2;}}}return n;}function cubicSubdivide(p0,p1,p2,p3,t,out){var p01=(p1-p0)*t+p0;var p12=(p2-p1)*t+p1;var p23=(p3-p2)*t+p2;var p012=(p12-p01)*t+p01;var p123=(p23-p12)*t+p12;var 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;var interval=0.005;var d=Infinity;var prev;var next;var d1;var d2;_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=distSquare(_v0,_v1);if(d1=0&&d1=0&&t1<=1){roots[n++]=t1;}}}else{var disc=b*b-4*a*c;if(isAroundZero(disc)){var t1=-b/(2*a);if(t1>=0&&t1<=1){roots[n++]=t1;}}else if(disc>0){var discSqrt=mathSqrt$3(disc);var t1=(-b+discSqrt)/(2*a);var t2=(-b-discSqrt)/(2*a);if(t1>=0&&t1<=1){roots[n++]=t1;}if(t2>=0&&t2<=1){roots[n++]=t2;}}}return n;}function quadraticExtremum(p0,p1,p2){var divider=p0+p2-2*p1;if(divider===0){return 0.5;}else{return(p0-p1)/divider;}}function quadraticSubdivide(p0,p1,p2,t,out){var p01=(p1-p0)*t+p0;var p12=(p2-p1)*t+p1;var 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;var interval=0.005;var d=Infinity;_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=distSquare(_v0,_v1);if(d1=0&&d1=1?1:cubicRootAt(0,a_1,c_1,1,p,roots_1)&&cubicAt(0,b_1,d_1,1,roots_1[0]);};}}var Clip=function(){function Clip(opts){this._inited=false;this._startTime=0;this._pausedTime=0;this._paused=false;this._life=opts.life||1000;this._delay=opts.delay||0;this.loop=opts.loop||false;this.onframe=opts.onframe||noop;this.ondestroy=opts.ondestroy||noop;this.onrestart=opts.onrestart||noop;opts.easing&&this.setEasing(opts.easing);}Clip.prototype.step=function(globalTime,deltaTime){if(!this._inited){this._startTime=globalTime+this._delay;this._inited=true;}if(this._paused){this._pausedTime+=deltaTime;return;}var life=this._life;var elapsedTime=globalTime-this._startTime-this._pausedTime;var percent=elapsedTime/life;if(percent<0){percent=0;}percent=Math.min(percent,1);var easingFunc=this.easingFunc;var schedule=easingFunc?easingFunc(percent):percent;this.onframe(schedule);if(percent===1){if(this.loop){var remainder=elapsedTime%life;this._startTime=globalTime-remainder;this._pausedTime=0;this.onrestart();}else{return true;}}return false;};Clip.prototype.pause=function(){this._paused=true;};Clip.prototype.resume=function(){this._paused=false;};Clip.prototype.setEasing=function(easing){this.easing=easing;this.easingFunc=isFunction(easing)?easing:easingFuncs$1[easing]||createCubicEasingFunc(easing);};return Clip;}();var Clip$1=Clip;var Entry=function(){function Entry(val){this.value=val;}return Entry;}();var LinkedList=function(){function LinkedList(){this._len=0;}LinkedList.prototype.insert=function(val){var entry=new Entry(val);this.insertEntry(entry);return entry;};LinkedList.prototype.insertEntry=function(entry){if(!this.head){this.head=this.tail=entry;}else{this.tail.next=entry;entry.prev=this.tail;entry.next=null;this.tail=entry;}this._len++;};LinkedList.prototype.remove=function(entry){var prev=entry.prev;var next=entry.next;if(prev){prev.next=next;}else{this.head=next;}if(next){next.prev=prev;}else{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;};return LinkedList;}();var LRU=function(){function LRU(maxSize){this._list=new LinkedList();this._maxSize=10;this._map={};this._maxSize=maxSize;}LRU.prototype.put=function(key,value){var list=this._list;var map=this._map;var removed=null;if(map[key]==null){var len=list.len();var 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;}if(entry){entry.value=value;}else{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];var list=this._list;if(entry!=null){if(entry!==list.tail){list.remove(entry);list.insertEntry(entry);}return entry.value;}};LRU.prototype.clear=function(){this._list.clear();this._map={};};LRU.prototype.len=function(){return this._list.len();};return LRU;}();var LRU$1=LRU;var 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){i=Math.round(i);return i<0?0:i>255?255:i;}function clampCssFloat(f){return f<0?0:f>1?1:f;}function parseCssInt(val){var str=val;if(str.length&&str.charAt(str.length-1)==='%'){return clampCssByte(parseFloat(str)/100*255);}return clampCssByte(parseInt(str,10));}function parseCssFloat(val){var str=val;if(str.length&&str.charAt(str.length-1)==='%'){return clampCssFloat(parseFloat(str)/100);}return clampCssFloat(parseFloat(str));}function cssHueToRgb(m1,m2,h){if(h<0){h+=1;}else if(h>1){h-=1;}if(h*6<1){return m1+(m2-m1)*h*6;}if(h*2<1){return m2;}if(h*3<2){return m1+(m2-m1)*(2/3-h)*6;}return m1;}function lerpNumber(a,b,p){return a+(b-a)*p;}function setRgba(out,r,g,b,a){out[0]=r;out[1]=g;out[2]=b;out[3]=a;return out;}function copyRgba(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];return out;}var colorCache=new LRU$1(20);var lastRemovedArr=null;function putToCache(colorStr,rgbaArr){if(lastRemovedArr){copyRgba(lastRemovedArr,rgbaArr);}lastRemovedArr=colorCache.put(colorStr,lastRemovedArr||rgbaArr.slice());}function parse(colorStr,rgbaArr){if(!colorStr){return;}rgbaArr=rgbaArr||[];var cached=colorCache.get(colorStr);if(cached){return copyRgba(rgbaArr,cached);}colorStr=colorStr+'';var str=colorStr.replace(/ /g,'').toLowerCase();if(str in kCSSColorTable){copyRgba(rgbaArr,kCSSColorTable[str]);putToCache(colorStr,rgbaArr);return rgbaArr;}var strLen=str.length;if(str.charAt(0)==='#'){if(strLen===4||strLen===5){var iv=parseInt(str.slice(1,4),16);if(!(iv>=0&&iv<=0xfff)){setRgba(rgbaArr,0,0,0,1);return;}setRgba(rgbaArr,(iv&0xf00)>>4|(iv&0xf00)>>8,iv&0xf0|(iv&0xf0)>>4,iv&0xf|(iv&0xf)<<4,strLen===5?parseInt(str.slice(4),16)/0xf:1);putToCache(colorStr,rgbaArr);return rgbaArr;}else if(strLen===7||strLen===9){var iv=parseInt(str.slice(1,7),16);if(!(iv>=0&&iv<=0xffffff)){setRgba(rgbaArr,0,0,0,1);return;}setRgba(rgbaArr,(iv&0xff0000)>>16,(iv&0xff00)>>8,iv&0xff,strLen===9?parseInt(str.slice(7),16)/0xff:1);putToCache(colorStr,rgbaArr);return rgbaArr;}return;}var op=str.indexOf('(');var ep=str.indexOf(')');if(op!==-1&&ep+1===strLen){var fname=str.substr(0,op);var params=str.substr(op+1,ep-(op+1)).split(',');var alpha=1;switch(fname){case'rgba':if(params.length!==4){return params.length===3?setRgba(rgbaArr,+params[0],+params[1],+params[2],1):setRgba(rgbaArr,0,0,0,1);}alpha=parseCssFloat(params.pop());case'rgb':if(params.length!==3){setRgba(rgbaArr,0,0,0,1);return;}setRgba(rgbaArr,parseCssInt(params[0]),parseCssInt(params[1]),parseCssInt(params[2]),alpha);putToCache(colorStr,rgbaArr);return rgbaArr;case'hsla':if(params.length!==4){setRgba(rgbaArr,0,0,0,1);return;}params[3]=parseCssFloat(params[3]);hsla2rgba(params,rgbaArr);putToCache(colorStr,rgbaArr);return rgbaArr;case'hsl':if(params.length!==3){setRgba(rgbaArr,0,0,0,1);return;}hsla2rgba(params,rgbaArr);putToCache(colorStr,rgbaArr);return rgbaArr;default:return;}}setRgba(rgbaArr,0,0,0,1);return;}function hsla2rgba(hsla,rgba){var h=(parseFloat(hsla[0])%360+360)%360/360;var s=parseCssFloat(hsla[1]);var l=parseCssFloat(hsla[2]);var m2=l<=0.5?l*(s+1):l+s-l*s;var m1=l*2-m2;rgba=rgba||[];setRgba(rgba,clampCssByte(cssHueToRgb(m1,m2,h+1/3)*255),clampCssByte(cssHueToRgb(m1,m2,h)*255),clampCssByte(cssHueToRgb(m1,m2,h-1/3)*255),1);if(hsla.length===4){rgba[3]=hsla[3];}return rgba;}function lift(color,level){var colorArr=parse(color);if(colorArr){for(var i=0;i<3;i++){if(level<0){colorArr[i]=colorArr[i]*(1-level)|0;}else{colorArr[i]=(255-colorArr[i])*level+colorArr[i]|0;}if(colorArr[i]>255){colorArr[i]=255;}else if(colorArr[i]<0){colorArr[i]=0;}}return stringify(colorArr,colorArr.length===4?'rgba':'rgb');}}function lerp(normalizedValue,colors,fullOutput){if(!(colors&&colors.length)||!(normalizedValue>=0&&normalizedValue<=1)){return;}var value=normalizedValue*(colors.length-1);var leftIndex=Math.floor(value);var rightIndex=Math.ceil(value);var leftColor=parse(colors[leftIndex]);var rightColor=parse(colors[rightIndex]);var dv=value-leftIndex;var color=stringify([clampCssByte(lerpNumber(leftColor[0],rightColor[0],dv)),clampCssByte(lerpNumber(leftColor[1],rightColor[1],dv)),clampCssByte(lerpNumber(leftColor[2],rightColor[2],dv)),clampCssFloat(lerpNumber(leftColor[3],rightColor[3],dv))],'rgba');return fullOutput?{color:color,leftIndex:leftIndex,rightIndex:rightIndex,value:value}:color;}function stringify(arrColor,type){if(!arrColor||!arrColor.length){return;}var colorStr=arrColor[0]+','+arrColor[1]+','+arrColor[2];if(type==='rgba'||type==='hsva'||type==='hsla'){colorStr+=','+arrColor[3];}return 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;}function isLinearGradient(val){return val.type==='linear';}function isRadialGradient(val){return val.type==='radial';}(function(){if(env$1.hasGlobalWindow&&isFunction(window.btoa)){return function(str){return window.btoa(unescape(str));};}if(typeof Buffer!=='undefined'){return function(str){return Buffer.from(str).toString('base64');};}return function(str){return null;};})();var arraySlice=Array.prototype.slice;function interpolateNumber$1(p0,p1,percent){return(p1-p0)*percent+p0;}function interpolate1DArray(out,p0,p1,percent){var len=p0.length;for(var i=0;ilen1?val1:val0;var shorterLen=Math.min(len0,len1);var last=shorterArr[shorterLen-1]||{color:[0,0,0,0],offset:0};for(var i=shorterLen;iarr1Len;if(isPreviousLarger){arr0.length=arr1Len;}else{for(var i=arr0Len;i=1;};Track.prototype.getAdditiveTrack=function(){return this._additiveTrack;};Track.prototype.addKeyframe=function(time,rawValue,easing){this._needsSort=true;var keyframes=this.keyframes;var len=keyframes.length;var discrete=false;var valType=VALUE_TYPE_UNKOWN;var value=rawValue;if(isArrayLike(rawValue)){var arrayDim=guessArrayDim(rawValue);valType=arrayDim;if(arrayDim===1&&!isNumber(rawValue[0])||arrayDim===2&&!isNumber(rawValue[0][0])){discrete=true;}}else{if(isNumber(rawValue)&&!eqNaN(rawValue)){valType=VALUE_TYPE_NUMBER;}else if(isString(rawValue)){if(!isNaN(+rawValue)){valType=VALUE_TYPE_NUMBER;}else{var colorArray=parse(rawValue);if(colorArray){value=colorArray;valType=VALUE_TYPE_COLOR;}}}else if(isGradientObject(rawValue)){var parsedGradient=extend({},value);parsedGradient.colorStops=map$1(rawValue.colorStops,function(colorStop){return{offset:colorStop.offset,color:parse(colorStop.color)};});if(isLinearGradient(rawValue)){valType=VALUE_TYPE_LINEAR_GRADIENT;}else if(isRadialGradient(rawValue)){valType=VALUE_TYPE_RADIAL_GRADIENT;}value=parsedGradient;}}if(len===0){this.valType=valType;}else if(valType!==this.valType||valType===VALUE_TYPE_UNKOWN){discrete=true;}this.discrete=this.discrete||discrete;var kf={time:time,value:value,rawValue:rawValue,percent:0};if(easing){kf.easing=easing;kf.easingFunc=isFunction(easing)?easing:easingFuncs$1[easing]||createCubicEasingFunc(easing);}keyframes.push(kf);return kf;};Track.prototype.prepare=function(maxTime,additiveTrack){var kfs=this.keyframes;if(this._needsSort){kfs.sort(function(a,b){return a.time-b.time;});}var valType=this.valType;var kfsLen=kfs.length;var lastKf=kfs[kfsLen-1];var isDiscrete=this.discrete;var isArr=isArrayValueType(valType);var isGradient=isGradientValueType(valType);for(var i=0;i=0;frameIdx--){if(keyframes[frameIdx].percent<=percent){break;}}frameIdx=mathMin(frameIdx,kfsNum-2);}else{for(frameIdx=lastFrame;frameIdxpercent){break;}}frameIdx=mathMin(frameIdx-1,kfsNum-2);}nextFrame=keyframes[frameIdx+1];frame=keyframes[frameIdx];}if(!(frame&&nextFrame)){return;}this._lastFr=frameIdx;this._lastFrP=percent;var interval=nextFrame.percent-frame.percent;var w=interval===0?1:mathMin((percent-frame.percent)/interval,1);if(nextFrame.easingFunc){w=nextFrame.easingFunc(w);}var targetArr=isAdditive?this._additiveValue:isValueColor?tmpRgba:target[propName];if((isArrayValueType(valType)||isValueColor)&&!targetArr){targetArr=this._additiveValue=[];}if(this.discrete){target[propName]=w<1?frame.rawValue:nextFrame.rawValue;}else if(isArrayValueType(valType)){valType===VALUE_TYPE_1D_ARRAY?interpolate1DArray(targetArr,frame[valueKey],nextFrame[valueKey],w):interpolate2DArray(targetArr,frame[valueKey],nextFrame[valueKey],w);}else if(isGradientValueType(valType)){var val=frame[valueKey];var nextVal_1=nextFrame[valueKey];var isLinearGradient_1=valType===VALUE_TYPE_LINEAR_GRADIENT;target[propName]={type:isLinearGradient_1?'linear':'radial',x:interpolateNumber$1(val.x,nextVal_1.x,w),y:interpolateNumber$1(val.y,nextVal_1.y,w),colorStops:map$1(val.colorStops,function(colorStop,idx){var nextColorStop=nextVal_1.colorStops[idx];return{offset:interpolateNumber$1(colorStop.offset,nextColorStop.offset,w),color:rgba2String(interpolate1DArray([],colorStop.color,nextColorStop.color,w))};}),global:nextVal_1.global};if(isLinearGradient_1){target[propName].x2=interpolateNumber$1(val.x2,nextVal_1.x2,w);target[propName].y2=interpolateNumber$1(val.y2,nextVal_1.y2,w);}else{target[propName].r=interpolateNumber$1(val.r,nextVal_1.r,w);}}else if(isValueColor){interpolate1DArray(targetArr,frame[valueKey],nextFrame[valueKey],w);if(!isAdditive){target[propName]=rgba2String(targetArr);}}else{var value=interpolateNumber$1(frame[valueKey],nextFrame[valueKey],w);if(isAdditive){this._additiveValue=value;}else{target[propName]=value;}}if(isAdditive){this._addToTarget(target);}};Track.prototype._addToTarget=function(target){var valType=this.valType;var propName=this.propName;var additiveValue=this._additiveValue;if(valType===VALUE_TYPE_NUMBER){target[propName]=target[propName]+additiveValue;}else if(valType===VALUE_TYPE_COLOR){parse(target[propName],tmpRgba);add1DArray(tmpRgba,tmpRgba,additiveValue,1);target[propName]=rgba2String(tmpRgba);}else if(valType===VALUE_TYPE_1D_ARRAY){add1DArray(target[propName],target[propName],additiveValue,1);}else if(valType===VALUE_TYPE_2D_ARRAY){add2DArray(target[propName],target[propName],additiveValue,1);}};return Track;}();var Animator=function(){function Animator(target,loop,allowDiscreteAnimation,additiveTo){this._tracks={};this._trackKeys=[];this._maxTime=0;this._started=0;this._clip=null;this._target=target;this._loop=loop;if(loop&&additiveTo){logError('Can\' use additive animation on looped animation.');return;}this._additiveAnimators=additiveTo;this._allowDiscrete=allowDiscreteAnimation;}Animator.prototype.getMaxTime=function(){return this._maxTime;};Animator.prototype.getDelay=function(){return this._delay;};Animator.prototype.getLoop=function(){return this._loop;};Animator.prototype.getTarget=function(){return this._target;};Animator.prototype.changeTarget=function(target){this._target=target;};Animator.prototype.when=function(time,props,easing){return this.whenWithKeys(time,props,keys(props),easing);};Animator.prototype.whenWithKeys=function(time,props,propNames,easing){var tracks=this._tracks;for(var i=0;i0){track.addKeyframe(0,cloneValue(initialValue),easing);}this._trackKeys.push(propName);}track.addKeyframe(time,cloneValue(props[propName]),easing);}this._maxTime=Math.max(this._maxTime,time);return this;};Animator.prototype.pause=function(){this._clip.pause();this._paused=true;};Animator.prototype.resume=function(){this._clip.resume();this._paused=false;};Animator.prototype.isPaused=function(){return!!this._paused;};Animator.prototype.duration=function(duration){this._maxTime=duration;this._force=true;return this;};Animator.prototype._doneCallback=function(){this._setTracksFinished();this._clip=null;var doneList=this._doneCbs;if(doneList){var len=doneList.length;for(var i=0;i0){return;}this._started=1;var self=this;var tracks=[];var maxTime=this._maxTime||0;for(var i=0;i1){var lastKf=kfs.pop();track.addKeyframe(lastKf.time,finalProps[propName]);track.prepare(this._maxTime,track.getAdditiveTrack());}}};return Animator;}();var Animator$1=Animator;function getTime(){return new Date().getTime();}var Animation=function(_super){__extends(Animation,_super);function Animation(opts){var _this=_super.call(this)||this;_this._running=false;_this._time=0;_this._pausedTime=0;_this._pauseStart=0;_this._paused=false;opts=opts||{};_this.stage=opts.stage||{};return _this;}Animation.prototype.addClip=function(clip){if(clip.animation){this.removeClip(clip);}if(!this._head){this._head=this._tail=clip;}else{this._tail.next=clip;clip.prev=this._tail;clip.next=null;this._tail=clip;}clip.animation=this;};Animation.prototype.addAnimator=function(animator){animator.animation=this;var clip=animator.getClip();if(clip){this.addClip(clip);}};Animation.prototype.removeClip=function(clip){if(!clip.animation){return;}var prev=clip.prev;var next=clip.next;if(prev){prev.next=next;}else{this._head=next;}if(next){next.prev=prev;}else{this._tail=prev;}clip.next=clip.prev=clip.animation=null;};Animation.prototype.removeAnimator=function(animator){var clip=animator.getClip();if(clip){this.removeClip(clip);}animator.animation=null;};Animation.prototype.update=function(notTriggerFrameAndStageUpdate){var time=getTime()-this._pausedTime;var delta=time-this._time;var clip=this._head;while(clip){var nextClip=clip.next;var finished=clip.step(time,delta);if(finished){clip.ondestroy();this.removeClip(clip);clip=nextClip;}else{clip=nextClip;}}this._time=time;if(!notTriggerFrameAndStageUpdate){this.trigger('frame',delta);this.stage.update&&this.stage.update();}};Animation.prototype._startLoop=function(){var self=this;this._running=true;function step(){if(self._running){requestAnimationFrame$1(step);!self._paused&&self.update();}}requestAnimationFrame$1(step);};Animation.prototype.start=function(){if(this._running){return;}this._time=getTime();this._pausedTime=0;this._startLoop();};Animation.prototype.stop=function(){this._running=false;};Animation.prototype.pause=function(){if(!this._paused){this._pauseStart=getTime();this._paused=true;}};Animation.prototype.resume=function(){if(this._paused){this._pausedTime+=getTime()-this._pauseStart;this._paused=false;}};Animation.prototype.clear=function(){var clip=this._head;while(clip){var nextClip=clip.next;clip.prev=clip.next=clip.animation=null;clip=nextClip;}this._head=this._tail=null;};Animation.prototype.isFinished=function(){return this._head==null;};Animation.prototype.animate=function(target,options){options=options||{};this.start();var animator=new Animator$1(target,options.loop);this.addAnimator(animator);return animator;};return Animation;}(Eventful$1);var Animation$1=Animation;var TOUCH_CLICK_DELAY=300;var globalEventSupported=env$1.domSupported;var localNativeListenerNames=function(){var mouseHandlerNames=['click','dblclick','mousewheel','wheel','mouseout','mouseup','mousedown','mousemove','contextmenu'];var touchHandlerNames=['touchstart','touchend','touchmove'];var pointerEventNameMap={pointerdown:1,pointerup:1,pointermove:1,pointerout:1};var pointerHandlerNames=map$1(mouseHandlerNames,function(name){var nm=name.replace('mouse','pointer');return pointerEventNameMap.hasOwnProperty(nm)?nm:name;});return{mouse:mouseHandlerNames,touch:touchHandlerNames,pointer:pointerHandlerNames};}();var globalNativeListenerNames={mouse:['mousemove','mouseup'],pointer:['pointermove','pointerup']};var wheelEventSupported=false;function isPointerFromTouch(event){var pointerType=event.pointerType;return pointerType==='pen'||pointerType==='touch';}function setTouchTimer(scope){scope.touching=true;if(scope.touchTimer!=null){clearTimeout(scope.touchTimer);scope.touchTimer=null;}scope.touchTimer=setTimeout(function(){scope.touching=false;scope.touchTimer=null;},700);}function markTouch(event){event&&(event.zrByTouch=true);}function normalizeGlobalEvent(instance,event){return normalizeEvent(instance.dom,new FakeGlobalEvent(instance,event),true);}function isLocalEl(instance,el){var elTmp=el;var isLocal=false;while(elTmp&&elTmp.nodeType!==9&&!(isLocal=elTmp.domBelongToZr||elTmp!==el&&elTmp===instance.painterRoot)){elTmp=elTmp.parentNode;}return isLocal;}var FakeGlobalEvent=function(){function FakeGlobalEvent(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;}return FakeGlobalEvent;}();var localDOMHandlers={mousedown:function mousedown(event){event=normalizeEvent(this.dom,event);this.__mayPointerCapture=[event.zrX,event.zrY];this.trigger('mousedown',event);},mousemove:function mousemove(event){event=normalizeEvent(this.dom,event);var downPoint=this.__mayPointerCapture;if(downPoint&&(event.zrX!==downPoint[0]||event.zrY!==downPoint[1])){this.__togglePointerCapture(true);}this.trigger('mousemove',event);},mouseup:function mouseup(event){event=normalizeEvent(this.dom,event);this.__togglePointerCapture(false);this.trigger('mouseup',event);},mouseout:function mouseout(event){event=normalizeEvent(this.dom,event);var element=event.toElement||event.relatedTarget;if(!isLocalEl(this,element)){if(this.__pointerCapturing){event.zrEventControl='no_globalout';}this.trigger('mouseout',event);}},wheel:function wheel(event){wheelEventSupported=true;event=normalizeEvent(this.dom,event);this.trigger('mousewheel',event);},mousewheel:function mousewheel(event){if(wheelEventSupported){return;}event=normalizeEvent(this.dom,event);this.trigger('mousewheel',event);},touchstart:function touchstart(event){event=normalizeEvent(this.dom,event);markTouch(event);this.__lastTouchMoment=new Date();this.handler.processGesture(event,'start');localDOMHandlers.mousemove.call(this,event);localDOMHandlers.mousedown.call(this,event);},touchmove:function touchmove(event){event=normalizeEvent(this.dom,event);markTouch(event);this.handler.processGesture(event,'change');localDOMHandlers.mousemove.call(this,event);},touchend:function touchend(event){event=normalizeEvent(this.dom,event);markTouch(event);this.handler.processGesture(event,'end');localDOMHandlers.mouseup.call(this,event);if(+new Date()-+this.__lastTouchMomentEPSILON$1||val<-EPSILON$1;}var scaleTmp=[];var tmpTransform=[];var originTransform=create();var abs=Math.abs;var Transformable=function(){function Transformable(){}Transformable.prototype.getLocalTransform=function(m){return Transformable.getLocalTransform(this,m);};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.setSkew=function(arr){this.skewX=arr[0];this.skewY=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)||isNotAroundZero(this.skewX)||isNotAroundZero(this.skewY);};Transformable.prototype.updateTransform=function(){var parentTransform=this.parent&&this.parent.transform;var needLocalTransform=this.needLocalTransform();var m=this.transform;if(!(needLocalTransform||parentTransform)){m&&mIdentity(m);return;}m=m||create();if(needLocalTransform){this.getLocalTransform(m);}else{mIdentity(m);}if(parentTransform){if(needLocalTransform){mul(m,parentTransform,m);}else{copy(m,parentTransform);}}this.transform=m;this._resolveGlobalScaleRatio(m);};Transformable.prototype._resolveGlobalScaleRatio=function(m){var globalScaleRatio=this.globalScaleRatio;if(globalScaleRatio!=null&&globalScaleRatio!==1){this.getGlobalScale(scaleTmp);var relX=scaleTmp[0]<0?-1:1;var relY=scaleTmp[1]<0?-1:1;var sx=((scaleTmp[0]-relX)*globalScaleRatio+relX)/scaleTmp[0]||0;var 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();invert(this.invTransform,m);};Transformable.prototype.getComputedTransform=function(){var transformNode=this;var ancestors=[];while(transformNode){ancestors.push(transformNode);transformNode=transformNode.parent;}while(transformNode=ancestors.pop()){transformNode.updateTransform();}return this.transform;};Transformable.prototype.setLocalTransform=function(m){if(!m){return;}var sx=m[0]*m[0]+m[1]*m[1];var sy=m[2]*m[2]+m[3]*m[3];var rotation=Math.atan2(m[1],m[0]);var shearX=Math.PI/2+rotation-Math.atan2(m[3],m[2]);sy=Math.sqrt(sy)*Math.cos(shearX);sx=Math.sqrt(sx);this.skewX=shearX;this.skewY=0;this.rotation=-rotation;this.x=+m[4];this.y=+m[5];this.scaleX=sx;this.scaleY=sy;this.originX=0;this.originY=0;};Transformable.prototype.decomposeTransform=function(){if(!this.transform){return;}var parent=this.parent;var m=this.transform;if(parent&&parent.transform){mul(tmpTransform,parent.invTransform,m);m=tmpTransform;}var ox=this.originX;var oy=this.originY;if(ox||oy){originTransform[4]=ox;originTransform[5]=oy;mul(tmpTransform,m,originTransform);tmpTransform[4]-=ox;tmpTransform[5]-=oy;m=tmpTransform;}this.setLocalTransform(m);};Transformable.prototype.getGlobalScale=function(out){var m=this.transform;out=out||[];if(!m){out[0]=1;out[1]=1;return out;}out[0]=Math.sqrt(m[0]*m[0]+m[1]*m[1]);out[1]=Math.sqrt(m[2]*m[2]+m[3]*m[3]);if(m[0]<0){out[0]=-out[0];}if(m[3]<0){out[1]=-out[1];}return out;};Transformable.prototype.transformCoordToLocal=function(x,y){var v2=[x,y];var invTransform=this.invTransform;if(invTransform){applyTransform$1(v2,v2,invTransform);}return v2;};Transformable.prototype.transformCoordToGlobal=function(x,y){var v2=[x,y];var transform=this.transform;if(transform){applyTransform$1(v2,v2,transform);}return 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.prototype.copyTransform=function(source){copyTransform(this,source);};Transformable.getLocalTransform=function(target,m){m=m||[];var ox=target.originX||0;var oy=target.originY||0;var sx=target.scaleX;var sy=target.scaleY;var ax=target.anchorX;var ay=target.anchorY;var rotation=target.rotation||0;var x=target.x;var y=target.y;var skewX=target.skewX?Math.tan(target.skewX):0;var skewY=target.skewY?Math.tan(-target.skewY):0;if(ox||oy||ax||ay){var dx=ox+ax;var dy=oy+ay;m[4]=-dx*sx-skewX*dy*sy;m[5]=-dy*sy-skewY*dx*sx;}else{m[4]=m[5]=0;}m[0]=sx;m[3]=sy;m[1]=skewY*sx;m[2]=skewX*sy;rotation&&rotate(m,m,rotation);m[4]+=ox+x;m[5]+=oy+y;return m;};Transformable.initDefaultProps=function(){var proto=Transformable.prototype;proto.scaleX=proto.scaleY=proto.globalScaleRatio=1;proto.x=proto.y=proto.originX=proto.originY=proto.skewX=proto.skewY=proto.rotation=proto.anchorX=proto.anchorY=0;}();return Transformable;}();var TRANSFORMABLE_PROPS=['x','y','originX','originY','anchorX','anchorY','rotation','scaleX','scaleY','skewX','skewY'];function copyTransform(target,source){for(var i=0;idMax){dMax=dx;if(d0dMax){dMax=dy;if(d2=rect.x&&x<=rect.x+rect.width&&y>=rect.y&&y<=rect.y+rect.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 this.width===0||this.height===0;};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){if(target!==source){BoundingRect.copy(target,source);}return;}if(m[1]<1e-5&&m[1]>-1e-5&&m[2]<1e-5&&m[2]>-1e-5){var sx=m[0];var sy=m[3];var tx=m[4];var 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;if(target.width<0){target.x+=target.width;target.width=-target.width;}if(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$7(lt.x,rb.x,lb.x,rt.x);target.y=mathMin$7(lt.y,rb.y,lb.y,rt.y);var maxX=mathMax$7(lt.x,rb.x,lb.x,rt.x);var maxY=mathMax$7(lt.y,rb.y,lb.y,rt.y);target.width=maxX-target.x;target.height=maxY-target.y;};return BoundingRect;}();var BoundingRect$1=BoundingRect;var textWidthCache={};function getWidth(text,font){font=font||DEFAULT_FONT;var cacheOfFont=textWidthCache[font];if(!cacheOfFont){cacheOfFont=textWidthCache[font]=new LRU$1(500);}var width=cacheOfFont.get(text);if(width==null){width=platformApi.measureText(text,font).width;cacheOfFont.put(text,width);}return width;}function innerGetBoundingRect(text,font,textAlign,textBaseline){var width=getWidth(text,font);var height=getLineHeight(font);var x=adjustTextX(0,width,textAlign);var y=adjustTextY(0,height,textBaseline);var rect=new BoundingRect$1(x,y,width,height);return rect;}function getBoundingRect(text,font,textAlign,textBaseline){var textLines=((text||'')+'').split('\n');var len=textLines.length;if(len===1){return innerGetBoundingRect(textLines[0],font,textAlign,textBaseline);}else{var uniondRect=new BoundingRect$1(0,0,0,0);for(var i=0;i=0){return parseFloat(value)/100*maxValue;}return parseFloat(value);}return value;}function _calculateTextPosition(out,opts,rect){var textPosition=opts.position||'inside';var distance=opts.distance!=null?opts.distance:5;var height=rect.height;var width=rect.width;var halfHeight=height/2;var x=rect.x;var y=rect.y;var textAlign='left';var textVerticalAlign='top';if(textPosition instanceof Array){x+=parsePercent$1(textPosition[0],rect.width);y+=parsePercent$1(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';break;}}out=out||{};out.x=x;out.y=y;out.align=textAlign;out.verticalAlign=textVerticalAlign;return out;}var PRESERVED_NORMAL_STATE='__zr_normal__';var PRIMARY_STATES_KEYS$1=TRANSFORMABLE_PROPS.concat(['ignore']);var DEFAULT_ANIMATABLE_MAP=reduce(TRANSFORMABLE_PROPS,function(obj,key){obj[key]=true;return obj;},{ignore:false});var tmpTextPosCalcRes={};var tmpBoundingRect=new BoundingRect$1(0,0,0,0);var Element=function(){function Element(props){this.id=guid();this.animators=[];this.currentStates=[];this.states={};this._init(props);}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;break;}var m=this.transform;if(!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();if(this.__dirty){this.updateInnerText();}};Element.prototype.updateInnerText=function(forceUpdate){var textEl=this._textContent;if(textEl&&(!textEl.ignore||forceUpdate)){if(!this.textConfig){this.textConfig={};}var textConfig=this.textConfig;var isLocal=textConfig.local;var innerTransformable=textEl.innerTransformable;var textAlign=void 0;var textVerticalAlign=void 0;var textStyleChanged=false;innerTransformable.parent=isLocal?this:null;var innerOrigin=false;innerTransformable.copyTransform(textEl);if(textConfig.position!=null){var layoutRect=tmpBoundingRect;if(textConfig.layoutRect){layoutRect.copy(textConfig.layoutRect);}else{layoutRect.copy(this.getBoundingRect());}if(!isLocal){layoutRect.applyTransform(this.transform);}if(this.calculateTextPosition){this.calculateTextPosition(tmpTextPosCalcRes,textConfig,layoutRect);}else{_calculateTextPosition(tmpTextPosCalcRes,textConfig,layoutRect);}innerTransformable.x=tmpTextPosCalcRes.x;innerTransformable.y=tmpTextPosCalcRes.y;textAlign=tmpTextPosCalcRes.align;textVerticalAlign=tmpTextPosCalcRes.verticalAlign;var textOrigin=textConfig.origin;if(textOrigin&&textConfig.rotation!=null){var relOriginX=void 0;var relOriginY=void 0;if(textOrigin==='center'){relOriginX=layoutRect.width*0.5;relOriginY=layoutRect.height*0.5;}else{relOriginX=parsePercent$1(textOrigin[0],layoutRect.width);relOriginY=parsePercent$1(textOrigin[1],layoutRect.height);}innerOrigin=true;innerTransformable.originX=-innerTransformable.x+relOriginX+(isLocal?0:layoutRect.x);innerTransformable.originY=-innerTransformable.y+relOriginY+(isLocal?0:layoutRect.y);}}if(textConfig.rotation!=null){innerTransformable.rotation=textConfig.rotation;}var textOffset=textConfig.offset;if(textOffset){innerTransformable.x+=textOffset[0];innerTransformable.y+=textOffset[1];if(!innerOrigin){innerTransformable.originX=-textOffset[0];innerTransformable.originY=-textOffset[1];}}var isInside=textConfig.inside==null?typeof textConfig.position==='string'&&textConfig.position.indexOf('inside')>=0:textConfig.inside;var innerTextDefaultStyle=this._innerTextDefaultStyle||(this._innerTextDefaultStyle={});var textFill=void 0;var textStroke=void 0;var autoStroke=void 0;if(isInside&&this.canBeInsideText()){textFill=textConfig.insideFill;textStroke=textConfig.insideStroke;if(textFill==null||textFill==='auto'){textFill=this.getInsideTextFill();}if(textStroke==null||textStroke==='auto'){textStroke=this.getInsideTextStroke(textFill);autoStroke=true;}}else{textFill=textConfig.outsideFill;textStroke=textConfig.outsideStroke;if(textFill==null||textFill==='auto'){textFill=this.getOutsideFill();}if(textStroke==null||textStroke==='auto'){textStroke=this.getOutsideStroke(textFill);autoStroke=true;}}textFill=textFill||'#000';if(textFill!==innerTextDefaultStyle.fill||textStroke!==innerTextDefaultStyle.stroke||autoStroke!==innerTextDefaultStyle.autoStroke||textAlign!==innerTextDefaultStyle.align||textVerticalAlign!==innerTextDefaultStyle.verticalAlign){textStyleChanged=true;innerTextDefaultStyle.fill=textFill;innerTextDefaultStyle.stroke=textStroke;innerTextDefaultStyle.autoStroke=autoStroke;innerTextDefaultStyle.align=textAlign;innerTextDefaultStyle.verticalAlign=textVerticalAlign;textEl.setDefaultTextStyle(innerTextDefaultStyle);}textEl.__dirty|=REDRAW_BIT;if(textStyleChanged){textEl.dirtyStyle(true);}}};Element.prototype.canBeInsideText=function(){return true;};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();var colorArr=typeof backgroundColor==='string'&&parse(backgroundColor);if(!colorArr){colorArr=[255,255,255,1];}var alpha=colorArr[3];var isDark=this.__zr.isDarkMode();for(var i=0;i<3;i++){colorArr[i]=colorArr[i]*alpha+(isDark?0:255)*(1-alpha);}colorArr[3]=1;return stringify(colorArr,'rgba');};Element.prototype.traverse=function(cb,context){};Element.prototype.attrKV=function(key,value){if(key==='textConfig'){this.setTextConfig(value);}else if(key==='textContent'){this.setTextContent(value);}else if(key==='clipPath'){this.setClipPath(value);}else if(key==='extra'){this.extra=this.extra||{};extend(this.extra,value);}else{this[key]=value;}};Element.prototype.hide=function(){this.ignore=true;this.markRedraw();};Element.prototype.show=function(){this.ignore=false;this.markRedraw();};Element.prototype.attr=function(keyOrObj,value){if(typeof keyOrObj==='string'){this.attrKV(keyOrObj,value);}else if(isObject$2(keyOrObj)){var obj=keyOrObj;var keysArr=keys(obj);for(var i=0;i0;};Element.prototype.getState=function(name){return this.states[name];};Element.prototype.ensureState=function(name){var states=this.states;if(!states[name]){states[name]={};}return states[name];};Element.prototype.clearStates=function(noAnimation){this.useState(PRESERVED_NORMAL_STATE,false,noAnimation);};Element.prototype.useState=function(stateName,keepCurrentStates,noAnimation,forceUseHoverLayer){var toNormalState=stateName===PRESERVED_NORMAL_STATE;var hasStates=this.hasState();if(!hasStates&&toNormalState){return;}var currentStates=this.currentStates;var animationCfg=this.stateTransition;if(indexOf(currentStates,stateName)>=0&&(keepCurrentStates||currentStates.length===1)){return;}var state;if(this.stateProxy&&!toNormalState){state=this.stateProxy(stateName);}if(!state){state=this.states&&this.states[stateName];}if(!state&&!toNormalState){logError("State "+stateName+" not exists.");return;}if(!toNormalState){this.saveCurrentToNormalState(state);}var useHoverLayer=!!(state&&state.hoverLayer||forceUseHoverLayer);if(useHoverLayer){this._toggleHoverLayerFlag(true);}this._applyStateObj(stateName,state,this._normalState,keepCurrentStates,!noAnimation&&!this.__inHover&&animationCfg&&animationCfg.duration>0,animationCfg);var textContent=this._textContent;var textGuide=this._textGuide;if(textContent){textContent.useState(stateName,keepCurrentStates,noAnimation,useHoverLayer);}if(textGuide){textGuide.useState(stateName,keepCurrentStates,noAnimation,useHoverLayer);}if(toNormalState){this.currentStates=[];this._normalState={};}else{if(!keepCurrentStates){this.currentStates=[stateName];}else{this.currentStates.push(stateName);}}this._updateAnimationTargets();this.markRedraw();if(!useHoverLayer&&this.__inHover){this._toggleHoverLayerFlag(false);this.__dirty&=~REDRAW_BIT;}return state;};Element.prototype.useStates=function(states,noAnimation,forceUseHoverLayer){if(!states.length){this.clearStates();}else{var stateObjects=[];var currentStates=this.currentStates;var len=states.length;var notChange=len===currentStates.length;if(notChange){for(var i=0;i0,animationCfg);var textContent=this._textContent;var textGuide=this._textGuide;if(textContent){textContent.useStates(states,noAnimation,useHoverLayer);}if(textGuide){textGuide.useStates(states,noAnimation,useHoverLayer);}this._updateAnimationTargets();this.currentStates=states.slice();this.markRedraw();if(!useHoverLayer&&this.__inHover){this._toggleHoverLayerFlag(false);this.__dirty&=~REDRAW_BIT;}}};Element.prototype._updateAnimationTargets=function(){for(var i=0;i=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();var idx=indexOf(currentStates,oldState);var newStateExists=indexOf(currentStates,newState)>=0;if(idx>=0){if(!newStateExists){currentStates[idx]=newState;}else{currentStates.splice(idx,1);}}else if(forceAdd&&!newStateExists){currentStates.push(newState);}this.useStates(currentStates);};Element.prototype.toggleState=function(state,enable){if(enable){this.useState(state,true);}else{this.removeState(state);}};Element.prototype._mergeStates=function(states){var mergedState={};var mergedTextConfig;for(var i=0;i=0){animators.splice(idx,1);}});this.animators.push(animator);if(zr){zr.animation.addAnimator(animator);}zr&&zr.wakeUp();};Element.prototype.updateDuringAnimation=function(key){this.markRedraw();};Element.prototype.stopAnimation=function(scope,forwardToLast){var animators=this.animators;var len=animators.length;var leftAnimators=[];for(var i=0;i0&&cfg.during){animators[0].during(function(target,percent){cfg.during(percent);});}for(var i=0;i0||cfg.force&&!animators.length){var revertedSource=void 0;var reversedTarget=void 0;var sourceClone=void 0;if(reverse){reversedTarget={};if(setToFinal){revertedSource={};}for(var i=0;i=0){children.splice(idx,0,child);this._doAdd(child);}}return this;};Group.prototype.replace=function(oldChild,newChild){var idx=indexOf(this._children,oldChild);if(idx>=0){this.replaceAt(newChild,idx);}return this;};Group.prototype.replaceAt=function(child,index){var children=this._children;var old=children[index];if(child&&child!==this&&child.parent!==this&&child!==old){children[index]=child;old.parent=null;var zr=this.__zr;if(zr){old.removeSelfFromZr(zr);}this._doAdd(child);}return this;};Group.prototype._doAdd=function(child){if(child.parent){child.parent.remove(child);}child.parent=this;var zr=this.__zr;if(zr&&zr!==child.__zr){child.addSelfToZr(zr);}zr&&zr.refresh();};Group.prototype.remove=function(child){var zr=this.__zr;var children=this._children;var idx=indexOf(children,child);if(idx<0){return this;}children.splice(idx,1);child.parent=null;if(zr){child.removeSelfFromZr(zr);}zr&&zr.refresh();return this;};Group.prototype.removeAll=function(){var children=this._children;var zr=this.__zr;for(var i=0;i0){this._stillFrameAccum++;if(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.refreshHover=function(){this._needsRefreshHover=true;};ZRender.prototype.refreshHoverImmediately=function(){this._needsRefreshHover=false;if(this.painter.refreshHover&&this.painter.getType()==='canvas'){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.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){this.handler.on(eventName,eventHandler,context);return 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(){var roots=this.storage.getRoots();for(var i=0;i0){if(val<=d0){return r0;}else if(val>=d1){return r1;}}else{if(val>=d0){return r0;}else if(val<=d1){return r1;}}}else{if(val===d0){return r0;}if(val===d1){return r1;}}return(val-d0)/subDomain*subRange+r0;}/** * Convert a percent string to absolute number. * Returns NaN if percent is not a valid string or number */function parsePercent(percent,all){switch(percent){case'center':case'middle':percent='50%';break;case'left':case'top':percent='0%';break;case'right':case'bottom':percent='100%';break;}if(isString(percent)){if(_trim(percent).match(/%$/)){return parseFloat(percent)/100*all;}return parseFloat(percent);}return percent==null?NaN:+percent;}function round$1(x,precision,returnStr){if(precision==null){precision=10;}// Avoid range error precision=Math.min(Math.max(0,precision),ROUND_SUPPORTED_PRECISION_MAX);// PENDING: 1.005.toFixed(2) is '1.00' rather than '1.01' x=(+x).toFixed(precision);return returnStr?x:+x;}/** * Inplacd asc sort arr. * The input arr will be modified. */function asc$1(arr){arr.sort(function(a,b){return a-b;});return arr;}/** * Get precision. */function getPrecision(val){val=+val;if(isNaN(val)){return 0;}// It is much faster than methods converting number to string as follows // let tmp = val.toString(); // return tmp.length - 1 - tmp.indexOf('.'); // especially when precision is low // Notice: // (1) If the loop count is over about 20, it is slower than `getPrecisionSafe`. // (see https://jsbench.me/2vkpcekkvw/1) // (2) If the val is less than for example 1e-15, the result may be incorrect. // (see test/ut/spec/util/number.test.ts `getPrecision_equal_random`) if(val>1e-14){var e=1;for(var i=0;i<15;i++,e*=10){if(Math.round(val*e)/e===val){return i;}}}return getPrecisionSafe(val);}/** * Get precision with slow but safe method */function getPrecisionSafe(val){// toLowerCase for: '3.4E-12' var str=val.toString().toLowerCase();// Consider scientific notation: '3.4e-12' '3.4e+12' var eIndex=str.indexOf('e');var exp=eIndex>0?+str.slice(eIndex+1):0;var significandPartLen=eIndex>0?eIndex:str.length;var dotIndex=str.indexOf('.');var decimalPartLen=dotIndex<0?0:significandPartLen-1-dotIndex;return Math.max(0,decimalPartLen-exp);}/** * Minimal dicernible data precisioin according to a single pixel. */function getPixelPrecision(dataExtent,pixelExtent){var log=Math.log;var LN10=Math.LN10;var dataQuantity=Math.floor(log(dataExtent[1]-dataExtent[0])/LN10);var sizeQuantity=Math.round(log(Math.abs(pixelExtent[1]-pixelExtent[0]))/LN10);// toFixed() digits argument must be between 0 and 20. var precision=Math.min(Math.max(-dataQuantity+sizeQuantity,0),20);return!isFinite(precision)?20:precision;}/** * Get a data of given precision, assuring the sum of percentages * in valueList is 1. * The largest remainer method is used. * https://en.wikipedia.org/wiki/Largest_remainder_method * * @param valueList a list of all data * @param idx index of the data to be processed in valueList * @param precision integer number showing digits of precision * @return percent ranging from 0 to 100 */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(sum===0){return 0;}var digits=Math.pow(10,precision);var votesPerQuota=map$1(valueList,function(val){return(isNaN(val)?0:val)/sum*digits*100;});var targetSeats=digits*100;var seats=map$1(votesPerQuota,function(votes){// Assign automatic seats. return Math.floor(votes);});var currentSum=reduce(seats,function(acc,val){return acc+val;},0);var remainder=map$1(votesPerQuota,function(votes,idx){return votes-seats[idx];});// Has remainding votes. while(currentSummax){max=remainder[i];maxId=i;}}// Add a vote to max remainder. ++seats[maxId];remainder[maxId]=0;++currentSum;}return seats[idx]/digits;}/** * Solve the floating point adding problem like 0.1 + 0.2 === 0.30000000000000004 * See */function addSafe(val0,val1){var maxPrecision=Math.max(getPrecision(val0),getPrecision(val1));// const multiplier = Math.pow(10, maxPrecision); // return (Math.round(val0 * multiplier) + Math.round(val1 * multiplier)) / multiplier; var sum=val0+val1;// // PENDING: support more? return maxPrecision>ROUND_SUPPORTED_PRECISION_MAX?sum:round$1(sum,maxPrecision);}// Number.MAX_SAFE_INTEGER, ie do not support. /** * To 0 - 2 * PI, considering negative radian. */function remRadian(radian){var pi2=Math.PI*2;return(radian%pi2+pi2)%pi2;}/** * @param {type} radian * @return {boolean} */function isRadianAroundZero(val){return val>-RADIAN_EPSILON&&val). * + Or other string format, including (all of which will be treated as loacal time): * '2012', '2012-3-1', '2012/3/1', '2012/03/01', * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123' * + a timestamp, which represent a time in UTC. * @return date Never be null/undefined. If invalid, return `new Date(NaN)`. */function parseDate(value){if(value instanceof Date){return value;}else if(isString(value)){// Different browsers parse date in different way, so we parse it manually. // Some other issues: // new Date('1970-01-01') is UTC, // new Date('1970/01/01') and new Date('1970-1-01') is local. // See issue #3623 var match=TIME_REG.exec(value);if(!match){// return Invalid Date. return new Date(NaN);}// Use local time when no timezone offset specifed. if(!match[8]){// match[n] can only be string or undefined. // But take care of '12' + 1 => '121'. return new Date(+match[1],+(match[2]||1)-1,+match[3]||1,+match[4]||0,+(match[5]||0),+match[6]||0,match[7]?+match[7].substring(0,3):0);}// Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time, // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment). // For example, system timezone is set as "Time Zone: America/Toronto", // then these code will get different result: // `new Date(1478411999999).getTimezoneOffset(); // get 240` // `new Date(1478412000000).getTimezoneOffset(); // get 300` // So we should not use `new Date`, but use `Date.UTC`. else{var hour=+match[4]||0;if(match[8].toUpperCase()!=='Z'){hour-=+match[8].slice(0,3);}return new Date(Date.UTC(+match[1],+(match[2]||1)-1,+match[3]||1,hour,+(match[5]||0),+match[6]||0,match[7]?+match[7].substring(0,3):0));}}else if(value==null){return new Date(NaN);}return new Date(Math.round(value));}/** * Quantity of a number. e.g. 0.1, 1, 10, 100 * * @param val * @return */function quantity(val){return Math.pow(10,quantityExponent(val));}/** * Exponent of the quantity of a number * e.g., 1234 equals to 1.234*10^3, so quantityExponent(1234) is 3 * * @param val non-negative value * @return */function quantityExponent(val){if(val===0){return 0;}var exp=Math.floor(Math.log(val)/Math.LN10);/** * exp is expected to be the rounded-down result of the base-10 log of val. * But due to the precision loss with Math.log(val), we need to restore it * using 10^exp to make sure we can get val back from exp. #11249 */if(val/Math.pow(10,exp)>=10){exp++;}return exp;}/** * find a “nice” number approximately equal to x. Round the number if round = true, * take ceiling if round = false. The primary observation is that the “nicest” * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers. * * See "Nice Numbers for Graph Labels" of Graphic Gems. * * @param val Non-negative value. * @param round * @return Niced number */function nice(val,round){var exponent=quantityExponent(val);var exp10=Math.pow(10,exponent);var f=val/exp10;// 1 <= f < 10 var nf;if(round){if(f<1.5){nf=1;}else if(f<2.5){nf=2;}else if(f<4){nf=3;}else if(f<7){nf=5;}else{nf=10;}}else{if(f<1){nf=1;}else if(f<2){nf=2;}else if(f<3){nf=3;}else if(f<5){nf=5;}else{nf=10;}}val=nf*exp10;// Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754). // 20 is the uppper bound of toFixed. return exponent>=-20?+val.toFixed(exponent<0?-exponent:0):val;}/** * [Numberic is defined as]: * `parseFloat(val) == val` * For example: * numeric: * typeof number except NaN, '-123', '123', '2e3', '-2e3', '011', 'Infinity', Infinity, * and they rounded by white-spaces or line-terminal like ' -123 \n ' (see es spec) * not-numeric: * null, undefined, [], {}, true, false, 'NaN', NaN, '123ab', * empty string, string with only white-spaces or line-terminal (see es spec), * 0x12, '0x12', '-0x12', 012, '012', '-012', * non-string, ... * * @test See full test cases in `test/ut/spec/util/number.js`. * @return Must be a typeof number. If not numeric, return NaN. */function numericToNumber(val){var valFloat=parseFloat(val);return valFloat==val// eslint-disable-line eqeqeq &&(valFloat!==0||!isString(val)||val.indexOf('x')<=0)// For case ' 0x0 '. ?valFloat:NaN;}/** * Definition of "numeric": see `numericToNumber`. */function isNumeric(val){return!isNaN(numericToNumber(val));}/** * Use random base to prevent users hard code depending on * this auto generated marker id. * @return An positive integer. */function getRandomIdBase(){return Math.round(Math.random()*9);}/** * Get the greatest common dividor * * @param {number} a one number * @param {number} b the other number */function getGreatestCommonDividor(a,b){if(b===0){return a;}return getGreatestCommonDividor(b,a%b);}/** * Get the least common multiple * * @param {number} a one number * @param {number} b the other number */function getLeastCommonMultiple(a,b){if(a==null){return b;}if(b==null){return a;}return a*b/getGreatestCommonDividor(a,b);}/** * @throws Error */function throwError(msg){throw new Error(msg);}function interpolateNumber(p0,p1,percent){return(p1-p0)*percent+p0;}/** * Make the name displayable. But we should * make sure it is not duplicated with user * specified name, so use '\0'; */var DUMMY_COMPONENT_NAME_PREFIX='series\0';var INTERNAL_COMPONENT_ID_PREFIX='\0_ec_\0';/** * If value is not array, then translate it to array. * @param {*} value * @return {Array} [value] or value */function normalizeToArray(value){return value instanceof Array?value:value==null?[]:[value];}/** * Sync default option between normal and emphasis like `position` and `show` * In case some one will write code like * label: { * show: false, * position: 'outside', * fontSize: 18 * }, * emphasis: { * label: { show: true } * } */function defaultEmphasis(opt,key,subOpts){// Caution: performance sensitive. if(opt){opt[key]=opt[key]||{};opt.emphasis=opt.emphasis||{};opt.emphasis[key]=opt.emphasis[key]||{};// Default emphasis option from normal for(var i=0,len=subOpts.length;i. */function mappingToExists(existings,newCmptOptions,mode){var isNormalMergeMode=mode==='normalMerge';var isReplaceMergeMode=mode==='replaceMerge';var isReplaceAllMode=mode==='replaceAll';existings=existings||[];newCmptOptions=(newCmptOptions||[]).slice();var existingIdIdxMap=createHashMap();// Validate id and name on user input option. each$7(newCmptOptions,function(cmptOption,index){if(!isObject$2(cmptOption)){newCmptOptions[index]=null;return;}});var result=prepareResult(existings,existingIdIdxMap,mode);if(isNormalMergeMode||isReplaceMergeMode){mappingById(result,existings,existingIdIdxMap,newCmptOptions);}if(isNormalMergeMode){mappingByName(result,newCmptOptions);}if(isNormalMergeMode||isReplaceMergeMode){mappingByIndex(result,newCmptOptions,isReplaceMergeMode);}else if(isReplaceAllMode){mappingInReplaceAllMode(result,newCmptOptions);}makeIdAndName(result);// The array `result` MUST NOT contain elided items, otherwise the // forEach will ommit those items and result in incorrect result. return result;}function prepareResult(existings,existingIdIdxMap,mode){var result=[];if(mode==='replaceAll'){return result;}// Do not use native `map` to in case that the array `existings` // contains elided items, which will be ommited. for(var index=0;index= result.length`. (resultItem=result[nextIdx])&&(// (1) Existing models that already have id should be able to mapped to. Because // after mapping performed, model will always be assigned with an id if user not given. // After that all models have id. // (2) If new option has id, it can only set to a hole or append to the last. It should // not be merged to the existings with different id. Because id should not be overwritten. // (3) Name can be overwritten, because axis use name as 'show label text'. resultItem.newOption||isComponentIdInternal(resultItem.existing)||// In mode "replaceMerge", here no not-mapped-non-internal-existing. resultItem.existing&&cmptOption.id!=null&&!keyExistAndEqual('id',cmptOption,resultItem.existing))){nextIdx++;}if(resultItem){resultItem.newOption=cmptOption;resultItem.brandNew=brandNew;}else{result.push({newOption:cmptOption,brandNew:brandNew,existing:null,keyInfo:null});}nextIdx++;});}function mappingInReplaceAllMode(result,newCmptOptions){each$7(newCmptOptions,function(cmptOption){// The feature "reproduce" requires "hole" will also reproduced // in case that compoennt index referring are broken. result.push({newOption:cmptOption,brandNew:true,existing:null,keyInfo:null});});}/** * Make id and name for mapping result (result of mappingToExists) * into `keyInfo` field. */function makeIdAndName(mapResult){// We use this id to hash component models and view instances // in echarts. id can be specified by user, or auto generated. // The id generation rule ensures new view instance are able // to mapped to old instance when setOption are called in // no-merge mode. So we generate model id by name and plus // type in view id. // name can be duplicated among components, which is convenient // to specify multi components (like series) by one name. // Ensure that each id is distinct. var idMap=createHashMap();each$7(mapResult,function(item){var existing=item.existing;existing&&idMap.set(existing.id,item);});each$7(mapResult,function(item){var opt=item.newOption;// Force ensure id not duplicated. assert(!opt||opt.id==null||!idMap.get(opt.id)||idMap.get(opt.id)===item,'id duplicates: '+(opt&&opt.id));opt&&opt.id!=null&&idMap.set(opt.id,item);!item.keyInfo&&(item.keyInfo={});});// Make name and id. each$7(mapResult,function(item,index){var existing=item.existing;var opt=item.newOption;var keyInfo=item.keyInfo;if(!isObject$2(opt)){return;}// name can be overwitten. Consider case: axis.name = '20km'. // But id generated by name will not be changed, which affect // only in that case: setOption with 'not merge mode' and view // instance will be recreated, which can be accepted. keyInfo.name=opt.name!=null?makeComparableKey(opt.name):existing?existing.name// Avoid diffferent series has the same name, // because name may be used like in color pallet. :DUMMY_COMPONENT_NAME_PREFIX+index;if(existing){keyInfo.id=makeComparableKey(existing.id);}else if(opt.id!=null){keyInfo.id=makeComparableKey(opt.id);}else{// Consider this situatoin: // optionA: [{name: 'a'}, {name: 'a'}, {..}] // optionB [{..}, {name: 'a'}, {name: 'a'}] // Series with the same name between optionA and optionB // should be mapped. var idNum=0;do{keyInfo.id='\0'+keyInfo.name+'\0'+idNum++;}while(idMap.get(keyInfo.id));}idMap.set(keyInfo.id,item);});}function keyExistAndEqual(attr,obj1,obj2){var key1=convertOptionIdName(obj1[attr],null);var key2=convertOptionIdName(obj2[attr],null);// See `MappingExistingItem`. `id` and `name` trade string equals to number. return key1!=null&&key2!=null&&key1===key2;}/** * @return return null if not exist. */function makeComparableKey(val){return convertOptionIdName(val,'');}function convertOptionIdName(idOrName,defaultValue){if(idOrName==null){return defaultValue;}return isString(idOrName)?idOrName:isNumber(idOrName)||isStringSafe(idOrName)?idOrName+'':defaultValue;}function isNameSpecified(componentModel){var name=componentModel.name;// Is specified when `indexOf` get -1 or > 0. return!!(name&&name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));}/** * @public * @param {Object} cmptOption * @return {boolean} */function isComponentIdInternal(cmptOption){return cmptOption&&cmptOption.id!=null&&makeComparableKey(cmptOption.id).indexOf(INTERNAL_COMPONENT_ID_PREFIX)===0;}function makeInternalComponentId(idSuffix){return INTERNAL_COMPONENT_ID_PREFIX+idSuffix;}function setComponentTypeToKeyInfo(mappingResult,mainType,componentModelCtor){// Set mainType and complete subType. each$7(mappingResult,function(item){var newOption=item.newOption;if(isObject$2(newOption)){item.keyInfo.mainType=mainType;item.keyInfo.subType=determineSubType(mainType,newOption,item.existing,componentModelCtor);}});}function determineSubType(mainType,newCmptOption,existComponent,componentModelCtor){var subType=newCmptOption.type?newCmptOption.type:existComponent?existComponent.subType// Use determineSubType only when there is no existComponent. :componentModelCtor.determineSubType(mainType,newCmptOption);// tooltip, markline, markpoint may always has no subType return subType;}/** * @param payload Contains dataIndex (means rawIndex) / dataIndexInside / name * each of which can be Array or primary type. * @return dataIndex If not found, return undefined/null. */function queryDataIndex(data,payload){if(payload.dataIndexInside!=null){return payload.dataIndexInside;}else if(payload.dataIndex!=null){return isArray(payload.dataIndex)?map$1(payload.dataIndex,function(value){return data.indexOfRawIndex(value);}):data.indexOfRawIndex(payload.dataIndex);}else if(payload.name!=null){return isArray(payload.name)?map$1(payload.name,function(value){return data.indexOfName(value);}):data.indexOfName(payload.name);}}/** * Enable property storage to any host object. * Notice: Serialization is not supported. * * For example: * let inner = zrUitl.makeInner(); * * function some1(hostObj) { * inner(hostObj).someProperty = 1212; * ... * } * function some2() { * let fields = inner(this); * fields.someProperty1 = 1212; * fields.someProperty2 = 'xx'; * ... * } * * @return {Function} */function makeInner(){var key='__ec_inner_'+innerUniqueIndex++;return function(hostObj){return hostObj[key]||(hostObj[key]={});};}var innerUniqueIndex=getRandomIdBase();/** * The same behavior as `component.getReferringComponents`. */function parseFinder$1(ecModel,finderInput,opt){var _a=preParseFinder(finderInput,opt),mainTypeSpecified=_a.mainTypeSpecified,queryOptionMap=_a.queryOptionMap,others=_a.others;var result=others;var defaultMainType=opt?opt.defaultMainType:null;if(!mainTypeSpecified&&defaultMainType){queryOptionMap.set(defaultMainType,{});}queryOptionMap.each(function(queryOption,mainType){var queryResult=queryReferringComponents(ecModel,mainType,queryOption,{useDefault:defaultMainType===mainType,enableAll:opt&&opt.enableAll!=null?opt.enableAll:true,enableNone:opt&&opt.enableNone!=null?opt.enableNone:true});result[mainType+'Models']=queryResult.models;result[mainType+'Model']=queryResult.models[0];});return result;}function preParseFinder(finderInput,opt){var finder;if(isString(finderInput)){var obj={};obj[finderInput+'Index']=0;finder=obj;}else{finder=finderInput;}var queryOptionMap=createHashMap();var others={};var mainTypeSpecified=false;each$7(finder,function(value,key){// Exclude 'dataIndex' and other illgal keys. if(key==='dataIndex'||key==='dataIndexInside'){others[key]=value;return;}var parsedKey=key.match(/^(\w+)(Index|Id|Name)$/)||[];var mainType=parsedKey[1];var queryType=(parsedKey[2]||'').toLowerCase();if(!mainType||!queryType||opt&&opt.includeMainTypes&&indexOf(opt.includeMainTypes,mainType)<0){return;}mainTypeSpecified=mainTypeSpecified||!!mainType;var queryOption=queryOptionMap.get(mainType)||queryOptionMap.set(mainType,{});queryOption[queryType]=value;});return{mainTypeSpecified:mainTypeSpecified,queryOptionMap:queryOptionMap,others:others};}var SINGLE_REFERRING={useDefault:true,enableAll:false,enableNone:false};var MULTIPLE_REFERRING={useDefault:false,enableAll:true,enableNone:true};function queryReferringComponents(ecModel,mainType,userOption,opt){opt=opt||SINGLE_REFERRING;var indexOption=userOption.index;var idOption=userOption.id;var nameOption=userOption.name;var result={models:null,specified:indexOption!=null||idOption!=null||nameOption!=null};if(!result.specified){// Use the first as default if `useDefault`. var firstCmpt=void 0;result.models=opt.useDefault&&(firstCmpt=ecModel.getComponent(mainType))?[firstCmpt]:[];return result;}if(indexOption==='none'||indexOption===false){assert(opt.enableNone,'`"none"` or `false` is not a valid value on index option.');result.models=[];return result;}// `queryComponents` will return all components if // both all of index/id/name are null/undefined. if(indexOption==='all'){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});return result;}function setAttribute(dom,key,value){dom.setAttribute?dom.setAttribute(key,value):dom[key]=value;}function getAttribute(dom,key){return dom.getAttribute?dom.getAttribute(key):dom[key];}function getTooltipRenderMode(renderModeOption){if(renderModeOption==='auto'){// Using html when `document` exists, use richText otherwise return env$1.domSupported?'html':'richText';}else{return renderModeOption||'html';}}/** * Interpolate raw values of a series with percent * * @param data data * @param labelModel label model of the text element * @param sourceValue start value. May be null/undefined when init. * @param targetValue end value * @param percent 0~1 percentage; 0 uses start value while 1 uses end value * @return interpolated values * If `sourceValue` and `targetValue` are `number`, return `number`. * If `sourceValue` and `targetValue` are `string`, return `string`. * If `sourceValue` and `targetValue` are `(string | number)[]`, return `(string | number)[]`. * Other cases do not supported. */function interpolateRawValues(data,precision,sourceValue,targetValue,percent){var isAutoPrecision=precision==null||precision==='auto';if(targetValue==null){return targetValue;}if(isNumber(targetValue)){var value=interpolateNumber(sourceValue||0,targetValue,percent);return round$1(value,isAutoPrecision?Math.max(getPrecision(sourceValue||0),getPrecision(targetValue)):precision);}else if(isString(targetValue)){return percent<1?sourceValue:targetValue;}else{var interpolated=[];var leftArr=sourceValue;var rightArr=targetValue;var length_1=Math.max(leftArr?leftArr.length:0,rightArr.length);for(var i=0;i, when componentType is 'a.b' */var storage={};target.registerClass=function(clz){// `type` should not be a "instance memeber". // If using TS class, should better declared as `static type = 'series.pie'`. // otherwise users have to mount `type` on prototype manually. // For backward compat and enable instance visit type via `this.type`, // we stil support fetch `type` from prototype. var componentFullType=clz.type||clz.prototype.type;if(componentFullType){checkClassType(componentFullType);// If only static type declared, we assign it to prototype mandatorily. clz.prototype.type=componentFullType;var componentTypeInfo=parseClassType(componentFullType);if(!componentTypeInfo.sub){storage[componentTypeInfo.main]=clz;}else if(componentTypeInfo.sub!==IS_CONTAINER){var container=makeContainer(componentTypeInfo);container[componentTypeInfo.sub]=clz;}}return clz;};target.getClass=function(mainType,subType,throwWhenNotFound){var clz=storage[mainType];if(clz&&clz[IS_CONTAINER]){clz=subType?clz[subType]:null;}if(throwWhenNotFound&&!clz){throw new Error(!subType?mainType+'.'+'type should be specified.':'Component '+mainType+'.'+(subType||'')+' is used but not imported.');}return clz;};target.getClassesByMainType=function(componentType){var componentTypeInfo=parseClassType(componentType);var result=[];var obj=storage[componentTypeInfo.main];if(obj&&obj[IS_CONTAINER]){each$7(obj,function(o,type){type!==IS_CONTAINER&&result.push(o);});}else{result.push(obj);}return result;};target.hasClass=function(componentType){// Just consider componentType.main. var componentTypeInfo=parseClassType(componentType);return!!storage[componentTypeInfo.main];};/** * @return Like ['aa', 'bb'], but can not be ['aa.xx'] */target.getAllClassMainTypes=function(){var types=[];each$7(storage,function(obj,type){types.push(type);});return types;};/** * If a main type is container and has sub types */target.hasSubTypes=function(componentType){var componentTypeInfo=parseClassType(componentType);var obj=storage[componentTypeInfo.main];return obj&&obj[IS_CONTAINER];};function makeContainer(componentTypeInfo){var container=storage[componentTypeInfo.main];if(!container||!container[IS_CONTAINER]){container=storage[componentTypeInfo.main]={};container[IS_CONTAINER]=true;}return container;}}// /** // * @param {string|Array.} properties // */ // export function setReadOnly(obj, properties) { // FIXME It seems broken in IE8 simulation of IE11 // if (!zrUtil.isArray(properties)) { // properties = properties != null ? [properties] : []; // } // zrUtil.each(properties, function (prop) { // let value = obj[prop]; // Object.defineProperty // && Object.defineProperty(obj, prop, { // value: value, writable: false // }); // zrUtil.isArray(obj[prop]) // && Object.freeze // && Object.freeze(obj[prop]); // }); // } function makeStyleMapper(properties,ignoreParent){// Normalize for(var i=0;i=0||includes&&indexOf(includes,propName)<0){continue;}var val=model.getShallow(propName,ignoreParent);if(val!=null){style[properties[i][0]]=val;}}// TODO Text or image? return style;};}var AREA_STYLE_KEY_MAP=[['fill','color'],['shadowBlur'],['shadowOffsetX'],['shadowOffsetY'],['opacity'],['shadowColor']// Option decal is in `DecalObject` but style.decal is in `PatternObject`. // So do not transfer decal directly. ];var getAreaStyle=makeStyleMapper(AREA_STYLE_KEY_MAP);var AreaStyleMixin=/** @class */function(){function AreaStyleMixin(){}AreaStyleMixin.prototype.getAreaStyle=function(excludes,includes){return getAreaStyle(this,excludes,includes);};return AreaStyleMixin;}();var globalImageCache=new LRU$1(50);function findExistImage(newImageOrSrc){if(typeof newImageOrSrc==='string'){var cachedImgObj=globalImageCache.get(newImageOrSrc);return cachedImgObj&&cachedImgObj.image;}else{return newImageOrSrc;}}function createOrUpdateImage(newImageOrSrc,image,hostEl,onload,cbPayload){if(!newImageOrSrc){return image;}else if(typeof newImageOrSrc==='string'){if(image&&image.__zrImageSrc===newImageOrSrc||!hostEl){return image;}var cachedImgObj=globalImageCache.get(newImageOrSrc);var pendingWrap={hostEl:hostEl,cb:onload,cbPayload:cbPayload};if(cachedImgObj){image=cachedImgObj.image;!isImageReady(image)&&cachedImgObj.pending.push(pendingWrap);}else{image=platformApi.loadImage(newImageOrSrc,imageOnLoad,imageOnLoad);image.__zrImageSrc=newImageOrSrc;globalImageCache.put(newImageOrSrc,image.__cachedImgObj={image:image,pending:[pendingWrap]});}return image;}else{return newImageOrSrc;}}function imageOnLoad(){var cachedImgObj=this.__cachedImgObj;this.onload=this.onerror=this.__cachedImgObj=null;for(var i=0;i=ascCharWidth;i++){contentWidth-=ascCharWidth;}var ellipsisWidth=getWidth(ellipsis,font);if(ellipsisWidth>contentWidth){ellipsis='';ellipsisWidth=0;}contentWidth=containerWidth-ellipsisWidth;preparedOpts.ellipsis=ellipsis;preparedOpts.ellipsisWidth=ellipsisWidth;preparedOpts.contentWidth=contentWidth;preparedOpts.containerWidth=containerWidth;return preparedOpts;}function truncateSingleLine(textLine,options){var containerWidth=options.containerWidth;var font=options.font;var 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=j===0?estimateLength(textLine,contentWidth,options.ascCharWidth,options.cnCharWidth):lineWidth>0?Math.floor(textLine.length*contentWidth/lineWidth):0;textLine=textLine.substr(0,subLength);lineWidth=getWidth(textLine,font);}if(textLine===''){textLine=options.placeholder;}return textLine;}function estimateLength(text,contentWidth,ascCharWidth,cnCharWidth){var width=0;var i=0;for(var len=text.length;iheight&&truncateLineOverflow){var lineCount=Math.floor(height/lineHeight);lines=lines.slice(0,lineCount);}if(text&&truncate&&width!=null){var options=prepareTruncateOptions(width,font,style.ellipsis,{minChar:style.truncateMinChar,placeholder:style.placeholder});for(var i=0;ilastIndex){pushTokens(contentBlock,text.substring(lastIndex,matchedIndex),style,wrapInfo);}pushTokens(contentBlock,result[2],style,wrapInfo,result[1]);lastIndex=STYLE_REG.lastIndex;}if(lastIndextopHeight){if(j>0){line.tokens=line.tokens.slice(0,j);finishLine(line,lineWidth,lineHeight);contentBlock.lines=contentBlock.lines.slice(0,i+1);}else{contentBlock.lines=contentBlock.lines.slice(0,i);}break outer;}var styleTokenWidth=tokenStyle.width;var tokenWidthNotSpecified=styleTokenWidth==null||styleTokenWidth==='auto';if(typeof styleTokenWidth==='string'&&styleTokenWidth.charAt(styleTokenWidth.length-1)==='%'){token.percentWidth=styleTokenWidth;pendingList.push(token);token.contentWidth=getWidth(token.text,font);}else{if(tokenWidthNotSpecified){var textBackgroundColor=tokenStyle.backgroundColor;var bgImg=textBackgroundColor&&textBackgroundColor.image;if(bgImg){bgImg=findExistImage(bgImg);if(isImageReady(bgImg)){token.width=Math.max(token.width,bgImg.width*tokenHeight/bgImg.height);}}}var remainTruncWidth=truncate&&topWidth!=null?topWidth-lineWidth:null;if(remainTruncWidth!=null&&remainTruncWidth0){if(outerWidth_1+wrapInfo.accumWidth>wrapInfo.width){strLines=str.split('\n');newLine=true;}}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=0x21&&code<=0x17F;}var breakCharMap=reduce(',&?/;] '.split(''),function(obj,ch){obj[ch]=true;return obj;},{});function isWordBreakChar(ch){if(isLatin(ch)){if(breakCharMap[ch]){return true;}return false;}return true;}function wrapText(text,font,lineWidth,isBreakAll,lastAccumWidth){var lines=[];var linesWidths=[];var line='';var currentWord='';var currentWordWidth=0;var accumWidth=0;for(var i=0;ilineWidth:accumWidth+chWidth>lineWidth){if(!accumWidth){if(inWord){lines.push(currentWord);linesWidths.push(currentWordWidth);currentWord=ch;currentWordWidth=chWidth;}else{lines.push(ch);linesWidths.push(chWidth);}}else if(line||currentWord){if(inWord){if(!line){line=currentWord;currentWord='';currentWordWidth=0;accumWidth=currentWordWidth;}lines.push(line);linesWidths.push(accumWidth-currentWordWidth);currentWord+=ch;currentWordWidth+=chWidth;line='';accumWidth=currentWordWidth;}else{if(currentWord){line+=currentWord;currentWord='';currentWordWidth=0;}lines.push(line);linesWidths.push(accumWidth);line=ch;accumWidth=chWidth;}}continue;}accumWidth+=chWidth;if(inWord){currentWord+=ch;currentWordWidth+=chWidth;}else{if(currentWord){line+=currentWord;currentWord='';currentWordWidth=0;}line+=ch;}}if(!lines.length&&!line){line=text;currentWord='';currentWordWidth=0;}if(currentWord){line+=currentWord;}if(line){lines.push(line);linesWidths.push(accumWidth);}if(lines.length===1){accumWidth+=lastAccumWidth;}return{accumWidth:accumWidth,lines:lines,linesWidths:linesWidths};}var STYLE_MAGIC_KEY='__zr_style_'+Math.round(Math.random()*10);var DEFAULT_COMMON_STYLE={shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,shadowColor:'#000',opacity:1,blend:'source-over'};var DEFAULT_COMMON_ANIMATION_PROPS={style:{shadowBlur:true,shadowOffsetX:true,shadowOffsetY:true,shadowColor:true,opacity:true}};DEFAULT_COMMON_STYLE[STYLE_MAGIC_KEY]=true;var PRIMARY_STATES_KEYS=['z','z2','invisible'];var PRIMARY_STATES_KEYS_IN_HOVER_LAYER=['invisible'];var Displayable=function(_super){__extends(Displayable,_super);function Displayable(props){return _super.call(this,props)||this;}Displayable.prototype._init=function(props){var keysArr=keys(props);for(var i=0;i1e-4){min[0]=x-rx;min[1]=y-ry;max[0]=x+rx;max[1]=y+ry;return;}start[0]=mathCos$3(startAngle)*rx+x;start[1]=mathSin$3(startAngle)*ry+y;end[0]=mathCos$3(endAngle)*rx+x;end[1]=mathSin$3(endAngle)*ry+y;vec2Min(min,start,end);vec2Max(max,start,end);startAngle=startAngle%PI2$7;if(startAngle<0){startAngle=startAngle+PI2$7;}endAngle=endAngle%PI2$7;if(endAngle<0){endAngle=endAngle+PI2$7;}if(startAngle>endAngle&&!anticlockwise){endAngle+=PI2$7;}else if(startAnglestartAngle){extremity[0]=mathCos$3(angle)*rx+x;extremity[1]=mathSin$3(angle)*ry+y;vec2Min(min,extremity,min);vec2Max(max,extremity,max);}}}var CMD$4={M:1,L:2,C:3,Q:4,A:5,Z:6,R:7};var tmpOutX=[];var tmpOutY=[];var min=[];var max=[];var min2=[];var max2=[];var mathMin$5=Math.min;var mathMax$5=Math.max;var mathCos$2=Math.cos;var mathSin$2=Math.sin;var mathAbs$1=Math.abs;var PI$4=Math.PI;var PI2$6=PI$4*2;var hasTypedArray=typeof Float32Array!=='undefined';var tmpAngles=[];function modPI2(radian){var n=Math.round(radian/PI$4*1e8)/1e8;return n%2*PI$4;}function normalizeArcAngles(angles,anticlockwise){var newStartAngle=modPI2(angles[0]);if(newStartAngle<0){newStartAngle+=PI2$6;}var delta=newStartAngle-angles[0];var newEndAngle=angles[1];newEndAngle+=delta;if(!anticlockwise&&newEndAngle-newStartAngle>=PI2$6){newEndAngle=newStartAngle+PI2$6;}else if(anticlockwise&&newStartAngle-newEndAngle>=PI2$6){newEndAngle=newStartAngle-PI2$6;}else if(!anticlockwise&&newStartAngle>newEndAngle){newEndAngle=newStartAngle+(PI2$6-modPI2(newStartAngle-newEndAngle));}else if(anticlockwise&&newStartAngle0){this._ux=mathAbs$1(segmentIgnoreThreshold/devicePixelRatio/sx)||0;this._uy=mathAbs$1(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(){this._ctx&&this._ctx.beginPath();this.reset();return this;};PathProxy.prototype.reset=function(){if(this._saveData){this._len=0;}if(this._pathSegLen){this._pathSegLen=null;this._pathLen=0;}this._version++;};PathProxy.prototype.moveTo=function(x,y){this._drawPendingPt();this.addData(CMD$4.M,x,y);this._ctx&&this._ctx.moveTo(x,y);this._x0=x;this._y0=y;this._xi=x;this._yi=y;return this;};PathProxy.prototype.lineTo=function(x,y){var dx=mathAbs$1(x-this._xi);var dy=mathAbs$1(y-this._yi);var exceedUnit=dx>this._ux||dy>this._uy;this.addData(CMD$4.L,x,y);if(this._ctx&&exceedUnit){this._ctx.lineTo(x,y);}if(exceedUnit){this._xi=x;this._yi=y;this._pendingPtDist=0;}else{var d2=dx*dx+dy*dy;if(d2>this._pendingPtDist){this._pendingPtX=x;this._pendingPtY=y;this._pendingPtDist=d2;}}return this;};PathProxy.prototype.bezierCurveTo=function(x1,y1,x2,y2,x3,y3){this._drawPendingPt();this.addData(CMD$4.C,x1,y1,x2,y2,x3,y3);if(this._ctx){this._ctx.bezierCurveTo(x1,y1,x2,y2,x3,y3);}this._xi=x3;this._yi=y3;return this;};PathProxy.prototype.quadraticCurveTo=function(x1,y1,x2,y2){this._drawPendingPt();this.addData(CMD$4.Q,x1,y1,x2,y2);if(this._ctx){this._ctx.quadraticCurveTo(x1,y1,x2,y2);}this._xi=x2;this._yi=y2;return this;};PathProxy.prototype.arc=function(cx,cy,r,startAngle,endAngle,anticlockwise){this._drawPendingPt();tmpAngles[0]=startAngle;tmpAngles[1]=endAngle;normalizeArcAngles(tmpAngles,anticlockwise);startAngle=tmpAngles[0];endAngle=tmpAngles[1];var delta=endAngle-startAngle;this.addData(CMD$4.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$2(endAngle)*r+cx;this._yi=mathSin$2(endAngle)*r+cy;return this;};PathProxy.prototype.arcTo=function(x1,y1,x2,y2,radius){this._drawPendingPt();if(this._ctx){this._ctx.arcTo(x1,y1,x2,y2,radius);}return this;};PathProxy.prototype.rect=function(x,y,w,h){this._drawPendingPt();this._ctx&&this._ctx.rect(x,y,w,h);this.addData(CMD$4.R,x,y,w,h);return this;};PathProxy.prototype.closePath=function(){this._drawPendingPt();this.addData(CMD$4.Z);var ctx=this._ctx;var x0=this._x0;var y0=this._y0;if(ctx){ctx.closePath();}this._xi=x0;this._yi=y0;return this;};PathProxy.prototype.fill=function(ctx){ctx&&ctx.fill();this.toStatic();};PathProxy.prototype.stroke=function(ctx){ctx&&ctx.stroke();this.toStatic();};PathProxy.prototype.len=function(){return this._len;};PathProxy.prototype.setData=function(data){var len=data.length;if(!(this.data&&this.data.length===len)&&hasTypedArray){this.data=new Float32Array(len);}for(var i=0;idata.length){this._expandData();data=this.data;}for(var i=0;i0){this._ctx&&this._ctx.lineTo(this._pendingPtX,this._pendingPtY);this._pendingPtDist=0;}};PathProxy.prototype._expandData=function(){if(!(this.data instanceof Array)){var newData=[];for(var i=0;i11){this.data=new Float32Array(data);}}};PathProxy.prototype.getBoundingRect=function(){min[0]=min[1]=min2[0]=min2[1]=Number.MAX_VALUE;max[0]=max[1]=max2[0]=max2[1]=-Number.MAX_VALUE;var data=this.data;var xi=0;var yi=0;var x0=0;var y0=0;var i;for(i=0;iux||mathAbs$1(dy)>uy||i===len-1){l=Math.sqrt(dx*dx+dy*dy);xi=x2;yi=y2;}break;}case CMD$4.C:{var x1=data[i++];var y1=data[i++];var x2=data[i++];var y2=data[i++];var x3=data[i++];var y3=data[i++];l=cubicLength(xi,yi,x1,y1,x2,y2,x3,y3,10);xi=x3;yi=y3;break;}case CMD$4.Q:{var x1=data[i++];var y1=data[i++];var x2=data[i++];var y2=data[i++];l=quadraticLength(xi,yi,x1,y1,x2,y2,10);xi=x2;yi=y2;break;}case CMD$4.A:var cx=data[i++];var cy=data[i++];var rx=data[i++];var ry=data[i++];var startAngle=data[i++];var delta=data[i++];var endAngle=delta+startAngle;i+=1;!data[i++];if(isFirst){x0=mathCos$2(startAngle)*rx+cx;y0=mathSin$2(startAngle)*ry+cy;}l=mathMax$5(rx,ry)*mathMin$5(PI2$6,Math.abs(delta));xi=mathCos$2(endAngle)*rx+cx;yi=mathSin$2(endAngle)*ry+cy;break;case CMD$4.R:{x0=xi=data[i++];y0=yi=data[i++];var width=data[i++];var height=data[i++];l=width*2+height*2;break;}case CMD$4.Z:{var dx=x0-xi;var dy=y0-yi;l=Math.sqrt(dx*dx+dy*dy);xi=x0;yi=y0;break;}}if(l>=0){pathSegLen[segCount++]=l;pathTotalLen+=l;}}this._pathLen=pathTotalLen;return pathTotalLen;};PathProxy.prototype.rebuildPath=function(ctx,percent){var d=this.data;var ux=this._ux;var uy=this._uy;var len=this._len;var x0;var y0;var xi;var yi;var x;var y;var drawPart=percent<1;var pathSegLen;var pathTotalLen;var accumLength=0;var segCount=0;var displayedLength;var pendingPtDist=0;var pendingPtX;var pendingPtY;if(drawPart){if(!this._pathSegLen){this._calculateLength();}pathSegLen=this._pathSegLen;pathTotalLen=this._pathLen;displayedLength=percent*pathTotalLen;if(!displayedLength){return;}}lo:for(var i=0;i0){ctx.lineTo(pendingPtX,pendingPtY);pendingPtDist=0;}switch(cmd){case CMD$4.M:x0=xi=d[i++];y0=yi=d[i++];ctx.moveTo(xi,yi);break;case CMD$4.L:{x=d[i++];y=d[i++];var dx=mathAbs$1(x-xi);var dy=mathAbs$1(y-yi);if(dx>ux||dy>uy){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;pendingPtDist=0;}else{var d2=dx*dx+dy*dy;if(d2>pendingPtDist){pendingPtX=x;pendingPtY=y;pendingPtDist=d2;}}break;}case CMD$4.C:{var x1=d[i++];var y1=d[i++];var x2=d[i++];var y2=d[i++];var x3=d[i++];var 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$4.Q:{var x1=d[i++];var y1=d[i++];var x2=d[i++];var 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$4.A:var cx=d[i++];var cy=d[i++];var rx=d[i++];var ry=d[i++];var startAngle=d[i++];var delta=d[i++];var psi=d[i++];var anticlockwise=!d[i++];var r=rx>ry?rx:ry;var isEllipse=mathAbs$1(rx-ry)>1e-3;var endAngle=startAngle+delta;var breakBuild=false;if(drawPart){var l=pathSegLen[segCount++];if(accumLength+l>displayedLength){endAngle=startAngle+delta*(displayedLength-accumLength)/l;breakBuild=true;}accumLength+=l;}if(isEllipse&&ctx.ellipse){ctx.ellipse(cx,cy,rx,ry,psi,startAngle,endAngle,anticlockwise);}else{ctx.arc(cx,cy,r,startAngle,endAngle,anticlockwise);}if(breakBuild){break lo;}if(isFirst){x0=mathCos$2(startAngle)*rx+cx;y0=mathSin$2(startAngle)*ry+cy;}xi=mathCos$2(endAngle)*rx+cx;yi=mathSin$2(endAngle)*ry+cy;break;case CMD$4.R:x0=xi=d[i];y0=yi=d[i+1];x=d[i++];y=d[i++];var width=d[i++];var 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$5(d_1,width),y);d_1-=width;if(d_1>0){ctx.lineTo(x+width,y+mathMin$5(d_1,height));}d_1-=height;if(d_1>0){ctx.lineTo(x+mathMax$5(width-d_1,0),y+height);}d_1-=width;if(d_1>0){ctx.lineTo(x,y+mathMax$5(height-d_1,0));}break lo;}accumLength+=l;}ctx.rect(x,y,width,height);break;case CMD$4.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.prototype.clone=function(){var newProxy=new PathProxy();var data=this.data;newProxy.data=data.slice?data.slice():Array.prototype.slice.call(data);newProxy._len=this._len;return newProxy;};PathProxy.CMD=CMD$4;PathProxy.initDefaultProps=function(){var proto=PathProxy.prototype;proto._saveData=true;proto._ux=0;proto._uy=0;proto._pendingPtDist=0;proto._version=0;}();return PathProxy;}();var PathProxy$1=PathProxy;function containStroke$4(x0,y0,x1,y1,lineWidth,x,y){if(lineWidth===0){return false;}var _l=lineWidth;var _a=0;var _b=x0;if(y>y0+_l&&y>y1+_l||yx0+_l&&x>x1+_l||xy0+_l&&y>y1+_l&&y>y2+_l&&y>y3+_l||yx0+_l&&x>x1+_l&&x>x2+_l&&x>x3+_l||xy0+_l&&y>y1+_l&&y>y2+_l||yx0+_l&&x>x1+_l&&x>x2+_l||xr||d+_lendAngle){endAngle+=PI2$4;}var angle=Math.atan2(y,x);if(angle<0){angle+=PI2$4;}return angle>=startAngle&&angle<=endAngle||angle+PI2$4>=startAngle&&angle+PI2$4<=endAngle;}function windingLine(x0,y0,x1,y1,x,y){if(y>y0&&y>y1||yx?dir:0;}var CMD$3=PathProxy$1.CMD;var PI2$3=Math.PI*2;var EPSILON=1e-4;function isAroundEqual(a,b){return Math.abs(a-b)y0&&y>y1&&y>y2&&y>y3||y1){swapExtrema();}y0_=cubicAt(y0,y1,y2,y3,extrema[0]);if(nExtrema>1){y1_=cubicAt(y0,y1,y2,y3,extrema[1]);}}if(nExtrema===2){if(ty0&&y>y1&&y>y2||y=0&&t<=1){var w=0;var y_=quadraticAt(y0,y1,y2,t);for(var i=0;ir||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$3-1e-4){startAngle=0;endAngle=PI2$3;var dir=anticlockwise?1:-1;if(x>=roots[0]+cx&&x<=roots[1]+cx){return dir;}else{return 0;}}if(startAngle>endAngle){var tmp_1=startAngle;startAngle=endAngle;endAngle=tmp_1;}if(startAngle<0){startAngle+=PI2$3;endAngle+=PI2$3;}var w=0;for(var i=0;i<2;i++){var x_=roots[i];if(x_+cx>x){var angle=Math.atan2(y,x_);var dir=anticlockwise?1:-1;if(angle<0){angle=PI2$3+angle;}if(angle>=startAngle&&angle<=endAngle||angle+PI2$3>=startAngle&&angle+PI2$3<=endAngle){if(angle>Math.PI/2&&angle1){if(!isStroke){w+=windingLine(xi,yi,x0,y0,x,y);}}if(isFirst){xi=data[i];yi=data[i+1];x0=xi;y0=yi;}switch(cmd){case CMD$3.M:x0=data[i++];y0=data[i++];xi=x0;yi=y0;break;case CMD$3.L:if(isStroke){if(containStroke$4(xi,yi,data[i],data[i+1],lineWidth,x,y)){return true;}}else{w+=windingLine(xi,yi,data[i],data[i+1],x,y)||0;}xi=data[i++];yi=data[i++];break;case CMD$3.C:if(isStroke){if(containStroke$3(xi,yi,data[i++],data[i++],data[i++],data[i++],data[i],data[i+1],lineWidth,x,y)){return true;}}else{w+=windingCubic(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$3.Q:if(isStroke){if(containStroke$2(xi,yi,data[i++],data[i++],data[i],data[i+1],lineWidth,x,y)){return true;}}else{w+=windingQuadratic(xi,yi,data[i++],data[i++],data[i],data[i+1],x,y)||0;}xi=data[i++];yi=data[i++];break;case CMD$3.A:var cx=data[i++];var cy=data[i++];var rx=data[i++];var ry=data[i++];var theta=data[i++];var dTheta=data[i++];i+=1;var anticlockwise=!!(1-data[i++]);x1=Math.cos(theta)*rx+cx;y1=Math.sin(theta)*ry+cy;if(!isFirst){w+=windingLine(xi,yi,x1,y1,x,y);}else{x0=x1;y0=y1;}var _x=(x-cx)*ry/rx+cx;if(isStroke){if(containStroke$1(cx,cy,ry,theta,theta+dTheta,anticlockwise,lineWidth,_x,y)){return true;}}else{w+=windingArc(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$3.R:x0=xi=data[i++];y0=yi=data[i++];var width=data[i++];var height=data[i++];x1=x0+width;y1=y0+height;if(isStroke){if(containStroke$4(x0,y0,x1,y0,lineWidth,x,y)||containStroke$4(x1,y0,x1,y1,lineWidth,x,y)||containStroke$4(x1,y1,x0,y1,lineWidth,x,y)||containStroke$4(x0,y1,x0,y0,lineWidth,x,y)){return true;}}else{w+=windingLine(x1,y0,x1,y1,x,y);w+=windingLine(x0,y1,x0,y0,x,y);}break;case CMD$3.Z:if(isStroke){if(containStroke$4(xi,yi,x0,y0,lineWidth,x,y)){return true;}}else{w+=windingLine(xi,yi,x0,y0,x,y);}xi=x0;yi=y0;break;}}if(!isStroke&&!isAroundEqual(yi,y0)){w+=windingLine(xi,yi,x0,y0,x,y)||0;}return w!==0;}function contain$1(pathProxy,x,y){return containPath(pathProxy,0,false,x,y);}function containStroke(pathProxy,lineWidth,x,y){return containPath(pathProxy,lineWidth,true,x,y);}var DEFAULT_PATH_STYLE=defaults({fill:'#000',stroke:null,strokePercent:1,fillOpacity:1,strokeOpacity:1,lineDashOffset:0,lineWidth:1,lineCap:'butt',miterLimit:10,strokeNoScale:false,strokeFirst:false},DEFAULT_COMMON_STYLE);var DEFAULT_PATH_ANIMATION_PROPS={style:defaults({fill:true,stroke:true,strokePercent:true,fillOpacity:true,strokeOpacity:true,lineDashOffset:true,lineWidth:true,miterLimit:true},DEFAULT_COMMON_ANIMATION_PROPS.style)};var pathCopyParams=TRANSFORMABLE_PROPS.concat(['invisible','culling','z','z2','zlevel','parent']);var Path=function(_super){__extends(Path,_super);function Path(opts){return _super.call(this,opts)||this;}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();if(decalEl.buildPath===Path.prototype.buildPath){decalEl.buildPath=function(ctx){_this.buildPath(ctx,_this.shape);};}decalEl.silent=true;var decalElStyle=decalEl.style;for(var key in style){if(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;i0.5){return DARK_LABEL_COLOR;}else if(fillLum>0.2){return LIGHTER_LABEL_COLOR;}return LIGHT_LABEL_COLOR;}else 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;var isDarkMode=!!(zr&&zr.isDarkMode());var isDarkLabel=lum(textFill,0)0));};Path.prototype.hasFill=function(){var style=this.style;var fill=style.fill;return fill!=null&&fill!=='none';};Path.prototype.getBoundingRect=function(){var rect=this._rect;var style=this.style;var needsUpdateRect=!rect;if(needsUpdateRect){var firstInvoke=false;if(!this.path){firstInvoke=true;this.createPathProxy();}var path=this.path;if(firstInvoke||this.__dirty&SHAPE_CHANGED_BIT){path.beginPath();this.buildPath(path,this.shape,false);this.pathUpdated();}rect=path.getBoundingRect();}this._rect=rect;if(this.hasStroke()&&this.path&&this.path.len()>0){var rectStroke=this._rectStroke||(this._rectStroke=rect.clone());if(this.__dirty||needsUpdateRect){rectStroke.copy(rect);var lineScale=style.strokeNoScale?this.getLineScale():1;var w=style.lineWidth;if(!this.hasFill()){var strokeContainThreshold=this.strokeContainThreshold;w=Math.max(w,strokeContainThreshold==null?4:strokeContainThreshold);}if(lineScale>1e-10){rectStroke.width+=w/lineScale;rectStroke.height+=w/lineScale;rectStroke.x-=w/lineScale/2;rectStroke.y-=w/lineScale/2;}}return rectStroke;}return rect;};Path.prototype.contain=function(x,y){var localPos=this.transformCoordToLocal(x,y);var rect=this.getBoundingRect();var style=this.style;x=localPos[0];y=localPos[1];if(rect.contain(x,y)){var pathProxy=this.path;if(this.hasStroke()){var lineWidth=style.lineWidth;var lineScale=style.strokeNoScale?this.getLineScale():1;if(lineScale>1e-10){if(!this.hasFill()){lineWidth=Math.max(lineWidth,this.strokeContainThreshold);}if(containStroke(pathProxy,lineWidth/lineScale,x,y)){return true;}}}if(this.hasFill()){return contain$1(pathProxy,x,y);}}return false;};Path.prototype.dirtyShape=function(){this.__dirty|=SHAPE_CHANGED_BIT;if(this._rect){this._rect=null;}if(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){if(targetKey==='style'){this.dirtyStyle();}else if(targetKey==='shape'){this.dirtyShape();}else{this.markRedraw();}};Path.prototype.attrKV=function(key,value){if(key==='shape'){this.setShape(value);}else{_super.prototype.attrKV.call(this,key,value);}};Path.prototype.setShape=function(keyOrObj,value){var shape=this.shape;if(!shape){shape=this.shape={};}if(typeof keyOrObj==='string'){shape[keyOrObj]=value;}else{extend(shape,keyOrObj);}this.dirtyShape();return this;};Path.prototype.shapeChanged=function(){return!!(this.__dirty&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;if(toState.shape&&!normalState.shape){normalState.shape=extend({},this.shape);}};Path.prototype._applyStateObj=function(stateName,state,normalState,keepCurrentStates,transition,animationCfg){_super.prototype._applyStateObj.call(this,stateName,state,normalState,keepCurrentStates,transition,animationCfg);var needsRestoreToNormal=!(state&&keepCurrentStates);var targetShape;if(state&&state.shape){if(transition){if(keepCurrentStates){targetShape=state.shape;}else{targetShape=extend({},normalState.shape);extend(targetShape,state.shape);}}else{targetShape=extend({},keepCurrentStates?this.shape:normalState.shape);extend(targetShape,state.shape);}}else if(needsRestoreToNormal){targetShape=normalState.shape;}if(targetShape){if(transition){this.shape=extend({},this.shape);var targetShapePrimaryProps={};var shapeKeys=keys(targetShape);for(var i=0;i0;};TSpan.prototype.hasFill=function(){var style=this.style;var fill=style.fill;return fill!=null&&fill!=='none';};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;text!=null?text+='':text='';var rect=getBoundingRect(text,style.font,style.textAlign,style.textBaseline);rect.x+=style.x||0;rect.y+=style.y||0;if(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=function(){var tspanProto=TSpan.prototype;tspanProto.dirtyRectTolerance=10;}();return TSpan;}(Displayable$1);TSpan.prototype.type='tspan';var TSpan$1=TSpan;var DEFAULT_IMAGE_STYLE=defaults({x:0,y:0},DEFAULT_COMMON_STYLE);var DEFAULT_IMAGE_ANIMATION_PROPS={style:defaults({x:true,y:true,width:true,height:true,sx:true,sy:true,sWidth:true,sHeight:true},DEFAULT_COMMON_ANIMATION_PROPS.style)};function isImageLike(source){return!!(source&&typeof source!=='string'&&source.width&&source.height);}var ZRImage=function(_super){__extends(ZRImage,_super);function ZRImage(){return _super!==null&&_super.apply(this,arguments)||this;}ZRImage.prototype.createStyle=function(obj){return createObject(DEFAULT_IMAGE_STYLE,obj);};ZRImage.prototype._getSize=function(dim){var style=this.style;var size=style[dim];if(size!=null){return size;}var imageSource=isImageLike(style.image)?style.image:this.__image;if(!imageSource){return 0;}var otherDim=dim==='width'?'height':'width';var otherDimSize=style[otherDim];if(otherDimSize==null){return imageSource[dim];}else{return 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;if(!this._rect){this._rect=new BoundingRect$1(style.x||0,style.y||0,this.getWidth(),this.getHeight());}return this._rect;};return ZRImage;}(Displayable$1);ZRImage.prototype.type='image';var ZRImage$1=ZRImage;function buildPath$2(ctx,shape){var x=shape.x;var y=shape.y;var width=shape.width;var height=shape.height;var r=shape.r;var r1;var r2;var r3;var r4;if(width<0){x=x+width;width=-width;}if(height<0){y=y+height;height=-height;}if(typeof r==='number'){r1=r2=r3=r4=r;}else if(r instanceof Array){if(r.length===1){r1=r2=r3=r4=r[0];}else if(r.length===2){r1=r3=r[0];r2=r4=r[1];}else if(r.length===3){r1=r[0];r2=r4=r[1];r3=r[2];}else{r1=r[0];r2=r[1];r3=r[2];r4=r[3];}}else{r1=r2=r3=r4=0;}var total;if(r1+r2>width){total=r1+r2;r1*=width/total;r2*=width/total;}if(r3+r4>width){total=r3+r4;r3*=width/total;r4*=width/total;}if(r2+r3>height){total=r2+r3;r2*=height/total;r3*=height/total;}if(r1+r4>height){total=r1+r4;r1*=height/total;r4*=height/total;}ctx.moveTo(x+r1,y);ctx.lineTo(x+width-r2,y);r2!==0&&ctx.arc(x+width-r2,y+r2,r2,-Math.PI/2,0);ctx.lineTo(x+width,y+height-r3);r3!==0&&ctx.arc(x+width-r3,y+height-r3,r3,0,Math.PI/2);ctx.lineTo(x+r4,y+height);r4!==0&&ctx.arc(x+r4,y+height-r4,r4,Math.PI/2,Math.PI);ctx.lineTo(x,y+r1);r1!==0&&ctx.arc(x+r1,y+r1,r1,Math.PI,Math.PI*1.5);}var round=Math.round;function subPixelOptimizeLine$1(outputShape,inputShape,style){if(!inputShape){return;}var x1=inputShape.x1;var x2=inputShape.x2;var y1=inputShape.y1;var y2=inputShape.y2;outputShape.x1=x1;outputShape.x2=x2;outputShape.y1=y1;outputShape.y2=y2;var lineWidth=style&&style.lineWidth;if(!lineWidth){return outputShape;}if(round(x1*2)===round(x2*2)){outputShape.x1=outputShape.x2=subPixelOptimize$1(x1,lineWidth,true);}if(round(y1*2)===round(y2*2)){outputShape.y1=outputShape.y2=subPixelOptimize$1(y1,lineWidth,true);}return outputShape;}function subPixelOptimizeRect$1(outputShape,inputShape,style){if(!inputShape){return;}var originX=inputShape.x;var originY=inputShape.y;var originWidth=inputShape.width;var originHeight=inputShape.height;outputShape.x=originX;outputShape.y=originY;outputShape.width=originWidth;outputShape.height=originHeight;var lineWidth=style&&style.lineWidth;if(!lineWidth){return outputShape;}outputShape.x=subPixelOptimize$1(originX,lineWidth,true);outputShape.y=subPixelOptimize$1(originY,lineWidth,true);outputShape.width=Math.max(subPixelOptimize$1(originX+originWidth,lineWidth,false)-outputShape.x,originWidth===0?0:1);outputShape.height=Math.max(subPixelOptimize$1(originY+originHeight,lineWidth,false)-outputShape.y,originHeight===0?0:1);return outputShape;}function subPixelOptimize$1(position,lineWidth,positiveOrNegative){if(!lineWidth){return position;}var doubledPosition=round(position*2);return(doubledPosition+round(lineWidth))%2===0?doubledPosition/2:(doubledPosition+(positiveOrNegative?1:-1))/2;}var RectShape=function(){function RectShape(){this.x=0;this.y=0;this.width=0;this.height=0;}return RectShape;}();var subPixelOptimizeOutputShape$1={};var Rect$1=function(_super){__extends(Rect,_super);function Rect(opts){return _super.call(this,opts)||this;}Rect.prototype.getDefaultShape=function(){return new RectShape();};Rect.prototype.buildPath=function(ctx,shape){var x;var y;var width;var height;if(this.subPixelOptimize){var optimizedShape=subPixelOptimizeRect$1(subPixelOptimizeOutputShape$1,shape,this.style);x=optimizedShape.x;y=optimizedShape.y;width=optimizedShape.width;height=optimizedShape.height;optimizedShape.r=shape.r;shape=optimizedShape;}else{x=shape.x;y=shape.y;width=shape.width;height=shape.height;}if(!shape.r){ctx.rect(x,y,width,height);}else{buildPath$2(ctx,shape);}};Rect.prototype.isZeroArea=function(){return!this.shape.width||!this.shape.height;};return Rect;}(Path$1);Rect$1.prototype.type='rect';var Rect$2=Rect$1;var DEFAULT_RICH_TEXT_COLOR={fill:'#000'};var DEFAULT_STROKE_LINE_WIDTH=2;var DEFAULT_TEXT_ANIMATION_PROPS={style:defaults({fill:true,stroke:true,fillOpacity:true,strokeOpacity:true,lineWidth:true,fontSize:true,lineHeight:true,width:true,height:true,textShadowColor:true,textShadowBlur:true,textShadowOffsetX:true,textShadowOffsetY:true,backgroundColor:true,padding:true,borderColor:true,borderWidth:true,borderRadius:true},DEFAULT_COMMON_ANIMATION_PROPS.style)};var ZRText=function(_super){__extends(ZRText,_super);function ZRText(opts){var _this=_super.call(this)||this;_this.type='text';_this._children=[];_this._defaultStyle=DEFAULT_RICH_TEXT_COLOR;_this.attr(opts);return _this;}ZRText.prototype.childrenRef=function(){return this._children;};ZRText.prototype.update=function(){_super.prototype.update.call(this);if(this.styleChanged()){this._updateSubTexts();}for(var i=0;i0;var fixedBoundingRect=style.width!=null&&(style.overflow==='truncate'||style.overflow==='break'||style.overflow==='breakAll');var calculatedLineHeight=contentBlock.calculatedLineHeight;for(var i=0;i=0&&(token=tokens[rightIndex],token.align==='right')){this._placeToken(token,style,lineHeight,lineTop,lineXRight,'right',bgColorDrawn);remainedWidth-=token.width;lineXRight-=token.width;rightIndex--;}lineXLeft+=(contentWidth-(lineXLeft-xLeft)-(xRight-lineXRight)-remainedWidth)/2;while(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;var y=lineTop+lineHeight/2;if(verticalAlign==='top'){y=lineTop+token.height/2;}else if(verticalAlign==='bottom'){y=lineTop+lineHeight-token.height/2;}var needDrawBg=!token.isLineHolder&&needDrawBackground(tokenStyle);needDrawBg&&this._renderBackground(tokenStyle,style,textAlign==='right'?x-token.width:textAlign==='center'?x-token.width/2:x,y-token.height/2,token.width,token.height);var bgColorDrawn=!!tokenStyle.backgroundColor;var textPadding=token.textPadding;if(textPadding){x=getTextXForPadding(x,textAlign,textPadding);y-=token.height/2-textPadding[0]-token.innerHeight/2;}var el=this._getOrCreateChild(TSpan$1);var subElStyle=el.createStyle();el.useStyle(subElStyle);var defaultStyle=this._defaultStyle;var useDefaultFill=false;var defaultLineWidth=0;var textFill=getFill('fill'in tokenStyle?tokenStyle.fill:'fill'in style?style.fill:(useDefaultFill=true,defaultStyle.fill));var textStroke=getStroke('stroke'in tokenStyle?tokenStyle.stroke:'stroke'in style?style.stroke:!bgColorDrawn&&!parentBgColorDrawn&&(!defaultStyle.autoStroke||useDefaultFill)?(defaultLineWidth=DEFAULT_STROKE_LINE_WIDTH,defaultStyle.stroke):null);var hasShadow=tokenStyle.textShadowBlur>0||style.textShadowBlur>0;subElStyle.text=token.text;subElStyle.x=x;subElStyle.y=y;if(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);setSeparateFont(subElStyle,tokenStyle);if(textStroke){subElStyle.lineWidth=retrieve3(tokenStyle.lineWidth,style.lineWidth,defaultLineWidth);subElStyle.lineDash=retrieve2(tokenStyle.lineDash,style.lineDash);subElStyle.lineDashOffset=style.lineDashOffset||0;subElStyle.stroke=textStroke;}if(textFill){subElStyle.fill=textFill;}var textWidth=token.contentWidth;var textHeight=token.contentHeight;el.setBoundingRect(new BoundingRect$1(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 textBackgroundColor=style.backgroundColor;var textBorderWidth=style.borderWidth;var textBorderColor=style.borderColor;var isImageBg=textBackgroundColor&&textBackgroundColor.image;var isPlainOrGradientBg=textBackgroundColor&&!isImageBg;var textBorderRadius=style.borderRadius;var self=this;var rectEl;var imgEl;if(isPlainOrGradientBg||style.lineHeight||textBorderWidth&&textBorderColor){rectEl=this._getOrCreateChild(Rect$2);rectEl.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(isPlainOrGradientBg){var rectStyle=rectEl.style;rectStyle.fill=textBackgroundColor||null;rectStyle.fillOpacity=retrieve2(style.fillOpacity,1);}else if(isImageBg){imgEl=this._getOrCreateChild(ZRImage$1);imgEl.onload=function(){self.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;if(rectEl.hasFill()&&rectEl.hasStroke()){rectStyle.strokeFirst=true;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(hasSeparateFont(style)){font=[style.fontStyle,style.fontWeight,parseFontSize(style.fontSize),style.fontFamily||'sans-serif'].join(' ');}return font&&trim$1(font)||style.textFont||style.font;};return ZRText;}(Displayable$1);var VALID_TEXT_ALIGN={left:true,right:1,center:1};var VALID_TEXT_VERTICAL_ALIGN={top:1,bottom:1,middle:1};var FONT_PARTS=['fontStyle','fontWeight','fontSize','fontFamily'];function parseFontSize(fontSize){if(typeof fontSize==='string'&&(fontSize.indexOf('px')!==-1||fontSize.indexOf('rem')!==-1||fontSize.indexOf('em')!==-1)){return fontSize;}else if(!isNaN(+fontSize)){return fontSize+'px';}else{return DEFAULT_FONT_SIZE+'px';}}function setSeparateFont(targetStyle,sourceStyle){for(var i=0;i=0;var cloned=false;if(el instanceof Path$1){var store=getSavedStates(el);var fromFill=hasSelect?store.selectFill||store.normalFill:store.normalFill;var fromStroke=hasSelect?store.selectStroke||store.normalStroke:store.normalStroke;if(hasFillOrStroke(fromFill)||hasFillOrStroke(fromStroke)){state=state||{};var emphasisStyle=state.style||{};// inherit case if(emphasisStyle.fill==='inherit'){cloned=true;state=extend({},state);emphasisStyle=extend({},emphasisStyle);emphasisStyle.fill=fromFill;}// Apply default color lift else if(!hasFillOrStroke(emphasisStyle.fill)&&hasFillOrStroke(fromFill)){cloned=true;// Not modify the original value. state=extend({},state);emphasisStyle=extend({},emphasisStyle);// Already being applied 'emphasis'. DON'T lift color multiple times. emphasisStyle.fill=liftColor(fromFill);}// Not highlight stroke if fill has been highlighted. else if(!hasFillOrStroke(emphasisStyle.stroke)&&hasFillOrStroke(fromStroke)){if(!cloned){state=extend({},state);emphasisStyle=extend({},emphasisStyle);}emphasisStyle.stroke=liftColor(fromStroke);}state.style=emphasisStyle;}}if(state){// TODO Share with textContent? if(state.z2==null){if(!cloned){state=extend({},state);}var z2EmphasisLift=el.z2EmphasisLift;state.z2=el.z2+(z2EmphasisLift!=null?z2EmphasisLift:Z2_EMPHASIS_LIFT);}}return state;}function createSelectDefaultState(el,stateName,state){// const hasSelect = indexOf(el.currentStates, stateName) >= 0; if(state){// TODO Share with textContent? if(state.z2==null){state=extend({},state);var z2SelectLift=el.z2SelectLift;state.z2=el.z2+(z2SelectLift!=null?z2SelectLift:Z2_SELECT_LIFT);}}return state;}function createBlurDefaultState(el,stateName,state){var hasBlur=indexOf(el.currentStates,stateName)>=0;var currentOpacity=el.style.opacity;var fromState=!hasBlur?getFromStateStyle(el,['opacity'],stateName,{opacity:1}):null;state=state||{};var blurStyle=state.style||{};if(blurStyle.opacity==null){// clone state state=extend({},state);blurStyle=extend({// Already being applied 'emphasis'. DON'T mul opacity multiple times. opacity:hasBlur?currentOpacity:fromState.opacity*0.1},blurStyle);state.style=blurStyle;}return state;}function elementStateProxy(stateName,targetStates){var state=this.states[stateName];if(this.style){if(stateName==='emphasis'){return createEmphasisDefaultState(this,stateName,targetStates,state);}else if(stateName==='blur'){return createBlurDefaultState(this,stateName,state);}else if(stateName==='select'){return createSelectDefaultState(this,stateName,state);}}return state;}/**FI * Set hover style (namely "emphasis style") of element. * @param el Should not be `zrender/graphic/Group`. * @param focus 'self' | 'selfInSeries' | 'series' */function setDefaultStateProxy(el){el.stateProxy=elementStateProxy;var textContent=el.getTextContent();var textGuide=el.getTextGuideLine();if(textContent){textContent.stateProxy=elementStateProxy;}if(textGuide){textGuide.stateProxy=elementStateProxy;}}function enterEmphasisWhenMouseOver(el,e){!shouldSilent(el,e)// "emphasis" event highlight has higher priority than mouse highlight. &&!el.__highByOuter&&traverseUpdateState(el,singleEnterEmphasis);}function leaveEmphasisWhenMouseOut(el,e){!shouldSilent(el,e)// "emphasis" event highlight has higher priority than mouse highlight. &&!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 enterBlur(el){traverseUpdateState(el,singleEnterBlur);}function leaveBlur(el){traverseUpdateState(el,singleLeaveBlur);}function enterSelect(el){traverseUpdateState(el,singleEnterSelect);}function leaveSelect(el){traverseUpdateState(el,singleLeaveSelect);}function shouldSilent(el,e){return el.__highDownSilentOnTouch&&e.zrByTouch;}function allLeaveBlur(api){var model=api.getModel();var leaveBlurredSeries=[];var allComponentViews=[];model.eachComponent(function(componentType,componentModel){var componentStates=getComponentStates(componentModel);var isSeries=componentType==='series';var view=isSeries?api.getViewOfSeriesModel(componentModel):api.getViewOfComponentModel(componentModel);!isSeries&&allComponentViews.push(view);if(componentStates.isBlured){// Leave blur anyway view.group.traverse(function(child){singleLeaveBlur(child);});isSeries&&leaveBlurredSeries.push(componentModel);}componentStates.isBlured=false;});each$7(allComponentViews,function(view){if(view&&view.toggleBlurSeries){view.toggleBlurSeries(leaveBlurredSeries,false,model);}});}function blurSeries(targetSeriesIndex,focus,blurScope,api){var ecModel=api.getModel();blurScope=blurScope||'coordinateSystem';function leaveBlurOfIndices(data,dataIndices){for(var i=0;i0){var item={dataIndex:dataIndices,seriesIndex:seriesModel.seriesIndex};if(type!=null){item.dataType=type;}ret.push(item);}});});return ret;}/** * Enable the function that mouseover will trigger the emphasis state. * * NOTE: * This function should be used on the element with dataIndex, seriesIndex. * */function enableHoverEmphasis(el,focus,blurScope){setAsHighDownDispatcher(el,true);traverseUpdateState(el,setDefaultStateProxy);enableHoverFocus(el,focus,blurScope);}function disableHoverEmphasis(el){setAsHighDownDispatcher(el,false);}function toggleHoverEmphasis(el,focus,blurScope,isDisabled){isDisabled?disableHoverEmphasis(el):enableHoverEmphasis(el,focus,blurScope);}function enableHoverFocus(el,focus,blurScope){var ecData=getECData(el);if(focus!=null){// TODO dataIndex may be set after this function. This check is not useful. // if (ecData.dataIndex == null) { // if (__DEV__) { // console.warn('focus can only been set on element with dataIndex'); // } // } // else { ecData.focus=focus;ecData.blurScope=blurScope;// } }else if(ecData.focus){ecData.focus=null;}}var OTHER_STATES=['emphasis','blur','select'];var defaultStyleGetterMap={itemStyle:'getItemStyle',lineStyle:'getLineStyle',areaStyle:'getAreaStyle'};/** * Set emphasis/blur/selected states of element. */function setStatesStylesFromModel(el,itemModel,styleType,// default itemStyle getter){styleType=styleType||'itemStyle';for(var i=0;i1){rx*=mathSqrt$1(lambda);ry*=mathSqrt$1(lambda);}var f=(fa===fs?-1:1)*mathSqrt$1((rx*rx*(ry*ry)-rx*rx*(yp*yp)-ry*ry*(xp*xp))/(rx*rx*(yp*yp)+ry*ry*(xp*xp)))||0;var cxp=f*rx*yp/ry;var cyp=f*-ry*xp/rx;var cx=(x1+x2)/2.0+mathCos$1(psi)*cxp-mathSin$1(psi)*cyp;var cy=(y1+y2)/2.0+mathSin$1(psi)*cxp+mathCos$1(psi)*cyp;var theta=vAngle([1,0],[(xp-cxp)/rx,(yp-cyp)/ry]);var u=[(xp-cxp)/rx,(yp-cyp)/ry];var v=[(-1*xp-cxp)/rx,(-1*yp-cyp)/ry];var dTheta=vAngle(u,v);if(vRatio(u,v)<=-1){dTheta=PI$3;}if(vRatio(u,v)>=1){dTheta=0;}if(dTheta<0){var n=Math.round(dTheta/PI$3*1e6)/1e6;dTheta=PI$3*2+n%2*PI$3;}path.addData(cmd,cx,cy,rx,ry,theta,dTheta,psi,fs);}var commandReg=/([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;var numberReg=/-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;function createPathProxyFromString(data){var path=new PathProxy$1();if(!data){return path;}var cpx=0;var cpy=0;var subpathX=cpx;var subpathY=cpy;var prevCmd;var CMD=PathProxy$1.CMD;var cmdList=data.match(commandReg);if(!cmdList){return path;}for(var l=0;ldx1*dx1+dy1*dy1){cx0=cx1;cy0=cy1;}return{cx:cx0,cy:cy0,x0:-ox,y0:-oy,x1:cx0*(radius/r-1),y1:cy0*(radius/r-1)};}function normalizeCornerRadius(cr){var arr;if(isArray(cr)){var len=cr.length;if(!len){return cr;}if(len===1){arr=[cr[0],cr[0],0,0];}else if(len===2){arr=[cr[0],cr[0],cr[1],cr[1]];}else if(len===3){arr=cr.concat(cr[2]);}else{arr=cr;}}else{arr=[cr,cr,cr,cr];}return arr;}function buildPath$1(ctx,shape){var _a;var radius=mathMax$4(shape.r,0);var innerRadius=mathMax$4(shape.r0||0,0);var hasRadius=radius>0;var hasInnerRadius=innerRadius>0;if(!hasRadius&&!hasInnerRadius){return;}if(!hasRadius){radius=innerRadius;innerRadius=0;}if(innerRadius>radius){var tmp=radius;radius=innerRadius;innerRadius=tmp;}var startAngle=shape.startAngle,endAngle=shape.endAngle;if(isNaN(startAngle)||isNaN(endAngle)){return;}var cx=shape.cx,cy=shape.cy;var clockwise=!!shape.clockwise;var arc=mathAbs(endAngle-startAngle);var mod=arc>PI2$2&&arc%PI2$2;mod>e&&(arc=mod);if(!(radius>e)){ctx.moveTo(cx,cy);}else if(arc>PI2$2-e){ctx.moveTo(cx+radius*mathCos(startAngle),cy+radius*mathSin(startAngle));ctx.arc(cx,cy,radius,startAngle,endAngle,!clockwise);if(innerRadius>e){ctx.moveTo(cx+innerRadius*mathCos(endAngle),cy+innerRadius*mathSin(endAngle));ctx.arc(cx,cy,innerRadius,endAngle,startAngle,clockwise);}}else{var icrStart=void 0;var icrEnd=void 0;var ocrStart=void 0;var ocrEnd=void 0;var ocrs=void 0;var ocre=void 0;var icrs=void 0;var icre=void 0;var ocrMax=void 0;var icrMax=void 0;var limitedOcrMax=void 0;var limitedIcrMax=void 0;var xre=void 0;var yre=void 0;var xirs=void 0;var yirs=void 0;var xrs=radius*mathCos(startAngle);var yrs=radius*mathSin(startAngle);var xire=innerRadius*mathCos(endAngle);var yire=innerRadius*mathSin(endAngle);var hasArc=arc>e;if(hasArc){var cornerRadius=shape.cornerRadius;if(cornerRadius){_a=normalizeCornerRadius(cornerRadius),icrStart=_a[0],icrEnd=_a[1],ocrStart=_a[2],ocrEnd=_a[3];}var halfRd=mathAbs(radius-innerRadius)/2;ocrs=mathMin$4(halfRd,ocrStart);ocre=mathMin$4(halfRd,ocrEnd);icrs=mathMin$4(halfRd,icrStart);icre=mathMin$4(halfRd,icrEnd);limitedOcrMax=ocrMax=mathMax$4(ocrs,ocre);limitedIcrMax=icrMax=mathMax$4(icrs,icre);if(ocrMax>e||icrMax>e){xre=radius*mathCos(endAngle);yre=radius*mathSin(endAngle);xirs=innerRadius*mathCos(startAngle);yirs=innerRadius*mathSin(startAngle);if(arce){var crStart=mathMin$4(ocrStart,limitedOcrMax);var crEnd=mathMin$4(ocrEnd,limitedOcrMax);var ct0=computeCornerTangents(xirs,yirs,xrs,yrs,radius,crStart,clockwise);var ct1=computeCornerTangents(xre,yre,xire,yire,radius,crEnd,clockwise);ctx.moveTo(cx+ct0.cx+ct0.x0,cy+ct0.cy+ct0.y0);if(limitedOcrMax0&&ctx.arc(cx+ct0.cx,cy+ct0.cy,crStart,mathATan2(ct0.y0,ct0.x0),mathATan2(ct0.y1,ct0.x1),!clockwise);ctx.arc(cx,cy,radius,mathATan2(ct0.cy+ct0.y1,ct0.cx+ct0.x1),mathATan2(ct1.cy+ct1.y1,ct1.cx+ct1.x1),!clockwise);crEnd>0&&ctx.arc(cx+ct1.cx,cy+ct1.cy,crEnd,mathATan2(ct1.y1,ct1.x1),mathATan2(ct1.y0,ct1.x0),!clockwise);}}else{ctx.moveTo(cx+xrs,cy+yrs);ctx.arc(cx,cy,radius,startAngle,endAngle,!clockwise);}if(!(innerRadius>e)||!hasArc){ctx.lineTo(cx+xire,cy+yire);}else if(limitedIcrMax>e){var crStart=mathMin$4(icrStart,limitedIcrMax);var crEnd=mathMin$4(icrEnd,limitedIcrMax);var ct0=computeCornerTangents(xire,yire,xre,yre,innerRadius,-crEnd,clockwise);var ct1=computeCornerTangents(xrs,yrs,xirs,yirs,innerRadius,-crStart,clockwise);ctx.lineTo(cx+ct0.cx+ct0.x0,cy+ct0.cy+ct0.y0);if(limitedIcrMax0&&ctx.arc(cx+ct0.cx,cy+ct0.cy,crEnd,mathATan2(ct0.y0,ct0.x0),mathATan2(ct0.y1,ct0.x1),!clockwise);ctx.arc(cx,cy,innerRadius,mathATan2(ct0.cy+ct0.y1,ct0.cx+ct0.x1),mathATan2(ct1.cy+ct1.y1,ct1.cx+ct1.x1),clockwise);crStart>0&&ctx.arc(cx+ct1.cx,cy+ct1.cy,crStart,mathATan2(ct1.y1,ct1.x1),mathATan2(ct1.y0,ct1.x0),!clockwise);}}else{ctx.lineTo(cx+xire,cy+yire);ctx.arc(cx,cy,innerRadius,endAngle,startAngle,clockwise);}}ctx.closePath();}var SectorShape=function(){function SectorShape(){this.cx=0;this.cy=0;this.r0=0;this.r=0;this.startAngle=0;this.endAngle=Math.PI*2;this.clockwise=true;this.cornerRadius=0;}return SectorShape;}();var Sector=function(_super){__extends(Sector,_super);function Sector(opts){return _super.call(this,opts)||this;}Sector.prototype.getDefaultShape=function(){return new SectorShape();};Sector.prototype.buildPath=function(ctx,shape){buildPath$1(ctx,shape);};Sector.prototype.isZeroArea=function(){return this.shape.startAngle===this.shape.endAngle||this.shape.r===this.shape.r0;};return Sector;}(Path$1);Sector.prototype.type='sector';var Sector$1=Sector;var RingShape=function(){function RingShape(){this.cx=0;this.cy=0;this.r=0;this.r0=0;}return RingShape;}();var Ring=function(_super){__extends(Ring,_super);function Ring(opts){return _super.call(this,opts)||this;}Ring.prototype.getDefaultShape=function(){return new RingShape();};Ring.prototype.buildPath=function(ctx,shape){var x=shape.cx;var y=shape.cy;var PI2=Math.PI*2;ctx.moveTo(x+shape.r,y);ctx.arc(x,y,shape.r,0,PI2,false);ctx.moveTo(x+shape.r0,y);ctx.arc(x,y,shape.r0,0,PI2,true);};return Ring;}(Path$1);Ring.prototype.type='ring';var Ring$1=Ring;function smoothBezier(points,smooth,isLoop,constraint){var cps=[];var v=[];var v1=[];var v2=[];var prevPoint;var nextPoint;var min;var max;if(constraint){min=[Infinity,Infinity];max=[-Infinity,-Infinity];for(var i=0,len=points.length;i=2){if(smooth){var controlPoints=smoothBezier(points,smooth,closePath,shape.smoothConstraint);ctx.moveTo(points[0][0],points[0][1]);var len=points.length;for(var i=0;i<(closePath?len:len-1);i++){var cp1=controlPoints[i*2];var cp2=controlPoints[i*2+1];var p=points[(i+1)%len];ctx.bezierCurveTo(cp1[0],cp1[1],cp2[0],cp2[1],p[0],p[1]);}}else{ctx.moveTo(points[0][0],points[0][1]);for(var i=1,l=points.length;iextent2[1]){overlapped=false;if(noMtv){return overlapped;}var dist0=Math.abs(extent2[0]-extent[1]);var dist1=Math.abs(extent[0]-extent2[1]);if(Math.min(dist0,dist1)>maxTv.len()){if(dist00){var duration=animationConfig.duration;var animationDelay=animationConfig.delay;var animationEasing=animationConfig.easing;var animateConfig={duration:duration,delay:animationDelay||0,easing:animationEasing,done:cb,force:!!cb||!!during,// Set to final state in update/init animation. // So the post processing based on the path shape can be done correctly. setToFinal:!isRemove,scope:animationType,during:during};isFrom?el.animateFrom(props,animateConfig):el.animateTo(props,animateConfig);}else{el.stopAnimation();// If `isFrom`, the props is the "from" props. !isFrom&&el.attr(props);// Call during at least once. during&&during(1);cb&&cb();}}/** * Update graphic element properties with or without animation according to the * configuration in series. * * Caution: this method will stop previous animation. * So do not use this method to one element twice before * animation starts, unless you know what you are doing. * @example * graphic.updateProps(el, { * position: [100, 100] * }, seriesModel, dataIndex, function () { console.log('Animation done!'); }); * // Or * graphic.updateProps(el, { * position: [100, 100] * }, seriesModel, function () { console.log('Animation done!'); }); */function updateProps$1(el,props,// TODO: TYPE AnimatableModel animatableModel,dataIndex,cb,during){animateOrSetProps('update',el,props,animatableModel,dataIndex,cb,during);}/** * Init graphic element properties with or without animation according to the * configuration in series. * * Caution: this method will stop previous animation. * So do not use this method to one element twice before * animation starts, unless you know what you are doing. */function initProps(el,props,animatableModel,dataIndex,cb,during){animateOrSetProps('enter',el,props,animatableModel,dataIndex,cb,during);}/** * If element is removed. * It can determine if element is having remove animation. */function isElementRemoved(el){if(!el.__zr){return true;}for(var i=0;iMath.abs(vertex[1])?vertex[0]>0?'right':'left':vertex[1]>0?'bottom':'top';}function isNotGroup(el){return!el.isGroup;}function isPath(el){return el.shape!=null;}/** * Apply group transition animation from g1 to g2. * If no animatableModel, no animation. */function groupTransition(g1,g2,animatableModel){if(!g1||!g2){return;}function getElMap(g){var elMap={};g.traverse(function(el){if(isNotGroup(el)&&el.anid){elMap[el.anid]=el;}});return elMap;}function getAnimatableProps(el){var obj={x:el.x,y:el.y,rotation:el.rotation};if(isPath(el)){obj.shape=extend({},el.shape);}return obj;}var elMap1=getElMap(g1);g2.traverse(function(el){if(isNotGroup(el)&&el.anid){var oldEl=elMap1[el.anid];if(oldEl){var newProp=getAnimatableProps(el);el.attr(getAnimatableProps(oldEl));updateProps$1(el,newProp,animatableModel,getECData(el).dataIndex);}}});}function clipPointsByRect(points,rect){// FIXME: this way migth be incorrect when grpahic clipped by a corner. // and when element have border. return map$1(points,function(point){var x=point[0];x=mathMax$3(x,rect.x);x=mathMin$3(x,rect.x+rect.width);var y=point[1];y=mathMax$3(y,rect.y);y=mathMin$3(y,rect.y+rect.height);return[x,y];});}/** * Return a new clipped rect. If rect size are negative, return undefined. */function clipRectByRect(targetRect,rect){var x=mathMax$3(targetRect.x,rect.x);var x2=mathMin$3(targetRect.x+targetRect.width,rect.x+rect.width);var y=mathMax$3(targetRect.y,rect.y);var y2=mathMin$3(targetRect.y+targetRect.height,rect.y+rect.height);// If the total rect is cliped, nothing, including the border, // should be painted. So return undefined. if(x2>=x&&y2>=y){return{x:x,y:y,width:x2-x,height:y2-y};}}function createIcon(iconStr,// Support 'image://' or 'path://' or direct svg path. opt,rect){var innerOpts=extend({rectHover:true},opt);var style=innerOpts.style={strokeNoScale:true};rect=rect||{x:-1,y:-1,width:2,height:2};if(iconStr){return iconStr.indexOf('image://')===0?(style.image=iconStr.slice(8),defaults(style,rect),new ZRImage$1(innerOpts)):makePath(iconStr.replace('path://',''),innerOpts,rect,'center');}}/** * Return `true` if the given line (line `a`) and the given polygon * are intersect. * Note that we do not count colinear as intersect here because no * requirement for that. We could do that if required in future. */function linePolygonIntersect(a1x,a1y,a2x,a2y,points){for(var i=0,p2=points[points.length-1];i1){return false;}var p=crossProduct2d$1(b1a1x,b1a1y,nx,ny)/nmCrossProduct;if(p<0||p>1){return false;}return true;}/** * Cross product of 2-dimension vector. */function crossProduct2d$1(x1,y1,x2,y2){return x1*y2-x2*y1;}function nearZero(val){return val<=1e-6&&val>=-1e-6;}function setTooltipConfig(opt){var itemTooltipOption=opt.itemTooltipOption;var componentModel=opt.componentModel;var itemName=opt.itemName;var itemTooltipOptionObj=isString(itemTooltipOption)?{formatter:itemTooltipOption}:itemTooltipOption;var mainType=componentModel.mainType;var componentIndex=componentModel.componentIndex;var formatterParams={componentType:mainType,name:itemName,$vars:['name']};formatterParams[mainType+'Index']=componentIndex;var formatterParamsExtra=opt.formatterParamsExtra;if(formatterParamsExtra){each$7(keys(formatterParamsExtra),function(key){if(!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)};}function traverseElement(el,cb){var stopped;// TODO // Polyfill for fixing zrender group traverse don't visit it's root issue. if(el.isGroup){stopped=cb(el);}if(!stopped){el.traverse(cb);}}function traverseElements(els,cb){if(els){if(isArray(els)){for(var i=0;i` // getModel(path: string | string[], parentModel?: Model): Model; // TODO 'a.b.c' is deprecated Model.prototype.getModel=function(path,parentModel){var hasPath=path!=null;var pathFinal=hasPath?this.parsePath(path):null;var obj=hasPath?this._doGet(pathFinal):this.option;parentModel=parentModel||this.parentModel&&this.parentModel.getModel(this.resolveParentPath(pathFinal));return new Model(obj,parentModel,this.ecModel);};/** * If model has option */Model.prototype.isEmpty=function(){return this.option==null;};Model.prototype.restoreData=function(){};// Pending Model.prototype.clone=function(){var Ctor=this.constructor;return new Ctor(clone$3(this.option));};// setReadOnly(properties): void { // clazzUtil.setReadOnly(this, properties); // } // If path is null/undefined, return null/undefined. Model.prototype.parsePath=function(path){if(typeof path==='string'){return path.split('.');}return path;};// Resolve path for parent. Perhaps useful when parent use a different property. // Default to be a identity resolver. // Can be modified to a different resolver. Model.prototype.resolveParentPath=function(path){return path;};// FIXME:TS check whether put this method here Model.prototype.isAnimationEnabled=function(){if(!env$1.node&&this.option){if(this.option.animation!=null){return!!this.option.animation;}else 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` for `entity`. * * Topological travel on Activity Network (Activity On Vertices). * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis']. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology. * If there is circular dependencey, Error will be thrown. */function enableTopologicalTravel(entity,dependencyGetter){/** * @param targetNameList Target Component type list. * Can be ['aa', 'bb', 'aa.xx'] * @param fullNameList By which we can build dependency graph. * @param callback Params: componentType, dependencies. * @param context Scope of callback. */entity.topologicalTravel=function(targetNameList,fullNameList,callback,context){if(!targetNameList.length){return;}var result=makeDepndencyGraph(fullNameList);var graph=result.graph;var noEntryList=result.noEntryList;var targetNameSet={};each$7(targetNameList,function(name){targetNameSet[name]=true;});while(noEntryList.length){var currComponentType=noEntryList.pop();var currVertex=graph[currComponentType];var isInTargetNameSet=!!targetNameSet[currComponentType];if(isInTargetNameSet){callback.call(context,currComponentType,currVertex.originalDeps.slice());delete targetNameSet[currComponentType];}each$7(currVertex.successor,isInTargetNameSet?removeEdgeAndAdd:removeEdge);}each$7(targetNameSet,function(){var errMsg='';throw new Error(errMsg);});function removeEdge(succComponentType){graph[succComponentType].entryCount--;if(graph[succComponentType].entryCount===0){noEntryList.push(succComponentType);}}// Consider this case: legend depends on series, and we call // chart.setOption({series: [...]}), where only series is in option. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will // not be called, but only sereis.mergeOption is called. Thus legend // have no chance to update its local record about series (like which // name of series is available in legend). function removeEdgeAndAdd(succComponentType){targetNameSet[succComponentType]=true;removeEdge(succComponentType);}};function makeDepndencyGraph(fullNameList){var graph={};var noEntryList=[];each$7(fullNameList,function(name){var thisItem=createDependencyGraphItem(graph,name);var originalDeps=thisItem.originalDeps=dependencyGetter(name);var availableDeps=getAvailableDependencies(originalDeps,fullNameList);thisItem.entryCount=availableDeps.length;if(thisItem.entryCount===0){noEntryList.push(name);}each$7(availableDeps,function(dependentName){if(indexOf(thisItem.predecessor,dependentName)<0){thisItem.predecessor.push(dependentName);}var thatItem=createDependencyGraphItem(graph,dependentName);if(indexOf(thatItem.successor,dependentName)<0){thatItem.successor.push(name);}});});return{graph:graph,noEntryList:noEntryList};}function createDependencyGraphItem(graph,name){if(!graph[name]){graph[name]={predecessor:[],successor:[]};}return graph[name];}function getAvailableDependencies(originalDeps,fullNameList){var availableDeps=[];each$7(originalDeps,function(dep){indexOf(fullNameList,dep)>=0&&availableDeps.push(dep);});return availableDeps;}}function inheritDefaultOption(superOption,subOption){// See also `model/Component.ts#getDefaultOption` return merge(merge({},superOption,true),subOption,true);}/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * AUTO-GENERATED FILE. DO NOT MODIFY. */ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * Language: English. */var langEN={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:'Gauge',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:'. '}}}};/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * AUTO-GENERATED FILE. DO NOT MODIFY. */ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */var langZH={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 LOCALE_ZH='ZH';var LOCALE_EN='EN';var DEFAULT_LOCALE=LOCALE_EN;var localeStorage={};var localeModels={};var SYSTEM_LANG=!env$1.domSupported?DEFAULT_LOCALE:function(){var langStr=(/* eslint-disable-next-line */document.documentElement.lang||navigator.language||navigator.browserLanguage).toUpperCase();return langStr.indexOf(LOCALE_ZH)>-1?LOCALE_ZH:DEFAULT_LOCALE;}();function registerLocale(locale,localeObj){locale=locale.toUpperCase();localeModels[locale]=new Model$1(localeObj);localeStorage[locale]=localeObj;}// export function getLocale(locale: string) { // return localeStorage[locale]; // } function createLocaleObject(locale){if(isString(locale)){var localeObj=localeStorage[locale.toUpperCase()]||{};if(locale===LOCALE_ZH||locale===LOCALE_EN){return clone$3(localeObj);}else{return merge(clone$3(localeObj),clone$3(localeStorage[DEFAULT_LOCALE]),false);}}else{return merge(clone$3(locale),clone$3(localeStorage[DEFAULT_LOCALE]),false);}}function getLocaleModel(lang){return localeModels[lang];}function getDefaultLocaleModel(){return localeModels[DEFAULT_LOCALE];}// Default locale registerLocale(LOCALE_EN,langEN);registerLocale(LOCALE_ZH,langZH);var ONE_SECOND=1000;var ONE_MINUTE=ONE_SECOND*60;var ONE_HOUR=ONE_MINUTE*60;var ONE_DAY=ONE_HOUR*24;var ONE_YEAR=ONE_DAY*365;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}'};var fullDayFormatter='{yyyy}-{MM}-{dd}';var fullLeveledFormatter={year:'{yyyy}',month:'{yyyy}-{MM}',day:fullDayFormatter,hour:fullDayFormatter+' '+defaultLeveledFormatter.hour,minute:fullDayFormatter+' '+defaultLeveledFormatter.minute,second:fullDayFormatter+' '+defaultLeveledFormatter.second,millisecond:defaultLeveledFormatter.none};var primaryTimeUnits=['year','month','day','hour','minute','second','millisecond'];var timeUnits=['year','half-year','quarter','month','week','half-week','day','half-day','quarter-day','hour','minute','second','millisecond'];function pad(str,len){str+='';return'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:// year, minutes, second, milliseconds return timeUnit;}}function isPrimaryTimeUnit(timeUnit){return timeUnit===getPrimaryTimeUnit(timeUnit);}function getDefaultFormatPrecisionOfInterval(timeUnit){switch(timeUnit){case'year':case'month':return'day';case'millisecond':return'millisecond';default:// Also for day, hour, minute, second return'second';}}function format(// Note: The result based on `isUTC` are totally different, which can not be just simply // substituted by the result without `isUTC`. So we make the param `isUTC` mandatory. time,template,isUTC,lang){var date=parseDate(time);var y=date[fullYearGetterName(isUTC)]();var M=date[monthGetterName(isUTC)]()+1;var q=Math.floor((M-1)/3)+1;var d=date[dateGetterName(isUTC)]();var e=date['get'+(isUTC?'UTC':'')+'Day']();var H=date[hoursGetterName(isUTC)]();var h=(H-1)%12+1;var m=date[minutesGetterName(isUTC)]();var s=date[secondsGetterName(isUTC)]();var S=date[millisecondsGetterName(isUTC)]();var localeModel=lang instanceof Model$1?lang:getLocaleModel(lang||SYSTEM_LANG)||getDefaultLocaleModel();var timeModel=localeModel.getModel('time');var month=timeModel.get('month');var monthAbbr=timeModel.get('monthAbbr');var dayOfWeek=timeModel.get('dayOfWeek');var dayOfWeekAbbr=timeModel.get('dayOfWeekAbbr');return(template||'').replace(/{yyyy}/g,y+'').replace(/{yy}/g,y%100+'').replace(/{Q}/g,q+'').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 leveledFormat(tick,idx,formatter,lang,isUTC){var template=null;if(isString(formatter)){// Single formatter for all units at all levels template=formatter;}else if(isFunction(formatter)){// Callback formatter template=formatter(tick.value,idx,{level:tick.level});}else{var defaults$1=extend({},defaultLeveledFormatter);if(tick.level>0){for(var i=0;i=0;--i){if(mergedFormatter[unit]){template=mergedFormatter[unit];break;}}template=template||defaults$1.none;}if(isArray(template)){var levelId=tick.level==null?0:tick.level>=0?tick.level:template.length+tick.level;levelId=Math.min(levelId,template.length-1);template=template[levelId];}}return format(new Date(tick.value),template,isUTC,lang);}function getUnitFromValue(value,isUTC){var date=parseDate(value);var M=date[monthGetterName(isUTC)]()+1;var d=date[dateGetterName(isUTC)]();var h=date[hoursGetterName(isUTC)]();var m=date[minutesGetterName(isUTC)]();var s=date[secondsGetterName(isUTC)]();var S=date[millisecondsGetterName(isUTC)]();var isSecond=S===0;var isMinute=isSecond&&s===0;var isHour=isMinute&&m===0;var isDay=isHour&&h===0;var isMonth=isDay&&d===1;var isYear=isMonth&&M===1;if(isYear){return'year';}else if(isMonth){return'month';}else if(isDay){return'day';}else if(isHour){return'hour';}else if(isMinute){return'minute';}else if(isSecond){return'second';}else{return'millisecond';}}function getUnitValue(value,unit,isUTC){var date=isNumber(value)?parseDate(value):value;unit=unit||getUnitFromValue(value,isUTC);switch(unit){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?'getUTCMilliseconds':'getMilliseconds';}function fullYearSetterName(isUTC){return isUTC?'setUTCFullYear':'setFullYear';}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?'setUTCMilliseconds':'setMilliseconds';}/** * Add a comma each three digit. */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){str=(str||'').toLowerCase().replace(/-(.)/g,function(match,group1){return group1.toUpperCase();});if(upperCaseFirst&&str){str=str.charAt(0).toUpperCase()+str.slice(1);}return str;}var normalizeCssArray=normalizeCssArray$1;var replaceReg=/([&<>"'])/g;var replaceMap={'&':'&','<':'<','>':'>','"':'"','\'':'''};function encodeHTML(source){return source==null?'':(source+'').replace(replaceReg,function(str,c){return replaceMap[c];});}/** * Make value user readable for tooltip and label. * "User readable": * Try to not print programmer-specific text like NaN, Infinity, null, undefined. * Avoid to display an empty string, which users can not recognize there is * a value and it might look like a bug. */function makeValueReadable(value,valueType,useUTC){var USER_READABLE_DEFUALT_TIME_PATTERN='{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}';function stringToUserReadable(str){return str&&trim$1(str)?str:'-';}function isNumberUserReadable(num){return!!(num!=null&&!isNaN(num)&&isFinite(num));}var isTypeTime=valueType==='time';var isValueDate=value instanceof Date;if(isTypeTime||isValueDate){var date=isTypeTime?parseDate(value):value;if(!isNaN(+date)){return format(date,USER_READABLE_DEFUALT_TIME_PATTERN,useUTC);}else if(isValueDate){return'-';}// In other cases, continue to try to display the value in the following code. }if(valueType==='ordinal'){return isStringSafe(value)?stringToUserReadable(value):isNumber(value)?isNumberUserReadable(value)?value+'':'-':'-';}// By default. var numericResult=numericToNumber(value);return isNumberUserReadable(numericResult)?addCommas(numericResult):isStringSafe(value)?stringToUserReadable(value):typeof value==='boolean'?value+'':'-';}var TPL_VAR_ALIAS=['a','b','c','d','e','f','g'];var wrapVar=function wrapVar(varName,seriesIdx){return'{'+varName+(seriesIdx==null?'':seriesIdx)+'}';};/** * Template formatter * @param {Array.|Object} paramsList */function formatTpl(tpl,paramsList,encode){if(!isArray(paramsList)){paramsList=[paramsList];}var seriesLen=paramsList.length;if(!seriesLen){return'';}var $vars=paramsList[0].$vars||[];for(var 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':'';}else{// Should better not to auto generate style name by auto-increment number here. // Because this util is usually called in tooltip formatter, which is probably // called repeatly when mouse move and the auto-increment number increases fast. // Users can make their own style name by theirselves, make it unique and readable. var markerId=opt.markerId||'markerX';return{renderMode:renderMode,content:'{'+markerId+'|} ',style:type==='subItem'?{width:4,height:4,borderRadius:2,backgroundColor:color}:{width:10,height:10,borderRadius:5,backgroundColor:color}};}}/** * @return Never be null/undefined. */function convertToColorString(color,defaultColor){defaultColor=defaultColor||'transparent';return isString(color)?color:isObject$2(color)?color.colorStops&&(color.colorStops[0]||{}).color||defaultColor:defaultColor;}/** * open new tab * @param link url * @param target blank or self */function windowOpen(link,target){/* global window */if(target==='_blank'||target==='blank'){var blank=window.open();blank.opener=null;blank.location.href=link;}else{window.open(link,target);}}var each$6=each$7;/** * @public */var LOCATION_PARAMS=['left','right','top','bottom','width','height'];/** * @public */var HV_NAMES=[['width','left','right'],['height','top','bottom']];function boxLayout(orient,group,gap,maxWidth,maxHeight){var x=0;var y=0;if(maxWidth==null){maxWidth=Infinity;}if(maxHeight==null){maxHeight=Infinity;}var currentLineMaxSize=0;group.eachChild(function(child,idx){var rect=child.getBoundingRect();var nextChild=group.childAt(idx+1);var nextChildRect=nextChild&&nextChild.getBoundingRect();var nextX;var nextY;if(orient==='horizontal'){var moveX=rect.width+(nextChildRect?-nextChildRect.x+rect.x:0);nextX=x+moveX;// Wrap when width exceeds maxWidth or meet a `newline` group // FIXME compare before adding gap? if(nextX>maxWidth||child.newline){x=0;nextX=moveX;y+=currentLineMaxSize+gap;currentLineMaxSize=rect.height;}else{// FIXME: consider rect.y is not `0`? currentLineMaxSize=Math.max(currentLineMaxSize,rect.height);}}else{var moveY=rect.height+(nextChildRect?-nextChildRect.y+rect.y:0);nextY=y+moveY;// Wrap when width exceeds maxHeight or meet a `newline` group if(nextY>maxHeight||child.newline){x+=currentLineMaxSize+gap;y=0;nextY=moveY;currentLineMaxSize=rect.width;}else{currentLineMaxSize=Math.max(currentLineMaxSize,rect.width);}}if(child.newline){return;}child.x=x;child.y=y;child.markRedraw();orient==='horizontal'?x=nextX+gap:y=nextY+gap;});}/** * VBox or HBox layouting * @param {string} orient * @param {module:zrender/graphic/Group} group * @param {number} gap * @param {number} [width=Infinity] * @param {number} [height=Infinity] */var box=boxLayout;/** * VBox layouting * @param {module:zrender/graphic/Group} group * @param {number} gap * @param {number} [width=Infinity] * @param {number} [height=Infinity] */curry$1(boxLayout,'vertical');/** * HBox layouting * @param {module:zrender/graphic/Group} group * @param {number} gap * @param {number} [width=Infinity] * @param {number} [height=Infinity] */curry$1(boxLayout,'horizontal');/** * Parse position info. */function getLayoutRect(positionInfo,containerRect,margin){margin=normalizeCssArray(margin||0);var containerWidth=containerRect.width;var containerHeight=containerRect.height;var left=parsePercent(positionInfo.left,containerWidth);var top=parsePercent(positionInfo.top,containerHeight);var right=parsePercent(positionInfo.right,containerWidth);var bottom=parsePercent(positionInfo.bottom,containerHeight);var width=parsePercent(positionInfo.width,containerWidth);var height=parsePercent(positionInfo.height,containerHeight);var verticalMargin=margin[2]+margin[0];var horizontalMargin=margin[1]+margin[3];var aspect=positionInfo.aspect;// If width is not specified, calculate width from left and right if(isNaN(width)){width=containerWidth-right-horizontalMargin-left;}if(isNaN(height)){height=containerHeight-bottom-verticalMargin-top;}if(aspect!=null){// If width and height are not given // 1. Graph should not exceeds the container // 2. Aspect must be keeped // 3. Graph should take the space as more as possible // FIXME // Margin is not considered, because there is no case that both // using margin and aspect so far. if(isNaN(width)&&isNaN(height)){if(aspect>containerWidth/containerHeight){width=containerWidth*0.8;}else{height=containerHeight*0.8;}}// Calculate width or height with given aspect if(isNaN(width)){width=aspect*height;}if(isNaN(height)){height=width/aspect;}}// If left is not specified, calculate left from right and width if(isNaN(left)){left=containerWidth-right-width-horizontalMargin;}if(isNaN(top)){top=containerHeight-bottom-height-verticalMargin;}// Align left and top switch(positionInfo.left||positionInfo.right){case'center':left=containerWidth/2-width/2-margin[3];break;case'right':left=containerWidth-width-horizontalMargin;break;}switch(positionInfo.top||positionInfo.bottom){case'middle':case'center':top=containerHeight/2-height/2-margin[0];break;case'bottom':top=containerHeight-height-verticalMargin;break;}// If something is wrong and left, top, width, height are calculated as NaN left=left||0;top=top||0;if(isNaN(width)){// Width may be NaN if only one value is given except width width=containerWidth-horizontalMargin-left-(right||0);}if(isNaN(height)){// Height may be NaN if only one value is given except height height=containerHeight-verticalMargin-top-(bottom||0);}var rect=new BoundingRect$1(left+margin[3],top+margin[0],width,height);rect.margin=margin;return rect;}/** * Position a zr element in viewport * Group position is specified by either * {left, top}, {right, bottom} * If all properties exists, right and bottom will be igonred. * * Logic: * 1. Scale (against origin point in parent coord) * 2. Rotate (against origin point in parent coord) * 3. Traslate (with el.position by this method) * So this method only fixes the last step 'Traslate', which does not affect * scaling and rotating. * * If be called repeatly with the same input el, the same result will be gotten. * * Return true if the layout happend. * * @param el Should have `getBoundingRect` method. * @param positionInfo * @param positionInfo.left * @param positionInfo.top * @param positionInfo.right * @param positionInfo.bottom * @param positionInfo.width Only for opt.boundingModel: 'raw' * @param positionInfo.height Only for opt.boundingModel: 'raw' * @param containerRect * @param margin * @param opt * @param opt.hv Only horizontal or only vertical. Default to be [1, 1] * @param opt.boundingMode * Specify how to calculate boundingRect when locating. * 'all': Position the boundingRect that is transformed and uioned * both itself and its descendants. * This mode simplies confine the elements in the bounding * of their container (e.g., using 'right: 0'). * 'raw': Position the boundingRect that is not transformed and only itself. * This mode is useful when you want a element can overflow its * container. (Consider a rotated circle needs to be located in a corner.) * In this mode positionInfo.width/height can only be number. */function positionElement(el,positionInfo,containerRect,margin,opt,out){var h=!opt||!opt.hv||opt.hv[0];var v=!opt||!opt.hv||opt.hv[1];var boundingMode=opt&&opt.boundingMode||'all';out=out||el;out.x=el.x;out.y=el.y;if(!h&&!v){return false;}var rect;if(boundingMode==='raw'){rect=el.type==='group'?new BoundingRect$1(0,0,+positionInfo.width||0,+positionInfo.height||0):el.getBoundingRect();}else{rect=el.getBoundingRect();if(el.needLocalTransform()){var transform=el.getLocalTransform();// Notice: raw rect may be inner object of el, // which should not be modified. rect=rect.clone();rect.applyTransform(transform);}}// The real width and height can not be specified but calculated by the given el. var layoutRect=getLayoutRect(defaults({width:rect.width,height:rect.height},positionInfo),containerRect,margin);// Because 'tranlate' is the last step in transform // (see zrender/core/Transformable#getLocalTransform), // we can just only modify el.position to get final result. var dx=h?layoutRect.x-rect.x:0;var dy=v?layoutRect.y-rect.y:0;if(boundingMode==='raw'){out.x=dx;out.y=dy;}else{out.x+=dx;out.y+=dy;}if(out===el){el.markRedraw();}return true;}function fetchLayoutMode(ins){var layoutMode=ins.layoutMode||ins.constructor.layoutMode;return isObject$2(layoutMode)?layoutMode:layoutMode?{type:layoutMode}:null;}/** * Consider Case: * When default option has {left: 0, width: 100}, and we set {right: 0} * through setOption or media query, using normal zrUtil.merge will cause * {right: 0} does not take effect. * * @example * ComponentModel.extend({ * init: function () { * ... * let inputPositionParams = layout.getLayoutParams(option); * this.mergeOption(inputPositionParams); * }, * mergeOption: function (newOption) { * newOption && zrUtil.merge(thisOption, newOption, true); * layout.mergeLayoutParam(thisOption, newOption); * } * }); * * @param targetOption * @param newOption * @param opt */function mergeLayoutParam(targetOption,newOption,opt){var ignoreSize=opt&&opt.ignoreSize;!isArray(ignoreSize)&&(ignoreSize=[ignoreSize,ignoreSize]);var hResult=merge(HV_NAMES[0],0);var vResult=merge(HV_NAMES[1],1);copy(HV_NAMES[0],targetOption,hResult);copy(HV_NAMES[1],targetOption,vResult);function merge(names,hvIdx){var newParams={};var newValueCount=0;var merged={};var mergedValueCount=0;var enoughParamNumber=2;each$6(names,function(name){merged[name]=targetOption[name];});each$6(names,function(name){// Consider case: newOption.width is null, which is // set by user for removing width setting. hasProp(newOption,name)&&(newParams[name]=merged[name]=newOption[name]);hasValue(newParams,name)&&newValueCount++;hasValue(merged,name)&&mergedValueCount++;});if(ignoreSize[hvIdx]){// Only one of left/right is premitted to exist. if(hasValue(newOption,names[1])){merged[names[2]]=null;}else if(hasValue(newOption,names[2])){merged[names[1]]=null;}return merged;}// Case: newOption: {width: ..., right: ...}, // or targetOption: {right: ...} and newOption: {width: ...}, // There is no conflict when merged only has params count // little than enoughParamNumber. if(mergedValueCount===enoughParamNumber||!newValueCount){return merged;}// Case: newOption: {width: ..., right: ...}, // Than we can make sure user only want those two, and ignore // all origin params in targetOption. else if(newValueCount>=enoughParamNumber){return newParams;}else{// Chose another param from targetOption by priority. for(var i=0;i=0;i--){defaultOption=merge(defaultOption,optList[i],true);}fields.defaultOption=defaultOption;}return fields.defaultOption;};/** * Notice: always force to input param `useDefault` in case that forget to consider it. * The same behavior as `modelUtil.parseFinder`. * * @param useDefault In many cases like series refer axis and axis refer grid, * If axis index / axis id not specified, use the first target as default. * In other cases like dataZoom refer axis, if not specified, measn no refer. */ComponentModel.prototype.getReferringComponents=function(mainType,opt){var indexKey=mainType+'Index';var idKey=mainType+'Id';return queryReferringComponents(this.ecModel,mainType,{index:this.get(indexKey,true),id:this.get(idKey,true)},opt);};ComponentModel.prototype.getBoxLayoutParams=function(){// Consider itself having box layout configs. var boxLayoutModel=this;return{left:boxLayoutModel.get('left'),top:boxLayoutModel.get('top'),right:boxLayoutModel.get('right'),bottom:boxLayoutModel.get('bottom'),width:boxLayoutModel.get('width'),height:boxLayoutModel.get('height')};};/** * Get key for zlevel. * If developers don't configure zlevel. We will assign zlevel to series based on the key. * For example, lines with trail effect and progressive series will in an individual zlevel. */ComponentModel.prototype.getZLevelKey=function(){return'';};ComponentModel.prototype.setZLevel=function(zlevel){this.option.zlevel=zlevel;};ComponentModel.protoInitialize=function(){var proto=ComponentModel.prototype;proto.type='component';proto.id='';proto.name='';proto.mainType='';proto.subType='';proto.componentIndex=0;}();return ComponentModel;}(Model$1);mountExtend(ComponentModel,Model$1);enableClassManagement(ComponentModel);enableSubTypeDefaulter(ComponentModel);enableTopologicalTravel(ComponentModel,getDependencies);function getDependencies(componentType){var deps=[];each$7(ComponentModel.getClassesByMainType(componentType),function(clz){deps=deps.concat(clz.dependencies||clz.prototype.dependencies||[]);});// Ensure main type. deps=map$1(deps,function(type){return parseClassType(type).main;});// Hack dataset for convenience. if(componentType!=='dataset'&&indexOf(deps,'dataset')<=0){deps.unshift('dataset');}return deps;}var ComponentModel$1=ComponentModel;/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * AUTO-GENERATED FILE. DO NOT MODIFY. */ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */var platform='';// Navigator not exists in node if(typeof navigator!=='undefined'){/* global navigator */platform=navigator.platform||'';}var decalColor='rgba(0, 0, 0, 0.2)';var globalDefault={darkMode:'auto',// backgroundColor: 'rgba(0,0,0,0)', colorBy:'series',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}]}},// If xAxis and yAxis declared, grid is created by default. // grid: {}, textStyle:{// color: '#000', // decoration: 'none', // PENDING fontFamily:platform.match(/^Win/)?'Microsoft YaHei':'sans-serif',// fontFamily: 'Arial, Verdana, sans-serif', fontSize:12,fontStyle:'normal',fontWeight:'normal'},// http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/ // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation // Default is source-over blendMode:null,stateAnimation:{duration:300,easing:'cubicOut'},animation:'auto',animationDuration:1000,animationDurationUpdate:500,animationEasing:'cubicInOut',animationEasingUpdate:'cubicInOut',animationThreshold:2000,// Configuration for progressive/incremental rendering progressiveThreshold:3000,progressive:400,// Threshold of if use single hover layer to optimize. // It is recommended that `hoverLayerThreshold` is equivalent to or less than // `progressiveThreshold`, otherwise hover will cause restart of progressive, // which is unexpected. // see example . hoverLayerThreshold:3000,// See: module:echarts/scale/Time useUTC:false};var VISUAL_DIMENSIONS=createHashMap(['tooltip','label','itemName','itemId','itemGroupId','seriesName']);var SOURCE_FORMAT_ORIGINAL='original';var SOURCE_FORMAT_ARRAY_ROWS='arrayRows';var SOURCE_FORMAT_OBJECT_ROWS='objectRows';var SOURCE_FORMAT_KEYED_COLUMNS='keyedColumns';var SOURCE_FORMAT_TYPED_ARRAY='typedArray';var SOURCE_FORMAT_UNKNOWN='unknown';var SERIES_LAYOUT_BY_COLUMN='column';var SERIES_LAYOUT_BY_ROW='row';var BE_ORDINAL={Must:1,Might:2,Not:3// Other cases };var innerGlobalModel=makeInner();/** * MUST be called before mergeOption of all series. */function resetSourceDefaulter(ecModel){// `datasetMap` is used to make default encode. innerGlobalModel(ecModel).datasetMap=createHashMap();}/** * [The strategy of the arrengment of data dimensions for dataset]: * "value way": all axes are non-category axes. So series one by one take * several (the number is coordSysDims.length) dimensions from dataset. * The result of data arrengment of data dimensions like: * | ser0_x | ser0_y | ser1_x | ser1_y | ser2_x | ser2_y | * "category way": at least one axis is category axis. So the the first data * dimension is always mapped to the first category axis and shared by * all of the series. The other data dimensions are taken by series like * "value way" does. * The result of data arrengment of data dimensions like: * | ser_shared_x | ser0_y | ser1_y | ser2_y | * * @return encode Never be `null/undefined`. */function makeSeriesEncodeForAxisCoordSys(coordDimensions,seriesModel,source){var encode={};var datasetModel=querySeriesUpstreamDatasetModel(seriesModel);// Currently only make default when using dataset, util more reqirements occur. if(!datasetModel||!coordDimensions){return encode;}var encodeItemName=[];var encodeSeriesName=[];var ecModel=seriesModel.ecModel;var datasetMap=innerGlobalModel(ecModel).datasetMap;var key=datasetModel.uid+'_'+source.seriesLayoutBy;var baseCategoryDimIndex;var categoryWayValueDimStart;coordDimensions=coordDimensions.slice();each$7(coordDimensions,function(coordDimInfoLoose,coordDimIdx){var coordDimInfo=isObject$2(coordDimInfoLoose)?coordDimInfoLoose:coordDimensions[coordDimIdx]={name:coordDimInfoLoose};if(coordDimInfo.type==='ordinal'&&baseCategoryDimIndex==null){baseCategoryDimIndex=coordDimIdx;categoryWayValueDimStart=getDataDimCountOnCoordDim(coordDimInfo);}encode[coordDimInfo.name]=[];});var datasetRecord=datasetMap.get(key)||datasetMap.set(key,{categoryWayDim:categoryWayValueDimStart,valueWayDim:0});// TODO // Auto detect first time axis and do arrangement. each$7(coordDimensions,function(coordDimInfo,coordDimIdx){var coordDimName=coordDimInfo.name;var count=getDataDimCountOnCoordDim(coordDimInfo);// In value way. if(baseCategoryDimIndex==null){var start=datasetRecord.valueWayDim;pushDim(encode[coordDimName],start,count);pushDim(encodeSeriesName,start,count);datasetRecord.valueWayDim+=count;// ??? TODO give a better default series name rule? // especially when encode x y specified. // consider: when mutiple series share one dimension // category axis, series name should better use // the other dimsion name. On the other hand, use // both dimensions name. }// In category way, the first category axis. else if(baseCategoryDimIndex===coordDimIdx){pushDim(encode[coordDimName],0,count);pushDim(encodeItemName,0,count);}// In category way, the other axis. else{var start=datasetRecord.categoryWayDim;pushDim(encode[coordDimName],start,count);pushDim(encodeSeriesName,start,count);datasetRecord.categoryWayDim+=count;}});function pushDim(dimIdxArr,idxFrom,idxCount){for(var i=0;i "other dim" > "the value dim itself". if(isPureNumber&&idxRes0.v==null&&i!==potentialNameDimIndex){idxRes0.v=i;}if(idxRes0.n==null||idxRes0.n===idxRes0.v||!isPureNumber&&guessRecords[idxRes0.n]===BE_ORDINAL.Not){idxRes0.n=i;}if(fulfilled(idxRes0)&&guessRecords[idxRes0.n]!==BE_ORDINAL.Not){return idxRes0;}// [Strategy of idxRes1]: if idxRes0 not satisfied (that is, no BE_ORDINAL.Not), // find the first BE_ORDINAL.Might as the value dim, // and then find a name dim with the priority: // "other dim" > "the value dim itself". // That is for backward compat: number-like (e.g., `'3'`, `'55'`) can be // treated as number. if(!isPureNumber){if(guessResult===BE_ORDINAL.Might&&idxRes1.v==null&&i!==potentialNameDimIndex){idxRes1.v=i;}if(idxRes1.n==null||idxRes1.n===idxRes1.v){idxRes1.n=i;}}}function fulfilled(idxResult){return idxResult.v!=null&&idxResult.n!=null;}return fulfilled(idxRes0)?idxRes0:fulfilled(idxRes1)?idxRes1:null;}();if(idxResult){encode.value=[idxResult.v];// `potentialNameDimIndex` has highest priority. var nameDimIndex=potentialNameDimIndex!=null?potentialNameDimIndex:idxResult.n;// By default, label use itemName in charts. // So we dont set encodeLabel here. encode.itemName=[nameDimIndex];encode.seriesName=[nameDimIndex];}return encode;}/** * @return If return null/undefined, indicate that should not use datasetModel. */function querySeriesUpstreamDatasetModel(seriesModel){// Caution: consider the scenario: // A dataset is declared and a series is not expected to use the dataset, // and at the beginning `setOption({series: { noData })` (just prepare other // option but no data), then `setOption({series: {data: [...]}); In this case, // the user should set an empty array to avoid that dataset is used by default. var thisData=seriesModel.get('data',true);if(!thisData){return queryReferringComponents(seriesModel.ecModel,'dataset',{index:seriesModel.get('datasetIndex',true),id:seriesModel.get('datasetId',true)},SINGLE_REFERRING).models[0];}}/** * @return Always return an array event empty. */function queryDatasetUpstreamDatasetModels(datasetModel){// Only these attributes declared, we by defualt reference to `datasetIndex: 0`. // Otherwise, no reference. if(!datasetModel.get('transform',true)&&!datasetModel.get('fromTransformResult',true)){return[];}return queryReferringComponents(datasetModel.ecModel,'dataset',{index:datasetModel.get('fromDatasetIndex',true),id:datasetModel.get('fromDatasetId',true)},SINGLE_REFERRING).models;}/** * The rule should not be complex, otherwise user might not * be able to known where the data is wrong. * The code is ugly, but how to make it neat? */function guessOrdinal(source,dimIndex){return doGuessOrdinal(source.data,source.sourceFormat,source.seriesLayoutBy,source.dimensionsDefine,source.startIndex,dimIndex);}// dimIndex may be overflow source data. // return {BE_ORDINAL} function doGuessOrdinal(data,sourceFormat,seriesLayoutBy,dimensionsDefine,startIndex,dimIndex){var result;// Experience value. var maxLoop=5;if(isTypedArray(data)){return BE_ORDINAL.Not;}// When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine // always exists in source. var dimName;var dimType;if(dimensionsDefine){var dimDefItem=dimensionsDefine[dimIndex];if(isObject$2(dimDefItem)){dimName=dimDefItem.name;dimType=dimDefItem.type;}else if(isString(dimDefItem)){dimName=dimDefItem;}}if(dimType!=null){return dimType==='ordinal'?BE_ORDINAL.Must:BE_ORDINAL.Not;}if(sourceFormat===SOURCE_FORMAT_ARRAY_ROWS){var dataArrayRows=data;if(seriesLayoutBy===SERIES_LAYOUT_BY_ROW){var sample=dataArrayRows[dimIndex];for(var i=0;i<(sample||[]).length&&irequestColorNum){return palettes[i];}}return palettes[paletteNum-1];}/** * @param name MUST NOT be null/undefined. Otherwise call this function * twise with the same parameters will get different result. * @param scope default this. * @return Can be null/undefined */function getFromPalette(that,inner,defaultPalette,layeredPalette,name,scope,requestNum){scope=scope||that;var scopeFields=inner(scope);var paletteIdx=scopeFields.paletteIdx||0;var paletteNameMap=scopeFields.paletteNameMap=scopeFields.paletteNameMap||{};// Use `hasOwnProperty` to avoid conflict with Object.prototype. if(paletteNameMap.hasOwnProperty(name)){return paletteNameMap[name];}var palette=requestNum==null||!layeredPalette?defaultPalette:getNearestPalette(layeredPalette,requestNum);// In case can't find in layered color palette. palette=palette||defaultPalette;if(!palette||!palette.length){return;}var pickedPaletteItem=palette[paletteIdx];if(name){paletteNameMap[name]=pickedPaletteItem;}scopeFields.paletteIdx=(paletteIdx+1)%palette.length;return pickedPaletteItem;}function clearPalette(that,inner){inner(that).paletteIdx=0;inner(that).paletteNameMap={};}// Internal method names: // ----------------------- var reCreateSeriesIndices;var assertSeriesInitialized;var initBase;var OPTION_INNER_KEY='\0_ec_inner';var OPTION_INNER_VALUE=1;var GlobalModel=/** @class */function(_super){__extends$1(GlobalModel,_super);function GlobalModel(){return _super!==null&&_super.apply(this,arguments)||this;}GlobalModel.prototype.init=function(option,parentModel,ecModel,theme,locale,optionManager){theme=theme||{};this.option=null;// Mark as not initialized. this._theme=new Model$1(theme);this._locale=new Model$1(locale);this._optionManager=optionManager;};GlobalModel.prototype.setOption=function(option,opts,optionPreprocessorFuncs){var innerOpt=normalizeSetOptionInput(opts);this._optionManager.setOption(option,optionPreprocessorFuncs,innerOpt);this._resetOption(null,innerOpt);};/** * @param type null/undefined: reset all. * 'recreate': force recreate all. * 'timeline': only reset timeline option * 'media': only reset media query option * @return Whether option changed. */GlobalModel.prototype.resetOption=function(type,opt){return this._resetOption(type,normalizeSetOptionInput(opt));};GlobalModel.prototype._resetOption=function(type,opt){var optionChanged=false;var optionManager=this._optionManager;if(!type||type==='recreate'){var baseOption=optionManager.mountOption(type==='recreate');if(!this.option||type==='recreate'){initBase(this,baseOption);}else{this.restoreData();this._mergeOption(baseOption,opt);}optionChanged=true;}if(type==='timeline'||type==='media'){this.restoreData();}// By design, if `setOption(option2)` at the second time, and `option2` is a `ECUnitOption`, // it should better not have the same props with `MediaUnit['option']`. // Becuase either `option2` or `MediaUnit['option']` will be always merged to "current option" // rather than original "baseOption". If they both override a prop, the result might be // unexpected when media state changed after `setOption` called. // If we really need to modify a props in each `MediaUnit['option']`, use the full version // (`{baseOption, media}`) in `setOption`. // For `timeline`, the case is the same. if(!type||type==='recreate'||type==='timeline'){var timelineOption=optionManager.getTimelineOption(this);if(timelineOption){optionChanged=true;this._mergeOption(timelineOption,opt);}}if(!type||type==='recreate'||type==='media'){var mediaOptions=optionManager.getMediaOption(this);if(mediaOptions.length){each$7(mediaOptions,function(mediaOption){optionChanged=true;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;var componentsMap=this._componentsMap;var componentsCount=this._componentsCount;var newCmptTypes=[];var newCmptTypeMap=createHashMap();var replaceMergeMainTypeMap=opt&&opt.replaceMergeMainTypeMap;resetSourceDefaulter(this);// If no component class, merge directly. // For example: color, animaiton options, etc. each$7(newOption,function(componentOption,mainType){if(componentOption==null){return;}if(!ComponentModel$1.hasClass(mainType)){// globalSettingTask.dirty(); option[mainType]=option[mainType]==null?clone$3(componentOption):merge(option[mainType],componentOption,true);}else if(mainType){newCmptTypes.push(mainType);newCmptTypeMap.set(mainType,true);}});if(replaceMergeMainTypeMap){// If there is a mainType `xxx` in `replaceMerge` but not declared in option, // we trade it as it is declared in option as `{xxx: []}`. Because: // (1) for normal merge, `{xxx: null/undefined}` are the same meaning as `{xxx: []}`. // (2) some preprocessor may convert some of `{xxx: null/undefined}` to `{xxx: []}`. replaceMergeMainTypeMap.each(function(val,mainTypeInReplaceMerge){if(ComponentModel$1.hasClass(mainTypeInReplaceMerge)&&!newCmptTypeMap.get(mainTypeInReplaceMerge)){newCmptTypes.push(mainTypeInReplaceMerge);newCmptTypeMap.set(mainTypeInReplaceMerge,true);}});}ComponentModel$1.topologicalTravel(newCmptTypes,ComponentModel$1.getAllClassMainTypes(),visitComponent,this);function visitComponent(mainType){var newCmptOptionList=concatInternalOptions(this,mainType,normalizeToArray(newOption[mainType]));var oldCmptList=componentsMap.get(mainType);var mergeMode=// `!oldCmptList` means init. See the comment in `mappingToExists` !oldCmptList?'replaceAll':replaceMergeMainTypeMap&&replaceMergeMainTypeMap.get(mainType)?'replaceMerge':'normalMerge';var mappingResult=mappingToExists(oldCmptList,newCmptOptionList,mergeMode);// Set mainType and complete subType. setComponentTypeToKeyInfo(mappingResult,mainType,ComponentModel$1);// Empty it before the travel, in order to prevent `this._componentsMap` // from being used in the `init`/`mergeOption`/`optionUpdated` of some // components, which is probably incorrect logic. option[mainType]=null;componentsMap.set(mainType,null);componentsCount.set(mainType,0);var optionsByMainType=[];var cmptsByMainType=[];var cmptsCountByMainType=0;var tooltipExists;each$7(mappingResult,function(resultItem,index){var componentModel=resultItem.existing;var newCmptOption=resultItem.newOption;if(!newCmptOption){if(componentModel){// Consider where is no new option and should be merged using {}, // see removeEdgeAndAdd in topologicalTravel and // ComponentModel.getAllClassMainTypes. componentModel.mergeOption({},this);componentModel.optionUpdated({},false);}// If no both `resultItem.exist` and `resultItem.option`, // either it is in `replaceMerge` and not matched by any id, // or it has been removed in previous `replaceMerge` and left a "hole" in this component index. }else{var isSeriesType=mainType==='series';var ComponentModelClass=ComponentModel$1.getClass(mainType,resultItem.keyInfo.subType,!isSeriesType// Give a more detailed warn later if series don't exists );if(!ComponentModelClass){return;}// TODO Before multiple tooltips get supported, we do this check to avoid unexpected exception. if(mainType==='tooltip'){if(tooltipExists){return;}tooltipExists=true;}if(componentModel&&componentModel.constructor===ComponentModelClass){componentModel.name=resultItem.keyInfo.name;// componentModel.settingTask && componentModel.settingTask.dirty(); componentModel.mergeOption(newCmptOption,this);componentModel.optionUpdated(newCmptOption,false);}else{// PENDING Global as parent ? var extraOpt=extend({componentIndex:index},resultItem.keyInfo);componentModel=new ComponentModelClass(newCmptOption,this,this,extraOpt);// Assign `keyInfo` extend(componentModel,extraOpt);if(resultItem.brandNew){componentModel.__requireNewView=true;}componentModel.init(newCmptOption,this,this);// Call optionUpdated after init. // newCmptOption has been used as componentModel.option // and may be merged with theme and default, so pass null // to avoid confusion. componentModel.optionUpdated(null,true);}}if(componentModel){optionsByMainType.push(componentModel.option);cmptsByMainType.push(componentModel);cmptsCountByMainType++;}else{// Always do assign to avoid elided item in array. optionsByMainType.push(void 0);cmptsByMainType.push(void 0);}},this);option[mainType]=optionsByMainType;componentsMap.set(mainType,cmptsByMainType);componentsCount.set(mainType,cmptsCountByMainType);// Backup series for filtering. if(mainType==='series'){reCreateSeriesIndices(this);}}// If no series declared, ensure `_seriesIndices` initialized. if(!this._seriesIndices){reCreateSeriesIndices(this);}};/** * Get option for output (cloned option and inner info removed) */GlobalModel.prototype.getOption=function(){var option=clone$3(this.option);each$7(option,function(optInMainType,mainType){if(ComponentModel$1.hasClass(mainType)){var opts=normalizeToArray(optInMainType);// Inner cmpts need to be removed. // Inner cmpts might not be at last since ec5.0, but still // compatible for users: if inner cmpt at last, splice the returned array. var realLen=opts.length;var metNonInner=false;for(var i=realLen-1;i>=0;i--){// Remove options with inner id. if(opts[i]&&!isComponentIdInternal(opts[i])){metNonInner=true;}else{opts[i]=null;!metNonInner&&realLen--;}}opts.length=realLen;option[mainType]=opts;}});delete option[OPTION_INNER_KEY];return option;};GlobalModel.prototype.getTheme=function(){return this._theme;};GlobalModel.prototype.getLocaleModel=function(){return this._locale;};GlobalModel.prototype.setUpdatePayload=function(payload){this._payload=payload;};GlobalModel.prototype.getUpdatePayload=function(){return this._payload;};/** * @param idx If not specified, return the first one. */GlobalModel.prototype.getComponent=function(mainType,idx){var list=this._componentsMap.get(mainType);if(list){var cmpt=list[idx||0];if(cmpt){return cmpt;}else if(idx==null){for(var i=0;i; /** * TERM EXPLANATIONS: * See `ECOption` and `ECUnitOption` in `src/util/types.ts`. */var OptionManager=/** @class */function(){// timeline.notMerge is not supported in ec3. Firstly there is rearly // case that notMerge is needed. Secondly supporting 'notMerge' requires // rawOption cloned and backuped when timeline changed, which does no // good to performance. What's more, that both timeline and setOption // method supply 'notMerge' brings complex and some problems. // Consider this case: // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false); // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false); function OptionManager(api){this._timelineOptions=[];this._mediaList=[];/** * -1, means default. * empty means no media. */this._currentMediaIndices=[];this._api=api;}OptionManager.prototype.setOption=function(rawOption,optionPreprocessorFuncs,opt){if(rawOption){// That set dat primitive is dangerous if user reuse the data when setOption again. each$7(normalizeToArray(rawOption.series),function(series){series&&series.data&&isTypedArray(series.data)&&setAsPrimitive(series.data);});each$7(normalizeToArray(rawOption.dataset),function(dataset){dataset&&dataset.source&&isTypedArray(dataset.source)&&setAsPrimitive(dataset.source);});}// Caution: some series modify option data, if do not clone, // it should ensure that the repeat modify correctly // (create a new object when modify itself). rawOption=clone$3(rawOption);// FIXME // If some property is set in timeline options or media option but // not set in baseOption, a warning should be given. var optionBackup=this._optionBackup;var newParsedOption=parseRawOption(rawOption,optionPreprocessorFuncs,!optionBackup);this._newBaseOption=newParsedOption.baseOption;// For setOption at second time (using merge mode); if(optionBackup){// FIXME // the restore merge solution is essentially incorrect. // the mapping can not be 100% consistent with ecModel, which probably brings // potential bug! // The first merge is delayed, becuase in most cases, users do not call `setOption` twice. // let fakeCmptsMap = this._fakeCmptsMap; // if (!fakeCmptsMap) { // fakeCmptsMap = this._fakeCmptsMap = createHashMap(); // mergeToBackupOption(fakeCmptsMap, null, optionBackup.baseOption, null); // } // mergeToBackupOption( // fakeCmptsMap, optionBackup.baseOption, newParsedOption.baseOption, opt // ); // For simplicity, timeline options and media options do not support merge, // that is, if you `setOption` twice and both has timeline options, the latter // timeline opitons will not be merged to the formers, but just substitude them. if(newParsedOption.timelineOptions.length){optionBackup.timelineOptions=newParsedOption.timelineOptions;}if(newParsedOption.mediaList.length){optionBackup.mediaList=newParsedOption.mediaList;}if(newParsedOption.mediaDefault){optionBackup.mediaDefault=newParsedOption.mediaDefault;}}else{this._optionBackup=newParsedOption;}};OptionManager.prototype.mountOption=function(isRecreate){var optionBackup=this._optionBackup;this._timelineOptions=optionBackup.timelineOptions;this._mediaList=optionBackup.mediaList;this._mediaDefault=optionBackup.mediaDefault;this._currentMediaIndices=[];return clone$3(isRecreate// this._optionBackup.baseOption, which is created at the first `setOption` // called, and is merged into every new option by inner method `mergeToBackupOption` // each time `setOption` called, can be only used in `isRecreate`, because // its reliability is under suspicion. In other cases option merge is // performed by `model.mergeOption`. ?optionBackup.baseOption:this._newBaseOption);};OptionManager.prototype.getTimelineOption=function(ecModel){var option;var timelineOptions=this._timelineOptions;if(timelineOptions.length){// getTimelineOption can only be called after ecModel inited, // so we can get currentIndex from timelineModel. var timelineModel=ecModel.getComponent('timeline');if(timelineModel){option=clone$3(// FIXME:TS as TimelineModel or quivlant interface timelineOptions[timelineModel.getCurrentIndex()]);}}return option;};OptionManager.prototype.getMediaOption=function(ecModel){var ecWidth=this._api.getWidth();var ecHeight=this._api.getHeight();var mediaList=this._mediaList;var mediaDefault=this._mediaDefault;var indices=[];var result=[];// No media defined. if(!mediaList.length&&!mediaDefault){return result;}// Multi media may be applied, the latter defined media has higher priority. for(var i=0,len=mediaList.length;i * Support: width, height, aspectRatio * Can use max or min as prefix. */function applyMediaQuery(query,ecWidth,ecHeight){var realMap={width:ecWidth,height:ecHeight,aspectratio:ecWidth/ecHeight// lowser case for convenientce. };var applicatable=true;each$7(query,function(value,attr){var matched=attr.match(QUERY_REG);if(!matched||!matched[1]||!matched[2]){return;}var operator=matched[1];var realAttr=matched[2].toLowerCase();if(!compare(realMap[realAttr],value,operator)){applicatable=false;}});return applicatable;}function compare(real,expect,operator){if(operator==='min'){return real>=expect;}else if(operator==='max'){return real<=expect;}else{// Equals return real===expect;}}function indicesEquals(indices1,indices2){// indices is always order by asc and has only finite number. return indices1.join(',')===indices2.join(',');}/** * Consider case: * `chart.setOption(opt1);` * Then user do some interaction like dataZoom, dataView changing. * `chart.setOption(opt2);` * Then user press 'reset button' in toolbox. * * After doing that all of the interaction effects should be reset, the * chart should be the same as the result of invoke * `chart.setOption(opt1); chart.setOption(opt2);`. * * Although it is not able ensure that * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to * `chart.setOption(merge(opt1, opt2));` exactly, * this might be the only simple way to implement that feature. * * MEMO: We've considered some other approaches: * 1. Each model handle its self restoration but not uniform treatment. * (Too complex in logic and error-prone) * 2. Use a shadow ecModel. (Performace expensive) * * FIXME: A possible solution: * Add a extra level of model for each component model. The inheritance chain would be: * ecModel <- componentModel <- componentActionModel <- dataItemModel * And all of the actions can only modify the `componentActionModel` rather than * `componentModel`. `setOption` will only modify the `ecModel` and `componentModel`. * When "resotre" action triggered, model from `componentActionModel` will be discarded * instead of recreating the "ecModel" from the "_optionBackup". */ // function mergeToBackupOption( // fakeCmptsMap: FakeComponentsMap, // // `tarOption` Can be null/undefined, means init // tarOption: ECUnitOption, // newOption: ECUnitOption, // // Can be null/undefined // opt: InnerSetOptionOpts // ): void { // newOption = newOption || {} as ECUnitOption; // const notInit = !!tarOption; // each(newOption, function (newOptsInMainType, mainType) { // if (newOptsInMainType == null) { // return; // } // if (!ComponentModel.hasClass(mainType)) { // if (tarOption) { // tarOption[mainType] = merge(tarOption[mainType], newOptsInMainType, true); // } // } // else { // const oldTarOptsInMainType = notInit ? normalizeToArray(tarOption[mainType]) : null; // const oldFakeCmptsInMainType = fakeCmptsMap.get(mainType) || []; // const resultTarOptsInMainType = notInit ? (tarOption[mainType] = [] as ComponentOption[]) : null; // const resultFakeCmptsInMainType = fakeCmptsMap.set(mainType, []); // const mappingResult = mappingToExists( // oldFakeCmptsInMainType, // normalizeToArray(newOptsInMainType), // (opt && opt.replaceMergeMainTypeMap.get(mainType)) ? 'replaceMerge' : 'normalMerge' // ); // setComponentTypeToKeyInfo(mappingResult, mainType, ComponentModel as ComponentModelConstructor); // each(mappingResult, function (resultItem, index) { // // The same logic as `Global.ts#_mergeOption`. // let fakeCmpt = resultItem.existing; // const newOption = resultItem.newOption; // const keyInfo = resultItem.keyInfo; // let fakeCmptOpt; // if (!newOption) { // fakeCmptOpt = oldTarOptsInMainType[index]; // } // else { // if (fakeCmpt && fakeCmpt.subType === keyInfo.subType) { // fakeCmpt.name = keyInfo.name; // if (notInit) { // fakeCmptOpt = merge(oldTarOptsInMainType[index], newOption, true); // } // } // else { // fakeCmpt = extend({}, keyInfo); // if (notInit) { // fakeCmptOpt = clone(newOption); // } // } // } // if (fakeCmpt) { // notInit && resultTarOptsInMainType.push(fakeCmptOpt); // resultFakeCmptsInMainType.push(fakeCmpt); // } // else { // notInit && resultTarOptsInMainType.push(void 0); // resultFakeCmptsInMainType.push(void 0); // } // }); // } // }); // } var OptionManager$1=OptionManager;var each$5=each$7;var isObject$1=isObject$2;var POSSIBLE_STYLES=['areaStyle','lineStyle','nodeStyle','linkStyle','chordStyle','label','labelLine'];function compatEC2ItemStyle(opt){var itemStyleOpt=opt&&opt.itemStyle;if(!itemStyleOpt){return;}for(var i=0,len=POSSIBLE_STYLES.length;i // (2) Only register once when import repeatedly. // Should be executed after series is filtered and before stack calculation. function dataStack(ecModel){var stackInfoMap=createHashMap();ecModel.eachSeries(function(seriesModel){var stack=seriesModel.get('stack');// Compatible: when `stack` is set as '', do not stack. if(stack){var stackInfoList=stackInfoMap.get(stack)||stackInfoMap.set(stack,[]);var data=seriesModel.getData();var stackInfo={// Used for calculate axis extent automatically. // TODO: Type getCalculationInfo return more specific type? 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 stacked on axis that do not support data stack. if(!stackInfo.stackedDimension||!(stackInfo.isStackedByIndex||stackInfo.stackedByDimension)){return;}stackInfoList.length&&data.setCalculationInfo('stackedOnSeries',stackInfoList[stackInfoList.length-1].seriesModel);stackInfoList.push(stackInfo);}});stackInfoMap.each(calculateStack);}function calculateStack(stackInfoList){each$7(stackInfoList,function(targetStackInfo,idxInStack){var resultVal=[];var resultNaN=[NaN,NaN];var dims=[targetStackInfo.stackResultDimension,targetStackInfo.stackedOverDimension];var targetData=targetStackInfo.data;var isStackedByIndex=targetStackInfo.isStackedByIndex;var stackStrategy=targetStackInfo.seriesModel.get('stackStrategy')||'samesign';// Should not write on raw data, because stack series model list changes // depending on legend selection. targetData.modify(dims,function(v0,v1,dataIndex){var sum=targetData.get(targetStackInfo.stackedDimension,dataIndex);// Consider `connectNulls` of line area, if value is NaN, stackedOver // should also be NaN, to draw a appropriate belt area. if(isNaN(sum)){return resultNaN;}var byValue;var stackedDataRawIndex;if(isStackedByIndex){stackedDataRawIndex=targetData.getRawIndex(dataIndex);}else{byValue=targetData.get(targetStackInfo.stackedByDimension,dataIndex);}// If stackOver is NaN, chart view will render point on value start. var stackedOver=NaN;for(var j=idxInStack-1;j>=0;j--){var stackInfo=stackInfoList[j];// Has been optimized by inverted indices on `stackedByDimension`. if(!isStackedByIndex){stackedDataRawIndex=stackInfo.data.rawIndexOf(stackInfo.stackedByDimension,byValue);}if(stackedDataRawIndex>=0){var val=stackInfo.data.getByRawIndex(stackInfo.stackResultDimension,stackedDataRawIndex);// Considering positive stack, negative stack and empty data if(stackStrategy==='all'// single stack group ||stackStrategy==='positive'&&val>0||stackStrategy==='negative'&&val<0||stackStrategy==='samesign'&&sum>=0&&val>0// All positive stack ||stackStrategy==='samesign'&&sum<=0&&val<0// All negative stack ){// The sum has to be very small to be affected by the // floating arithmetic problem. An incorrect result will probably // cause axis min/max to be filtered incorrectly. sum=addSafe(sum,val);stackedOver=val;break;}}}resultVal[0]=sum;resultVal[1]=stackedOver;return resultVal;});});}var SourceImpl=/** @class */function(){function SourceImpl(fields){this.data=fields.data||(fields.sourceFormat===SOURCE_FORMAT_KEYED_COLUMNS?{}:[]);this.sourceFormat=fields.sourceFormat||SOURCE_FORMAT_UNKNOWN;// Visit config this.seriesLayoutBy=fields.seriesLayoutBy||SERIES_LAYOUT_BY_COLUMN;this.startIndex=fields.startIndex||0;this.dimensionsDetectedCount=fields.dimensionsDetectedCount;this.metaRawOption=fields.metaRawOption;var dimensionsDefine=this.dimensionsDefine=fields.dimensionsDefine;if(dimensionsDefine){for(var i=0;imax&&(max=val);}dimExtent[0]=min;dimExtent[1]=max;}};var countForTypedArray=function countForTypedArray(){return this._data?this._data.length/this._dimSize:0;};providerMethods=(_a={},_a[SOURCE_FORMAT_ARRAY_ROWS+'_'+SERIES_LAYOUT_BY_COLUMN]={pure:true,appendData:appendDataSimply},_a[SOURCE_FORMAT_ARRAY_ROWS+'_'+SERIES_LAYOUT_BY_ROW]={pure:true,appendData:function appendData(){throw new Error('Do not support appendData when set seriesLayoutBy: "row".');}},_a[SOURCE_FORMAT_OBJECT_ROWS]={pure:true,appendData:appendDataSimply},_a[SOURCE_FORMAT_KEYED_COLUMNS]={pure:true,appendData:function appendData(newData){var data=this._data;each$7(newData,function(newCol,key){var oldCol=data[key]||(data[key]=[]);for(var i=0;i<(newCol||[]).length;i++){oldCol.push(newCol[i]);}});}},_a[SOURCE_FORMAT_ORIGINAL]={appendData:appendDataSimply},_a[SOURCE_FORMAT_TYPED_ARRAY]={persistent:false,pure:true,appendData:function appendData(newData){this._data=newData;},// Clean self if data is already used. clean:function clean(){// PENDING this._offset+=this.count();this._data=null;}},_a);function appendDataSimply(newData){for(var i=0;i 0 }var val=retrieveRawValue(data,dataIndex,dimLoose);if(extendParams&&isArray(extendParams.interpolatedValue)){var dimIndex=data.getDimensionIndex(dimLoose);if(dimIndex>=0){val=extendParams.interpolatedValue[dimIndex];}}return val!=null?val+'':'';});}};/** * Get raw value in option */DataFormatMixin.prototype.getRawValue=function(idx,dataType){return retrieveRawValue(this.getData(dataType),idx);};/** * Should be implemented. * @param {number} dataIndex * @param {boolean} [multipleSeries=false] * @param {string} [dataType] */DataFormatMixin.prototype.formatTooltip=function(dataIndex,multipleSeries,dataType){// Empty function return;};return DataFormatMixin;}();// but guess little chance has been used outside. Do we need to backward // compat it? // type TooltipFormatResultLegacyObject = { // // `html` means the markup language text, either in 'html' or 'richText'. // // The name `html` is not appropriate becuase in 'richText' it is not a HTML // // string. But still support it for backward compat. // html: string; // markers: Dictionary; // }; /** * For backward compat, normalize the return from `formatTooltip`. */function normalizeTooltipFormatResult(result){var markupText;// let markers: Dictionary; var markupFragment;if(isObject$2(result)){if(result.type){markupFragment=result;}// else { // markupText = (result as TooltipFormatResultLegacyObject).html; // markers = (result as TooltipFormatResultLegacyObject).markers; // if (markersExisting) { // markers = zrUtil.merge(markersExisting, markers); // } // } }else{markupText=result;}return{text:markupText,// markers: markers || markersExisting, frag:markupFragment};}/** * @param {Object} define * @return See the return of `createTask`. */function createTask(define){return new Task(define);}var Task=/** @class */function(){function Task(define){define=define||{};this._reset=define.reset;this._plan=define.plan;this._count=define.count;this._onDirty=define.onDirty;this._dirty=true;}/** * @param step Specified step. * @param skip Skip customer perform call. * @param modBy Sampling window size. * @param modDataCount Sampling count. * @return whether unfinished. */Task.prototype.perform=function(performArgs){var upTask=this._upstream;var skip=performArgs&&performArgs.skip;// TODO some refactor. // Pull data. Must pull data each time, because context.data // may be updated by Series.setData. if(this._dirty&&upTask){var context=this.context;context.data=context.outputData=upTask.context.outputData;}if(this.__pipeline){this.__pipeline.currentTask=this;}var planResult;if(this._plan&&!skip){planResult=this._plan(this.context);}// Support sharding by mod, which changes the render sequence and makes the rendered graphic // elements uniformed distributed when progress, especially when moving or zooming. var lastModBy=normalizeModBy(this._modBy);var lastModDataCount=this._modDataCount||0;var modBy=normalizeModBy(performArgs&&performArgs.modBy);var modDataCount=performArgs&&performArgs.modDataCount||0;if(lastModBy!==modBy||lastModDataCount!==modDataCount){planResult='reset';}function normalizeModBy(val){!(val>=1)&&(val=1);// jshint ignore:line return val;}var forceFirstProgress;if(this._dirty||planResult==='reset'){this._dirty=false;forceFirstProgress=this._doReset(skip);}this._modBy=modBy;this._modDataCount=modDataCount;var step=performArgs&&performArgs.step;if(upTask){this._dueEnd=upTask._outputDueEnd;}// DataTask or overallTask else{this._dueEnd=this._count?this._count(this.context):Infinity;}// Note: Stubs, that its host overall task let it has progress, has progress. // If no progress, pass index from upstream to downstream each time plan called. if(this._progress){var start=this._dueIndex;var end=Math.min(step!=null?this._dueIndex+step:Infinity,this._dueEnd);if(!skip&&(forceFirstProgress||start1&&modDataCount>0?modNext:sequentialNext;}};return it;function sequentialNext(){return current=end?null:dataIndex stubCount++); // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`}); // } // props.push({text: 'uid', value: task.uidDebug}); // if (task.__pipeline) { // props.push({text: 'pipelineId', value: task.__pipeline.id}); // task.agent && props.push( // {text: 'stubFor', value: task.agent.uidDebug} // ); // } // props.push( // {text: 'dirty', value: task._dirty}, // {text: 'dueIndex', value: task._dueIndex}, // {text: 'dueEnd', value: task._dueEnd}, // {text: 'outputDueEnd', value: task._outputDueEnd} // ); // if (extra) { // Object.keys(extra).forEach(key => { // props.push({text: key, value: extra[key]}); // }); // } // let args = ['color: blue']; // let msg = `%c[${prefix || 'T'}] %c` + props.map(item => ( // args.push('color: green', 'color: red'), // `${item.text}: %c${item.value}` // )).join('%c, '); // console.log.apply(console, [msg].concat(args)); // // console.log(this); // }; // window.printPipeline = function (task: any, prefix: string) { // const pipeline = task.__pipeline; // let currTask = pipeline.head; // while (currTask) { // window.printTask(currTask, prefix); // currTask = currTask._downstream; // } // }; // window.showChain = function (chainHeadTask) { // var chain = []; // var task = chainHeadTask; // while (task) { // chain.push({ // task: task, // up: task._upstream, // down: task._downstream, // idxInPipeline: task.__idxInPipeline // }); // task = task._downstream; // } // return chain; // }; // window.findTaskInChain = function (task, chainHeadTask) { // let chain = window.showChain(chainHeadTask); // let result = []; // for (let i = 0; i < chain.length; i++) { // let chainItem = chain[i]; // if (chainItem.task === task) { // result.push(i); // } // } // return result; // }; // window.printChainAEachInChainB = function (chainHeadTaskA, chainHeadTaskB) { // let chainA = window.showChain(chainHeadTaskA); // for (let i = 0; i < chainA.length; i++) { // console.log('chainAIdx:', i, 'inChainB:', window.findTaskInChain(chainA[i].task, chainHeadTaskB)); // } // }; /** * Convert raw the value in to inner value in List. * * [Performance sensitive] * * [Caution]: this is the key logic of user value parser. * For backward compatibiliy, do not modify it until have to! */function parseDataValue(value,// For high performance, do not omit the second param. opt){// Performance sensitive. var dimType=opt&&opt.type;if(dimType==='ordinal'){// If given value is a category string return value;}if(dimType==='time'// spead up when using timestamp &&!isNumber(value)&&value!=null&&value!=='-'){value=+parseDate(value);}// dimType defaults 'number'. // If dimType is not ordinal and value is null or undefined or NaN or '-', // parse to NaN. // number-like string (like ' 123 ') can be converted to a number. // where null/undefined or other string will be converted to NaN. return value==null||value===''?NaN// If string (like '-'), using '+' parse to NaN // If object, also parse to NaN :+value;}var valueParserMap=createHashMap({'number':function number(val){// Do not use `numericToNumber` here. We have by defualt `numericToNumber`. // Here the number parser can have loose rule: // enable to cut suffix: "120px" => 120, "14%" => 14. return parseFloat(val);},'time':function time(val){// return timestamp. return+parseDate(val);},'trim':function trim(val){return isString(val)?trim$1(val):val;}});function getRawValueParser(type){return valueParserMap.get(type);}var ORDER_COMPARISON_OP_MAP={lt:function lt(lval,rval){return lvalrval;},gte:function gte(lval,rval){return lval>=rval;}};var FilterOrderComparator=/** @class */function(){function FilterOrderComparator(op,rval){if(!isNumber(rval)){var errMsg='';throwError(errMsg);}this._opFn=ORDER_COMPARISON_OP_MAP[op];this._rvalFloat=numericToNumber(rval);}// Performance sensitive. FilterOrderComparator.prototype.evaluate=function(lval){// Most cases is 'number', and typeof maybe 10 times faseter than parseFloat. return isNumber(lval)?this._opFn(lval,this._rvalFloat):this._opFn(numericToNumber(lval),this._rvalFloat);};return FilterOrderComparator;}();var SortOrderComparator=/** @class */function(){/** * @param order by defualt: 'asc' * @param incomparable by defualt: Always on the tail. * That is, if 'asc' => 'max', if 'desc' => 'min' * See the definition of "incomparable" in [SORT_COMPARISON_RULE] */function SortOrderComparator(order,incomparable){var isDesc=order==='desc';this._resultLT=isDesc?1:-1;if(incomparable==null){incomparable=isDesc?'min':'max';}this._incomparable=incomparable==='min'?-Infinity:Infinity;}// See [SORT_COMPARISON_RULE]. // Performance sensitive. SortOrderComparator.prototype.evaluate=function(lval,rval){// Most cases is 'number', and typeof maybe 10 times faseter than parseFloat. var lvalFloat=isNumber(lval)?lval:numericToNumber(lval);var rvalFloat=isNumber(rval)?rval:numericToNumber(rval);var lvalNotNumeric=isNaN(lvalFloat);var rvalNotNumeric=isNaN(rvalFloat);if(lvalNotNumeric){lvalFloat=this._incomparable;}if(rvalNotNumeric){rvalFloat=this._incomparable;}if(lvalNotNumeric&&rvalNotNumeric){var lvalIsStr=isString(lval);var rvalIsStr=isString(rval);if(lvalIsStr){lvalFloat=rvalIsStr?lval:0;}if(rvalIsStr){rvalFloat=lvalIsStr?rval:0;}}return lvalFloatrvalFloat?-this._resultLT:0;};return SortOrderComparator;}();var FilterEqualityComparator=/** @class */function(){function FilterEqualityComparator(isEq,rval){this._rval=rval;this._isEQ=isEq;this._rvalTypeof=_typeof(rval);this._rvalFloat=numericToNumber(rval);}// Performance sensitive. FilterEqualityComparator.prototype.evaluate=function(lval){var eqResult=lval===this._rval;if(!eqResult){var lvalTypeof=_typeof(lval);if(lvalTypeof!==this._rvalTypeof&&(lvalTypeof==='number'||this._rvalTypeof==='number')){eqResult=numericToNumber(lval)===this._rvalFloat;}}return this._isEQ?eqResult:!eqResult;};return FilterEqualityComparator;}();/** * [FILTER_COMPARISON_RULE] * `lt`|`lte`|`gt`|`gte`: * + rval must be a number. And lval will be converted to number (`numericToNumber`) to compare. * `eq`: * + If same type, compare with `===`. * + If there is one number, convert to number (`numericToNumber`) to compare. * + Else return `false`. * `ne`: * + Not `eq`. * * * [SORT_COMPARISON_RULE] * All the values are grouped into three categories: * + "numeric" (number and numeric string) * + "non-numeric-string" (string that excluding numeric string) * + "others" * "numeric" vs "numeric": values are ordered by number order. * "non-numeric-string" vs "non-numeric-string": values are ordered by ES spec (#sec-abstract-relational-comparison). * "others" vs "others": do not change order (always return 0). * "numeric" vs "non-numeric-string": "non-numeric-string" is treated as "incomparable". * "number" vs "others": "others" is treated as "incomparable". * "non-numeric-string" vs "others": "others" is treated as "incomparable". * "incomparable" will be seen as -Infinity or Infinity (depends on the settings). * MEMO: * non-numeric string sort make sence when need to put the items with the same tag together. * But if we support string sort, we still need to avoid the misleading like `'2' > '12'`, * So we treat "numeric-string" sorted by number order rather than string comparison. * * * [CHECK_LIST_OF_THE_RULE_DESIGN] * + Do not support string comparison until required. And also need to * void the misleading of "2" > "12". * + Should avoid the misleading case: * `" 22 " gte "22"` is `true` but `" 22 " eq "22"` is `false`. * + JS bad case should be avoided: null <= 0, [] <= 0, ' ' <= 0, ... * + Only "numeric" can be converted to comparable number, otherwise converted to NaN. * See `util/number.ts#numericToNumber`. * * @return If `op` is not `RelationalOperator`, return null; */function createFilterComparator(op,rval){return op==='eq'||op==='ne'?new FilterEqualityComparator(op==='eq',rval):hasOwn(ORDER_COMPARISON_OP_MAP,op)?new FilterOrderComparator(op,rval):null;}/** * TODO: disable writable. * This structure will be exposed to users. */var ExternalSource=/** @class */function(){function ExternalSource(){}ExternalSource.prototype.getRawData=function(){// Only built-in transform available. throw new Error('not supported');};ExternalSource.prototype.getRawDataItem=function(dataIndex){// Only built-in transform available. throw new Error('not supported');};ExternalSource.prototype.cloneRawData=function(){return;};/** * @return If dimension not found, return null/undefined. */ExternalSource.prototype.getDimensionInfo=function(dim){return;};/** * dimensions defined if and only if either: * (a) dataset.dimensions are declared. * (b) dataset data include dimensions definitions in data (detected or via specified `sourceHeader`). * If dimensions are defined, `dimensionInfoAll` is corresponding to * the defined dimensions. * Otherwise, `dimensionInfoAll` is determined by data columns. * @return Always return an array (even empty array). */ExternalSource.prototype.cloneAllDimensionInfo=function(){return;};ExternalSource.prototype.count=function(){return;};/** * Only support by dimension index. * No need to support by dimension name in transform function, * becuase transform function is not case-specific, no need to use name literally. */ExternalSource.prototype.retrieveValue=function(dataIndex,dimIndex){return;};ExternalSource.prototype.retrieveValueFromItem=function(dataItem,dimIndex){return;};ExternalSource.prototype.convertValue=function(rawVal,dimInfo){return parseDataValue(rawVal,dimInfo);};return ExternalSource;}();function createExternalSource(internalSource,externalTransform){var extSource=new ExternalSource();var data=internalSource.data;var sourceFormat=extSource.sourceFormat=internalSource.sourceFormat;var sourceHeaderCount=internalSource.startIndex;var errMsg='';if(internalSource.seriesLayoutBy!==SERIES_LAYOUT_BY_COLUMN){throwError(errMsg);}// [MEMO] // Create a new dimensions structure for exposing. // Do not expose all dimension info to users directly. // Becuase the dimension is probably auto detected from data and not might reliable. // Should not lead the transformers to think that is relialbe and return it. // See [DIMENSION_INHERIT_RULE] in `sourceManager.ts`. var dimensions=[];var dimsByName={};var dimsDef=internalSource.dimensionsDefine;if(dimsDef){each$7(dimsDef,function(dimDef,idx){var name=dimDef.name;var dimDefExt={index:idx,name:name,displayName:dimDef.displayName};dimensions.push(dimDefExt);// Users probably not sepcify dimension name. For simplicity, data transform // do not generate dimension name. if(name!=null){// Dimension name should not be duplicated. // For simplicity, data transform forbid name duplication, do not generate // new name like module `completeDimensions.ts` did, but just tell users. var errMsg_1='';if(hasOwn(dimsByName,name)){throwError(errMsg_1);}dimsByName[name]=dimDefExt;}});}// If dimension definitions are not defined and can not be detected. // e.g., pure data `[[11, 22], ...]`. else{for(var i=0;i65535?CtorUint32Array:CtorUint16Array;}function getInitialExtent(){return[Infinity,-Infinity];}function cloneChunk(originalChunk){var Ctor=originalChunk.constructor;// Only shallow clone is enough when Array. return Ctor===Array?originalChunk.slice():new Ctor(originalChunk);}function prepareStore(store,dimIdx,dimType,end,append){var DataCtor=dataCtors[dimType||'float'];if(append){var oldStore=store[dimIdx];var oldLen=oldStore&&oldStore.length;if(!(oldLen===end)){var newStore=new DataCtor(end);// The cost of the copy is probably inconsiderable // within the initial chunkSize. for(var j=0;jdimRawExtent[1]&&(dimRawExtent[1]=val);}}this._rawCount=this._count=end;return{start:start,end:end};};DataStore.prototype._initDataFromProvider=function(start,end,append){var provider=this._provider;var chunks=this._chunks;var dimensions=this._dimensions;var dimLen=dimensions.length;var rawExtent=this._rawExtent;var dimNames=map$1(dimensions,function(dim){return dim.property;});for(var i=0;idimRawExtent[1]&&(dimRawExtent[1]=val);}}}if(!provider.persistent&&provider.clean){// Clean unused data if data source is typed array. provider.clean();}this._rawCount=this._count=end;// Reset data extent this._extent=[];};DataStore.prototype.count=function(){return this._count;};/** * Get value. Return NaN if idx is out of range. */DataStore.prototype.get=function(dim,idx){if(!(idx>=0&&idx=0&&rawIdx=this._rawCount||rawIndex<0){return-1;}if(!this._indices){return rawIndex;}// Indices are ascending var indices=this._indices;// If rawIndex === dataIndex var rawDataIndex=indices[rawIndex];if(rawDataIndex!=null&&rawDataIndexrawIndex){right=mid-1;}else{return mid;}}return-1;};/** * Retreive the index of nearest value * @param dim * @param value * @param [maxDistance=Infinity] * @return If and only if multiple indices has * the same value, they are put to the result. */DataStore.prototype.indicesOfNearest=function(dim,value,maxDistance){var chunks=this._chunks;var dimData=chunks[dim];var nearestIndices=[];if(!dimData){return nearestIndices;}if(maxDistance==null){maxDistance=Infinity;}var minDist=Infinity;var minDiff=-1;var nearestIndicesLen=0;// Check the test case of `test/ut/spec/data/SeriesData.js`. for(var i=0,len=this.count();i= 0` in this csae. // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them // should be push to `nearestIndices`. if(dist=0&&minDiff<0){minDist=dist;minDiff=diff;nearestIndicesLen=0;}if(diff===minDiff){nearestIndices[nearestIndicesLen++]=i;}}}nearestIndices.length=nearestIndicesLen;return nearestIndices;};DataStore.prototype.getIndices=function(){var newIndices;var indices=this._indices;if(indices){var Ctor=indices.constructor;var thisCount=this._count;// `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`. if(Ctor===Array){newIndices=new Ctor(thisCount);for(var i=0;i=min&&val<=max||isNaN(val)){newIndices[offset++]=idx;}idx++;}quickFinished=true;}else if(dimSize===2){var dimStorage=storeArr[dims[0]];var dimStorage2=storeArr[dims[1]];var min2=range[dims[1]][0];var max2=range[dims[1]][1];for(var i=0;i=min&&val<=max||isNaN(val))&&(val2>=min2&&val2<=max2||isNaN(val2))){newIndices[offset++]=idx;}idx++;}quickFinished=true;}}if(!quickFinished){if(dimSize===1){for(var i=0;i=min&&val<=max||isNaN(val)){newIndices[offset++]=rawIndex;}}}else{for(var i=0;irange[dimk][1]){keep=false;}}if(keep){newIndices[offset++]=newStore.getRawIndex(i);}}}}// Set indices after filtered. if(offsetrawExtentOnDim[1]){rawExtentOnDim[1]=val;}}}}};/** * Large data down sampling using largest-triangle-three-buckets * @param {string} valueDimension * @param {number} targetCount */DataStore.prototype.lttbDownSample=function(valueDimension,rate){var target=this.clone([valueDimension],true);var targetStorage=target._chunks;var dimStore=targetStorage[valueDimension];var len=this.count();var sampledIndex=0;var frameSize=Math.floor(1/rate);var currentRawIndex=this.getRawIndex(0);var maxArea;var area;var nextRawIndex;var newIndices=new(getIndicesCtor(this._rawCount))(Math.min((Math.ceil(len/frameSize)+2)*2,len));// First frame use the first data. newIndices[sampledIndex++]=currentRawIndex;for(var i=1;imaxArea){maxArea=area;nextRawIndex=rawIndex;// Next a is this b }}if(countNaN>0&&countNaNlen-i){frameSize=len-i;frameValues.length=frameSize;}for(var k=0;krawExtentOnDim[1]){rawExtentOnDim[1]=value;}newIndices[offset++]=sampleFrameIdx;}target._count=offset;target._indices=newIndices;target._updateGetRawIdx();return target;};/** * Data iteration * @param ctx default this * @example * list.each('x', function (x, idx) {}); * list.each(['x', 'y'], function (x, y, idx) {}); * list.each(function (idx) {}) */DataStore.prototype.each=function(dims,cb){if(!this._count){return;}var dimSize=dims.length;var chunks=this._chunks;for(var i=0,len=this.count();imax&&(max=value);}dimExtent=[min,max];this._extent[dim]=dimExtent;return dimExtent;};/** * Get raw data item */DataStore.prototype.getRawDataItem=function(idx){var rawIdx=this.getRawIndex(idx);if(!this._provider.persistent){var val=[];var chunks=this._chunks;for(var i=0;i=0){return this._indices[idx];}return-1;};DataStore.prototype._updateGetRawIdx=function(){this.getRawIndex=this._indices?this._getRawIdx:this._getRawIdxIdentity;};DataStore.internalField=function(){function getDimValueSimply(dataItem,property,dataIndex,dimIndex){return parseDataValue(dataItem[dimIndex],this._dimensions[dimIndex]);}defaultDimValueGetters={arrayRows:getDimValueSimply,objectRows:function objectRows(dataItem,property,dataIndex,dimIndex){return parseDataValue(dataItem[property],this._dimensions[dimIndex]);},keyedColumns:getDimValueSimply,original:function original(dataItem,property,dataIndex,dimIndex){// Performance sensitive, do not use modelUtil.getDataItemValue. // If dataItem is an plain object with no value field, the let `value` // will be assigned with the object, but it will be tread correctly // in the `convertValue`. var value=dataItem&&(dataItem.value==null?dataItem:dataItem.value);return parseDataValue(value instanceof Array?value[dimIndex]// If value is a single number or something else not array. :value,this._dimensions[dimIndex]);},typedArray:function typedArray(dataItem,property,dataIndex,dimIndex){return dataItem[dimIndex];}};}();return DataStore;}();/** * [REQUIREMENT_MEMO]: * (0) `metaRawOption` means `dimensions`/`sourceHeader`/`seriesLayoutBy` in raw option. * (1) Keep support the feature: `metaRawOption` can be specified both on `series` and * `root-dataset`. Them on `series` has higher priority. * (2) Do not support to set `metaRawOption` on a `non-root-dataset`, because it might * confuse users: whether those props indicate how to visit the upstream source or visit * the transform result source, and some transforms has nothing to do with these props, * and some transforms might have multiple upstream. * (3) Transforms should specify `metaRawOption` in each output, just like they can be * declared in `root-dataset`. * (4) At present only support visit source in `SERIES_LAYOUT_BY_COLUMN` in transforms. * That is for reducing complexity in transfroms. * PENDING: Whether to provide transposition transform? * * [IMPLEMENTAION_MEMO]: * "sourceVisitConfig" are calculated from `metaRawOption` and `data`. * They will not be calculated until `source` is about to be visited (to prevent from * duplicate calcuation). `source` is visited only in series and input to transforms. * * [DIMENSION_INHERIT_RULE]: * By default the dimensions are inherited from ancestors, unless a transform return * a new dimensions definition. * Consider the case: * ```js * dataset: [{ * source: [ ['Product', 'Sales', 'Prise'], ['Cookies', 321, 44.21], ...] * }, { * transform: { type: 'filter', ... } * }] * dataset: [{ * dimension: ['Product', 'Sales', 'Prise'], * source: [ ['Cookies', 321, 44.21], ...] * }, { * transform: { type: 'filter', ... } * }] * ``` * The two types of option should have the same behavior after transform. * * * [SCENARIO]: * (1) Provide source data directly: * ```js * series: { * encode: {...}, * dimensions: [...] * seriesLayoutBy: 'row', * data: [[...]] * } * ``` * (2) Series refer to dataset. * ```js * series: [{ * encode: {...} * // Ignore datasetIndex means `datasetIndex: 0` * // and the dimensions defination in dataset is used * }, { * encode: {...}, * seriesLayoutBy: 'column', * datasetIndex: 1 * }] * ``` * (3) dataset transform * ```js * dataset: [{ * source: [...] * }, { * source: [...] * }, { * // By default from 0. * transform: { type: 'filter', config: {...} } * }, { * // Piped. * transform: [ * { type: 'filter', config: {...} }, * { type: 'sort', config: {...} } * ] * }, { * id: 'regressionData', * fromDatasetIndex: 1, * // Third-party transform * transform: { type: 'ecStat:regression', config: {...} } * }, { * // retrieve the extra result. * id: 'regressionFormula', * fromDatasetId: 'regressionData', * fromTransformResult: 1 * }] * ``` */var SourceManager=/** @class */function(){function SourceManager(sourceHost){// Cached source. Do not repeat calculating if not dirty. this._sourceList=[];this._storeList=[];// version sign of each upstream source manager. this._upstreamSignList=[];this._versionSignBase=0;this._dirty=true;this._sourceHost=sourceHost;}/** * Mark dirty. */SourceManager.prototype.dirty=function(){this._setLocalSource([],[]);this._storeList=[];this._dirty=true;};SourceManager.prototype._setLocalSource=function(sourceList,upstreamSignList){this._sourceList=sourceList;this._upstreamSignList=upstreamSignList;this._versionSignBase++;if(this._versionSignBase>9e10){this._versionSignBase=0;}};/** * For detecting whether the upstream source is dirty, so that * the local cached source (in `_sourceList`) should be discarded. */SourceManager.prototype._getVersionSign=function(){return this._sourceHost.uid+'_'+this._versionSignBase;};/** * Always return a source instance. Otherwise throw error. */SourceManager.prototype.prepareSource=function(){// For the case that call `setOption` multiple time but no data changed, // cache the result source to prevent from repeating transform. if(this._isDirty()){this._createSource();this._dirty=false;}};SourceManager.prototype._createSource=function(){this._setLocalSource([],[]);var sourceHost=this._sourceHost;var upSourceMgrList=this._getUpstreamSourceManagers();var hasUpstream=!!upSourceMgrList.length;var resultSourceList;var upstreamSignList;if(isSeries(sourceHost)){var seriesModel=sourceHost;var data=void 0;var sourceFormat=void 0;var upSource=void 0;// Has upstream dataset if(hasUpstream){var upSourceMgr=upSourceMgrList[0];upSourceMgr.prepareSource();upSource=upSourceMgr.getSource();data=upSource.data;sourceFormat=upSource.sourceFormat;upstreamSignList=[upSourceMgr._getVersionSign()];}// Series data is from own. else{data=seriesModel.get('data',true);sourceFormat=isTypedArray(data)?SOURCE_FORMAT_TYPED_ARRAY:SOURCE_FORMAT_ORIGINAL;upstreamSignList=[];}// See [REQUIREMENT_MEMO], merge settings on series and parent dataset if it is root. var newMetaRawOption=this._getSourceMetaRawOption()||{};var upMetaRawOption=upSource&&upSource.metaRawOption||{};var seriesLayoutBy=retrieve2(newMetaRawOption.seriesLayoutBy,upMetaRawOption.seriesLayoutBy)||null;var sourceHeader=retrieve2(newMetaRawOption.sourceHeader,upMetaRawOption.sourceHeader);// Note here we should not use `upSource.dimensionsDefine`. Consider the case: // `upSource.dimensionsDefine` is detected by `seriesLayoutBy: 'column'`, // but series need `seriesLayoutBy: 'row'`. var dimensions=retrieve2(newMetaRawOption.dimensions,upMetaRawOption.dimensions);// We share source with dataset as much as possible // to avoid extra memroy cost of high dimensional data. var needsCreateSource=seriesLayoutBy!==upMetaRawOption.seriesLayoutBy||!!sourceHeader!==!!upMetaRawOption.sourceHeader||dimensions;resultSourceList=needsCreateSource?[createSource(data,{seriesLayoutBy:seriesLayoutBy,sourceHeader:sourceHeader,dimensions:dimensions},sourceFormat)]:[];}else{var datasetModel=sourceHost;// Has upstream dataset. if(hasUpstream){var result=this._applyTransform(upSourceMgrList);resultSourceList=result.sourceList;upstreamSignList=result.upstreamSignList;}// Is root dataset. else{var sourceData=datasetModel.get('source',true);resultSourceList=[createSource(sourceData,this._getSourceMetaRawOption(),null)];upstreamSignList=[];}}this._setLocalSource(resultSourceList,upstreamSignList);};SourceManager.prototype._applyTransform=function(upMgrList){var datasetModel=this._sourceHost;var transformOption=datasetModel.get('transform',true);var fromTransformResult=datasetModel.get('fromTransformResult',true);if(fromTransformResult!=null){var errMsg='';if(upMgrList.length!==1){doThrow(errMsg);}}var sourceList;var upSourceList=[];var upstreamSignList=[];each$7(upMgrList,function(upMgr){upMgr.prepareSource();var upSource=upMgr.getSource(fromTransformResult||0);var errMsg='';if(fromTransformResult!=null&&!upSource){doThrow(errMsg);}upSourceList.push(upSource);upstreamSignList.push(upMgr._getVersionSign());});if(transformOption){sourceList=applyDataTransform(transformOption,upSourceList,{datasetIndex:datasetModel.componentIndex});}else if(fromTransformResult!=null){sourceList=[cloneSourceShallow(upSourceList[0])];}return{sourceList:sourceList,upstreamSignList:upstreamSignList};};SourceManager.prototype._isDirty=function(){if(this._dirty){return true;}// All sourceList is from the some upsteam. var upSourceMgrList=this._getUpstreamSourceManagers();for(var i=0;i1||subBlockLen>0&&!frag.noHeader;each$7(frag.blocks,function(subBlock){var subGapLevel=getBlockGapLevel(subBlock);// If the some of the sub-blocks have some gaps (like 10px) inside, this block // should use a larger gap (like 20px) to distinguish those sub-blocks. if(subGapLevel>=gapLevel_1){gapLevel_1=subGapLevel+ +(hasInnerGap_1&&(// 0 always can not be readable gap level. !subGapLevel// If no header, always keep the sub gap level. Otherwise // look weird in case `multipleSeries`. ||isSectionFragment(subBlock)&&!subBlock.noHeader));}});return gapLevel_1;}return 0;}function buildSection(ctx,fragment,topMarginForOuterGap,toolTipTextStyle){var noHeader=fragment.noHeader;var gaps=getGap(getBlockGapLevel(fragment));var subMarkupTextList=[];var 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);});}// FIXME 'seriesDesc' necessary? else if(orderMode==='seriesDesc'){subBlocks.reverse();}}each$7(subBlocks,function(subBlock,idx){var valueFormatter=fragment.valueFormatter;var subMarkupText=getBuilder(subBlock)(// Inherit valueFormatter valueFormatter?extend(extend({},ctx),{valueFormatter:valueFormatter}):ctx,subBlock,idx>0?gaps.html:0,toolTipTextStyle);subMarkupText!=null&&subMarkupTextList.push(subMarkupText);});var subMarkupText=ctx.renderMode==='richText'?subMarkupTextList.join(gaps.richText):wrapBlockHTML(subMarkupTextList.join(''),noHeader?topMarginForOuterGap:gaps.html);if(noHeader){return subMarkupText;}var displayableHeader=makeValueReadable(fragment.header,'ordinal',ctx.useUTC);var nameStyle=getTooltipTextStyle(toolTipTextStyle,ctx.renderMode).nameStyle;if(ctx.renderMode==='richText'){return wrapInlineNameRichText(ctx,displayableHeader,nameStyle)+gaps.richText+subMarkupText;}else{return wrapBlockHTML("
"+encodeHTML(displayableHeader)+'
'+subMarkupText,topMarginForOuterGap);}}function buildNameValue(ctx,fragment,topMarginForOuterGap,toolTipTextStyle){var renderMode=ctx.renderMode;var noName=fragment.noName;var noValue=fragment.noValue;var noMarker=!fragment.markerType;var name=fragment.name;var useUTC=ctx.useUTC;var valueFormatter=fragment.valueFormatter||ctx.valueFormatter||function(value){value=isArray(value)?value:[value];return map$1(value,function(val,idx){return makeValueReadable(val,isArray(valueTypeOption)?valueTypeOption[idx]:valueTypeOption,useUTC);});};if(noName&&noValue){return;}var markerStr=noMarker?'':ctx.markupStyleCreator.makeTooltipMarker(fragment.markerType,fragment.markerColor||'#333',renderMode);var readableName=noName?'':makeValueReadable(name,'ordinal',useUTC);var valueTypeOption=fragment.valueType;var readableValueList=noValue?[]:valueFormatter(fragment.value);var valueAlignRight=!noMarker||!noName;// It little weird if only value next to marker but far from marker. var valueCloseToMarker=!noMarker&&noName;var _a=getTooltipTextStyle(toolTipTextStyle,renderMode),nameStyle=_a.nameStyle,valueStyle=_a.valueStyle;return renderMode==='richText'?(noMarker?'':markerStr)+(noName?'':wrapInlineNameRichText(ctx,readableName,nameStyle))// Value has commas inside, so use ' ' as delimiter for multiple values. +(noValue?'':wrapInlineValueRichText(ctx,readableValueList,valueAlignRight,valueCloseToMarker,valueStyle)):wrapBlockHTML((noMarker?'':markerStr)+(noName?'':wrapInlineNameHTML(readableName,!noMarker,nameStyle))+(noValue?'':wrapInlineValueHTML(readableValueList,valueAlignRight,valueCloseToMarker,valueStyle)),topMarginForOuterGap);}/** * @return markupText. null/undefined means no content. */function buildTooltipMarkup(fragment,markupStyleCreator,renderMode,orderMode,useUTC,toolTipTextStyle){if(!fragment){return;}var builder=getBuilder(fragment);var ctx={useUTC:useUTC,renderMode:renderMode,orderMode:orderMode,markupStyleCreator:markupStyleCreator,valueFormatter:fragment.valueFormatter};return builder(ctx,fragment,0,toolTipTextStyle);}function getGap(gapLevel){return{html:HTML_GAPS[gapLevel],richText:RICH_TEXT_GAPS[gapLevel]};}function wrapBlockHTML(encodedContent,topGap){var clearfix='
';var marginCSS="margin: "+topGap+"px 0 0";return"
"+encodedContent+clearfix+'
';}function wrapInlineNameHTML(name,leftHasMarker,style){var marginCss=leftHasMarker?'margin-left:2px':'';return""+encodeHTML(name)+'';}function wrapInlineValueHTML(valueList,alignRight,valueCloseToMarker,style){// Do not too close to marker, considering there are multiple values separated by spaces. var paddingStr=valueCloseToMarker?'10px':'20px';var alignCSS=alignRight?"float:right;margin-left:"+paddingStr:'';valueList=isArray(valueList)?valueList:[valueList];return""// Value has commas inside, so use ' ' as delimiter for multiple values. +map$1(valueList,function(value){return encodeHTML(value);}).join('  ')+'';}function wrapInlineNameRichText(ctx,name,style){return ctx.markupStyleCreator.wrapRichTextStyle(name,style);}function wrapInlineValueRichText(ctx,values,alignRight,valueCloseToMarker,style){var styles=[style];var paddingLeft=valueCloseToMarker?10:20;alignRight&&styles.push({padding:[0,0,0,paddingLeft],align:'right'});// Value has commas inside, so use ' ' as delimiter for multiple values. return ctx.markupStyleCreator.wrapRichTextStyle(isArray(values)?values.join(' '):values,styles);}function retrieveVisualColorForTooltipMarker(series,dataIndex){var style=series.getData().getItemVisual(dataIndex,'style');var color=style[series.visualDrawType];return convertToColorString(color);}function getPaddingFromTooltipModel(model,renderMode){var padding=model.get('padding');return padding!=null?padding// We give slightly different to look pretty. :renderMode==='richText'?[8,10]:10;}/** * The major feature is generate styles for `renderMode: 'richText'`. * But it also serves `renderMode: 'html'` to provide * "renderMode-independent" API. */var TooltipMarkupStyleCreator=/** @class */function(){function TooltipMarkupStyleCreator(){this.richTextStyles={};// Notice that "generate a style name" usuall happens repeatly when mouse moving and // displaying a tooltip. So we put the `_nextStyleNameId` as a member of each creator // rather than static shared by all creators (which will cause it increase to fast). this._nextStyleNameId=getRandomIdBase();}TooltipMarkupStyleCreator.prototype._generateStyleName=function(){return'__EC_aUTo_'+this._nextStyleNameId++;};TooltipMarkupStyleCreator.prototype.makeTooltipMarker=function(markerType,colorStr,renderMode){var markerId=renderMode==='richText'?this._generateStyleName():null;var marker=getTooltipMarker({color:colorStr,type:markerType,renderMode:renderMode,markerId:markerId});if(isString(marker)){return marker;}else{this.richTextStyles[markerId]=marker.style;return marker.content;}};/** * @usage * ```ts * const styledText = markupStyleCreator.wrapRichTextStyle([ * // The styles will be auto merged. * { * fontSize: 12, * color: 'blue' * }, * { * padding: 20 * } * ]); * ``` */TooltipMarkupStyleCreator.prototype.wrapRichTextStyle=function(text,styles){var finalStl={};if(isArray(styles)){each$7(styles,function(stl){return extend(finalStl,stl);});}else{extend(finalStl,styles);}var styleName=this._generateStyleName();this.richTextStyles[styleName]=finalStl;return"{"+styleName+"|"+text+"}";};return TooltipMarkupStyleCreator;}();function defaultSeriesFormatTooltip(opt){var series=opt.series;var dataIndex=opt.dataIndex;var multipleSeries=opt.multipleSeries;var data=series.getData();var tooltipDims=data.mapDimensionsAll('defaultedTooltip');var tooltipDimLen=tooltipDims.length;var value=series.getRawValue(dataIndex);var isValueArr=isArray(value);var markerColor=retrieveVisualColorForTooltipMarker(series,dataIndex);// Complicated rule for pretty tooltip. var inlineValue;var inlineValueType;var subBlocks;var sortParam;if(tooltipDimLen>1||isValueArr&&!tooltipDimLen){var formatArrResult=formatTooltipArrayValue(value,series,dataIndex,tooltipDims,markerColor);inlineValue=formatArrResult.inlineValues;inlineValueType=formatArrResult.inlineValueTypes;subBlocks=formatArrResult.blocks;// Only support tooltip sort by the first inline value. It's enough in most cases. 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;}// Do not show generated series name. It might not be readable. var seriesNameSpecified=isNameSpecified(series);var seriesName=seriesNameSpecified&&series.name||'';var itemName=data.getName(dataIndex);var inlineName=multipleSeries?seriesName:itemName;return createTooltipMarkup('section',{header:seriesName,// When series name not specified, do not show a header line with only '-'. // This case alway happen in tooltip.trigger: 'item'. noHeader:multipleSeries||!seriesNameSpecified,sortParam:sortParam,blocks:[createTooltipMarkup('nameValue',{markerType:'item',markerColor:markerColor,// Do not mix display seriesName and itemName in one tooltip, // which might confuses users. name:inlineName,// name dimension might be auto assigned, where the name might // be not readable. So we check trim here. noName:!trim$1(inlineName),value:inlineValue,valueType:inlineValueType})].concat(subBlocks||[])});}function formatTooltipArrayValue(value,series,dataIndex,tooltipDims,colorStr){// check: category-no-encode-has-axis-data in dataset.html var data=series.getData();var isValueMultipleLine=reduce(value,function(isValueMultipleLine,val,idx){var dimItem=data.getDimensionInfo(idx);return isValueMultipleLine=isValueMultipleLine||dimItem&&dimItem.tooltip!==false&&dimItem.displayName!=null;},false);var inlineValues=[];var inlineValueTypes=[];var blocks=[];tooltipDims.length?each$7(tooltipDims,function(dim){setEachItem(retrieveRawValue(data,dataIndex,dim),dim);})// By default, all dims is used on tooltip. :each$7(value,setEachItem);function setEachItem(val,dim){var dimInfo=data.getDimensionInfo(dim);// If `dimInfo.tooltip` is not set, show tooltip. if(!dimInfo||dimInfo.otherDims.tooltip===false){return;}if(isValueMultipleLine){blocks.push(createTooltipMarkup('nameValue',{markerType:'subItem',markerColor:colorStr,name:dimInfo.displayName,value:val,valueType:dimInfo.type}));}else{inlineValues.push(val);inlineValueTypes.push(dimInfo.type);}}return{inlineValues:inlineValues,inlineValueTypes:inlineValueTypes,blocks:blocks};}var inner$a=makeInner();function getSelectionKey(data,dataIndex){return data.getName(dataIndex)||data.getId(dataIndex);}var SERIES_UNIVERSAL_TRANSITION_PROP='__universalTransitionEnabled';var SeriesModel=/** @class */function(_super){__extends$1(SeriesModel,_super);function SeriesModel(){// [Caution]: Becuase this class or desecendants can be used as `XXX.extend(subProto)`, // the class members must not be initialized in constructor or declaration place. // Otherwise there is bad case: // class A {xxx = 1;} // enableClassExtend(A); // class B extends A {} // var C = B.extend({xxx: 5}); // var c = new C(); // console.log(c.xxx); // expect 5 but always 1. var _this=_super!==null&&_super.apply(this,arguments)||this;// --------------------------------------- // Props about data selection // --------------------------------------- _this._selectedDataIndicesMap={};return _this;}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);var sourceManager=inner$a(this).sourceManager=new SourceManager(this);sourceManager.prepareSource();var data=this.getInitialData(option,ecModel);wrapData(data,this);this.dataTask.context.data=data;inner$a(this).dataBeforeProcessed=data;// If we reverse the order (make data firstly, and then make // dataBeforeProcessed by cloneShallow), cloneShallow will // cause data.graph.data !== data when using // module:echarts/data/Graph or module:echarts/data/Tree. // See module:echarts/data/helper/linkSeriesData // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model // init or merge stage, because the data can be restored. So we do not `restoreData` // and `setData` here, which forbids calling `seriesModel.getData()` in this stage. // Call `seriesModel.getRawData()` instead. // this.restoreData(); autoSeriesName(this);this._initSelectedMapFromData(data);};/** * Util for merge default and theme to option */SeriesModel.prototype.mergeDefaultAndTheme=function(option,ecModel){var layoutMode=fetchLayoutMode(this);var inputPositionParams=layoutMode?getLayoutParams(option):{};// Backward compat: using subType on theme. // But if name duplicate between series subType // (for example: parallel) add component mainType, // add suffix 'Series'. var themeSubType=this.subType;if(ComponentModel$1.hasClass(themeSubType)){themeSubType+='Series';}merge(option,ecModel.getTheme().get(this.subType));merge(option,this.getDefaultOption());// Default label emphasis `show` defaultEmphasis(option,'label',['show']);this.fillDataTextStyle(option.data);if(layoutMode){mergeLayoutParam(option,inputPositionParams,layoutMode);}};SeriesModel.prototype.mergeOption=function(newSeriesOption,ecModel){// this.settingTask.dirty(); newSeriesOption=merge(this.option,newSeriesOption,true);this.fillDataTextStyle(newSeriesOption.data);var layoutMode=fetchLayoutMode(this);if(layoutMode){mergeLayoutParam(this.option,newSeriesOption,layoutMode);}var sourceManager=inner$a(this).sourceManager;sourceManager.dirty();sourceManager.prepareSource();var data=this.getInitialData(newSeriesOption,ecModel);wrapData(data,this);this.dataTask.dirty();this.dataTask.context.data=data;inner$a(this).dataBeforeProcessed=data;autoSeriesName(this);this._initSelectedMapFromData(data);};SeriesModel.prototype.fillDataTextStyle=function(data){// Default data label emphasis `show` // FIXME Tree structure data ? // FIXME Performance ? if(data&&!isTypedArray(data)){var props=['show'];for(var i=0;ithis.getShallow('animationThreshold')){animationEnabled=false;}}return!!animationEnabled;};SeriesModel.prototype.restoreData=function(){this.dataTask.dirty();};SeriesModel.prototype.getColorFromPalette=function(name,scope,requestColorNum){var ecModel=this.ecModel;// PENDING var color=PaletteMixin.prototype.getColorFromPalette.call(this,name,scope,requestColorNum);if(!color){color=ecModel.getColorFromPalette(name,scope,requestColorNum);}return color;};/** * Use `data.mapDimensionsAll(coordDim)` instead. * @deprecated */SeriesModel.prototype.coordDimToDataDim=function(coordDim){return this.getRawData().mapDimensionsAll(coordDim);};/** * Get progressive rendering count each step */SeriesModel.prototype.getProgressive=function(){return this.get('progressive');};/** * Get progressive rendering count each step */SeriesModel.prototype.getProgressiveThreshold=function(){return this.get('progressiveThreshold');};// PENGING If selectedMode is null ? 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){return;}var selectedMode=this.option.selectedMode;var data=this.getData(dataType);if(selectedMode==='series'||selectedMap==='all'){this.option.selectedMap={};this._selectedDataIndicesMap={};return;}for(var i=0;i=0){dataIndices.push(dataIndex);}}return dataIndices;};SeriesModel.prototype.isSelected=function(dataIndex,dataType){var selectedMap=this.option.selectedMap;if(!selectedMap){return false;}var data=this.getData(dataType);return(selectedMap==='all'||selectedMap[getSelectionKey(data,dataIndex)])&&!data.getItemModel(dataIndex).get(['select','disabled']);};SeriesModel.prototype.isUniversalTransitionEnabled=function(){if(this[SERIES_UNIVERSAL_TRANSITION_PROP]){return true;}var universalTransitionOpt=this.option.universalTransition;// Quick reject if(!universalTransitionOpt){return false;}if(universalTransitionOpt===true){return true;}// Can be simply 'universalTransition: true' return universalTransitionOpt&&universalTransitionOpt.enabled;};SeriesModel.prototype._innerSelect=function(data,innerDataIndices){var _a,_b;var option=this.option;var selectedMode=option.selectedMode;var len=innerDataIndices.length;if(!selectedMode||!len){return;}if(selectedMode==='series'){option.selectedMap='all';}else if(selectedMode==='multiple'){if(!isObject$2(option.selectedMap)){option.selectedMap={};}var selectedMap=option.selectedMap;for(var i=0;i0){this._innerSelect(data,dataIndices);}};// /** // * @see {module:echarts/stream/Scheduler} // */ // abstract pipeTask: null SeriesModel.registerClass=function(clz){return ComponentModel$1.registerClass(clz);};SeriesModel.protoInitialize=function(){var proto=SeriesModel.prototype;proto.type='series.__base__';proto.seriesIndex=0;proto.ignoreStyleOnData=false;proto.hasSymbolVisual=false;proto.defaultSymbol='circle';// Make sure the values can be accessed! proto.visualStyleAccessPath='itemStyle';proto.visualDrawType='fill';}();return SeriesModel;}(ComponentModel$1);mixin(SeriesModel,DataFormatMixin);mixin(SeriesModel,PaletteMixin);mountExtend(SeriesModel,ComponentModel$1);/** * MUST be called after `prepareSource` called * Here we need to make auto series, especially for auto legend. But we * do not modify series.name in option to avoid side effects. */function autoSeriesName(seriesModel){// User specified name has higher priority, otherwise it may cause // series can not be queried unexpectedly. var name=seriesModel.name;if(!isNameSpecified(seriesModel)){seriesModel.name=getSeriesAutoName(seriesModel)||name;}}function getSeriesAutoName(seriesModel){var data=seriesModel.getRawData();var dataDims=data.mapDimensionsAll('seriesName');var nameArr=[];each$7(dataDims,function(dataDim){var dimInfo=data.getDimensionInfo(dataDim);dimInfo.displayName&&nameArr.push(dimInfo.displayName);});return nameArr.join(' ');}function dataTaskCount(context){return context.model.getRawData().count();}function dataTaskReset(context){var seriesModel=context.model;seriesModel.setData(seriesModel.getRawData().cloneShallow());return dataTaskProgress;}function dataTaskProgress(param,context){// Avoid repead cloneShallow when data just created in reset. if(context.outputData&¶m.end>context.outputData.count()){context.model.getRawData().cloneShallow(context.outputData);}}// TODO refactor function wrapData(data,seriesModel){each$7(concatArray(data.CHANGABLE_METHODS,data.DOWNSAMPLE_METHODS),function(methodName){data.wrapMethod(methodName,curry$1(onDataChange,seriesModel));});}function onDataChange(seriesModel,newList){var task=getCurrentTask(seriesModel);if(task){// Consider case: filter, selectRange task.setOutputEnd((newList||this).count());}return newList;}function getCurrentTask(seriesModel){var scheduler=(seriesModel.ecModel||{}).scheduler;var pipeline=scheduler&&scheduler.getPipeline(seriesModel.uid);if(pipeline){// When pipline finished, the currrentTask keep the last // task (renderTask). var task=pipeline.currentTask;if(task){var agentStubMap=task.agentStubMap;if(agentStubMap){task=agentStubMap.get(seriesModel.uid);}}return task;}}var SeriesModel$1=SeriesModel;var ComponentView=/** @class */function(){function ComponentView(){this.group=new Group$3();this.uid=getUID('viewComponent');}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){// Do nothing; };ComponentView.prototype.updateLayout=function(model,ecModel,api,payload){// Do nothing; };ComponentView.prototype.updateVisual=function(model,ecModel,api,payload){// Do nothing; };/** * Hook for toggle blur target series. * Can be used in marker for blur or leave blur the markers */ComponentView.prototype.toggleBlurSeries=function(seriesModels,isBlur,ecModel){// Do nothing; };/** * Traverse the new rendered elements. * * It will traverse the new added element in progressive rendering. * And traverse all in normal rendering. */ComponentView.prototype.eachRendered=function(cb){var group=this.group;if(group){group.traverse(cb);}};return ComponentView;}();enableClassExtend(ComponentView);enableClassManagement(ComponentView);var ComponentView$1=ComponentView;/** * @return {string} If large mode changed, return string 'reset'; */function createRenderPlanner(){var inner=makeInner();return function(seriesModel){var fields=inner(seriesModel);var pipelineContext=seriesModel.pipelineContext;var originalLarge=!!fields.large;var originalProgressive=!!fields.progressiveRender;// FIXME: if the planner works on a filtered series, `pipelineContext` does not // exists. See #11611 . Probably we need to modify this structure, see the comment // on `performRawSeries` in `Schedular.js`. var large=fields.large=!!(pipelineContext&&pipelineContext.large);var progressive=fields.progressiveRender=!!(pipelineContext&&pipelineContext.progressiveRender);return!!(originalLarge!==large||originalProgressive!==progressive)&&'reset';};}var inner$9=makeInner();var renderPlanner=createRenderPlanner();var ChartView=/** @class */function(){function ChartView(){this.group=new Group$3();this.uid=getUID('viewChart');this.renderTask=createTask({plan:renderTaskPlan,reset:renderTaskReset});this.renderTask.context={view:this};}ChartView.prototype.init=function(ecModel,api){};ChartView.prototype.render=function(seriesModel,ecModel,api,payload){};/** * Highlight series or specified data item. */ChartView.prototype.highlight=function(seriesModel,ecModel,api,payload){var data=seriesModel.getData(payload&&payload.dataType);if(!data){return;}toggleHighlight(data,payload,'emphasis');};/** * Downplay series or specified data item. */ChartView.prototype.downplay=function(seriesModel,ecModel,api,payload){var data=seriesModel.getData(payload&&payload.dataType);if(!data){return;}toggleHighlight(data,payload,'normal');};/** * Remove self. */ChartView.prototype.remove=function(ecModel,api){this.group.removeAll();};/** * Dispose self. */ChartView.prototype.dispose=function(ecModel,api){};ChartView.prototype.updateView=function(seriesModel,ecModel,api,payload){this.render(seriesModel,ecModel,api,payload);};// FIXME never used? ChartView.prototype.updateLayout=function(seriesModel,ecModel,api,payload){this.render(seriesModel,ecModel,api,payload);};// FIXME never used? ChartView.prototype.updateVisual=function(seriesModel,ecModel,api,payload){this.render(seriesModel,ecModel,api,payload);};/** * Traverse the new rendered elements. * * It will traverse the new added element in progressive rendering. * And traverse all in normal rendering. */ChartView.prototype.eachRendered=function(cb){traverseElements(this.group,cb);};ChartView.markUpdateMethod=function(payload,methodName){inner$9(payload).updateMethod=methodName;};ChartView.protoInitialize=function(){var proto=ChartView.prototype;proto.type='chart';}();return ChartView;}();/** * Set state of single element */function elSetState(el,state,highlightDigit){if(el&&isHighDownDispatcher(el)){(state==='emphasis'?enterEmphasis:leaveEmphasis)(el,highlightDigit);}}function toggleHighlight(data,payload,state){var dataIndex=queryDataIndex(data,payload);var highlightDigit=payload&&payload.highlightKey!=null?getHighlightDigit(payload.highlightKey):null;if(dataIndex!=null){each$7(normalizeToArray(dataIndex),function(dataIdx){elSetState(data.getItemGraphicEl(dataIdx),state,highlightDigit);});}else{data.eachItemGraphicEl(function(el){elSetState(el,state,highlightDigit);});}}enableClassExtend(ChartView);enableClassManagement(ChartView);function renderTaskPlan(context){return renderPlanner(context.model);}function renderTaskReset(context){var seriesModel=context.model;var ecModel=context.ecModel;var api=context.api;var payload=context.payload;// FIXME: remove updateView updateVisual var progressiveRender=seriesModel.pipelineContext.progressiveRender;var view=context.view;var updateMethod=payload&&inner$9(payload).updateMethod;var methodName=progressiveRender?'incrementalPrepareRender':updateMethod&&view[updateMethod]?updateMethod// `appendData` is also supported when data amount // is less than progressive threshold. :'render';if(methodName!=='render'){view[methodName](seriesModel,ecModel,api,payload);}return progressMethodMap[methodName];}var progressMethodMap={incrementalPrepareRender:{progress:function progress(params,context){context.view.incrementalRender(params,context.model,context.ecModel,context.api,context.payload);}},render:{// Put view.render in `progress` to support appendData. But in this case // view.render should not be called in reset, otherwise it will be called // twise. Use `forceFirstProgress` to make sure that view.render is called // in any cases. forceFirstProgress:true,progress:function progress(params,context){context.view.render(context.model,context.ecModel,context.api,context.payload);}}};var ChartView$1=ChartView;/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * AUTO-GENERATED FILE. DO NOT MODIFY. */ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */var ORIGIN_METHOD='\0__throttleOriginMethod';var RATE='\0__throttleRate';var THROTTLE_TYPE='\0__throttleType';/** * @public * @param {(Function)} fn * @param {number} [delay=0] Unit: ms. * @param {boolean} [debounce=false] * true: If call interval less than `delay`, only the last call works. * false: If call interval less than `delay, call works on fixed rate. * @return {(Function)} throttled fn. */function throttle(fn,delay,debounce){var currCall;var lastCall=0;var lastExec=0;var timer=null;var diff;var scope;var args;var debounceNextCall;delay=delay||0;function exec(){lastExec=new Date().getTime();timer=null;fn.apply(scope,args||[]);}var cb=function cb(){var cbArgs=[];for(var _i=0;_i=0){exec();}else{timer=setTimeout(exec,-diff);}}lastCall=currCall;};/** * Clear throttle. * @public */cb.clear=function(){if(timer){clearTimeout(timer);timer=null;}};/** * Enable debounce once. */cb.debounceNextCall=function(debounceDelay){debounceNextCall=debounceDelay;};return cb;}/** * Create throttle method or update throttle rate. * * @example * ComponentView.prototype.render = function () { * ... * throttle.createOrUpdate( * this, * '_dispatchAction', * this.model.get('throttle'), * 'fixRate' * ); * }; * ComponentView.prototype.remove = function () { * throttle.clear(this, '_dispatchAction'); * }; * ComponentView.prototype.dispose = function () { * throttle.clear(this, '_dispatchAction'); * }; * */function createOrUpdate(obj,fnAttr,rate,throttleType){var fn=obj[fnAttr];if(!fn){return;}var originFn=fn[ORIGIN_METHOD]||fn;var lastThrottleType=fn[THROTTLE_TYPE];var lastRate=fn[RATE];if(lastRate!==rate||lastThrottleType!==throttleType){if(rate==null||!throttleType){return obj[fnAttr]=originFn;}fn=obj[fnAttr]=throttle(originFn,rate,throttleType==='debounce');fn[ORIGIN_METHOD]=originFn;fn[THROTTLE_TYPE]=throttleType;fn[RATE]=rate;}return fn;}/** * Clear throttle. Example see throttle.createOrUpdate. */function clear$1(obj,fnAttr){var fn=obj[fnAttr];if(fn&&fn[ORIGIN_METHOD]){// Clear throttle fn.clear&&fn.clear();obj[fnAttr]=fn[ORIGIN_METHOD];}}var inner$8=makeInner();var defaultStyleMappers={itemStyle:makeStyleMapper(ITEM_STYLE_KEY_MAP,true),lineStyle:makeStyleMapper(LINE_STYLE_KEY_MAP,true)};var defaultColorKey={lineStyle:'stroke',itemStyle:'fill'};function getStyleMapper(seriesModel,stylePath){var styleMapper=seriesModel.visualStyleMapper||defaultStyleMappers[stylePath];if(!styleMapper){console.warn("Unkown style type '"+stylePath+"'.");return defaultStyleMappers.itemStyle;}return styleMapper;}function getDefaultColorKey(seriesModel,stylePath){// return defaultColorKey[stylePath] || var colorKey=seriesModel.visualDrawType||defaultColorKey[stylePath];if(!colorKey){console.warn("Unkown style type '"+stylePath+"'.");return'fill';}return colorKey;}var seriesStyleTask={createOnAllSeries:true,performRawSeries:true,reset:function reset(seriesModel,ecModel){var data=seriesModel.getData();var stylePath=seriesModel.visualStyleAccessPath||'itemStyle';// Set in itemStyle var styleModel=seriesModel.getModel(stylePath);var getStyle=getStyleMapper(seriesModel,stylePath);var globalStyle=getStyle(styleModel);var decalOption=styleModel.getShallow('decal');if(decalOption){data.setVisual('decal',decalOption);decalOption.dirty=true;}// TODO var colorKey=getDefaultColorKey(seriesModel,stylePath);var color=globalStyle[colorKey];// TODO style callback var colorCallback=isFunction(color)?color:null;var hasAutoColor=globalStyle.fill==='auto'||globalStyle.stroke==='auto';// Get from color palette by default. if(!globalStyle[colorKey]||colorCallback||hasAutoColor){// Note: if some series has color specified (e.g., by itemStyle.color), we DO NOT // make it effect palette. Bacause some scenarios users need to make some series // transparent or as background, which should better not effect the palette. var colorPalette=seriesModel.getColorFromPalette(// TODO series count changed. seriesModel.name,null,ecModel.getSeriesCount());if(!globalStyle[colorKey]){globalStyle[colorKey]=colorPalette;data.setVisual('colorFromPalette',true);}globalStyle.fill=globalStyle.fill==='auto'||isFunction(globalStyle.fill)?colorPalette:globalStyle.fill;globalStyle.stroke=globalStyle.stroke==='auto'||isFunction(globalStyle.stroke)?colorPalette:globalStyle.stroke;}data.setVisual('style',globalStyle);data.setVisual('drawType',colorKey);// Only visible series has each data be visual encoded if(!ecModel.isSeriesFiltered(seriesModel)&&colorCallback){data.setVisual('colorFromPalette',false);return{dataEach:function dataEach(data,idx){var dataParams=seriesModel.getDataParams(idx);var itemStyle=extend({},globalStyle);itemStyle[colorKey]=colorCallback(dataParams);data.setItemVisual(idx,'style',itemStyle);}};}}};var sharedModel=new Model$1();var dataStyleTask={createOnAllSeries:true,performRawSeries:true,reset:function reset(seriesModel,ecModel){if(seriesModel.ignoreStyleOnData||ecModel.isSeriesFiltered(seriesModel)){return;}var data=seriesModel.getData();var stylePath=seriesModel.visualStyleAccessPath||'itemStyle';// Set in itemStyle var getStyle=getStyleMapper(seriesModel,stylePath);var colorKey=data.getVisual('drawType');return{dataEach:data.hasItemOption?function(data,idx){// Not use getItemModel for performance considuration var rawItem=data.getRawDataItem(idx);if(rawItem&&rawItem[stylePath]){sharedModel.option=rawItem[stylePath];var style=getStyle(sharedModel);var existsStyle=data.ensureUniqueItemVisual(idx,'style');extend(existsStyle,style);if(sharedModel.option.decal){data.setItemVisual(idx,'decal',sharedModel.option.decal);sharedModel.option.decal.dirty=true;}if(colorKey in style){data.setItemVisual(idx,'colorFromPalette',false);}}}:null};}};// Pick color from palette for the data which has not been set with color yet. // Note: do not support stream rendering. No such cases yet. var dataColorPaletteTask={performRawSeries:true,overallReset:function overallReset(ecModel){// Each type of series use one scope. // Pie and funnel are using diferrent scopes var paletteScopeGroupByType=createHashMap();ecModel.eachSeries(function(seriesModel){var colorBy=seriesModel.getColorBy();if(seriesModel.isColorBySeries()){return;}var key=seriesModel.type+'-'+colorBy;var colorScope=paletteScopeGroupByType.get(key);if(!colorScope){colorScope={};paletteScopeGroupByType.set(key,colorScope);}inner$8(seriesModel).scope=colorScope;});ecModel.eachSeries(function(seriesModel){if(seriesModel.isColorBySeries()||ecModel.isSeriesFiltered(seriesModel)){return;}var dataAll=seriesModel.getRawData();var idxMap={};var data=seriesModel.getData();var colorScope=inner$8(seriesModel).scope;var stylePath=seriesModel.visualStyleAccessPath||'itemStyle';var colorKey=getDefaultColorKey(seriesModel,stylePath);data.each(function(idx){var rawIdx=data.getRawIndex(idx);idxMap[rawIdx]=idx;});// Iterate on data before filtered. To make sure color from palette can be // Consistent when toggling legend. dataAll.each(function(rawIdx){var idx=idxMap[rawIdx];var fromPalette=data.getItemVisual(idx,'colorFromPalette');// Get color from palette for each data only when the color is inherited from series color, which is // also picked from color palette. So following situation is not in the case: // 1. series.itemStyle.color is set // 2. color is encoded by visualMap if(fromPalette){var itemStyle=data.ensureUniqueItemVisual(idx,'style');var name_1=dataAll.getName(rawIdx)||rawIdx+'';var dataCount=dataAll.count();itemStyle[colorKey]=seriesModel.getColorFromPalette(name_1,colorScope,dataCount);}});});}};var PI$1=Math.PI;/** * @param {module:echarts/ExtensionAPI} api * @param {Object} [opts] * @param {string} [opts.text] * @param {string} [opts.color] * @param {string} [opts.textColor] * @return {module:zrender/Element} */function defaultLoading(api,opts){opts=opts||{};defaults(opts,{text:'loading',textColor:'#000',fontSize:12,fontWeight:'normal',fontStyle:'normal',fontFamily:'sans-serif',maskColor:'rgba(255, 255, 255, 0.8)',showSpinner:true,color:'#5470c6',spinnerRadius:10,lineWidth:5,zlevel:0});var group=new Group$3();var mask=new Rect$2({style:{fill:opts.maskColor},zlevel:opts.zlevel,z:10000});group.add(mask);var textContent=new ZRText$1({style:{text:opts.text,fill:opts.textColor,fontSize:opts.fontSize,fontWeight:opts.fontWeight,fontStyle:opts.fontStyle,fontFamily:opts.fontFamily},zlevel:opts.zlevel,z:10001});var labelRect=new Rect$2({style:{fill:'none'},textContent:textContent,textConfig:{position:'right',distance:10},zlevel:opts.zlevel,z:10001});group.add(labelRect);var arc;if(opts.showSpinner){arc=new Arc$1({shape:{startAngle:-PI$1/2,endAngle:-PI$1/2+0.1,r:opts.spinnerRadius},style:{stroke:opts.color,lineCap:'round',lineWidth:opts.lineWidth},zlevel:opts.zlevel,z:10001});arc.animateShape(true).when(1000,{endAngle:PI$1*3/2}).start('circularInOut');arc.animateShape(true).when(1000,{startAngle:PI$1*3/2}).delay(300).start('circularInOut');group.add(arc);}// Inject resize group.resize=function(){var textWidth=textContent.getBoundingRect().width;var r=opts.showSpinner?opts.spinnerRadius:0;// cx = (containerWidth - arcDiameter - textDistance - textWidth) / 2 // textDistance needs to be calculated when both animation and text exist var cx=(api.getWidth()-r*2-(opts.showSpinner&&textWidth?10:0)-textWidth)/2-(opts.showSpinner&&textWidth?0:5+textWidth/2)// only show the text +(opts.showSpinner?0:textWidth/2)// only show the spinner +(textWidth?0:r);var cy=api.getHeight()/2;opts.showSpinner&&arc.setShape({cx:cx,cy:cy});labelRect.setShape({x:cx-r,y:cy-r,width:r*2,height:r*2});mask.setShape({x:0,y:0,width:api.getWidth(),height:api.getHeight()});};group.resize();return group;}var Scheduler=/** @class */function(){function Scheduler(ecInstance,api,dataProcessorHandlers,visualHandlers){// key: handlerUID this._stageTaskMap=createHashMap();this.ecInstance=ecInstance;this.api=api;// Fix current processors in case that in some rear cases that // processors might be registered after echarts instance created. // Register processors incrementally for a echarts instance is // not supported by this stream architecture. dataProcessorHandlers=this._dataProcessorHandlers=dataProcessorHandlers.slice();visualHandlers=this._visualHandlers=visualHandlers.slice();this._allHandlers=dataProcessorHandlers.concat(visualHandlers);}Scheduler.prototype.restoreData=function(ecModel,payload){// TODO: Only restore needed series and components, but not all components. // Currently `restoreData` of all of the series and component will be called. // But some independent components like `title`, `legend`, `graphic`, `toolbox`, // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`, // and some components like coordinate system, axes, dataZoom, visualMap only // need their target series refresh. // (1) If we are implementing this feature some day, we should consider these cases: // if a data processor depends on a component (e.g., dataZoomProcessor depends // on the settings of `dataZoom`), it should be re-performed if the component // is modified by `setOption`. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`, // it should be re-performed when the result array of `getTargetSeries` changed. // We use `dependencies` to cover these issues. // (3) How to update target series when coordinate system related components modified. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty, // and this case all of the tasks will be set as dirty. ecModel.restoreData(payload);// Theoretically an overall task not only depends on each of its target series, but also // depends on all of the series. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure // that the overall task is set as dirty and to be performed, otherwise it probably cause // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it // probably cause state chaos (consider `dataZoomProcessor`). this._stageTaskMap.each(function(taskRecord){var overallTask=taskRecord.overallTask;overallTask&&overallTask.dirty();});};// If seriesModel provided, incremental threshold is check by series data. Scheduler.prototype.getPerformArgs=function(task,isBlock){// For overall task if(!task.__pipeline){return;}var pipeline=this._pipelineMap.get(task.__pipeline.id);var pCtx=pipeline.context;var incremental=!isBlock&&pipeline.progressiveEnabled&&(!pCtx||pCtx.progressiveRender)&&task.__idxInPipeline>pipeline.blockIndex;var step=incremental?pipeline.step:null;var modDataCount=pCtx&&pCtx.modDataCount;var modBy=modDataCount!=null?Math.ceil(modDataCount/step):null;return{step:step,modBy:modBy,modDataCount:modDataCount};};Scheduler.prototype.getPipeline=function(pipelineId){return this._pipelineMap.get(pipelineId);};/** * Current, progressive rendering starts from visual and layout. * Always detect render mode in the same stage, avoiding that incorrect * detection caused by data filtering. * Caution: * `updateStreamModes` use `seriesModel.getData()`. */Scheduler.prototype.updateStreamModes=function(seriesModel,view){var pipeline=this._pipelineMap.get(seriesModel.uid);var data=seriesModel.getData();var dataLen=data.count();// `progressiveRender` means that can render progressively in each // animation frame. Note that some types of series do not provide // `view.incrementalPrepareRender` but support `chart.appendData`. We // use the term `incremental` but not `progressive` to describe the // case that `chart.appendData`. var progressiveRender=pipeline.progressiveEnabled&&view.incrementalPrepareRender&&dataLen>=pipeline.threshold;var large=seriesModel.get('large')&&dataLen>=seriesModel.get('largeThreshold');// TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint. // see `test/candlestick-large3.html` var modDataCount=seriesModel.get('progressiveChunkMode')==='mod'?dataLen:null;seriesModel.pipelineContext=pipeline.context={progressiveRender:progressiveRender,modDataCount:modDataCount,large:large};};Scheduler.prototype.restorePipelines=function(ecModel){var scheduler=this;var pipelineMap=scheduler._pipelineMap=createHashMap();ecModel.eachSeries(function(seriesModel){var progressive=seriesModel.getProgressive();var 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;var ecModel=this.api.getModel();var api=this.api;each$7(this._allHandlers,function(handler){var record=stageTaskMap.get(handler.uid)||stageTaskMap.set(handler.uid,{});var errMsg='';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;var 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){// If we do not use `block` here, it should be considered when to update modes. this._performStageTasks(this._dataProcessorHandlers,ecModel,payload,{block:true});};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=false;var scheduler=this;each$7(stageHandlers,function(stageHandler,idx){if(opt.visualType&&opt.visualType!==stageHandler.visualType){return;}var stageHandlerRecord=scheduler._stageTaskMap.get(stageHandler.uid);var seriesTaskMap=stageHandlerRecord.seriesTaskMap;var overallTask=stageHandlerRecord.overallTask;if(overallTask){var overallNeedDirty_1;var agentStubMap=overallTask.agentStubMap;agentStubMap.each(function(stub){if(needSetDirty(opt,stub)){stub.dirty();overallNeedDirty_1=true;}});overallNeedDirty_1&&overallTask.dirty();scheduler.updatePayload(overallTask,payload);var performArgs_1=scheduler.getPerformArgs(overallTask,opt.block);// Execute stubs firstly, which may set the overall task dirty, // then execute the overall task. And stub will call seriesModel.setData, // which ensures that in the overallTask seriesModel.getData() will not // return incorrect data. agentStubMap.each(function(stub){stub.perform(performArgs_1);});if(overallTask.perform(performArgs_1)){unfinished=true;}}else if(seriesTaskMap){seriesTaskMap.each(function(task,pipelineId){if(needSetDirty(opt,task)){task.dirty();}var performArgs=scheduler.getPerformArgs(task,opt.block);// FIXME // if intending to decalare `performRawSeries` in handlers, only // stream-independent (specifically, data item independent) operations can be // performed. Because is a series is filtered, most of the tasks will not // be performed. A stream-dependent operation probably cause wrong biz logic. // Perhaps we should not provide a separate callback for this case instead // of providing the config `performRawSeries`. The stream-dependent operaions // and stream-independent operations should better not be mixed. performArgs.skip=!stageHandler.performRawSeries&&ecModel.isSeriesFiltered(task.context.model);scheduler.updatePayload(task,payload);if(task.perform(performArgs)){unfinished=true;}});}});function needSetDirty(opt,task){return opt.setDirty&&(!opt.dirtyMap||opt.dirtyMap.get(task.__pipeline.id));}this.unfinished=unfinished||this.unfinished;};Scheduler.prototype.performSeriesTasks=function(ecModel){var unfinished;ecModel.eachSeries(function(seriesModel){// Progress to the end for dataInit and dataRestore. unfinished=seriesModel.dataTask.perform()||unfinished;});this.unfinished=unfinished||this.unfinished;};Scheduler.prototype.plan=function(){// Travel pipelines, check block. 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){payload!=='remain'&&(task.context.payload=payload);};Scheduler.prototype._createSeriesStageTask=function(stageHandler,stageHandlerRecord,ecModel,api){var scheduler=this;var oldSeriesTaskMap=stageHandlerRecord.seriesTaskMap;// The count of stages are totally about only several dozen, so // do not need to reuse the map. var newSeriesTaskMap=stageHandlerRecord.seriesTaskMap=createHashMap();var seriesType=stageHandler.seriesType;var getTargetSeries=stageHandler.getTargetSeries;// If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily, // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`, // it works but it may cause other irrelevant charts blocked. if(stageHandler.createOnAllSeries){ecModel.eachRawSeries(create);}else if(seriesType){ecModel.eachRawSeriesByType(seriesType,create);}else if(getTargetSeries){getTargetSeries(ecModel,api).each(create);}function create(seriesModel){var pipelineId=seriesModel.uid;// Init tasks for each seriesModel only once. // Reuse original task instance. var task=newSeriesTaskMap.set(pipelineId,oldSeriesTaskMap&&oldSeriesTaskMap.get(pipelineId)||createTask({plan:seriesTaskPlan,reset:seriesTaskReset,count:seriesTaskCount}));task.context={model:seriesModel,ecModel:ecModel,api:api,// PENDING: `useClearVisual` not used? useClearVisual:stageHandler.isVisual&&!stageHandler.isLayout,plan:stageHandler.plan,reset:stageHandler.reset,scheduler:scheduler};scheduler._pipe(seriesModel,task);}};Scheduler.prototype._createOverallStageTask=function(stageHandler,stageHandlerRecord,ecModel,api){var scheduler=this;var overallTask=stageHandlerRecord.overallTask=stageHandlerRecord.overallTask// For overall task, the function only be called on reset stage. ||createTask({reset:overallTaskReset});overallTask.context={ecModel:ecModel,api:api,overallReset:stageHandler.overallReset,scheduler:scheduler};var oldAgentStubMap=overallTask.agentStubMap;// The count of stages are totally about only several dozen, so // do not need to reuse the map. var newAgentStubMap=overallTask.agentStubMap=createHashMap();var seriesType=stageHandler.seriesType;var getTargetSeries=stageHandler.getTargetSeries;var overallProgress=true;var shouldOverallTaskDirty=false;// FIXME:TS never used, so comment it // let modifyOutputEnd = stageHandler.modifyOutputEnd; // An overall task with seriesType detected or has `getTargetSeries`, we add // stub in each pipelines, it will set the overall task dirty when the pipeline // progress. Moreover, to avoid call the overall task each frame (too frequent), // we set the pipeline block. var errMsg='';assert(!stageHandler.createOnAllSeries,errMsg);if(seriesType){ecModel.eachRawSeriesByType(seriesType,createStub);}else if(getTargetSeries){getTargetSeries(ecModel,api).each(createStub);}// Otherwise, (usually it is legancy case), the overall task will only be // executed when upstream dirty. Otherwise the progressive rendering of all // pipelines will be disabled unexpectedly. But it still needs stubs to receive // dirty info from upsteam. else{overallProgress=false;each$7(ecModel.getSeries(),createStub);}function createStub(seriesModel){var pipelineId=seriesModel.uid;var stub=newAgentStubMap.set(pipelineId,oldAgentStubMap&&oldAgentStubMap.get(pipelineId)||(// When the result of `getTargetSeries` changed, the overallTask // should be set as dirty and re-performed. shouldOverallTaskDirty=true,createTask({reset:stubReset,onDirty:stubOnDirty})));stub.context={model:seriesModel,overallProgress:overallProgress// FIXME:TS never used, so comment it // modifyOutputEnd: modifyOutputEnd };stub.agent=overallTask;stub.__block=overallProgress;scheduler._pipe(seriesModel,stub);}if(shouldOverallTaskDirty){overallTask.dirty();}};Scheduler.prototype._pipe=function(seriesModel,task){var pipelineId=seriesModel.uid;var 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){if(isFunction(stageHandler)){stageHandler={overallReset:stageHandler,seriesType:detectSeriseType(stageHandler)};}stageHandler.uid=getUID('stageHandler');visualType&&(stageHandler.visualType=visualType);return stageHandler;};return 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){if(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$1(resetDefines,function(v,idx){return makeSeriesTaskProgress(idx);}):singleSeriesTaskProgress;}var singleSeriesTaskProgress=makeSeriesTaskProgress(0);function makeSeriesTaskProgress(resetDefineIdx){return function(params,context){var data=context.data;var resetDefine=context.resetDefines[resetDefineIdx];if(resetDefine&&resetDefine.dataEach){for(var i=params.start;i0&&suffixPos===key.length-propSuffix.length){var mainType=key.slice(0,suffixPos);// Consider `dataIndex`. if(mainType!=='data'){cptQuery.mainType=mainType;cptQuery[propSuffix.toLowerCase()]=val;reserved=true;}}}if(dataKeys_1.hasOwnProperty(key)){dataQuery[key]=val;reserved=true;}if(!reserved){otherQuery[key]=val;}});}return{cptQuery:cptQuery,dataQuery:dataQuery,otherQuery:otherQuery};};ECEventProcessor.prototype.filter=function(eventType,query){// They should be assigned before each trigger call. var eventInfo=this.eventInfo;if(!eventInfo){return true;}var targetEl=eventInfo.targetEl;var packedEvent=eventInfo.packedEvent;var model=eventInfo.model;var view=eventInfo.view;// For event like 'globalout'. if(!model||!view){return true;}var cptQuery=query.cptQuery;var 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 query[prop]==null||host[propOnHost||prop]===query[prop];}};ECEventProcessor.prototype.afterTrigger=function(){// Make sure the eventInfo wont be used in next trigger. this.eventInfo=null;};return ECEventProcessor;}();var SYMBOL_PROPS_WITH_CB=['symbol','symbolSize','symbolRotate','symbolOffset'];var SYMBOL_PROPS=SYMBOL_PROPS_WITH_CB.concat(['symbolKeepAspect']);// Encoding visual for all series include which is filtered for legend drawing var seriesSymbolTask={createOnAllSeries:true,// For legend. performRawSeries:true,reset:function reset(seriesModel,ecModel){var data=seriesModel.getData();if(seriesModel.legendIcon){data.setVisual('legendIcon',seriesModel.legendIcon);}if(!seriesModel.hasSymbolVisual){return;}var symbolOptions={};var symbolOptionsCb={};var hasCallback=false;for(var i=0;i=0&&isSafeNum(r)?r:0.5;var canvasGradient=ctx.createRadialGradient(x,y,0,x,y,r);return canvasGradient;}function getCanvasGradient(ctx,obj,rect){var canvasGradient=obj.type==='radial'?createRadialGradient(ctx,obj,rect):createLinearGradient(ctx,obj,rect);var colorStops=obj.colorStops;for(var i=0;i0)){return null;}return lineType==='dashed'?[4*lineWidth,2*lineWidth]:lineType==='dotted'?[lineWidth]:isNumber(lineType)?[lineType]:isArray(lineType)?lineType:null;}function getLineDash(el){var style=el.style;var lineDash=style.lineDash&&style.lineWidth>0&&normalizeLineDash(style.lineDash,style.lineWidth);var lineDashOffset=style.lineDashOffset;if(lineDash){var lineScale_1=style.strokeNoScale&&el.getLineScale?el.getLineScale():1;if(lineScale_1&&lineScale_1!==1){lineDash=map$1(lineDash,function(rawVal){return rawVal/lineScale_1;});lineDashOffset/=lineScale_1;}}return[lineDash,lineDashOffset];}var pathProxyForDraw=new PathProxy$1(true);function styleHasStroke(style){var stroke=style.stroke;return!(stroke==null||stroke==='none'||!(style.lineWidth>0));}function isValidStrokeFillStyle(strokeOrFill){return typeof strokeOrFill==='string'&&strokeOrFill!=='none';}function styleHasFill(style){var fill=style.fill;return fill!=null&&fill!=='none';}function doFillPath(ctx,style){if(style.fillOpacity!=null&&style.fillOpacity!==1){var originalGlobalAlpha=ctx.globalAlpha;ctx.globalAlpha=style.fillOpacity*style.opacity;ctx.fill();ctx.globalAlpha=originalGlobalAlpha;}else{ctx.fill();}}function doStrokePath(ctx,style){if(style.strokeOpacity!=null&&style.strokeOpacity!==1){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(typeof DOMMatrix==='function'&&canvasPattern&&canvasPattern.setTransform){var matrix=new DOMMatrix();matrix.translateSelf(pattern.x||0,pattern.y||0);matrix.rotateSelf(0,0,(pattern.rotation||0)*RADIAN_TO_DEGREE);matrix.scaleSelf(pattern.scaleX||1,pattern.scaleY||1);canvasPattern.setTransform(matrix);}return canvasPattern;}}function brushPath(ctx,el,style,inBatch){var _a;var hasStroke=styleHasStroke(style);var hasFill=styleHasFill(style);var strokePercent=style.strokePercent;var strokePart=strokePercent<1;var firstDraw=!el.path;if((!el.silent||strokePart)&&firstDraw){el.createPathProxy();}var path=el.path||pathProxyForDraw;var dirtyFlag=el.__dirty;if(!inBatch){var fill=style.fill;var stroke=style.stroke;var hasFillGradient=hasFill&&!!fill.colorStops;var hasStrokeGradient=hasStroke&&!!stroke.colorStops;var hasFillPattern=hasFill&&!!fill.image;var hasStrokePattern=hasStroke&&!!stroke.image;var fillGradient=void 0;var strokeGradient=void 0;var fillPattern=void 0;var strokePattern=void 0;var rect=void 0;if(hasFillGradient||hasStrokeGradient){rect=el.getBoundingRect();}if(hasFillGradient){fillGradient=dirtyFlag?getCanvasGradient(ctx,fill,rect):el.__canvasFillGradient;el.__canvasFillGradient=fillGradient;}if(hasStrokeGradient){strokeGradient=dirtyFlag?getCanvasGradient(ctx,stroke,rect):el.__canvasStrokeGradient;el.__canvasStrokeGradient=strokeGradient;}if(hasFillPattern){fillPattern=dirtyFlag||!el.__canvasFillPattern?createCanvasPattern(ctx,fill,el):el.__canvasFillPattern;el.__canvasFillPattern=fillPattern;}if(hasStrokePattern){strokePattern=dirtyFlag||!el.__canvasStrokePattern?createCanvasPattern(ctx,stroke,el):el.__canvasStrokePattern;el.__canvasStrokePattern=fillPattern;}if(hasFillGradient){ctx.fillStyle=fillGradient;}else if(hasFillPattern){if(fillPattern){ctx.fillStyle=fillPattern;}else{hasFill=false;}}if(hasStrokeGradient){ctx.strokeStyle=strokeGradient;}else if(hasStrokePattern){if(strokePattern){ctx.strokeStyle=strokePattern;}else{hasStroke=false;}}}var scale=el.getGlobalScale();path.setScale(scale[0],scale[1],el.segmentIgnoreThreshold);var lineDash;var lineDashOffset;if(ctx.setLineDash&&style.lineDash){_a=getLineDash(el),lineDash=_a[0],lineDashOffset=_a[1];}var needsRebuild=true;if(firstDraw||dirtyFlag&SHAPE_CHANGED_BIT){path.setDPR(ctx.dpr);if(strokePart){path.setContext(null);}else{path.setContext(ctx);needsRebuild=false;}path.reset();el.buildPath(path,el.shape,inBatch);path.toStatic();el.pathUpdated();}if(needsRebuild){path.rebuildPath(ctx,strokePart?strokePercent:1);}if(lineDash){ctx.setLineDash(lineDash);ctx.lineDashOffset=lineDashOffset;}if(!inBatch){if(style.strokeFirst){if(hasStroke){doStrokePath(ctx,style);}if(hasFill){doFillPath(ctx,style);}}else{if(hasFill){doFillPath(ctx,style);}if(hasStroke){doStrokePath(ctx,style);}}}if(lineDash){ctx.setLineDash([]);}}function brushImage(ctx,el,style){var image=el.__image=createOrUpdateImage(style.image,el.__image,el,el.onload);if(!image||!isImageReady(image)){return;}var x=style.x||0;var y=style.y||0;var width=el.getWidth();var height=el.getHeight();var aspect=image.width/image.height;if(width==null&&height!=null){width=height*aspect;}else if(height==null&&width!=null){height=width/aspect;}else if(width==null&&height==null){width=image.width;height=image.height;}if(style.sWidth&&style.sHeight){var sx=style.sx||0;var 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;var sy=style.sy;var sWidth=width-sx;var sHeight=height-sy;ctx.drawImage(image,sx,sy,sWidth,sHeight,x,y,width,height);}else{ctx.drawImage(image,x,y,width,height);}}function brushText(ctx,el,style){var _a;var text=style.text;text!=null&&(text+='');if(text){ctx.font=style.font||DEFAULT_FONT;ctx.textAlign=style.textAlign;ctx.textBaseline=style.textBaseline;var lineDash=void 0;var lineDashOffset=void 0;if(ctx.setLineDash&&style.lineDash){_a=getLineDash(el),lineDash=_a[0],lineDashOffset=_a[1];}if(lineDash){ctx.setLineDash(lineDash);ctx.lineDashOffset=lineDashOffset;}if(style.strokeFirst){if(styleHasStroke(style)){ctx.strokeText(text,style.x,style.y);}if(styleHasFill(style)){ctx.fillText(text,style.x,style.y);}}else{if(styleHasFill(style)){ctx.fillText(text,style.x,style.y);}if(styleHasStroke(style)){ctx.strokeText(text,style.x,style.y);}}if(lineDash){ctx.setLineDash([]);}}}var SHADOW_NUMBER_PROPS=['shadowBlur','shadowOffsetX','shadowOffsetY'];var STROKE_PROPS=[['lineCap','butt'],['lineJoin','miter'],['miterLimit',10]];function bindCommonProps(ctx,style,prevStyle,forceSetAll,scope){var styleChanged=false;if(!forceSetAll){prevStyle=prevStyle||{};if(style===prevStyle){return false;}}if(forceSetAll||style.opacity!==prevStyle.opacity){flushPathDrawn(ctx,scope);styleChanged=true;var opacity=Math.max(Math.min(style.opacity,1),0);ctx.globalAlpha=isNaN(opacity)?DEFAULT_COMMON_STYLE.opacity:opacity;}if(forceSetAll||style.blend!==prevStyle.blend){if(!styleChanged){flushPathDrawn(ctx,scope);styleChanged=true;}ctx.globalCompositeOperation=style.blend||DEFAULT_COMMON_STYLE.blend;}for(var i=0;i0&&scheduler.unfinished);// Call flush explicitly for trigger finished event. if(!scheduler.unfinished){this._zr.flush();}// Else, zr flushing be ensue within the same frame, // because zr flushing is after onframe event. }};ECharts.prototype.getDom=function(){return this._dom;};ECharts.prototype.getId=function(){return this.id;};ECharts.prototype.getZr=function(){return this._zr;};ECharts.prototype.isSSR=function(){return this._ssr;};/* eslint-disable-next-line */ECharts.prototype.setOption=function(option,notMerge,lazyUpdate){if(this[IN_MAIN_PROCESS_KEY]){return;}if(this._disposed){disposedWarning(this.id);return;}var silent;var replaceMerge;var transitionOpt;if(isObject$2(notMerge)){lazyUpdate=notMerge.lazyUpdate;silent=notMerge.silent;replaceMerge=notMerge.replaceMerge;transitionOpt=notMerge.transition;notMerge=notMerge.notMerge;}this[IN_MAIN_PROCESS_KEY]=true;if(!this._model||notMerge){var optionManager=new OptionManager$1(this._api);var theme=this._theme;var ecModel=this._model=new GlobalModel$1();ecModel.scheduler=this._scheduler;ecModel.ssr=this._ssr;ecModel.init(null,null,null,theme,this._locale,optionManager);}this._model.setOption(option,{replaceMerge:replaceMerge},optionPreprocessorFuncs);var updateParams={seriesTransition:transitionOpt,optionChanged:true};if(lazyUpdate){this[PENDING_UPDATE]={silent:silent,updateParams:updateParams};this[IN_MAIN_PROCESS_KEY]=false;// `setOption(option, {lazyMode: true})` may be called when zrender has been slept. // It should wake it up to make sure zrender start to render at the next frame. this.getZr().wakeUp();}else{try{prepare(this);updateMethods.update.call(this,null,updateParams);}catch(e){this[PENDING_UPDATE]=null;this[IN_MAIN_PROCESS_KEY]=false;throw e;}// Ensure zr refresh sychronously, and then pixel in canvas can be // fetched after `setOption`. if(!this._ssr){// not use flush when using ssr mode. this._zr.flush();}this[PENDING_UPDATE]=null;this[IN_MAIN_PROCESS_KEY]=false;flushPendingActions.call(this,silent);triggerUpdatedEvent.call(this,silent);}};/** * @deprecated */ECharts.prototype.setTheme=function(){};// We don't want developers to use getModel directly. 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/* eslint-disable-next-line */||hasWindow&&window.devicePixelRatio||1;};/** * Get canvas which has all thing rendered * @deprecated Use renderToCanvas instead. */ECharts.prototype.getRenderedCanvas=function(opts){return this.renderToCanvas(opts);};ECharts.prototype.renderToCanvas=function(opts){opts=opts||{};var painter=this._zr.painter;return painter.getRenderedCanvas({backgroundColor:opts.backgroundColor||this._model.get('backgroundColor'),pixelRatio:opts.pixelRatio||this.getDevicePixelRatio()});};ECharts.prototype.renderToSVGString=function(opts){opts=opts||{};var painter=this._zr.painter;return painter.renderToString({useViewBox:opts.useViewBox});};/** * Get svg data url */ECharts.prototype.getSvgDataURL=function(){if(!env$1.svgSupported){return;}var zr=this._zr;var list=zr.storage.getDisplayList();// Stop animations each$7(list,function(el){el.stopAnimation(null,true);});return zr.painter.toDataURL();};ECharts.prototype.getDataURL=function(opts){if(this._disposed){disposedWarning(this.id);return;}opts=opts||{};var excludeComponents=opts.excludeComponents;var ecModel=this._model;var excludesComponentViews=[];var self=this;each$7(excludeComponents,function(componentType){ecModel.eachComponent({mainType:componentType},function(component){var view=self._componentsMap[component.__viewId];if(!view.group.ignore){excludesComponentViews.push(view);view.group.ignore=true;}});});var url=this._zr.painter.getType()==='svg'?this.getSvgDataURL():this.renderToCanvas(opts).toDataURL('image/'+(opts&&opts.type||'png'));each$7(excludesComponentViews,function(view){view.group.ignore=false;});return url;};ECharts.prototype.getConnectedDataURL=function(opts){if(this._disposed){disposedWarning(this.id);return;}var isSvg=opts.type==='svg';var groupId=this.group;var mathMin=Math.min;var mathMax=Math.max;var MAX_NUMBER=Infinity;if(connectedGroups[groupId]){var left_1=MAX_NUMBER;var top_1=MAX_NUMBER;var right_1=-MAX_NUMBER;var bottom_1=-MAX_NUMBER;var canvasList_1=[];var dpr_1=opts&&opts.pixelRatio||this.getDevicePixelRatio();each$7(instances,function(chart,id){if(chart.group===groupId){var canvas=isSvg?chart.getZr().painter.getSvgDom().innerHTML:chart.renderToCanvas(clone$3(opts));var 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;right_1*=dpr_1;bottom_1*=dpr_1;var width=right_1-left_1;var height=bottom_1-top_1;var targetCanvas=platformApi.createCanvas();var zr_1=init$1(targetCanvas,{renderer:isSvg?'svg':'canvas'});zr_1.resize({width:width,height:height});if(isSvg){var content_1='';each$7(canvasList_1,function(item){var x=item.left-left_1;var y=item.top-top_1;content_1+=''+item.dom+'';});zr_1.painter.getSvgRoot().innerHTML=content_1;if(opts.connectedBackgroundColor){zr_1.painter.setBackgroundColor(opts.connectedBackgroundColor);}zr_1.refreshImmediately();return zr_1.painter.toDataURL();}else{// Background between the charts if(opts.connectedBackgroundColor){zr_1.add(new Rect$2({shape:{x:0,y:0,width:width,height:height},style:{fill:opts.connectedBackgroundColor}}));}each$7(canvasList_1,function(item){var img=new ZRImage$1({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();return targetCanvas.toDataURL('image/'+(opts&&opts.type||'png'));}}else{return this.getDataURL(opts);}};ECharts.prototype.convertToPixel=function(finder,value){return doConvertPixel(this,'convertToPixel',finder,value);};ECharts.prototype.convertFromPixel=function(finder,value){return doConvertPixel(this,'convertFromPixel',finder,value);};/** * Is the specified coordinate systems or components contain the given pixel point. * @param {Array|number} value * @return {boolean} result */ECharts.prototype.containPixel=function(finder,value){if(this._disposed){disposedWarning(this.id);return;}var ecModel=this._model;var result;var findResult=parseFinder$1(ecModel,finder);each$7(findResult,function(models,key){key.indexOf('Models')>=0&&each$7(models,function(model){var coordSys=model.coordinateSystem;if(coordSys&&coordSys.containPoint){result=result||!!coordSys.containPoint(value);}else if(key==='seriesModels'){var view=this._chartsMap[model.__viewId];if(view&&view.containPoint){result=result||view.containPoint(value,model);}}else;},this);},this);return!!result;};/** * Get visual from series or data. * @param finder * If string, e.g., 'series', means {seriesIndex: 0}. * If Object, could contain some of these properties below: * { * seriesIndex / seriesId / seriesName, * dataIndex / dataIndexInside * } * If dataIndex is not specified, series visual will be fetched, * but not data item visual. * If all of seriesIndex, seriesId, seriesName are not specified, * visual will be fetched from first series. * @param visualType 'color', 'symbol', 'symbolSize' */ECharts.prototype.getVisual=function(finder,visualType){var ecModel=this._model;var parsedFinder=parseFinder$1(ecModel,finder,{defaultMainType:'series'});var seriesModel=parsedFinder.seriesModel;var data=seriesModel.getData();var dataIndexInside=parsedFinder.hasOwnProperty('dataIndexInside')?parsedFinder.dataIndexInside:parsedFinder.hasOwnProperty('dataIndex')?data.indexOfRawIndex(parsedFinder.dataIndex):null;return dataIndexInside!=null?getItemVisualFromData(data,dataIndexInside,visualType):getVisualFromData(data,visualType);};/** * Get view of corresponding component model */ECharts.prototype.getViewOfComponentModel=function(componentModel){return this._componentsMap[componentModel.__viewId];};/** * Get view of corresponding series model */ECharts.prototype.getViewOfSeriesModel=function(seriesModel){return this._chartsMap[seriesModel.__viewId];};ECharts.prototype._initEvents=function(){var _this=this;each$7(MOUSE_EVENT_NAMES,function(eveName){var handler=function handler(e){var ecModel=_this.getModel();var el=e.target;var params;var isGlobalOut=eveName==='globalout';// no e.target when 'globalout'. if(isGlobalOut){params={};}else{el&&findEventDispatcher(el,function(parent){var ecData=getECData(parent);if(ecData&&ecData.dataIndex!=null){var dataModel=ecData.dataModel||ecModel.getSeriesByIndex(ecData.seriesIndex);params=dataModel&&dataModel.getDataParams(ecData.dataIndex,ecData.dataType)||{};return true;}// If element has custom eventData of components else if(ecData.eventData){params=extend({},ecData.eventData);return true;}},true);}// Contract: if params prepared in mouse event, // these properties must be specified: // { // componentType: string (component main type) // componentIndex: number // } // Otherwise event query can not work. if(params){var componentType=params.componentType;var componentIndex=params.componentIndex;// Special handling for historic reason: when trigger by // markLine/markPoint/markArea, the componentType is // 'markLine'/'markPoint'/'markArea', but we should better // enable them to be queried by seriesIndex, since their // option is set in each series. if(componentType==='markLine'||componentType==='markPoint'||componentType==='markArea'){componentType='series';componentIndex=params.seriesIndex;}var model=componentType&&componentIndex!=null&&ecModel.getComponent(componentType,componentIndex);var view=model&&_this[model.mainType==='series'?'_chartsMap':'_componentsMap'][model.__viewId];params.event=e;params.type=eveName;_this._$eventProcessor.eventInfo={targetEl:el,packedEvent:params,model:model,view:view};_this.trigger(eveName,params);}};// Consider that some component (like tooltip, brush, ...) // register zr event handler, but user event handler might // do anything, such as call `setOption` or `dispatchAction`, // which probably update any of the content and probably // cause problem if it is called previous other inner handlers. handler.zrEventfulCallAtLast=true;_this._zr.on(eveName,handler,_this);});each$7(eventActionMap,function(actionType,eventType){_this._messageCenter.on(eventType,function(event){this.trigger(eventType,event);},_this);});// Extra events // TODO register? each$7(['selectchanged'],function(eventType){_this._messageCenter.on(eventType,function(event){this.trigger(eventType,event);},_this);});handleLegacySelectEvents(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:[]},true);};ECharts.prototype.dispose=function(){if(this._disposed){disposedWarning(this.id);return;}this._disposed=true;var dom=this.getDom();if(dom){setAttribute(this.getDom(),DOM_ATTRIBUTE_KEY,'');}var chart=this;var api=chart._api;var ecModel=chart._model;each$7(chart._componentsViews,function(component){component.dispose(ecModel,api);});each$7(chart._chartsViews,function(chart){chart.dispose(ecModel,api);});// Dispose after all views disposed chart._zr.dispose();// Set properties to null. // To reduce the memory cost in case the top code still holds this instance unexpectedly. chart._dom=chart._model=chart._chartsMap=chart._componentsMap=chart._chartsViews=chart._componentsViews=chart._scheduler=chart._api=chart._zr=chart._throttledZrFlush=chart._theme=chart._coordSysMgr=chart._messageCenter=null;delete instances[chart.id];};/** * Resize the chart */ECharts.prototype.resize=function(opts){if(this[IN_MAIN_PROCESS_KEY]){return;}if(this._disposed){disposedWarning(this.id);return;}this._zr.resize(opts);var ecModel=this._model;// Resize loading effect this._loadingFX&&this._loadingFX.resize();if(!ecModel){return;}var needPrepare=ecModel.resetOption('media');var silent=opts&&opts.silent;// There is some real cases that: // chart.setOption(option, { lazyUpdate: true }); // chart.resize(); if(this[PENDING_UPDATE]){if(silent==null){silent=this[PENDING_UPDATE].silent;}needPrepare=true;this[PENDING_UPDATE]=null;}this[IN_MAIN_PROCESS_KEY]=true;try{needPrepare&&prepare(this);updateMethods.update.call(this,{type:'resize',animation:extend({// Disable animation duration:0},opts&&opts.animation)});}catch(e){this[IN_MAIN_PROCESS_KEY]=false;throw e;}this[IN_MAIN_PROCESS_KEY]=false;flushPendingActions.call(this,silent);triggerUpdatedEvent.call(this,silent);};ECharts.prototype.showLoading=function(name,cfg){if(this._disposed){disposedWarning(this.id);return;}if(isObject$2(name)){cfg=name;name='';}name=name||'default';this.hideLoading();if(!loadingEffects[name]){return;}var el=loadingEffects[name](this._api,cfg);var zr=this._zr;this._loadingFX=el;zr.add(el);};/** * Hide loading effect */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);payload.type=eventActionMap[eventObj.type];return payload;};/** * @param opt If pass boolean, means opt.silent * @param opt.silent Default `false`. Whether trigger events. * @param opt.flush Default `undefined`. * true: Flush immediately, and then pixel in canvas can be fetched * immediately. Caution: it might affect performance. * false: Not flush. * undefined: Auto decide whether perform flush. */ECharts.prototype.dispatchAction=function(payload,opt){if(this._disposed){disposedWarning(this.id);return;}if(!isObject$2(opt)){opt={silent:!!opt};}if(!actions[payload.type]){return;}// Avoid dispatch action before setOption. Especially in `connect`. if(!this._model){return;}// May dispatchAction in rendering procedure if(this[IN_MAIN_PROCESS_KEY]){this._pendingActions.push(payload);return;}var silent=opt.silent;doDispatchAction.call(this,payload,silent);var flush=opt.flush;if(flush){this._zr.flush();}else if(flush!==false&&env$1.browser.weChat){// In WeChat embeded browser, `requestAnimationFrame` and `setInterval` // hang when sliding page (on touch event), which cause that zr does not // refresh util user interaction finished, which is not expected. // But `dispatchAction` may be called too frequently when pan on touch // screen, which impacts performance if do not throttle them. this._throttledZrFlush();}flushPendingActions.call(this,silent);triggerUpdatedEvent.call(this,silent);};ECharts.prototype.updateLabelLayout=function(){lifecycle$1.trigger('series:layoutlabels',this._model,this._api,{// Not adding series labels. // TODO updatedSeries:[]});};ECharts.prototype.appendData=function(params){if(this._disposed){disposedWarning(this.id);return;}var seriesIndex=params.seriesIndex;var ecModel=this.getModel();var seriesModel=ecModel.getSeriesByIndex(seriesIndex);seriesModel.appendData(params);// Note: `appendData` does not support that update extent of coordinate // system, util some scenario require that. In the expected usage of // `appendData`, the initial extent of coordinate system should better // be fixed by axis `min`/`max` setting or initial data, otherwise if // the extent changed while `appendData`, the location of the painted // graphic elements have to be changed, which make the usage of // `appendData` meaningless. this._scheduler.unfinished=true;this.getZr().wakeUp();};// A work around for no `internal` modifier in ts yet but // need to strictly hide private methods to JS users. ECharts.internalField=function(){prepare=function prepare(ecIns){var scheduler=ecIns._scheduler;scheduler.restorePipelines(ecIns._model);scheduler.prepareStageTasks();prepareView(ecIns,true);prepareView(ecIns,false);scheduler.plan();};/** * Prepare view instances of charts and components */prepareView=function prepareView(ecIns,isComponent){var ecModel=ecIns._model;var scheduler=ecIns._scheduler;var viewList=isComponent?ecIns._componentsViews:ecIns._chartsViews;var viewMap=isComponent?ecIns._componentsMap:ecIns._chartsMap;var zr=ecIns._zr;var api=ecIns._api;for(var i=0;iecModel.get('hoverLayerThreshold')&&!env$1.node&&!env$1.worker){ecModel.eachSeries(function(seriesModel){if(seriesModel.preventUsingHoverLayer){return;}var chartView=ecIns._chartsMap[seriesModel.__viewId];if(chartView.__alive){chartView.eachRendered(function(el){if(el.states.emphasis){el.states.emphasis.hoverLayer=true;}});}});}}/** * Update chart and blend. */function updateBlend(seriesModel,chartView){var blendMode=seriesModel.get('blendMode')||null;chartView.eachRendered(function(el){// FIXME marker and other components if(!el.isGroup){// DONT mark the element dirty. In case element is incremental and don't wan't to rerender. el.style.blend=blendMode;}});}function updateZ(model,view){if(model.preventAutoZ){return;}var z=model.get('z')||0;var zlevel=model.get('zlevel')||0;// Set z and zlevel view.eachRendered(function(el){doUpdateZ(el,z,zlevel,-Infinity);// Don't traverse the children because it has been traversed in _updateZ. return true;});}function doUpdateZ(el,z,zlevel,maxZ2){// Group may also have textContent var label=el.getTextContent();var labelLine=el.getTextGuideLine();var isGroup=el.isGroup;if(isGroup){// set z & zlevel of children elements of Group var children=el.childrenRef();for(var i=0;i0?{duration:duration,delay:stateAnimationModel.get('delay'),easing:stateAnimationModel.get('easing')// additive: stateAnimationModel.get('additive') }:null;view.eachRendered(function(el){if(el.states&&el.states.emphasis){// Not applied on removed elements, it may still in fading. if(isElementRemoved(el)){return;}if(el instanceof Path$1){savePathStates(el);}// Only updated on changed element. In case element is incremental and don't wan't to rerender. // TODO, a more proper way? if(el.__dirty){var prevStates=el.prevStates;// Restore states without animation if(prevStates){el.useStates(prevStates);}}// Update state transition and enable animation again. if(enableAnimation){el.stateTransition=stateTransition;var textContent=el.getTextContent();var textGuide=el.getTextGuideLine();// TODO Is it necessary to animate label? if(textContent){textContent.stateTransition=stateTransition;}if(textGuide){textGuide.stateTransition=stateTransition;}}// The use higlighted and selected flag to toggle states. if(el.__dirty){applyElementStates(el);}}});}createExtensionAPI=function createExtensionAPI(ecIns){return new(/** @class */function(_super){__extends$1(class_1,_super);function class_1(){return _super!==null&&_super.apply(this,arguments)||this;}class_1.prototype.getCoordinateSystems=function(){return ecIns._coordSysMgr.getCoordinateSystems();};class_1.prototype.getComponentByElement=function(el){while(el){var modelInfo=el.__ecComponentInfo;if(modelInfo!=null){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){enterBlur(el);markStatusToUpdate(ecIns);};class_1.prototype.leaveBlur=function(el){leaveBlur(el);markStatusToUpdate(ecIns);};class_1.prototype.enterSelect=function(el){enterSelect(el);markStatusToUpdate(ecIns);};class_1.prototype.leaveSelect=function(el){leaveSelect(el);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);};return class_1;}(ExtensionAPI$1))(ecIns);};enableConnect=function enableConnect(chart){function updateConnectedChartsStatus(charts,status){for(var i=0;i=0){return;}registeredTasks.push(fn);var stageHandler=Scheduler$1.wrapStageHandler(fn,visualType);stageHandler.__prio=priority;stageHandler.__raw=fn;targetList.push(stageHandler);}function registerLoading(name,loadingFx){loadingEffects[name]=loadingFx;}/** * The parameters and usage: see `geoSourceManager.registerMap`. * Compatible with previous `echarts.registerMap`. */function registerMap(mapName,geoJson,specialAreas){var registerMap=getImpl('registerMap');registerMap&®isterMap(mapName,geoJson,specialAreas);}var registerTransform=registerExternalTransform;/** * Globa dispatchAction to a specified chart instance. */ // export function dispatchAction(payload: { chartId: string } & Payload, opt?: Parameters[1]) { // if (!payload || !payload.chartId) { // // Must have chartId to find chart // return; // } // const chart = instances[payload.chartId]; // if (chart) { // chart.dispatchAction(payload, opt); // } // } // Buitlin global visual registerVisual(PRIORITY_VISUAL_GLOBAL,seriesStyleTask);registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM,dataStyleTask);registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM,dataColorPaletteTask);registerVisual(PRIORITY_VISUAL_GLOBAL,seriesSymbolTask);registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM,dataSymbolTask);registerVisual(PRIORITY_VISUAL_DECAL,decalVisual);registerPreprocessor(globalBackwardCompat);registerProcessor(PRIORITY_PROCESSOR_DATASTACK,dataStack);registerLoading('default',defaultLoading);// Default actions 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);// Default theme registerTheme('light',lightTheme);registerTheme('dark',darkTheme);// For backward compatibility, where the namespace `dataTool` will /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * AUTO-GENERATED FILE. DO NOT MODIFY. */ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */function dataIndexMapValueLength(valNumOrArrLengthMoreThan2){return valNumOrArrLengthMoreThan2==null?0:valNumOrArrLengthMoreThan2.length||1;}function defaultKeyGetter(item){return item;}var DataDiffer=/** @class */function(){/** * @param context Can be visited by this.context in callback. */function DataDiffer(oldArr,newArr,oldKeyGetter,newKeyGetter,context,// By default: 'oneToOne'. diffMode){this._old=oldArr;this._new=newArr;this._oldKeyGetter=oldKeyGetter||defaultKeyGetter;this._newKeyGetter=newKeyGetter||defaultKeyGetter;// Visible in callback via `this.context`; this.context=context;this._diffModeMultiple=diffMode==='multiple';}/** * Callback function when add a data */DataDiffer.prototype.add=function(func){this._add=func;return this;};/** * Callback function when update a data */DataDiffer.prototype.update=function(func){this._update=func;return this;};/** * Callback function when update a data and only work in `cbMode: 'byKey'`. */DataDiffer.prototype.updateManyToOne=function(func){this._updateManyToOne=func;return this;};/** * Callback function when update a data and only work in `cbMode: 'byKey'`. */DataDiffer.prototype.updateOneToMany=function(func){this._updateOneToMany=func;return this;};/** * Callback function when update a data and only work in `cbMode: 'byKey'`. */DataDiffer.prototype.updateManyToMany=function(func){this._updateManyToMany=func;return this;};/** * Callback function when remove a data */DataDiffer.prototype.remove=function(func){this._remove=func;return this;};DataDiffer.prototype.execute=function(){this[this._diffModeMultiple?'_executeMultiple':'_executeOneToOne']();};DataDiffer.prototype._executeOneToOne=function(){var oldArr=this._old;var newArr=this._new;var newDataIndexMap={};var oldDataKeyArr=new Array(oldArr.length);var newDataKeyArr=new Array(newArr.length);this._initIndexMap(oldArr,null,oldDataKeyArr,'_oldKeyGetter');this._initIndexMap(newArr,newDataIndexMap,newDataKeyArr,'_newKeyGetter');for(var i=0;i1){// Consider there is duplicate key (for example, use dataItem.name as key). // We should make sure every item in newArr and oldArr can be visited. var newIdx=newIdxMapVal.shift();if(newIdxMapVal.length===1){newDataIndexMap[oldKey]=newIdxMapVal[0];}this._update&&this._update(newIdx,i);}else if(newIdxMapValLen===1){newDataIndexMap[oldKey]=null;this._update&&this._update(newIdxMapVal,i);}else{this._remove&&this._remove(i);}}this._performRestAdd(newDataKeyArr,newDataIndexMap);};/** * For example, consider the case: * oldData: [o0, o1, o2, o3, o4, o5, o6, o7], * newData: [n0, n1, n2, n3, n4, n5, n6, n7, n8], * Where: * o0, o1, n0 has key 'a' (many to one) * o5, n4, n5, n6 has key 'b' (one to many) * o2, n1 has key 'c' (one to one) * n2, n3 has key 'd' (add) * o3, o4 has key 'e' (remove) * o6, o7, n7, n8 has key 'f' (many to many, treated as add and remove) * Then: * (The order of the following directives are not ensured.) * this._updateManyToOne(n0, [o0, o1]); * this._updateOneToMany([n4, n5, n6], o5); * this._update(n1, o2); * this._remove(o3); * this._remove(o4); * this._remove(o6); * this._remove(o7); * this._add(n2); * this._add(n3); * this._add(n7); * this._add(n8); */DataDiffer.prototype._executeMultiple=function(){var oldArr=this._old;var newArr=this._new;var oldDataIndexMap={};var newDataIndexMap={};var oldDataKeyArr=[];var newDataKeyArr=[];this._initIndexMap(oldArr,oldDataIndexMap,oldDataKeyArr,'_oldKeyGetter');this._initIndexMap(newArr,newDataIndexMap,newDataKeyArr,'_newKeyGetter');for(var i=0;i1&&newIdxMapValLen===1){this._updateManyToOne&&this._updateManyToOne(newIdxMapVal,oldIdxMapVal);newDataIndexMap[oldKey]=null;}else if(oldIdxMapValLen===1&&newIdxMapValLen>1){this._updateOneToMany&&this._updateOneToMany(newIdxMapVal,oldIdxMapVal);newDataIndexMap[oldKey]=null;}else if(oldIdxMapValLen===1&&newIdxMapValLen===1){this._update&&this._update(newIdxMapVal,oldIdxMapVal);newDataIndexMap[oldKey]=null;}else if(oldIdxMapValLen>1&&newIdxMapValLen>1){this._updateManyToMany&&this._updateManyToMany(newIdxMapVal,oldIdxMapVal);newDataIndexMap[oldKey]=null;}else if(oldIdxMapValLen>1){for(var i_1=0;i_11){for(var j=0;j to determine whether data can be shared. // (Becuase in this case there might be no dimension name defined in dataset, but indices always exists). // (indices are always 0, 1, 2, ..., so we can ignore them to shorten the hash). // Otherwise if retrieving data by property name (like `data: [{aa: 123, bb: 765}, ...]`), // use in hash. if(willRetrieveDataByName&&property!=null// For data stack, we have make sure each series has its own dim on this store. // So we do not add property to hash to make sure they can share this store. &&(!seriesDimDef||!seriesDimDef.isCalculationCoord)){dimHash+=makeHashStrict// Use escape character '`' in case that property name contains '$'. ?property.replace(/\`/g,'`1').replace(/\$/g,'`2')// For better performance, when there are large dimensions, tolerant this defects that hardly meet. :property;}dimHash+='$';dimHash+=dimTypeShort[type]||'f';if(ordinalMeta){dimHash+=ordinalMeta.uid;}dimHash+='$';}// Source from endpoint(usually series) will be read differently // when seriesLayoutBy or startIndex(which is affected by sourceHeader) are different. // So we use this three props as key. var source=this.source;var hash=[source.seriesLayoutBy,source.startIndex,dimHash].join('$$');return{dimensions:dims,hash:hash};};SeriesDataSchema.prototype.makeOutputDimensionNames=function(){var result=[];for(var fullDimIdx=0,seriesDimIdx=0;fullDimIdx30;}var isObject=isObject$2;var map=map$1;var CtorInt32Array=typeof Int32Array==='undefined'?Array:Int32Array;// Use prefix to avoid index to be the same as otherIdList[idx], // which will cause weird udpate animation. var ID_PREFIX='e\0\0';var INDEX_NOT_FOUND=-1;// type SeriesDimensionIndex = DimensionIndex; var TRANSFERABLE_PROPERTIES=['hasItemOption','_nameList','_idList','_invertedIndicesMap','_dimSummary','userOutput','_rawData','_dimValueGetter','_nameDimIdx','_idDimIdx','_nameRepeatCount'];var CLONE_PROPERTIES=['_approximateExtent'];// ----------------------------- // Internal method declarations: // ----------------------------- var prepareInvertedIndex;var getId;var getIdNameFromStore;var normalizeDimensions;var transferProperties;var cloneListForMapAndSample;var makeIdFromName;var SeriesData=/** @class */function(){/** * @param dimensionsInput.dimensions * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...]. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius */function SeriesData(dimensionsInput,hostModel){this.type='list';this._dimOmitted=false;this._nameList=[];this._idList=[];// Models of data option is stored sparse for optimizing memory cost // Never used yet (not used yet). // private _optionModels: Model[] = []; // Global visual properties after visual coding this._visual={};// Globel layout properties. this._layout={};// Item visual properties after visual coding this._itemVisuals=[];// Item layout properties after layout this._itemLayouts=[];// Graphic elemnents this._graphicEls=[];// key: dim, value: extent this._approximateExtent={};this._calculationInfo={};// Having detected that there is data item is non primitive type // (in type `OptionDataItemObject`). // Like `data: [ { value: xx, itemStyle: {...} }, ...]` // At present it only happen in `SOURCE_FORMAT_ORIGINAL`. this.hasItemOption=false;// Methods that create a new list based on this list should be listed here. // Notice that those method should `RETURN` the new list. this.TRANSFERABLE_METHODS=['cloneShallow','downSample','lttbDownSample','map'];// Methods that change indices of this list should be listed here. this.CHANGABLE_METHODS=['filterSelf','selectRange'];this.DOWNSAMPLE_METHODS=['downSample','lttbDownSample'];var dimensions;var assignStoreDimIdx=false;if(isSeriesDataSchema(dimensionsInput)){dimensions=dimensionsInput.dimensions;this._dimOmitted=dimensionsInput.isDimensionOmitted();this._schema=dimensionsInput;}else{assignStoreDimIdx=true;dimensions=dimensionsInput;}dimensions=dimensions||['x','y'];var dimensionInfos={};var dimensionNames=[];var invertedIndicesMap={};var needsHasOwn=false;var emptyObj={};for(var i=0;i=end){return;}var store=this._store;var provider=store.getProvider();this._updateOrdinalMeta();var nameList=this._nameList;var idList=this._idList;var sourceFormat=provider.getSource().sourceFormat;var isFormatOriginal=sourceFormat===SOURCE_FORMAT_ORIGINAL;// Each data item is value // [1, 2] // 2 // Bar chart, line chart which uses category axis // only gives the 'y' value. 'x' value is the indices of category // Use a tempValue to normalize the value to be a (x, y) value // If dataItem is {name: ...} or {id: ...}, it has highest priority. // This kind of ids and names are always stored `_nameList` and `_idList`. if(isFormatOriginal&&!provider.pure){var sharedDataItem=[];for(var idx=start;idx0;};/** * Make sure itemVisual property is unique */ // TODO: use key to save visual to reduce memory. SeriesData.prototype.ensureUniqueItemVisual=function(idx,key){var itemVisuals=this._itemVisuals;var itemVisual=itemVisuals[idx];if(!itemVisual){itemVisual=itemVisuals[idx]={};}var val=itemVisual[key];if(val==null){val=this.getVisual(key);// TODO Performance? if(isArray(val)){val=val.slice();}else if(isObject(val)){val=extend({},val);}itemVisual[key]=val;}return val;};// eslint-disable-next-line SeriesData.prototype.setItemVisual=function(idx,key,value){var itemVisual=this._itemVisuals[idx]||{};this._itemVisuals[idx]=itemVisual;if(isObject(key)){extend(itemVisual,key);}else{itemVisual[key]=value;}};/** * Clear itemVisuals and list visual. */SeriesData.prototype.clearAllVisual=function(){this._visual={};this._itemVisuals=[];};SeriesData.prototype.setLayout=function(key,val){isObject(key)?extend(this._layout,key):this._layout[key]=val;};/** * Get layout property. */SeriesData.prototype.getLayout=function(key){return this._layout[key];};/** * Get layout of single data item */SeriesData.prototype.getItemLayout=function(idx){return this._itemLayouts[idx];};/** * Set layout of single data item */SeriesData.prototype.setItemLayout=function(idx,layout,merge){this._itemLayouts[idx]=merge?extend(this._itemLayouts[idx]||{},layout):layout;};/** * Clear all layout of single data item */SeriesData.prototype.clearItemLayouts=function(){this._itemLayouts.length=0;};/** * Set graphic element relative to data. It can be set as null */SeriesData.prototype.setItemGraphicEl=function(idx,el){var seriesIndex=this.hostModel&&this.hostModel.seriesIndex;setCommonECData(seriesIndex,this.dataType,idx,el);this._graphicEls[idx]=el;};SeriesData.prototype.getItemGraphicEl=function(idx){return this._graphicEls[idx];};SeriesData.prototype.eachItemGraphicEl=function(cb,context){each$7(this._graphicEls,function(el,idx){if(el){cb&&cb.call(context,el,idx);}});};/** * Shallow clone a new list except visual and layout properties, and graph elements. * New list only change the indices. */SeriesData.prototype.cloneShallow=function(list){if(!list){list=new SeriesData(this._schema?this._schema:map(this.dimensions,this._getDimInfo,this),this.hostModel);}transferProperties(list,this);list._store=this._store;return list;};/** * Wrap some method to add more feature */SeriesData.prototype.wrapMethod=function(methodName,injectFunction){var originalMethod=this[methodName];if(!isFunction(originalMethod)){return;}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)));};};// ---------------------------------------------------------- // A work around for internal method visiting private member. // ---------------------------------------------------------- SeriesData.internalField=function(){prepareInvertedIndex=function prepareInvertedIndex(data){var invertedIndicesMap=data._invertedIndicesMap;each$7(invertedIndicesMap,function(invertedIndices,dim){var dimInfo=data._dimInfos[dim];// Currently, only dimensions that has ordinalMeta can create inverted indices. var ordinalMeta=dimInfo.ordinalMeta;var store=data._store;if(ordinalMeta){invertedIndices=invertedIndicesMap[dim]=new CtorInt32Array(ordinalMeta.categories.length);// The default value of TypedArray is 0. To avoid miss // mapping to 0, we should set it as INDEX_NOT_FOUND. for(var i=0;i1){id+='__ec__'+nmCnt;}idList[idx]=id;}};}();return SeriesData;}();var SeriesData$1=SeriesData;/** * This method builds the relationship between: * + "what the coord sys or series requires (see `coordDimensions`)", * + "what the user defines (in `encode` and `dimensions`, see `opt.dimensionsDefine` and `opt.encodeDefine`)" * + "what the data source provids (see `source`)". * * Some guess strategy will be adapted if user does not define something. * If no 'value' dimension specified, the first no-named dimension will be * named as 'value'. * * @return The results are always sorted by `storeDimIndex` asc. */function prepareSeriesDataSchema(// TODO: TYPE completeDimensions type source,opt){if(!isSourceInstance(source)){source=createSourceFromSeriesDataOption(source);}opt=opt||{};var sysDims=opt.coordDimensions||[];var dimsDef=opt.dimensionsDefine||source.dimensionsDefine||[];var coordDimNameMap=createHashMap();var resultList=[];var dimCount=getDimCount(source,sysDims,dimsDef,opt.dimensionsCount);// Try to ignore unsed dimensions if sharing a high dimension datastore // 30 is an experience value. var omitUnusedDimensions=opt.canOmitUnusedDimensions&&shouldOmitUnusedDimensions(dimCount);var isUsingSourceDimensionsDef=dimsDef===source.dimensionsDefine;var dataDimNameMap=isUsingSourceDimensionsDef?ensureSourceDimNameMap(source):createDimNameMap(dimsDef);var encodeDef=opt.encodeDefine;if(!encodeDef&&opt.encodeDefaulter){encodeDef=opt.encodeDefaulter(source,dimCount);}var encodeDefMap=createHashMap(encodeDef);var indicesMap=new CtorInt32Array$1(dimCount);for(var i=0;i0){// Starts from 0. dim.name=dimOriginalName+(count-1);}count++;duplicationMap.set(dimOriginalName,count);}}// ??? TODO // Originally detect dimCount by data[0]. Should we // optimize it to only by sysDims and dimensions and encode. // So only necessary dims will be initialized. // But // (1) custom series should be considered. where other dims // may be visited. // (2) sometimes user need to calcualte bubble size or use visualMap // on other dimensions besides coordSys needed. // So, dims that is not used by system, should be shared in data store? function getDimCount(source,sysDims,dimsDef,optDimCount){// Note that the result dimCount should not small than columns count // of data, otherwise `dataDimNameMap` checking will be incorrect. var dimCount=Math.max(source.dimensionsDetectedCount||1,sysDims.length,dimsDef.length,optDimCount||0);each$7(sysDims,function(sysDimItem){var sysDimItemDimsDef;if(isObject$2(sysDimItem)&&(sysDimItemDimsDef=sysDimItem.dimsDef)){dimCount=Math.max(dimCount,sysDimItemDimsDef.length);}});return dimCount;}function genCoordDimName(name,map,fromZero){var mapData=map.data;if(fromZero||mapData.hasOwnProperty(name)){var i=0;while(mapData.hasOwnProperty(name+i)){i++;}name+=i;}map.set(name,true);return name;}/** * @class * For example: * { * coordSysName: 'cartesian2d', * coordSysDims: ['x', 'y', ...], * axisMap: HashMap({ * x: xAxisModel, * y: yAxisModel * }), * categoryAxisMap: HashMap({ * x: xAxisModel, * y: undefined * }), * // The index of the first category axis in `coordSysDims`. * // `null/undefined` means no category axis exists. * firstCategoryDimIndex: 1, * // To replace user specified encode. * } */var CoordSysInfo=/** @class */function(){function CoordSysInfo(coordSysName){this.coordSysDims=[];this.axisMap=createHashMap();this.categoryAxisMap=createHashMap();this.coordSysName=coordSysName;}return CoordSysInfo;}();function getCoordSysInfoBySeries(seriesModel){var coordSysName=seriesModel.get('coordinateSystem');var result=new CoordSysInfo(coordSysName);var fetch=fetchers[coordSysName];if(fetch){fetch(seriesModel,result,result.axisMap,result.categoryAxisMap);return result;}}var fetchers={cartesian2d:function cartesian2d(seriesModel,result,axisMap,categoryAxisMap){var xAxisModel=seriesModel.getReferringComponents('xAxis',SINGLE_REFERRING).models[0];var yAxisModel=seriesModel.getReferringComponents('yAxis',SINGLE_REFERRING).models[0];result.coordSysDims=['x','y'];axisMap.set('x',xAxisModel);axisMap.set('y',yAxisModel);if(isCategory(xAxisModel)){categoryAxisMap.set('x',xAxisModel);result.firstCategoryDimIndex=0;}if(isCategory(yAxisModel)){categoryAxisMap.set('y',yAxisModel);result.firstCategoryDimIndex==null&&(result.firstCategoryDimIndex=1);}},singleAxis:function singleAxis(seriesModel,result,axisMap,categoryAxisMap){var singleAxisModel=seriesModel.getReferringComponents('singleAxis',SINGLE_REFERRING).models[0];result.coordSysDims=['single'];axisMap.set('single',singleAxisModel);if(isCategory(singleAxisModel)){categoryAxisMap.set('single',singleAxisModel);result.firstCategoryDimIndex=0;}},polar:function polar(seriesModel,result,axisMap,categoryAxisMap){var polarModel=seriesModel.getReferringComponents('polar',SINGLE_REFERRING).models[0];var radiusAxisModel=polarModel.findAxisModel('radiusAxis');var angleAxisModel=polarModel.findAxisModel('angleAxis');result.coordSysDims=['radius','angle'];axisMap.set('radius',radiusAxisModel);axisMap.set('angle',angleAxisModel);if(isCategory(radiusAxisModel)){categoryAxisMap.set('radius',radiusAxisModel);result.firstCategoryDimIndex=0;}if(isCategory(angleAxisModel)){categoryAxisMap.set('angle',angleAxisModel);result.firstCategoryDimIndex==null&&(result.firstCategoryDimIndex=1);}},geo:function geo(seriesModel,result,axisMap,categoryAxisMap){result.coordSysDims=['lng','lat'];},parallel:function parallel(seriesModel,result,axisMap,categoryAxisMap){var ecModel=seriesModel.ecModel;var parallelModel=ecModel.getComponent('parallel',seriesModel.get('parallelIndex'));var coordSysDims=result.coordSysDims=parallelModel.dimensions.slice();each$7(parallelModel.parallelAxisIndex,function(axisIndex,index){var axisModel=ecModel.getComponent('parallelAxis',axisIndex);var axisDim=coordSysDims[index];axisMap.set(axisDim,axisModel);if(isCategory(axisModel)){categoryAxisMap.set(axisDim,axisModel);if(result.firstCategoryDimIndex==null){result.firstCategoryDimIndex=index;}}});}};function isCategory(axisModel){return axisModel.get('type')==='category';}/** * Note that it is too complicated to support 3d stack by value * (have to create two-dimension inverted index), so in 3d case * we just support that stacked by index. * * @param seriesModel * @param dimensionsInput The same as the input of . * The input will be modified. * @param opt * @param opt.stackedCoordDimension Specify a coord dimension if needed. * @param opt.byIndex=false * @return calculationInfo * { * stackedDimension: string * stackedByDimension: string * isStackedByIndex: boolean * stackedOverDimension: string * stackResultDimension: string * } */function enableDataStack(seriesModel,dimensionsInput,opt){opt=opt||{};var byIndex=opt.byIndex;var stackedCoordDimension=opt.stackedCoordDimension;var dimensionDefineList;var schema;var store;if(isLegacyDimensionsInput(dimensionsInput)){dimensionDefineList=dimensionsInput;}else{schema=dimensionsInput.schema;dimensionDefineList=schema.dimensions;store=dimensionsInput.store;}// Compatibal: when `stack` is set as '', do not stack. var mayStack=!!(seriesModel&&seriesModel.get('stack'));var stackedByDimInfo;var stackedDimInfo;var stackResultDimension;var stackedOverDimension;each$7(dimensionDefineList,function(dimensionInfo,index){if(isString(dimensionInfo)){dimensionDefineList[index]=dimensionInfo={name:dimensionInfo};}if(mayStack&&!dimensionInfo.isExtraCoord){// Find the first ordinal dimension as the stackedByDimInfo. if(!byIndex&&!stackedByDimInfo&&dimensionInfo.ordinalMeta){stackedByDimInfo=dimensionInfo;}// Find the first stackable dimension as the stackedDimInfo. if(!stackedDimInfo&&dimensionInfo.type!=='ordinal'&&dimensionInfo.type!=='time'&&(!stackedCoordDimension||stackedCoordDimension===dimensionInfo.coordDim)){stackedDimInfo=dimensionInfo;}}});if(stackedDimInfo&&!byIndex&&!stackedByDimInfo){// Compatible with previous design, value axis (time axis) only stack by index. // It may make sense if the user provides elaborately constructed data. byIndex=true;}// Add stack dimension, they can be both calculated by coordinate system in `unionExtent`. // That put stack logic in List is for using conveniently in echarts extensions, but it // might not be a good way. if(stackedDimInfo){// Use a weird name that not duplicated with other names. // Also need to use seriesModel.id as postfix because different // series may share same data store. The stack dimension needs to be distinguished. stackResultDimension='__\0ecstackresult_'+seriesModel.id;stackedOverDimension='__\0ecstackedover_'+seriesModel.id;// Create inverted index to fast query index by value. if(stackedByDimInfo){stackedByDimInfo.createInvertedIndices=true;}var stackedDimCoordDim_1=stackedDimInfo.coordDim;var stackedDimType=stackedDimInfo.type;var stackedDimCoordIndex_1=0;each$7(dimensionDefineList,function(dimensionInfo){if(dimensionInfo.coordDim===stackedDimCoordDim_1){stackedDimCoordIndex_1++;}});var stackedOverDimensionDefine={name:stackResultDimension,coordDim:stackedDimCoordDim_1,coordDimIndex:stackedDimCoordIndex_1,type:stackedDimType,isExtraCoord:true,isCalculationCoord:true,storeDimIndex:dimensionDefineList.length};var stackResultDimensionDefine={name:stackedOverDimension,// This dimension contains stack base (generally, 0), so do not set it as // `stackedDimCoordDim` to avoid extent calculation, consider log scale. coordDim:stackedOverDimension,coordDimIndex:stackedDimCoordIndex_1+1,type:stackedDimType,isExtraCoord:true,isCalculationCoord:true,storeDimIndex:dimensionDefineList.length+1};if(schema){if(store){stackedOverDimensionDefine.storeDimIndex=store.ensureCalculationDimension(stackedOverDimension,stackedDimType);stackResultDimensionDefine.storeDimIndex=store.ensureCalculationDimension(stackResultDimension,stackedDimType);}schema.appendCalculationDimension(stackedOverDimensionDefine);schema.appendCalculationDimension(stackResultDimensionDefine);}else{dimensionDefineList.push(stackedOverDimensionDefine);dimensionDefineList.push(stackResultDimensionDefine);}}return{stackedDimension:stackedDimInfo&&stackedDimInfo.name,stackedByDimension:stackedByDimInfo&&stackedByDimInfo.name,isStackedByIndex:byIndex,stackedOverDimension:stackedOverDimension,stackResultDimension:stackResultDimension};}function isLegacyDimensionsInput(dimensionsInput){return!isSeriesDataSchema(dimensionsInput.schema);}function isDimensionStacked(data,stackedDim){// Each single series only maps to one pair of axis. So we do not need to // check stackByDim, whatever stacked by a dimension or stacked by index. return!!stackedDim&&stackedDim===data.getCalculationInfo('stackedDimension');}function getStackedDimension(data,targetDim){return isDimensionStacked(data,targetDim)?data.getCalculationInfo('stackResultDimension'):targetDim;}function getCoordSysDimDefs(seriesModel,coordSysInfo){var coordSysName=seriesModel.get('coordinateSystem');var registeredCoordSys=CoordinateSystem.get(coordSysName);var coordSysDimDefs;if(coordSysInfo&&coordSysInfo.coordSysDims){coordSysDimDefs=map$1(coordSysInfo.coordSysDims,function(dim){var dimInfo={name:dim};var axisModel=coordSysInfo.axisMap.get(dim);if(axisModel){var axisType=axisModel.get('type');dimInfo.type=getDimensionTypeByAxis(axisType);}return dimInfo;});}if(!coordSysDimDefs){// Get dimensions from registered coordinate system coordSysDimDefs=registeredCoordSys&&(registeredCoordSys.getDimensionsInfo?registeredCoordSys.getDimensionsInfo():registeredCoordSys.dimensions.slice())||['x','y'];}return coordSysDimDefs;}function injectOrdinalMeta(dimInfoList,createInvertedIndices,coordSysInfo){var firstCategoryDimIndex;var hasNameEncode;coordSysInfo&&each$7(dimInfoList,function(dimInfo,dimIndex){var coordDim=dimInfo.coordDim;var categoryAxisModel=coordSysInfo.categoryAxisMap.get(coordDim);if(categoryAxisModel){if(firstCategoryDimIndex==null){firstCategoryDimIndex=dimIndex;}dimInfo.ordinalMeta=categoryAxisModel.getOrdinalMeta();if(createInvertedIndices){dimInfo.createInvertedIndices=true;}}if(dimInfo.otherDims.itemName!=null){hasNameEncode=true;}});if(!hasNameEncode&&firstCategoryDimIndex!=null){dimInfoList[firstCategoryDimIndex].otherDims.itemName=0;}return firstCategoryDimIndex;}/** * Caution: there are side effects to `sourceManager` in this method. * Should better only be called in `Series['getInitialData']`. */function createSeriesData(sourceRaw,seriesModel,opt){opt=opt||{};var sourceManager=seriesModel.getSourceManager();var source;var isOriginalSource=false;if(sourceRaw){isOriginalSource=true;source=createSourceFromSeriesDataOption(sourceRaw);}else{source=sourceManager.getSource();// Is series.data. not dataset. isOriginalSource=source.sourceFormat===SOURCE_FORMAT_ORIGINAL;}var coordSysInfo=getCoordSysInfoBySeries(seriesModel);var coordSysDimDefs=getCoordSysDimDefs(seriesModel,coordSysInfo);var useEncodeDefaulter=opt.useEncodeDefaulter;var encodeDefaulter=isFunction(useEncodeDefaulter)?useEncodeDefaulter:useEncodeDefaulter?curry$1(makeSeriesEncodeForAxisCoordSys,coordSysDimDefs,seriesModel):null;var createDimensionOptions={coordDimensions:coordSysDimDefs,generateCoord:opt.generateCoord,encodeDefine:seriesModel.getEncode(),encodeDefaulter:encodeDefaulter,canOmitUnusedDimensions:!isOriginalSource};var schema=prepareSeriesDataSchema(source,createDimensionOptions);var firstCategoryDimIndex=injectOrdinalMeta(schema.dimensions,opt.createInvertedIndices,coordSysInfo);var store=!isOriginalSource?sourceManager.getSharedDataStore(schema):null;var stackCalculationInfo=enableDataStack(seriesModel,{schema:schema,store:store});var data=new SeriesData$1(schema,seriesModel);data.setCalculationInfo(stackCalculationInfo);var dimValueGetter=firstCategoryDimIndex!=null&&isNeedCompleteOrdinalData(source)?function(itemOpt,dimName,dataIndex,dimIndex){// Use dataIndex as ordinal value in categoryAxis return dimIndex===firstCategoryDimIndex?dataIndex:this.defaultDimValueGetter(itemOpt,dimName,dataIndex,dimIndex);}:null;data.hasItemOption=false;data.initData(// Try to reuse the data store in sourceManager if using dataset. isOriginalSource?source:store,null,dimValueGetter);return data;}function isNeedCompleteOrdinalData(source){if(source.sourceFormat===SOURCE_FORMAT_ORIGINAL){var sampleItem=firstDataNotNull(source.data||[]);return!isArray(getDataItemValue(sampleItem));}}function firstDataNotNull(arr){var i=0;while(iextent[1]&&(extent[1]=other[1]);// not setExtent because in log axis it may transformed to power // this.setExtent(extent[0], extent[1]); };/** * Set extent from data */Scale.prototype.unionExtentFromData=function(data,dim){this.unionExtent(data.getApproximateExtent(dim));};/** * Get extent * * Extent is always in increase order. */Scale.prototype.getExtent=function(){return this._extent.slice();};/** * Set extent */Scale.prototype.setExtent=function(start,end){var thisExtent=this._extent;if(!isNaN(start)){thisExtent[0]=start;}if(!isNaN(end)){thisExtent[1]=end;}};/** * If value is in extent range */Scale.prototype.isInExtentRange=function(value){return this._extent[0]<=value&&this._extent[1]>=value;};/** * When axis extent depends on data and no data exists, * axis ticks should not be drawn, which is named 'blank'. */Scale.prototype.isBlank=function(){return this._isBlank;};/** * When axis extent depends on data and no data exists, * axis ticks should not be drawn, which is named 'blank'. */Scale.prototype.setBlank=function(isBlank){this._isBlank=isBlank;};return Scale;}();enableClassManagement(Scale);var Scale$1=Scale;var uidBase=0;var OrdinalMeta=/** @class */function(){function OrdinalMeta(opt){this.categories=opt.categories||[];this._needCollect=opt.needCollect;this._deduplication=opt.deduplication;this.uid=++uidBase;}OrdinalMeta.createByAxisModel=function(axisModel){var option=axisModel.option;var data=option.data;var categories=data&&map$1(data,getName);return new OrdinalMeta({categories:categories,needCollect:!categories,// deduplication is default in axis. deduplication:option.dedplication!==false});};OrdinalMeta.prototype.getOrdinal=function(category){// @ts-ignore return this._getOrCreateMap().get(category);};/** * @return The ordinal. If not found, return NaN. */OrdinalMeta.prototype.parseAndCollect=function(category){var index;var needCollect=this._needCollect;// The value of category dim can be the index of the given category set. // This feature is only supported when !needCollect, because we should // consider a common case: a value is 2017, which is a number but is // expected to be tread as a category. This case usually happen in dataset, // where it happent to be no need of the index feature. if(!isString(category)&&!needCollect){return category;}// Optimize for the scenario: // category is ['2012-01-01', '2012-01-02', ...], where the input // data has been ensured not duplicate and is large data. // Notice, if a dataset dimension provide categroies, usually echarts // should remove duplication except user tell echarts dont do that // (set axis.deduplication = false), because echarts do not know whether // the values in the category dimension has duplication (consider the // parallel-aqi example) if(needCollect&&!this._deduplication){index=this.categories.length;this.categories[index]=category;return index;}var map=this._getOrCreateMap();// @ts-ignore index=map.get(category);if(index==null){if(needCollect){index=this.categories.length;this.categories[index]=category;// @ts-ignore map.set(category,index);}else{index=NaN;}}return index;};// Consider big data, do not create map until needed. OrdinalMeta.prototype._getOrCreateMap=function(){return this._map||(this._map=createHashMap(this.categories));};return OrdinalMeta;}();function getName(obj){if(isObject$2(obj)&&obj.value!=null){return obj.value;}else{return obj+'';}}var OrdinalMeta$1=OrdinalMeta;function isIntervalOrLogScale(scale){return scale.type==='interval'||scale.type==='log';}/** * @param extent Both extent[0] and extent[1] should be valid number. * Should be extent[0] < extent[1]. * @param splitNumber splitNumber should be >= 1. */function intervalScaleNiceTicks(extent,splitNumber,minInterval,maxInterval){var result={};var span=extent[1]-extent[0];var interval=result.interval=nice(span/splitNumber,true);if(minInterval!=null&&intervalmaxInterval){interval=result.interval=maxInterval;}// Tow more digital for tick. var precision=result.intervalPrecision=getIntervalPrecision(interval);// Niced extent inside original extent var niceTickExtent=result.niceTickExtent=[round$1(Math.ceil(extent[0]/interval)*interval,precision),round$1(Math.floor(extent[1]/interval)*interval,precision)];fixExtent(niceTickExtent,extent);return result;}function increaseInterval(interval){var exp10=Math.pow(10,quantityExponent(interval));// Increase interval var f=interval/exp10;if(!f){f=1;}else if(f===2){f=3;}else if(f===3){f=5;}else{// f is 1 or 5 f*=2;}return round$1(f*exp10);}/** * @return interval precision */function getIntervalPrecision(interval){// Tow more digital for tick. return getPrecision(interval)+2;}function clamp(niceTickExtent,idx,extent){niceTickExtent[idx]=Math.max(Math.min(niceTickExtent[idx],extent[1]),extent[0]);}// In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent. function fixExtent(niceTickExtent,extent){!isFinite(niceTickExtent[0])&&(niceTickExtent[0]=extent[0]);!isFinite(niceTickExtent[1])&&(niceTickExtent[1]=extent[1]);clamp(niceTickExtent,0,extent);clamp(niceTickExtent,1,extent);if(niceTickExtent[0]>niceTickExtent[1]){niceTickExtent[0]=niceTickExtent[1];}}function contain(val,extent){return val>=extent[0]&&val<=extent[1];}function normalize(val,extent){if(extent[1]===extent[0]){return 0.5;}return(val-extent[0])/(extent[1]-extent[0]);}function scale(val,extent){return val*(extent[1]-extent[0])+extent[0];}var OrdinalScale=/** @class */function(_super){__extends$1(OrdinalScale,_super);function OrdinalScale(setting){var _this=_super.call(this,setting)||this;_this.type='ordinal';var ordinalMeta=_this.getSetting('ordinalMeta');// Caution: Should not use instanceof, consider ec-extensions using // import approach to get OrdinalMeta class. if(!ordinalMeta){ordinalMeta=new OrdinalMeta$1({});}if(isArray(ordinalMeta)){ordinalMeta=new OrdinalMeta$1({categories:map$1(ordinalMeta,function(item){return isObject$2(item)?item.value:item;})});}_this._ordinalMeta=ordinalMeta;_this._extent=_this.getSetting('extent')||[0,ordinalMeta.categories.length-1];return _this;}OrdinalScale.prototype.parse=function(val){// Caution: Math.round(null) will return `0` rather than `NaN` if(val==null){return NaN;}return isString(val)?this._ordinalMeta.getOrdinal(val)// val might be float. :Math.round(val);};OrdinalScale.prototype.contain=function(rank){rank=this.parse(rank);return contain(rank,this._extent)&&this._ordinalMeta.categories[rank]!=null;};/** * Normalize given rank or name to linear [0, 1] * @param val raw ordinal number. * @return normalized value in [0, 1]. */OrdinalScale.prototype.normalize=function(val){val=this._getTickNumber(this.parse(val));return normalize(val,this._extent);};/** * @param val normalized value in [0, 1]. * @return raw ordinal number. */OrdinalScale.prototype.scale=function(val){val=Math.round(scale(val,this._extent));return this.getRawOrdinalNumber(val);};OrdinalScale.prototype.getTicks=function(){var ticks=[];var extent=this._extent;var rank=extent[0];while(rank<=extent[1]){ticks.push({value:rank});rank++;}return ticks;};OrdinalScale.prototype.getMinorTicks=function(splitNumber){// Not support. return;};/** * @see `Ordinal['_ordinalNumbersByTick']` */OrdinalScale.prototype.setSortInfo=function(info){if(info==null){this._ordinalNumbersByTick=this._ticksByOrdinalNumber=null;return;}var infoOrdinalNumbers=info.ordinalNumbers;var ordinalsByTick=this._ordinalNumbersByTick=[];var ticksByOrdinal=this._ticksByOrdinalNumber=[];// Unnecessary support negative tick in `realtimeSort`. var tickNum=0;var allCategoryLen=this._ordinalMeta.categories.length;for(var len=Math.min(allCategoryLen,infoOrdinalNumbers.length);tickNum=0&&ordinal=0&&tickNumber=value;};OrdinalScale.prototype.getOrdinalMeta=function(){return this._ordinalMeta;};OrdinalScale.prototype.calcNiceTicks=function(){};OrdinalScale.prototype.calcNiceExtent=function(){};OrdinalScale.type='ordinal';return OrdinalScale;}(Scale$1);Scale$1.registerClass(OrdinalScale);var OrdinalScale$1=OrdinalScale;var roundNumber=round$1;var IntervalScale=/** @class */function(_super){__extends$1(IntervalScale,_super);function IntervalScale(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.type='interval';// Step is calculated in adjustExtent. _this._interval=0;_this._intervalPrecision=2;return _this;}IntervalScale.prototype.parse=function(val){return val;};IntervalScale.prototype.contain=function(val){return contain(val,this._extent);};IntervalScale.prototype.normalize=function(val){return normalize(val,this._extent);};IntervalScale.prototype.scale=function(val){return scale(val,this._extent);};IntervalScale.prototype.setExtent=function(start,end){var thisExtent=this._extent;// start,end may be a Number like '25',so... if(!isNaN(start)){thisExtent[0]=parseFloat(start);}if(!isNaN(end)){thisExtent[1]=parseFloat(end);}};IntervalScale.prototype.unionExtent=function(other){var extent=this._extent;other[0]extent[1]&&(extent[1]=other[1]);// unionExtent may called by it's sub classes this.setExtent(extent[0],extent[1]);};IntervalScale.prototype.getInterval=function(){return this._interval;};IntervalScale.prototype.setInterval=function(interval){this._interval=interval;// Dropped auto calculated niceExtent and use user setted extent // We assume user wan't to set both interval, min, max to get a better result this._niceExtent=this._extent.slice();this._intervalPrecision=getIntervalPrecision(interval);};/** * @param expandToNicedExtent Whether expand the ticks to niced extent. */IntervalScale.prototype.getTicks=function(expandToNicedExtent){var interval=this._interval;var extent=this._extent;var niceTickExtent=this._niceExtent;var intervalPrecision=this._intervalPrecision;var ticks=[];// If interval is 0, return []; if(!interval){return ticks;}// Consider this case: using dataZoom toolbox, zoom and zoom. var safeLimit=10000;if(extent[0]safeLimit){return[];}}// Consider this case: the last item of ticks is smaller // than niceTickExtent[1] and niceTickExtent[1] === extent[1]. var lastNiceTick=ticks.length?ticks[ticks.length-1].value:niceTickExtent[1];if(extent[1]>lastNiceTick){if(expandToNicedExtent){ticks.push({value:roundNumber(lastNiceTick+interval,intervalPrecision)});}else{ticks.push({value:extent[1]});}}return ticks;};IntervalScale.prototype.getMinorTicks=function(splitNumber){var ticks=this.getTicks(true);var minorTicks=[];var extent=this.getExtent();for(var i=1;iextent[0]&&minorTick0){// Ignore 0 delta because they are of the same axis value min=min===null?delta:Math.min(min,delta);}}// Set to null if only have one data axisMinGaps[key]=min;}}}return axisMinGaps;}function makeColumnLayout(barSeries){var axisMinGaps=getValueAxesMinGaps(barSeries);var seriesInfoList=[];each$7(barSeries,function(seriesModel){var cartesian=seriesModel.coordinateSystem;var baseAxis=cartesian.getBaseAxis();var axisExtent=baseAxis.getExtent();var bandWidth;if(baseAxis.type==='category'){bandWidth=baseAxis.getBandWidth();}else if(baseAxis.type==='value'||baseAxis.type==='time'){var key=baseAxis.dim+'_'+baseAxis.index;var minGap=axisMinGaps[key];var extentSpan=Math.abs(axisExtent[1]-axisExtent[0]);var scale=baseAxis.scale.getExtent();var scaleSpan=Math.abs(scale[1]-scale[0]);bandWidth=minGap?extentSpan/scaleSpan*minGap:extentSpan;// When there is only one data value }else{var data=seriesModel.getData();bandWidth=Math.abs(axisExtent[1]-axisExtent[0])/data.count();}var barWidth=parsePercent(seriesModel.get('barWidth'),bandWidth);var barMaxWidth=parsePercent(seriesModel.get('barMaxWidth'),bandWidth);var barMinWidth=parsePercent(// barMinWidth by default is 0.5 / 1 in cartesian. Because in value axis, // the auto-calculated bar width might be less than 0.5 / 1. seriesModel.get('barMinWidth')||(isInLargeMode(seriesModel)?0.5:1),bandWidth);var barGap=seriesModel.get('barGap');var barCategoryGap=seriesModel.get('barCategoryGap');seriesInfoList.push({bandWidth:bandWidth,barWidth:barWidth,barMaxWidth:barMaxWidth,barMinWidth:barMinWidth,barGap:barGap,barCategoryGap:barCategoryGap,axisKey:getAxisKey(baseAxis),stackId:getSeriesStackId(seriesModel)});});return doCalBarWidthAndOffset(seriesInfoList);}function doCalBarWidthAndOffset(seriesInfoList){// Columns info on each category axis. Key is cartesian name var columnsMap={};each$7(seriesInfoList,function(seriesInfo,idx){var axisKey=seriesInfo.axisKey;var bandWidth=seriesInfo.bandWidth;var columnsOnAxis=columnsMap[axisKey]||{bandWidth:bandWidth,remainedWidth:bandWidth,autoWidthCount:0,categoryGap:null,gap:'20%',stacks:{}};var stacks=columnsOnAxis.stacks;columnsMap[axisKey]=columnsOnAxis;var stackId=seriesInfo.stackId;if(!stacks[stackId]){columnsOnAxis.autoWidthCount++;}stacks[stackId]=stacks[stackId]||{width:0,maxWidth:0};// Caution: In a single coordinate system, these barGrid attributes // will be shared by series. Consider that they have default values, // only the attributes set on the last series will work. // Do not change this fact unless there will be a break change. var barWidth=seriesInfo.barWidth;if(barWidth&&!stacks[stackId].width){// See #6312, do not restrict 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;barGap!=null&&(columnsOnAxis.gap=barGap);var barCategoryGap=seriesInfo.barCategoryGap;barCategoryGap!=null&&(columnsOnAxis.categoryGap=barCategoryGap);});var result={};each$7(columnsMap,function(columnsOnAxis,coordSysName){result[coordSysName]={};var stacks=columnsOnAxis.stacks;var bandWidth=columnsOnAxis.bandWidth;var categoryGapPercent=columnsOnAxis.categoryGap;if(categoryGapPercent==null){var columnCount=keys(stacks).length;// More columns in one group // the spaces between group is smaller. Or the column will be too thin. categoryGapPercent=Math.max(35-columnCount*4,15)+'%';}var categoryGap=parsePercent(categoryGapPercent,bandWidth);var barGapPercent=parsePercent(columnsOnAxis.gap,1);var remainedWidth=columnsOnAxis.remainedWidth;var autoWidthCount=columnsOnAxis.autoWidthCount;var autoWidth=(remainedWidth-categoryGap)/(autoWidthCount+(autoWidthCount-1)*barGapPercent);autoWidth=Math.max(autoWidth,0);// Find if any auto calculated bar exceeded maxBarWidth each$7(stacks,function(column){var maxWidth=column.maxWidth;var minWidth=column.minWidth;if(!column.width){var finalWidth=autoWidth;if(maxWidth&&maxWidthfinalWidth){finalWidth=minWidth;}if(finalWidth!==autoWidth){column.width=finalWidth;remainedWidth-=finalWidth+barGapPercent*finalWidth;autoWidthCount--;}}else{// `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as // CSS does. Becuase barWidth can be a percent value, where // `barMaxWidth` can be used to restrict the final width. var finalWidth=column.width;if(maxWidth){finalWidth=Math.min(finalWidth,maxWidth);}// `minWidth` has higher priority, as described above if(minWidth){finalWidth=Math.max(finalWidth,minWidth);}column.width=finalWidth;remainedWidth-=finalWidth+barGapPercent*finalWidth;autoWidthCount--;}});// Recalculate width again autoWidth=(remainedWidth-categoryGap)/(autoWidthCount+(autoWidthCount-1)*barGapPercent);autoWidth=Math.max(autoWidth,0);var widthSum=0;var lastColumn;each$7(stacks,function(column,idx){if(!column.width){column.width=autoWidth;}lastColumn=column;widthSum+=column.width*(1+barGapPercent);});if(lastColumn){widthSum-=lastColumn.width*barGapPercent;}var offset=-widthSum/2;each$7(stacks,function(column,stackId){result[coordSysName][stackId]=result[coordSysName][stackId]||{bandWidth:bandWidth,offset:offset,width:column.width};offset+=column.width*(1+barGapPercent);});});return result;}function retrieveColumnLayout(barWidthAndOffset,axis,seriesModel){if(barWidthAndOffset&&axis){var result=barWidthAndOffset[getAxisKey(axis)];if(result!=null&&seriesModel!=null){return result[getSeriesStackId(seriesModel)];}return result;}}function layout$2(seriesType,ecModel){var seriesModels=prepareLayoutBarSeries(seriesType,ecModel);var barWidthAndOffset=makeColumnLayout(seriesModels);each$7(seriesModels,function(seriesModel){var data=seriesModel.getData();var cartesian=seriesModel.coordinateSystem;var baseAxis=cartesian.getBaseAxis();var stackId=getSeriesStackId(seriesModel);var columnLayoutInfo=barWidthAndOffset[getAxisKey(baseAxis)][stackId];var columnOffset=columnLayoutInfo.offset;var columnWidth=columnLayoutInfo.width;data.setLayout({bandWidth:columnLayoutInfo.bandWidth,offset:columnOffset,size:columnWidth});});}// TODO: Do not support stack in large mode yet. function createProgressiveLayout(seriesType){return{seriesType:seriesType,plan:createRenderPlanner(),reset:function reset(seriesModel){if(!isOnCartesian(seriesModel)){return;}var data=seriesModel.getData();var cartesian=seriesModel.coordinateSystem;var baseAxis=cartesian.getBaseAxis();var valueAxis=cartesian.getOtherAxis(baseAxis);var valueDimIdx=data.getDimensionIndex(data.mapDimension(valueAxis.dim));var baseDimIdx=data.getDimensionIndex(data.mapDimension(baseAxis.dim));var drawBackground=seriesModel.get('showBackground',true);var valueDim=data.mapDimension(valueAxis.dim);var stackResultDim=data.getCalculationInfo('stackResultDimension');var stacked=isDimensionStacked(data,valueDim)&&!!data.getCalculationInfo('stackedOnSeries');var isValueAxisH=valueAxis.isHorizontal();var valueAxisStart=getValueAxisStart(baseAxis,valueAxis);var isLarge=isInLargeMode(seriesModel);var barMinHeight=seriesModel.get('barMinHeight')||0;var stackedDimIdx=stackResultDim&&data.getDimensionIndex(stackResultDim);// Layout info. var columnWidth=data.getLayout('size');var columnOffset=data.getLayout('offset');return{progress:function progress(params,data){var count=params.count;var largePoints=isLarge&&createFloat32Array(count*3);var largeBackgroundPoints=isLarge&&drawBackground&&createFloat32Array(count*3);var largeDataIndices=isLarge&&createFloat32Array(count);var coordLayout=cartesian.master.getRect();var bgSize=isValueAxisH?coordLayout.width:coordLayout.height;var dataIndex;var store=data.getStore();var idxOffset=0;while((dataIndex=params.next())!=null){var value=store.get(stacked?stackedDimIdx:valueDimIdx,dataIndex);var baseValue=store.get(baseDimIdx,dataIndex);var baseCoord=valueAxisStart;var startValue=void 0;// Because of the barMinHeight, we can not use the value in // stackResultDimension directly. if(stacked){startValue=+value-store.get(valueDimIdx,dataIndex);}var x=void 0;var y=void 0;var width=void 0;var height=void 0;if(isValueAxisH){var coord=cartesian.dataToPoint([value,baseValue]);if(stacked){var startCoord=cartesian.dataToPoint([startValue,baseValue]);baseCoord=startCoord[0];}x=baseCoord;y=coord[1]+columnOffset;width=coord[0]-baseCoord;height=columnWidth;if(Math.abs(width)>>1;if(a[mid][1]maxInterval){this._approxInterval=maxInterval;}var scaleIntervalsLen=scaleIntervals.length;var idx=Math.min(bisect(scaleIntervals,this._approxInterval,0,scaleIntervalsLen),scaleIntervalsLen-1);// Interval that can be used to calculate ticks this._interval=scaleIntervals[idx][1];// Min level used when picking ticks from top down. // We check one more level to avoid the ticks are to sparse in some case. this._minLevelUnit=scaleIntervals[Math.max(idx-1,0)][0];};TimeScale.prototype.parse=function(val){// val might be float. return isNumber(val)?val:+parseDate(val);};TimeScale.prototype.contain=function(val){return contain(this.parse(val),this._extent);};TimeScale.prototype.normalize=function(val){return normalize(this.parse(val),this._extent);};TimeScale.prototype.scale=function(val){return scale(val,this._extent);};TimeScale.type='time';return TimeScale;}(IntervalScale$1);/** * This implementation was originally copied from "d3.js" * * with some modifications made for this program. * See the license statement at the head of this file. */var scaleIntervals=[// Format interval ['second',ONE_SECOND],['minute',ONE_MINUTE],['hour',ONE_HOUR],['quarter-day',ONE_HOUR*6],['half-day',ONE_HOUR*12],['day',ONE_DAY*1.2],['half-week',ONE_DAY*3.5],['week',ONE_DAY*7],['month',ONE_DAY*31],['quarter',ONE_DAY*95],['half-year',ONE_YEAR/2],['year',ONE_YEAR]// 1Y ];function isUnitValueSame(unit,valueA,valueB,isUTC){var dateA=parseDate(valueA);var dateB=parseDate(valueB);var isSame=function isSame(unit){return getUnitValue(dateA,unit,isUTC)===getUnitValue(dateB,unit,isUTC);};var isSameYear=function isSameYear(){return isSame('year');};// const isSameHalfYear = () => isSameYear() && isSame('half-year'); // const isSameQuater = () => isSameYear() && isSame('quarter'); var isSameMonth=function isSameMonth(){return isSameYear()&&isSame('month');};var isSameDay=function isSameDay(){return isSameMonth()&&isSame('day');};// const isSameHalfDay = () => isSameDay() && isSame('half-day'); var isSameHour=function isSameHour(){return isSameDay()&&isSame('hour');};var isSameMinute=function isSameMinute(){return isSameHour()&&isSame('minute');};var isSameSecond=function isSameSecond(){return isSameMinute()&&isSame('second');};var isSameMilliSecond=function isSameMilliSecond(){return isSameSecond()&&isSame('millisecond');};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 isSameMilliSecond();}}// const primaryUnitGetters = { // year: fullYearGetterName(), // month: monthGetterName(), // day: dateGetterName(), // hour: hoursGetterName(), // minute: minutesGetterName(), // second: secondsGetterName(), // millisecond: millisecondsGetterName() // }; // const primaryUnitUTCGetters = { // year: fullYearGetterName(true), // month: monthGetterName(true), // day: dateGetterName(true), // hour: hoursGetterName(true), // minute: minutesGetterName(true), // second: secondsGetterName(true), // millisecond: millisecondsGetterName(true) // }; // function moveTick(date: Date, unitName: TimeUnit, step: number, isUTC: boolean) { // step = step || 1; // switch (getPrimaryTimeUnit(unitName)) { // case 'year': // date[fullYearSetterName(isUTC)](date[fullYearGetterName(isUTC)]() + step); // break; // case 'month': // date[monthSetterName(isUTC)](date[monthGetterName(isUTC)]() + step); // break; // case 'day': // date[dateSetterName(isUTC)](date[dateGetterName(isUTC)]() + step); // break; // case 'hour': // date[hoursSetterName(isUTC)](date[hoursGetterName(isUTC)]() + step); // break; // case 'minute': // date[minutesSetterName(isUTC)](date[minutesGetterName(isUTC)]() + step); // break; // case 'second': // date[secondsSetterName(isUTC)](date[secondsGetterName(isUTC)]() + step); // break; // case 'millisecond': // date[millisecondsSetterName(isUTC)](date[millisecondsGetterName(isUTC)]() + step); // break; // } // return date.getTime(); // } // const DATE_INTERVALS = [[8, 7.5], [4, 3.5], [2, 1.5]]; // const MONTH_INTERVALS = [[6, 5.5], [3, 2.5], [2, 1.5]]; // const MINUTES_SECONDS_INTERVALS = [[30, 30], [20, 20], [15, 15], [10, 10], [5, 5], [2, 2]]; function getDateInterval(approxInterval,daysInMonth){approxInterval/=ONE_DAY;return approxInterval>16?16// Math.floor(daysInMonth / 2) + 1 // In this case we only want one tick betwen two month. :approxInterval>7.5?7// TODO week 7 or day 8? :approxInterval>3.5?4:approxInterval>1.5?2:1;}function getMonthInterval(approxInterval){var APPROX_ONE_MONTH=30*ONE_DAY;approxInterval/=APPROX_ONE_MONTH;return approxInterval>6?6:approxInterval>3?3:approxInterval>2?2:1;}function getHourInterval(approxInterval){approxInterval/=ONE_HOUR;return approxInterval>12?12:approxInterval>6?6:approxInterval>3.5?4:approxInterval>2?2:1;}function getMinutesAndSecondsInterval(approxInterval,isMinutes){approxInterval/=isMinutes?ONE_MINUTE:ONE_SECOND;return approxInterval>30?30:approxInterval>20?20:approxInterval>15?15:approxInterval>10?10:approxInterval>5?5:approxInterval>2?2:1;}function getMillisecondsInterval(approxInterval){return nice(approxInterval,true);}function getFirstTimestampOfUnit(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();}function getIntervalTicks(bottomUnitName,approxInterval,isUTC,extent){var safeLimit=10000;var unitNames=timeUnits;var iter=0;function addTicksInSpan(interval,minTimestamp,maxTimestamp,getMethodName,setMethodName,isDate,out){var date=new Date(minTimestamp);var dateTime=minTimestamp;var d=date[getMethodName]();// if (isDate) { // d -= 1; // Starts with 0; PENDING // } while(dateTime1&&i===0){// Add nearest years to the left extent. levelTicks.unshift({value:levelTicks[0].value-interval});}}for(var i=0;i=extent[0]&&tickValue<=extent[1]){tickCount++;}}}var targetTickNum=(extent[1]-extent[0])/approxInterval;// Added too much in this level and not too less in last level if(tickCount>targetTickNum*1.5&&lastLevelTickCount>targetTickNum/1.5){break;}// Only treat primary time unit as one level. levelsTicks.push(levelTicksRemoveDuplicated);if(tickCount>targetTickNum||bottomUnitName===unitNames[i]){break;}}// Reset if next unitName is primary currentLevelTicks=[];}}var levelsTicksInExtent=filter(map$1(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;});var ticks=[];var maxLevel=levelsTicksInExtent.length-1;for(var i=0;i0){interval*=10;}var niceExtent=[round$1(mathCeil(extent[0]/interval)*interval),round$1(mathFloor(extent[1]/interval)*interval)];this._interval=interval;this._niceExtent=niceExtent;};LogScale.prototype.calcNiceExtent=function(opt){intervalScaleProto.calcNiceExtent.call(this,opt);this._fixMin=opt.fixMin;this._fixMax=opt.fixMax;};LogScale.prototype.parse=function(val){return val;};LogScale.prototype.contain=function(val){val=mathLog$1(val)/mathLog$1(this.base);return contain(val,this._extent);};LogScale.prototype.normalize=function(val){val=mathLog$1(val)/mathLog$1(this.base);return normalize(val,this._extent);};LogScale.prototype.scale=function(val){val=scale(val,this._extent);return mathPow$1(this.base,val);};LogScale.type='log';return LogScale;}(Scale$1);var proto=LogScale.prototype;proto.getMinorTicks=intervalScaleProto.getMinorTicks;proto.getLabel=intervalScaleProto.getLabel;function fixRoundingError(val,originalVal){return roundingErrorFix(val,getPrecision(originalVal));}Scale$1.registerClass(LogScale);var LogScale$1=LogScale;var ScaleRawExtentInfo=/** @class */function(){function ScaleRawExtentInfo(scale,model,// Usually: data extent from all series on this axis. originalExtent){this._prepareParams(scale,model,originalExtent);}/** * Parameters depending on ouside (like model, user callback) * are prepared and fixed here. */ScaleRawExtentInfo.prototype._prepareParams=function(scale,model,// Usually: data extent from all series on this axis. dataExtent){if(dataExtent[1]0&&max>0&&!minFixed){min=0;// minFixed = true; }// Axis is under zero and max is not set if(min<0&&max<0&&!maxFixed){max=0;// maxFixed = true; }// PENDING: // When `needCrossZero` and all data is positive/negative, should it be ensured // that the results processed by boundaryGap are positive/negative? // If so, here `minFixed`/`maxFixed` need to be set. }var determinedMin=this._determinedMin;var determinedMax=this._determinedMax;if(determinedMin!=null){min=determinedMin;minFixed=true;}if(determinedMax!=null){max=determinedMax;maxFixed=true;}// Ensure min/max be finite number or NaN here. (not to be null/undefined) // `NaN` means min/max axis is blank. return{min:min,max:max,minFixed:minFixed,maxFixed:maxFixed,isBlank:isBlank};};ScaleRawExtentInfo.prototype.modifyDataMinMax=function(minMaxName,val){this[DATA_MIN_MAX_ATTR[minMaxName]]=val;};ScaleRawExtentInfo.prototype.setDeterminedMinMax=function(minMaxName,val){var attr=DETERMINED_MIN_MAX_ATTR[minMaxName];this[attr]=val;};ScaleRawExtentInfo.prototype.freeze=function(){// @ts-ignore this.frozen=true;};return ScaleRawExtentInfo;}();var DETERMINED_MIN_MAX_ATTR={min:'_determinedMin',max:'_determinedMax'};var DATA_MIN_MAX_ATTR={min:'_dataMin',max:'_dataMax'};/** * Get scale min max and related info only depends on model settings. * This method can be called after coordinate system created. * For example, in data processing stage. * * Scale extent info probably be required multiple times during a workflow. * For example: * (1) `dataZoom` depends it to get the axis extent in "100%" state. * (2) `processor/extentCalculator` depends it to make sure whether axis extent is specified. * (3) `coordSys.update` use it to finally decide the scale extent. * But the callback of `min`/`max` should not be called multiple times. * The code below should not be implemented repeatedly either. * So we cache the result in the scale instance, which will be recreated at the begining * of the workflow (because `scale` instance will be recreated each round of the workflow). */function ensureScaleRawExtentInfo(scale,model,// Usually: data extent from all series on this axis. originalExtent){// Do not permit to recreate. var rawExtentInfo=scale.rawExtentInfo;if(rawExtentInfo){return rawExtentInfo;}rawExtentInfo=new ScaleRawExtentInfo(scale,model,originalExtent);// @ts-ignore scale.rawExtentInfo=rawExtentInfo;return rawExtentInfo;}function parseAxisModelMinMax(scale,minMax){return minMax==null?null:eqNaN(minMax)?NaN:scale.parse(minMax);}/** * Get axis scale extent before niced. * Item of returned array can only be number (including Infinity and NaN). * * Caution: * Precondition of calling this method: * The scale extent has been initialized using series data extent via * `scale.setExtent` or `scale.unionExtentFromData`; */function getScaleExtent(scale,model){var scaleType=scale.type;var rawExtentResult=ensureScaleRawExtentInfo(scale,model,scale.getExtent()).calculate();scale.setBlank(rawExtentResult.isBlank);var min=rawExtentResult.min;var max=rawExtentResult.max;// If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis // is base axis // FIXME // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent? // Should not depend on series type `bar`? // (3) Fix that might overlap when using dataZoom. // (4) Consider other chart types using `barGrid`? // See #6728, #4862, `test/bar-overflow-time-plot.html` var ecModel=model.ecModel;if(ecModel&&scaleType==='time'/*|| scaleType === 'interval' */){var barSeriesModels=prepareLayoutBarSeries('bar',ecModel);var isBaseAxisAndHasBarSeries_1=false;each$7(barSeriesModels,function(seriesModel){isBaseAxisAndHasBarSeries_1=isBaseAxisAndHasBarSeries_1||seriesModel.getBaseAxis()===model.axis;});if(isBaseAxisAndHasBarSeries_1){// Calculate placement of bars on axis. TODO should be decoupled // with barLayout var barWidthAndOffset=makeColumnLayout(barSeriesModels);// Adjust axis min and max to account for overflow var adjustedScale=adjustScaleForOverflow(min,max,model,barWidthAndOffset);min=adjustedScale.min;max=adjustedScale.max;}}return{extent:[min,max],// "fix" means "fixed", the value should not be // changed in the subsequent steps. fixMin:rawExtentResult.minFixed,fixMax:rawExtentResult.maxFixed};}function adjustScaleForOverflow(min,max,model,// Only support cartesian coord yet. barWidthAndOffset){// Get Axis Length var axisExtent=model.axis.getExtent();var axisLength=axisExtent[1]-axisExtent[0];// Get bars on current base axis and calculate min and max overflow var barsOnCurrentAxis=retrieveColumnLayout(barWidthAndOffset,model.axis);if(barsOnCurrentAxis===undefined){return{min:min,max:max};}var minOverflow=Infinity;each$7(barsOnCurrentAxis,function(item){minOverflow=Math.min(item.offset,minOverflow);});var maxOverflow=-Infinity;each$7(barsOnCurrentAxis,function(item){maxOverflow=Math.max(item.offset+item.width,maxOverflow);});minOverflow=Math.abs(minOverflow);maxOverflow=Math.abs(maxOverflow);var totalOverFlow=minOverflow+maxOverflow;// Calculate required buffer based on old range and overflow var oldRange=max-min;var oldRangePercentOfNew=1-(minOverflow+maxOverflow)/axisLength;var overflowBuffer=oldRange/oldRangePercentOfNew-oldRange;max+=overflowBuffer*(maxOverflow/totalOverFlow);min-=overflowBuffer*(minOverflow/totalOverFlow);return{min:min,max:max};}// Precondition of calling this method: // The scale extent has been initailized using series data extent via // `scale.setExtent` or `scale.unionExtentFromData`; function niceScaleExtent(scale,inModel){var model=inModel;var extentInfo=getScaleExtent(scale,model);var extent=extentInfo.extent;var splitNumber=model.get('splitNumber');if(scale instanceof LogScale$1){scale.base=model.get('logBase');}var scaleType=scale.type;var interval=model.get('interval');var isIntervalOrTime=scaleType==='interval'||scaleType==='time';scale.setExtent(extent[0],extent[1]);scale.calcNiceExtent({splitNumber:splitNumber,fixMin:extentInfo.fixMin,fixMax:extentInfo.fixMax,minInterval:isIntervalOrTime?model.get('minInterval'):null,maxInterval:isIntervalOrTime?model.get('maxInterval'):null});// If some one specified the min, max. And the default calculated interval // is not good enough. He can specify the interval. It is often appeared // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard // to be 60. // FIXME if(interval!=null){scale.setInterval&&scale.setInterval(interval);}}/** * @param axisType Default retrieve from model.type */function createScaleByModel(model,axisType){axisType=axisType||model.get('type');if(axisType){switch(axisType){// Buildin scale case'category':return new OrdinalScale$1({ordinalMeta:model.getOrdinalMeta?model.getOrdinalMeta():model.getCategories(),extent:[Infinity,-Infinity]});case'time':return new TimeScale$1({locale:model.ecModel.getLocaleModel(),useUTC:model.ecModel.get('useUTC')});default:// case 'value'/'interval', 'log', or others. return new(Scale$1.getClass(axisType)||IntervalScale$1)();}}}/** * Check if the axis cross 0 */function ifAxisCrossZero(axis){var dataExtent=axis.scale.getExtent();var min=dataExtent[0];var max=dataExtent[1];return!(min>0&&max>0||min<0&&max<0);}/** * @param axis * @return Label formatter function. * param: {number} tickValue, * param: {number} idx, the index in all ticks. * If category axis, this param is not required. * return: {string} label string. */function makeLabelFormatter(axis){var labelFormatter=axis.getLabelModel().get('formatter');var categoryTickStart=axis.type==='category'?axis.scale.getExtent()[0]:null;if(axis.scale.type==='time'){return function(tpl){return function(tick,idx){return axis.scale.getFormattedLabel(tick,idx,tpl);};}(labelFormatter);}else if(isString(labelFormatter)){return function(tpl){return function(tick){// For category axis, get raw value; for numeric axis, // get formatted label like '1,333,444'. var label=axis.scale.getLabel(tick);var text=tpl.replace('{value}',label!=null?label:'');return text;};}(labelFormatter);}else if(isFunction(labelFormatter)){return function(cb){return function(tick,idx){// The original intention of `idx` is "the index of the tick in all ticks". // But the previous implementation of category axis do not consider the // `axisLabel.interval`, which cause that, for example, the `interval` is // `1`, then the ticks "name5", "name7", "name9" are displayed, where the // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep // the definition here for back compatibility. if(categoryTickStart!=null){idx=tick.value-categoryTickStart;}return cb(getAxisRawValue(axis,tick),idx,tick.level!=null?{level:tick.level}:null);};}(labelFormatter);}else{return function(tick){return axis.scale.getLabel(tick);};}}function getAxisRawValue(axis,tick){// In category axis with data zoom, tick is not the original // index of axis.data. So tick should not be exposed to user // in category axis. return axis.type==='category'?axis.scale.getLabel(tick):tick.value;}/** * @param axis * @return Be null/undefined if no labels. */function estimateLabelUnionRect(axis){var axisModel=axis.model;var scale=axis.scale;if(!axisModel.get(['axisLabel','show'])||scale.isBlank()){return;}var realNumberScaleTicks;var tickCount;var categoryScaleExtent=scale.getExtent();// Optimize for large category data, avoid call `getTicks()`. if(scale instanceof OrdinalScale$1){tickCount=scale.count();}else{realNumberScaleTicks=scale.getTicks();tickCount=realNumberScaleTicks.length;}var axisLabelModel=axis.getLabelModel();var labelFormatter=makeLabelFormatter(axis);var rect;var step=1;// Simple optimization for large amount of labels if(tickCount>40){step=Math.ceil(tickCount/40);}for(var i=0;idataExtent[1]&&(dataExtent[1]=seriesExtent[1]);});}}/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * AUTO-GENERATED FILE. DO NOT MODIFY. */ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ // eslint-disable-next-line @typescript-eslint/no-unused-vars var AxisModelCommonMixin=/** @class */function(){function AxisModelCommonMixin(){}AxisModelCommonMixin.prototype.getNeedCrossZero=function(){var option=this.option;return!option.scale;};/** * Should be implemented by each axis model if necessary. * @return coordinate system model */AxisModelCommonMixin.prototype.getCoordSysModel=function(){return;};return AxisModelCommonMixin;}();var extensions=[];var extensionRegisters={registerPreprocessor:registerPreprocessor,registerProcessor:registerProcessor,registerPostInit:registerPostInit,registerPostUpdate:registerPostUpdate,registerUpdateLifecycle:registerUpdateLifecycle,registerAction:registerAction,registerCoordinateSystem:registerCoordinateSystem,registerLayout:registerLayout,registerVisual:registerVisual,registerTransform:registerTransform,registerLoading:registerLoading,registerMap:registerMap,registerImpl:registerImpl,PRIORITY:PRIORITY,ComponentModel:ComponentModel$1,ComponentView:ComponentView$1,SeriesModel:SeriesModel$1,ChartView:ChartView$1,// TODO Use ComponentModel and SeriesModel instead of Constructor registerComponentModel:function registerComponentModel(ComponentModelClass){ComponentModel$1.registerClass(ComponentModelClass);},registerComponentView:function registerComponentView(ComponentViewClass){ComponentView$1.registerClass(ComponentViewClass);},registerSeriesModel:function registerSeriesModel(SeriesModelClass){SeriesModel$1.registerClass(SeriesModelClass);},registerChartView:function registerChartView(ChartViewClass){ChartView$1.registerClass(ChartViewClass);},registerSubTypeDefaulter:function registerSubTypeDefaulter(componentType,defaulter){ComponentModel$1.registerSubTypeDefaulter(componentType,defaulter);},registerPainter:function registerPainter(painterType,PainterCtor){_registerPainter(painterType,PainterCtor);}};function use(ext){if(isArray(ext)){// use([ChartLine, ChartBar]); each$7(ext,function(singleExt){use(singleExt);});return;}if(indexOf(extensions,ext)>=0){return;}extensions.push(ext);if(isFunction(ext)){ext={install:ext};}ext.install(extensionRegisters);}var inner$6=makeInner();function createAxisLabels(axis){// Only ordinal scale support tick interval return axis.type==='category'?makeCategoryLabels(axis):makeRealNumberLabels(axis);}/** * @param {module:echats/coord/Axis} axis * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea. * @return {Object} { * ticks: Array. * tickCategoryInterval: number * } */function createAxisTicks(axis,tickModel){// Only ordinal scale support tick interval return axis.type==='category'?makeCategoryTicks(axis,tickModel):{ticks:map$1(axis.scale.getTicks(),function(tick){return tick.value;})};}function makeCategoryLabels(axis){var labelModel=axis.getLabelModel();var result=makeCategoryLabelsActually(axis,labelModel);return!labelModel.get('show')||axis.scale.isBlank()?{labels:[],labelCategoryInterval:result.labelCategoryInterval}:result;}function makeCategoryLabelsActually(axis,labelModel){var labelsCache=getListCache(axis,'labels');var optionLabelInterval=getOptionCategoryInterval(labelModel);var result=listCacheGet(labelsCache,optionLabelInterval);if(result){return result;}var labels;var numericLabelInterval;if(isFunction(optionLabelInterval)){labels=makeLabelsByCustomizedCategoryInterval(axis,optionLabelInterval);}else{numericLabelInterval=optionLabelInterval==='auto'?makeAutoCategoryInterval(axis):optionLabelInterval;labels=makeLabelsByNumericCategoryInterval(axis,numericLabelInterval);}// Cache to avoid calling interval function repeatly. return listCacheSet(labelsCache,optionLabelInterval,{labels:labels,labelCategoryInterval:numericLabelInterval});}function makeCategoryTicks(axis,tickModel){var ticksCache=getListCache(axis,'ticks');var optionTickInterval=getOptionCategoryInterval(tickModel);var result=listCacheGet(ticksCache,optionTickInterval);if(result){return result;}var ticks;var tickCategoryInterval;// Optimize for the case that large category data and no label displayed, // we should not return all ticks. if(!tickModel.get('show')||axis.scale.isBlank()){ticks=[];}if(isFunction(optionTickInterval)){ticks=makeLabelsByCustomizedCategoryInterval(axis,optionTickInterval,true);}// Always use label interval by default despite label show. Consider this // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows // labels. `splitLine` and `axisTick` should be consistent in this case. else if(optionTickInterval==='auto'){var labelsResult=makeCategoryLabelsActually(axis,axis.getLabelModel());tickCategoryInterval=labelsResult.labelCategoryInterval;ticks=map$1(labelsResult.labels,function(labelItem){return labelItem.tickValue;});}else{tickCategoryInterval=optionTickInterval;ticks=makeLabelsByNumericCategoryInterval(axis,tickCategoryInterval,true);}// Cache to avoid calling interval function repeatly. return listCacheSet(ticksCache,optionTickInterval,{ticks:ticks,tickCategoryInterval:tickCategoryInterval});}function makeRealNumberLabels(axis){var ticks=axis.scale.getTicks();var labelFormatter=makeLabelFormatter(axis);return{labels:map$1(ticks,function(tick,idx){return{level:tick.level,formattedLabel:labelFormatter(tick,idx),rawLabel:axis.scale.getLabel(tick),tickValue:tick.value};})};}function getListCache(axis,prop){// Because key can be funciton, and cache size always be small, we use array cache. return inner$6(axis)[prop]||(inner$6(axis)[prop]=[]);}function listCacheGet(cache,key){for(var i=0;i40){step=Math.max(1,Math.floor(tickCount/40));}var tickValue=ordinalExtent[0];var unitSpan=axis.dataToCoord(tickValue+1)-axis.dataToCoord(tickValue);var unitW=Math.abs(unitSpan*Math.cos(rotation));var unitH=Math.abs(unitSpan*Math.sin(rotation));var maxW=0;var maxH=0;// Caution: Performance sensitive for large category data. // Consider dataZoom, we should make appropriate step to avoid O(n) loop. for(;tickValue<=ordinalExtent[1];tickValue+=step){var width=0;var height=0;// Not precise, do not consider align and vertical align // and each distance from axis line yet. var rect=getBoundingRect(labelFormatter({value:tickValue}),params.font,'center','top');// Magic number width=rect.width*1.3;height=rect.height*1.3;// Min size, void long loop. maxW=Math.max(maxW,width,7);maxH=Math.max(maxH,height,7);}var dw=maxW/unitW;var dh=maxH/unitH;// 0/0 is NaN, 1/0 is Infinity. isNaN(dw)&&(dw=Infinity);isNaN(dh)&&(dh=Infinity);var interval=Math.max(0,Math.floor(Math.min(dw,dh)));var cache=inner$6(axis.model);var axisExtent=axis.getExtent();var lastAutoInterval=cache.lastAutoInterval;var lastTickCount=cache.lastTickCount;// Use cache to keep interval stable while moving zoom window, // otherwise the calculated interval might jitter when the zoom // window size is close to the interval-changing size. // For example, if all of the axis labels are `a, b, c, d, e, f, g`. // The jitter will cause that sometimes the displayed labels are // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1). if(lastAutoInterval!=null&&lastTickCount!=null&&Math.abs(lastAutoInterval-interval)<=1&&Math.abs(lastTickCount-tickCount)<=1// Always choose the bigger one, otherwise the critical // point is not the same when zooming in or zooming out. &&lastAutoInterval>interval// If the axis change is caused by chart resize, the cache should not // be used. Otherwise some hiden labels might not be shown again. &&cache.axisExtent0===axisExtent[0]&&cache.axisExtent1===axisExtent[1]){interval=lastAutoInterval;}// Only update cache if cache not used, otherwise the // changing of interval is too insensitive. else{cache.lastTickCount=tickCount;cache.lastAutoInterval=interval;cache.axisExtent0=axisExtent[0];cache.axisExtent1=axisExtent[1];}return interval;}function fetchAutoCategoryIntervalCalculationParams(axis){var labelModel=axis.getLabelModel();return{axisRotate:axis.getRotate?axis.getRotate():axis.isHorizontal&&!axis.isHorizontal()?90:0,labelRotate:labelModel.get('rotate')||0,font:labelModel.getFont()};}function makeLabelsByNumericCategoryInterval(axis,categoryInterval,onlyTick){var labelFormatter=makeLabelFormatter(axis);var ordinalScale=axis.scale;var ordinalExtent=ordinalScale.getExtent();var labelModel=axis.getLabelModel();var result=[];// TODO: axisType: ordinalTime, pick the tick from each month/day/year/... var step=Math.max((categoryInterval||0)+1,1);var startTick=ordinalExtent[0];var tickCount=ordinalScale.count();// Calculate start tick based on zero if possible to keep label consistent // while zooming and moving while interval > 0. Otherwise the selection // of displayable ticks and symbols probably keep changing. // 3 is empirical value. if(startTick!==0&&step>1&&tickCount/step>2){startTick=Math.round(Math.ceil(startTick/step)*step);}// (1) Only add min max label here but leave overlap checking // to render stage, which also ensure the returned list // suitable for splitLine and splitArea rendering. // (2) Scales except category always contain min max label so // do not need to perform this process. var showAllLabel=shouldShowAllLabels(axis);var includeMinLabel=labelModel.get('showMinLabel')||showAllLabel;var includeMaxLabel=labelModel.get('showMaxLabel')||showAllLabel;if(includeMinLabel&&startTick!==ordinalExtent[0]){addItem(ordinalExtent[0]);}// Optimize: avoid generating large array by `ordinalScale.getTicks()`. var tickValue=startTick;for(;tickValue<=ordinalExtent[1];tickValue+=step){addItem(tickValue);}if(includeMaxLabel&&tickValue-step!==ordinalExtent[1]){addItem(ordinalExtent[1]);}function addItem(tickValue){var tickObj={value:tickValue};result.push(onlyTick?tickValue:{formattedLabel:labelFormatter(tickObj),rawLabel:ordinalScale.getLabel(tickObj),tickValue:tickValue});}return result;}function makeLabelsByCustomizedCategoryInterval(axis,categoryInterval,onlyTick){var ordinalScale=axis.scale;var labelFormatter=makeLabelFormatter(axis);var result=[];each$7(ordinalScale.getTicks(),function(tick){var rawLabel=ordinalScale.getLabel(tick);var tickValue=tick.value;if(categoryInterval(tick.value,rawLabel)){result.push(onlyTick?tickValue:{formattedLabel:labelFormatter(tick),rawLabel:rawLabel,tickValue:tickValue});}});return result;}var NORMALIZED_EXTENT=[0,1];/** * Base class of Axis. */var Axis=/** @class */function(){function Axis(dim,scale,extent){this.onBand=false;this.inverse=false;this.dim=dim;this.scale=scale;this._extent=extent||[0,0];}/** * If axis extent contain given coord */Axis.prototype.contain=function(coord){var extent=this._extent;var min=Math.min(extent[0],extent[1]);var max=Math.max(extent[0],extent[1]);return coord>=min&&coord<=max;};/** * If axis extent contain given data */Axis.prototype.containData=function(data){return this.scale.contain(data);};/** * Get coord extent. */Axis.prototype.getExtent=function(){return this._extent.slice();};/** * Get precision used for formatting */Axis.prototype.getPixelPrecision=function(dataExtent){return getPixelPrecision(dataExtent||this.scale.getExtent(),this._extent);};/** * Set coord extent */Axis.prototype.setExtent=function(start,end){var extent=this._extent;extent[0]=start;extent[1]=end;};/** * Convert data to coord. Data is the rank if it has an ordinal scale */Axis.prototype.dataToCoord=function(data,clamp){var extent=this._extent;var scale=this.scale;data=scale.normalize(data);if(this.onBand&&scale.type==='ordinal'){extent=extent.slice();fixExtentWithBands(extent,scale.count());}return linearMap(data,NORMALIZED_EXTENT,extent,clamp);};/** * Convert coord to data. Data is the rank if it has an ordinal scale */Axis.prototype.coordToData=function(coord,clamp){var extent=this._extent;var scale=this.scale;if(this.onBand&&scale.type==='ordinal'){extent=extent.slice();fixExtentWithBands(extent,scale.count());}var t=linearMap(coord,extent,NORMALIZED_EXTENT,clamp);return this.scale.scale(t);};/** * Convert pixel point to data in axis */Axis.prototype.pointToData=function(point,clamp){// Should be implemented in derived class if necessary. return;};/** * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`, * `axis.getTicksCoords` considers `onBand`, which is used by * `boundaryGap:true` of category axis and splitLine and splitArea. * @param opt.tickModel default: axis.model.getModel('axisTick') * @param opt.clamp If `true`, the first and the last * tick must be at the axis end points. Otherwise, clip ticks * that outside the axis extent. */Axis.prototype.getTicksCoords=function(opt){opt=opt||{};var tickModel=opt.tickModel||this.getTickModel();var result=createAxisTicks(this,tickModel);var ticks=result.ticks;var ticksCoords=map$1(ticks,function(tickVal){return{coord:this.dataToCoord(this.scale.type==='ordinal'?this.scale.getRawOrdinalNumber(tickVal):tickVal),tickValue:tickVal};},this);var alignWithLabel=tickModel.get('alignWithLabel');fixOnBandTicksCoords(this,ticksCoords,alignWithLabel,opt.clamp);return ticksCoords;};Axis.prototype.getMinorTicksCoords=function(){if(this.scale.type==='ordinal'){// Category axis doesn't support minor ticks return[];}var minorTickModel=this.model.getModel('minorTick');var splitNumber=minorTickModel.get('splitNumber');// Protection. if(!(splitNumber>0&&splitNumber<100)){splitNumber=5;}var minorTicks=this.scale.getMinorTicks(splitNumber);var minorTicksCoords=map$1(minorTicks,function(minorTicksGroup){return map$1(minorTicksGroup,function(minorTick){return{coord:this.dataToCoord(minorTick),tickValue:minorTick};},this);},this);return minorTicksCoords;};Axis.prototype.getViewLabels=function(){return createAxisLabels(this).labels;};Axis.prototype.getLabelModel=function(){return this.model.getModel('axisLabel');};/** * Notice here we only get the default tick model. For splitLine * or splitArea, we should pass the splitLineModel or splitAreaModel * manually when calling `getTicksCoords`. * In GL, this method may be overrided to: * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));` */Axis.prototype.getTickModel=function(){return this.model.getModel('axisTick');};/** * Get width of band */Axis.prototype.getBandWidth=function(){var axisExtent=this._extent;var dataExtent=this.scale.getExtent();var len=dataExtent[1]-dataExtent[0]+(this.onBand?1:0);// Fix #2728, avoid NaN when only one data. len===0&&(len=1);var size=Math.abs(axisExtent[1]-axisExtent[0]);return Math.abs(size)/len;};/** * Only be called in category axis. * Can be overrided, consider other axes like in 3D. * @return Auto interval for cateogry axis tick and label */Axis.prototype.calculateCategoryInterval=function(){return calculateCategoryInterval(this);};return Axis;}();function fixExtentWithBands(extent,nTick){var size=extent[1]-extent[0];var len=nTick;var margin=size/len/2;extent[0]+=margin;extent[1]-=margin;}// If axis has labels [1, 2, 3, 4]. Bands on the axis are // |---1---|---2---|---3---|---4---|. // So the displayed ticks and splitLine/splitArea should between // each data item, otherwise cause misleading (e.g., split tow bars // of a single data item when there are two bar series). // Also consider if tickCategoryInterval > 0 and onBand, ticks and // splitLine/spliteArea should layout appropriately corresponding // to displayed labels. (So we should not use `getBandWidth` in this // case). function fixOnBandTicksCoords(axis,ticksCoords,alignWithLabel,clamp){var ticksLen=ticksCoords.length;if(!axis.onBand||alignWithLabel||!ticksLen){return;}var axisExtent=axis.getExtent();var last;var diffSize;if(ticksLen===1){ticksCoords[0].coord=axisExtent[0];last=ticksCoords[1]={coord:axisExtent[0]};}else{var crossLen=ticksCoords[ticksLen-1].tickValue-ticksCoords[0].tickValue;var shift_1=(ticksCoords[ticksLen-1].coord-ticksCoords[0].coord)/crossLen;each$7(ticksCoords,function(ticksItem){ticksItem.coord-=shift_1/2;});var dataExtent=axis.scale.getExtent();diffSize=1+dataExtent[1]-ticksCoords[ticksLen-1].tickValue;last={coord:ticksCoords[ticksLen-1].coord+shift_1*diffSize};ticksCoords.push(last);}var inverse=axisExtent[0]>axisExtent[1];// Handling clamp. if(littleThan(ticksCoords[0].coord,axisExtent[0])){clamp?ticksCoords[0].coord=axisExtent[0]:ticksCoords.shift();}if(clamp&&littleThan(axisExtent[0],ticksCoords[0].coord)){ticksCoords.unshift({coord:axisExtent[0]});}if(littleThan(axisExtent[1],last.coord)){clamp?last.coord=axisExtent[1]:ticksCoords.pop();}if(clamp&&littleThan(last.coord,axisExtent[1])){ticksCoords.push({coord:axisExtent[1]});}function littleThan(a,b){// Avoid rounding error cause calculated tick coord different with extent. // It may cause an extra unecessary tick added. a=round$1(a);b=round$1(b);return inverse?a>b:aendAngle){endAngle+=PI2$1;}var angle=Math.atan2(y,x);if(angle<0){angle+=PI2$1;}if(angle>=startAngle&&angle<=endAngle||angle+PI2$1>=startAngle&&angle+PI2$1<=endAngle){// Project point is on the arc. out[0]=ox;out[1]=oy;return d-r;}var x1=r*Math.cos(startAngle)+cx;var y1=r*Math.sin(startAngle)+cy;var x2=r*Math.cos(endAngle)+cx;var y2=r*Math.sin(endAngle)+cy;var d1=(x1-x)*(x1-x)+(y1-y)*(y1-y);var d2=(x2-x)*(x2-x)+(y2-y)*(y2-y);if(d10)){return;}minTurnAngle=minTurnAngle/180*Math.PI;// The line points can be // /pt1----pt2 (label) // / // pt0/ pt0.fromArray(linePoints[0]);pt1.fromArray(linePoints[1]);pt2.fromArray(linePoints[2]);Point$1.sub(dir,pt0,pt1);Point$1.sub(dir2,pt2,pt1);var len1=dir.len();var len2=dir2.len();if(len1<1e-3||len2<1e-3){return;}dir.scale(1/len1);dir2.scale(1/len2);var angleCos=dir.dot(dir2);var minTurnAngleCos=Math.cos(minTurnAngle);if(minTurnAngleCos1){Point$1.copy(tmpProjPoint,pt2);}tmpProjPoint.toArray(linePoints[1]);}}/** * Limit the angle of line and the surface * @param maxSurfaceAngle Radian of minimum turn angle. 0 - 180. 0 is same direction to normal. 180 is opposite */function limitSurfaceAngle(linePoints,surfaceNormal,maxSurfaceAngle){if(!(maxSurfaceAngle<=180&&maxSurfaceAngle>0)){return;}maxSurfaceAngle=maxSurfaceAngle/180*Math.PI;pt0.fromArray(linePoints[0]);pt1.fromArray(linePoints[1]);pt2.fromArray(linePoints[2]);Point$1.sub(dir,pt1,pt0);Point$1.sub(dir2,pt2,pt1);var len1=dir.len();var len2=dir2.len();if(len1<1e-3||len2<1e-3){return;}dir.scale(1/len1);dir2.scale(1/len2);var angleCos=dir.dot(surfaceNormal);var maxSurfaceAngleCos=Math.cos(maxSurfaceAngle);if(angleCos=HALF_PI){// parallel Point$1.copy(tmpProjPoint,pt2);}else{// Calculate new projected length with limited minTurnAngle and get the new connect point tmpProjPoint.scaleAndAdd(dir2,d/Math.tan(Math.PI/2-newAngle));// Limit the new calculated connect point between pt1 and pt2. 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;}if(t<0){Point$1.copy(tmpProjPoint,pt1);}else if(t>1){Point$1.copy(tmpProjPoint,pt2);}}tmpProjPoint.toArray(linePoints[1]);}}function setLabelLineState(labelLine,ignore,stateName,stateModel){var isNormal=stateName==='normal';var stateObj=isNormal?labelLine:labelLine.ensureState(stateName);// Make sure display. stateObj.ignore=ignore;// Set smooth var smooth=stateModel.get('smooth');if(smooth&&smooth===true){smooth=0.3;}stateObj.shape=stateObj.shape||{};if(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;var points=shape.points;if(!points){return;}path.moveTo(points[0][0],points[0][1]);if(smooth>0&&points.length>=3){var len1=dist$1(points[0],points[1]);var len2=dist$1(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;var midPoint0=lerp$1([],points[1],points[0],moveLen/len1);var midPoint2=lerp$1([],points[1],points[2],moveLen/len2);var midPoint1=lerp$1([],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;i0&&balanceShift){// Shift back to make the distribution more equally. shiftList(-totalShifts/len,0,len);}// TODO bleedMargin? var first=list[0];var last=list[len-1];var minGap;var maxGap;updateMinMaxGap();// If ends exceed two bounds, squeeze at most 80%, then take the gap of two bounds. minGap<0&&squeezeGaps(-minGap,0.8);maxGap<0&&squeezeGaps(maxGap,0.8);updateMinMaxGap();takeBoundsGap(minGap,maxGap,1);takeBoundsGap(maxGap,minGap,-1);// Handle bailout when there is not enough space. updateMinMaxGap();if(minGap<0){squeezeWhenBailout(-minGap);}if(maxGap<0){squeezeWhenBailout(maxGap);}function updateMinMaxGap(){minGap=first.rect[xyDim]-minBound;maxGap=maxBound-last.rect[xyDim]-last.rect[sizeDim];}function takeBoundsGap(gapThisBound,gapOtherBound,moveDir){if(gapThisBound<0){// Move from other gap if can. var moveFromMaxGap=Math.min(gapOtherBound,-gapThisBound);if(moveFromMaxGap>0){shiftList(moveFromMaxGap*moveDir,0,len);var remained=moveFromMaxGap+gapThisBound;if(remained<0){squeezeGaps(-remained*moveDir,1);}}else{squeezeGaps(-gapThisBound*moveDir,1);}}}function shiftList(delta,start,end){if(delta!==0){adjusted=true;}for(var i=start;i0){for(var i=0;i0;i--){// Distribute the shift delta to all gaps. var movement=gaps[i-1]*squeezePercent;shiftList(-movement,i,len);}}}/** * Squeeze to allow overlap if there is no more space available. * Let other overlapping strategy like hideOverlap do the job instead of keep exceeding the bounds. */function squeezeWhenBailout(delta){var dir=delta<0?-1:1;delta=Math.abs(delta);var moveForEachLabel=Math.ceil(delta/(len-1));for(var i=0;i0){// Forward shiftList(moveForEachLabel,0,i+1);}else{// Backward shiftList(-moveForEachLabel,len-i-1,len);}delta-=moveForEachLabel;if(delta<=0){return;}}}return adjusted;}/** * Adjust labels on x direction to avoid overlap. */function shiftLayoutOnX(list,leftBound,rightBound,// If average the shifts on all labels and add them to 0 // TODO: Not sure if should enable it. // Pros: The angle of lines will distribute more equally // Cons: In some layout. It may not what user wanted. like in pie. the label of last sector is usually changed unexpectedly. balanceShift){return shiftLayout(list,'x','width',leftBound,rightBound,balanceShift);}/** * Adjust labels on y direction to avoid overlap. */function shiftLayoutOnY(list,topBound,bottomBound,// If average the shifts on all labels and add them to 0 balanceShift){return shiftLayout(list,'y','height',topBound,bottomBound,balanceShift);}function hideOverlap(labelList){var displayedLabels=[];// TODO, render overflow visible first, put in the displayedLabels. labelList.sort(function(a,b){return b.priority-a.priority;});var globalRect=new BoundingRect$1(0,0,0,0);function hideEl(el){if(!el.ignore){// Show on emphasis. var emphasisState=el.ensureState('emphasis');if(emphasisState.ignore==null){emphasisState.ignore=false;}}el.ignore=true;}for(var i=0;i