echarts.js 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. var _config = require("./config");
  20. var __DEV__ = _config.__DEV__;
  21. var zrender = require("zrender/lib/zrender");
  22. var zrUtil = require("zrender/lib/core/util");
  23. var colorTool = require("zrender/lib/tool/color");
  24. var env = require("zrender/lib/core/env");
  25. var timsort = require("zrender/lib/core/timsort");
  26. var Eventful = require("zrender/lib/mixin/Eventful");
  27. var GlobalModel = require("./model/Global");
  28. var ExtensionAPI = require("./ExtensionAPI");
  29. var CoordinateSystemManager = require("./CoordinateSystem");
  30. var OptionManager = require("./model/OptionManager");
  31. var backwardCompat = require("./preprocessor/backwardCompat");
  32. var dataStack = require("./processor/dataStack");
  33. var ComponentModel = require("./model/Component");
  34. var SeriesModel = require("./model/Series");
  35. var ComponentView = require("./view/Component");
  36. var ChartView = require("./view/Chart");
  37. var graphic = require("./util/graphic");
  38. var modelUtil = require("./util/model");
  39. var _throttle = require("./util/throttle");
  40. var throttle = _throttle.throttle;
  41. var seriesColor = require("./visual/seriesColor");
  42. var aria = require("./visual/aria");
  43. var loadingDefault = require("./loading/default");
  44. var Scheduler = require("./stream/Scheduler");
  45. var lightTheme = require("./theme/light");
  46. var darkTheme = require("./theme/dark");
  47. require("./component/dataset");
  48. var mapDataStorage = require("./coord/geo/mapDataStorage");
  49. /*
  50. * Licensed to the Apache Software Foundation (ASF) under one
  51. * or more contributor license agreements. See the NOTICE file
  52. * distributed with this work for additional information
  53. * regarding copyright ownership. The ASF licenses this file
  54. * to you under the Apache License, Version 2.0 (the
  55. * "License"); you may not use this file except in compliance
  56. * with the License. You may obtain a copy of the License at
  57. *
  58. * http://www.apache.org/licenses/LICENSE-2.0
  59. *
  60. * Unless required by applicable law or agreed to in writing,
  61. * software distributed under the License is distributed on an
  62. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63. * KIND, either express or implied. See the License for the
  64. * specific language governing permissions and limitations
  65. * under the License.
  66. */
  67. var assert = zrUtil.assert;
  68. var each = zrUtil.each;
  69. var isFunction = zrUtil.isFunction;
  70. var isObject = zrUtil.isObject;
  71. var parseClassType = ComponentModel.parseClassType;
  72. var version = '4.6.0';
  73. var dependencies = {
  74. zrender: '4.2.0'
  75. };
  76. var TEST_FRAME_REMAIN_TIME = 1;
  77. var PRIORITY_PROCESSOR_FILTER = 1000;
  78. var PRIORITY_PROCESSOR_SERIES_FILTER = 800;
  79. var PRIORITY_PROCESSOR_DATASTACK = 900;
  80. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  81. var PRIORITY_VISUAL_LAYOUT = 1000;
  82. var PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
  83. var PRIORITY_VISUAL_GLOBAL = 2000;
  84. var PRIORITY_VISUAL_CHART = 3000;
  85. var PRIORITY_VISUAL_POST_CHART_LAYOUT = 3500;
  86. var PRIORITY_VISUAL_COMPONENT = 4000; // FIXME
  87. // necessary?
  88. var PRIORITY_VISUAL_BRUSH = 5000;
  89. var PRIORITY = {
  90. PROCESSOR: {
  91. FILTER: PRIORITY_PROCESSOR_FILTER,
  92. SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
  93. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  94. },
  95. VISUAL: {
  96. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  97. PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
  98. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  99. CHART: PRIORITY_VISUAL_CHART,
  100. POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
  101. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  102. BRUSH: PRIORITY_VISUAL_BRUSH
  103. }
  104. }; // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  105. // where they must not be invoked nestedly, except the only case: invoke
  106. // dispatchAction with updateMethod "none" in main process.
  107. // This flag is used to carry out this rule.
  108. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  109. var IN_MAIN_PROCESS = '__flagInMainProcess';
  110. var OPTION_UPDATED = '__optionUpdated';
  111. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  112. function createRegisterEventWithLowercaseName(method, ignoreDisposed) {
  113. return function (eventName, handler, context) {
  114. if (!ignoreDisposed && this._disposed) {
  115. disposedWarning(this.id);
  116. return;
  117. } // Event name is all lowercase
  118. eventName = eventName && eventName.toLowerCase();
  119. Eventful.prototype[method].call(this, eventName, handler, context);
  120. };
  121. }
  122. /**
  123. * @module echarts~MessageCenter
  124. */
  125. function MessageCenter() {
  126. Eventful.call(this);
  127. }
  128. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on', true);
  129. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off', true);
  130. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one', true);
  131. zrUtil.mixin(MessageCenter, Eventful);
  132. /**
  133. * @module echarts~ECharts
  134. */
  135. function ECharts(dom, theme, opts) {
  136. opts = opts || {}; // Get theme by name
  137. if (typeof theme === 'string') {
  138. theme = themeStorage[theme];
  139. }
  140. /**
  141. * @type {string}
  142. */
  143. this.id;
  144. /**
  145. * Group id
  146. * @type {string}
  147. */
  148. this.group;
  149. /**
  150. * @type {HTMLElement}
  151. * @private
  152. */
  153. this._dom = dom;
  154. var defaultRenderer = 'canvas';
  155. /**
  156. * @type {module:zrender/ZRender}
  157. * @private
  158. */
  159. var zr = this._zr = zrender.init(dom, {
  160. renderer: opts.renderer || defaultRenderer,
  161. devicePixelRatio: opts.devicePixelRatio,
  162. width: opts.width,
  163. height: opts.height
  164. });
  165. /**
  166. * Expect 60 fps.
  167. * @type {Function}
  168. * @private
  169. */
  170. this._throttledZrFlush = throttle(zrUtil.bind(zr.flush, zr), 17);
  171. var theme = zrUtil.clone(theme);
  172. theme && backwardCompat(theme, true);
  173. /**
  174. * @type {Object}
  175. * @private
  176. */
  177. this._theme = theme;
  178. /**
  179. * @type {Array.<module:echarts/view/Chart>}
  180. * @private
  181. */
  182. this._chartsViews = [];
  183. /**
  184. * @type {Object.<string, module:echarts/view/Chart>}
  185. * @private
  186. */
  187. this._chartsMap = {};
  188. /**
  189. * @type {Array.<module:echarts/view/Component>}
  190. * @private
  191. */
  192. this._componentsViews = [];
  193. /**
  194. * @type {Object.<string, module:echarts/view/Component>}
  195. * @private
  196. */
  197. this._componentsMap = {};
  198. /**
  199. * @type {module:echarts/CoordinateSystem}
  200. * @private
  201. */
  202. this._coordSysMgr = new CoordinateSystemManager();
  203. /**
  204. * @type {module:echarts/ExtensionAPI}
  205. * @private
  206. */
  207. var api = this._api = createExtensionAPI(this); // Sort on demand
  208. function prioritySortFunc(a, b) {
  209. return a.__prio - b.__prio;
  210. }
  211. timsort(visualFuncs, prioritySortFunc);
  212. timsort(dataProcessorFuncs, prioritySortFunc);
  213. /**
  214. * @type {module:echarts/stream/Scheduler}
  215. */
  216. this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs);
  217. Eventful.call(this, this._ecEventProcessor = new EventProcessor());
  218. /**
  219. * @type {module:echarts~MessageCenter}
  220. * @private
  221. */
  222. this._messageCenter = new MessageCenter(); // Init mouse events
  223. this._initEvents(); // In case some people write `window.onresize = chart.resize`
  224. this.resize = zrUtil.bind(this.resize, this); // Can't dispatch action during rendering procedure
  225. this._pendingActions = [];
  226. zr.animation.on('frame', this._onframe, this);
  227. bindRenderedEvent(zr, this); // ECharts instance can be used as value.
  228. zrUtil.setAsPrimitive(this);
  229. }
  230. var echartsProto = ECharts.prototype;
  231. echartsProto._onframe = function () {
  232. if (this._disposed) {
  233. return;
  234. }
  235. var scheduler = this._scheduler; // Lazy update
  236. if (this[OPTION_UPDATED]) {
  237. var silent = this[OPTION_UPDATED].silent;
  238. this[IN_MAIN_PROCESS] = true;
  239. prepare(this);
  240. updateMethods.update.call(this);
  241. this[IN_MAIN_PROCESS] = false;
  242. this[OPTION_UPDATED] = false;
  243. flushPendingActions.call(this, silent);
  244. triggerUpdatedEvent.call(this, silent);
  245. } // Avoid do both lazy update and progress in one frame.
  246. else if (scheduler.unfinished) {
  247. // Stream progress.
  248. var remainTime = TEST_FRAME_REMAIN_TIME;
  249. var ecModel = this._model;
  250. var api = this._api;
  251. scheduler.unfinished = false;
  252. do {
  253. var startTime = +new Date();
  254. scheduler.performSeriesTasks(ecModel); // Currently dataProcessorFuncs do not check threshold.
  255. scheduler.performDataProcessorTasks(ecModel);
  256. updateStreamModes(this, ecModel); // Do not update coordinate system here. Because that coord system update in
  257. // each frame is not a good user experience. So we follow the rule that
  258. // the extent of the coordinate system is determin in the first frame (the
  259. // frame is executed immedietely after task reset.
  260. // this._coordSysMgr.update(ecModel, api);
  261. // console.log('--- ec frame visual ---', remainTime);
  262. scheduler.performVisualTasks(ecModel);
  263. renderSeries(this, this._model, api, 'remain');
  264. remainTime -= +new Date() - startTime;
  265. } while (remainTime > 0 && scheduler.unfinished); // Call flush explicitly for trigger finished event.
  266. if (!scheduler.unfinished) {
  267. this._zr.flush();
  268. } // Else, zr flushing be ensue within the same frame,
  269. // because zr flushing is after onframe event.
  270. }
  271. };
  272. /**
  273. * @return {HTMLElement}
  274. */
  275. echartsProto.getDom = function () {
  276. return this._dom;
  277. };
  278. /**
  279. * @return {module:zrender~ZRender}
  280. */
  281. echartsProto.getZr = function () {
  282. return this._zr;
  283. };
  284. /**
  285. * Usage:
  286. * chart.setOption(option, notMerge, lazyUpdate);
  287. * chart.setOption(option, {
  288. * notMerge: ...,
  289. * lazyUpdate: ...,
  290. * silent: ...
  291. * });
  292. *
  293. * @param {Object} option
  294. * @param {Object|boolean} [opts] opts or notMerge.
  295. * @param {boolean} [opts.notMerge=false]
  296. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  297. */
  298. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  299. if (this._disposed) {
  300. disposedWarning(this.id);
  301. return;
  302. }
  303. var silent;
  304. if (isObject(notMerge)) {
  305. lazyUpdate = notMerge.lazyUpdate;
  306. silent = notMerge.silent;
  307. notMerge = notMerge.notMerge;
  308. }
  309. this[IN_MAIN_PROCESS] = true;
  310. if (!this._model || notMerge) {
  311. var optionManager = new OptionManager(this._api);
  312. var theme = this._theme;
  313. var ecModel = this._model = new GlobalModel();
  314. ecModel.scheduler = this._scheduler;
  315. ecModel.init(null, null, theme, optionManager);
  316. }
  317. this._model.setOption(option, optionPreprocessorFuncs);
  318. if (lazyUpdate) {
  319. this[OPTION_UPDATED] = {
  320. silent: silent
  321. };
  322. this[IN_MAIN_PROCESS] = false;
  323. } else {
  324. prepare(this);
  325. updateMethods.update.call(this); // Ensure zr refresh sychronously, and then pixel in canvas can be
  326. // fetched after `setOption`.
  327. this._zr.flush();
  328. this[OPTION_UPDATED] = false;
  329. this[IN_MAIN_PROCESS] = false;
  330. flushPendingActions.call(this, silent);
  331. triggerUpdatedEvent.call(this, silent);
  332. }
  333. };
  334. /**
  335. * @DEPRECATED
  336. */
  337. echartsProto.setTheme = function () {
  338. console.error('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  339. };
  340. /**
  341. * @return {module:echarts/model/Global}
  342. */
  343. echartsProto.getModel = function () {
  344. return this._model;
  345. };
  346. /**
  347. * @return {Object}
  348. */
  349. echartsProto.getOption = function () {
  350. return this._model && this._model.getOption();
  351. };
  352. /**
  353. * @return {number}
  354. */
  355. echartsProto.getWidth = function () {
  356. return this._zr.getWidth();
  357. };
  358. /**
  359. * @return {number}
  360. */
  361. echartsProto.getHeight = function () {
  362. return this._zr.getHeight();
  363. };
  364. /**
  365. * @return {number}
  366. */
  367. echartsProto.getDevicePixelRatio = function () {
  368. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  369. };
  370. /**
  371. * Get canvas which has all thing rendered
  372. * @param {Object} opts
  373. * @param {string} [opts.backgroundColor]
  374. * @return {string}
  375. */
  376. echartsProto.getRenderedCanvas = function (opts) {
  377. if (!env.canvasSupported) {
  378. return;
  379. }
  380. opts = opts || {};
  381. opts.pixelRatio = opts.pixelRatio || 1;
  382. opts.backgroundColor = opts.backgroundColor || this._model.get('backgroundColor');
  383. var zr = this._zr; // var list = zr.storage.getDisplayList();
  384. // Stop animations
  385. // Never works before in init animation, so remove it.
  386. // zrUtil.each(list, function (el) {
  387. // el.stopAnimation(true);
  388. // });
  389. return zr.painter.getRenderedCanvas(opts);
  390. };
  391. /**
  392. * Get svg data url
  393. * @return {string}
  394. */
  395. echartsProto.getSvgDataUrl = function () {
  396. if (!env.svgSupported) {
  397. return;
  398. }
  399. var zr = this._zr;
  400. var list = zr.storage.getDisplayList(); // Stop animations
  401. zrUtil.each(list, function (el) {
  402. el.stopAnimation(true);
  403. });
  404. return zr.painter.pathToDataUrl();
  405. };
  406. /**
  407. * @return {string}
  408. * @param {Object} opts
  409. * @param {string} [opts.type='png']
  410. * @param {string} [opts.pixelRatio=1]
  411. * @param {string} [opts.backgroundColor]
  412. * @param {string} [opts.excludeComponents]
  413. */
  414. echartsProto.getDataURL = function (opts) {
  415. if (this._disposed) {
  416. disposedWarning(this.id);
  417. return;
  418. }
  419. opts = opts || {};
  420. var excludeComponents = opts.excludeComponents;
  421. var ecModel = this._model;
  422. var excludesComponentViews = [];
  423. var self = this;
  424. each(excludeComponents, function (componentType) {
  425. ecModel.eachComponent({
  426. mainType: componentType
  427. }, function (component) {
  428. var view = self._componentsMap[component.__viewId];
  429. if (!view.group.ignore) {
  430. excludesComponentViews.push(view);
  431. view.group.ignore = true;
  432. }
  433. });
  434. });
  435. var url = this._zr.painter.getType() === 'svg' ? this.getSvgDataUrl() : this.getRenderedCanvas(opts).toDataURL('image/' + (opts && opts.type || 'png'));
  436. each(excludesComponentViews, function (view) {
  437. view.group.ignore = false;
  438. });
  439. return url;
  440. };
  441. /**
  442. * @return {string}
  443. * @param {Object} opts
  444. * @param {string} [opts.type='png']
  445. * @param {string} [opts.pixelRatio=1]
  446. * @param {string} [opts.backgroundColor]
  447. */
  448. echartsProto.getConnectedDataURL = function (opts) {
  449. if (this._disposed) {
  450. disposedWarning(this.id);
  451. return;
  452. }
  453. if (!env.canvasSupported) {
  454. return;
  455. }
  456. var groupId = this.group;
  457. var mathMin = Math.min;
  458. var mathMax = Math.max;
  459. var MAX_NUMBER = Infinity;
  460. if (connectedGroups[groupId]) {
  461. var left = MAX_NUMBER;
  462. var top = MAX_NUMBER;
  463. var right = -MAX_NUMBER;
  464. var bottom = -MAX_NUMBER;
  465. var canvasList = [];
  466. var dpr = opts && opts.pixelRatio || 1;
  467. zrUtil.each(instances, function (chart, id) {
  468. if (chart.group === groupId) {
  469. var canvas = chart.getRenderedCanvas(zrUtil.clone(opts));
  470. var boundingRect = chart.getDom().getBoundingClientRect();
  471. left = mathMin(boundingRect.left, left);
  472. top = mathMin(boundingRect.top, top);
  473. right = mathMax(boundingRect.right, right);
  474. bottom = mathMax(boundingRect.bottom, bottom);
  475. canvasList.push({
  476. dom: canvas,
  477. left: boundingRect.left,
  478. top: boundingRect.top
  479. });
  480. }
  481. });
  482. left *= dpr;
  483. top *= dpr;
  484. right *= dpr;
  485. bottom *= dpr;
  486. var width = right - left;
  487. var height = bottom - top;
  488. var targetCanvas = zrUtil.createCanvas();
  489. targetCanvas.width = width;
  490. targetCanvas.height = height;
  491. var zr = zrender.init(targetCanvas); // Background between the charts
  492. if (opts.connectedBackgroundColor) {
  493. zr.add(new graphic.Rect({
  494. shape: {
  495. x: 0,
  496. y: 0,
  497. width: width,
  498. height: height
  499. },
  500. style: {
  501. fill: opts.connectedBackgroundColor
  502. }
  503. }));
  504. }
  505. each(canvasList, function (item) {
  506. var img = new graphic.Image({
  507. style: {
  508. x: item.left * dpr - left,
  509. y: item.top * dpr - top,
  510. image: item.dom
  511. }
  512. });
  513. zr.add(img);
  514. });
  515. zr.refreshImmediately();
  516. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  517. } else {
  518. return this.getDataURL(opts);
  519. }
  520. };
  521. /**
  522. * Convert from logical coordinate system to pixel coordinate system.
  523. * See CoordinateSystem#convertToPixel.
  524. * @param {string|Object} finder
  525. * If string, e.g., 'geo', means {geoIndex: 0}.
  526. * If Object, could contain some of these properties below:
  527. * {
  528. * seriesIndex / seriesId / seriesName,
  529. * geoIndex / geoId, geoName,
  530. * bmapIndex / bmapId / bmapName,
  531. * xAxisIndex / xAxisId / xAxisName,
  532. * yAxisIndex / yAxisId / yAxisName,
  533. * gridIndex / gridId / gridName,
  534. * ... (can be extended)
  535. * }
  536. * @param {Array|number} value
  537. * @return {Array|number} result
  538. */
  539. echartsProto.convertToPixel = zrUtil.curry(doConvertPixel, 'convertToPixel');
  540. /**
  541. * Convert from pixel coordinate system to logical coordinate system.
  542. * See CoordinateSystem#convertFromPixel.
  543. * @param {string|Object} finder
  544. * If string, e.g., 'geo', means {geoIndex: 0}.
  545. * If Object, could contain some of these properties below:
  546. * {
  547. * seriesIndex / seriesId / seriesName,
  548. * geoIndex / geoId / geoName,
  549. * bmapIndex / bmapId / bmapName,
  550. * xAxisIndex / xAxisId / xAxisName,
  551. * yAxisIndex / yAxisId / yAxisName
  552. * gridIndex / gridId / gridName,
  553. * ... (can be extended)
  554. * }
  555. * @param {Array|number} value
  556. * @return {Array|number} result
  557. */
  558. echartsProto.convertFromPixel = zrUtil.curry(doConvertPixel, 'convertFromPixel');
  559. function doConvertPixel(methodName, finder, value) {
  560. if (this._disposed) {
  561. disposedWarning(this.id);
  562. return;
  563. }
  564. var ecModel = this._model;
  565. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  566. var result;
  567. finder = modelUtil.parseFinder(ecModel, finder);
  568. for (var i = 0; i < coordSysList.length; i++) {
  569. var coordSys = coordSysList[i];
  570. if (coordSys[methodName] && (result = coordSys[methodName](ecModel, finder, value)) != null) {
  571. return result;
  572. }
  573. }
  574. }
  575. /**
  576. * Is the specified coordinate systems or components contain the given pixel point.
  577. * @param {string|Object} finder
  578. * If string, e.g., 'geo', means {geoIndex: 0}.
  579. * If Object, could contain some of these properties below:
  580. * {
  581. * seriesIndex / seriesId / seriesName,
  582. * geoIndex / geoId / geoName,
  583. * bmapIndex / bmapId / bmapName,
  584. * xAxisIndex / xAxisId / xAxisName,
  585. * yAxisIndex / yAxisId / yAxisName,
  586. * gridIndex / gridId / gridName,
  587. * ... (can be extended)
  588. * }
  589. * @param {Array|number} value
  590. * @return {boolean} result
  591. */
  592. echartsProto.containPixel = function (finder, value) {
  593. if (this._disposed) {
  594. disposedWarning(this.id);
  595. return;
  596. }
  597. var ecModel = this._model;
  598. var result;
  599. finder = modelUtil.parseFinder(ecModel, finder);
  600. zrUtil.each(finder, function (models, key) {
  601. key.indexOf('Models') >= 0 && zrUtil.each(models, function (model) {
  602. var coordSys = model.coordinateSystem;
  603. if (coordSys && coordSys.containPoint) {
  604. result |= !!coordSys.containPoint(value);
  605. } else if (key === 'seriesModels') {
  606. var view = this._chartsMap[model.__viewId];
  607. if (view && view.containPoint) {
  608. result |= view.containPoint(value, model);
  609. } else {}
  610. } else {}
  611. }, this);
  612. }, this);
  613. return !!result;
  614. };
  615. /**
  616. * Get visual from series or data.
  617. * @param {string|Object} finder
  618. * If string, e.g., 'series', means {seriesIndex: 0}.
  619. * If Object, could contain some of these properties below:
  620. * {
  621. * seriesIndex / seriesId / seriesName,
  622. * dataIndex / dataIndexInside
  623. * }
  624. * If dataIndex is not specified, series visual will be fetched,
  625. * but not data item visual.
  626. * If all of seriesIndex, seriesId, seriesName are not specified,
  627. * visual will be fetched from first series.
  628. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  629. */
  630. echartsProto.getVisual = function (finder, visualType) {
  631. var ecModel = this._model;
  632. finder = modelUtil.parseFinder(ecModel, finder, {
  633. defaultMainType: 'series'
  634. });
  635. var seriesModel = finder.seriesModel;
  636. var data = seriesModel.getData();
  637. var dataIndexInside = finder.hasOwnProperty('dataIndexInside') ? finder.dataIndexInside : finder.hasOwnProperty('dataIndex') ? data.indexOfRawIndex(finder.dataIndex) : null;
  638. return dataIndexInside != null ? data.getItemVisual(dataIndexInside, visualType) : data.getVisual(visualType);
  639. };
  640. /**
  641. * Get view of corresponding component model
  642. * @param {module:echarts/model/Component} componentModel
  643. * @return {module:echarts/view/Component}
  644. */
  645. echartsProto.getViewOfComponentModel = function (componentModel) {
  646. return this._componentsMap[componentModel.__viewId];
  647. };
  648. /**
  649. * Get view of corresponding series model
  650. * @param {module:echarts/model/Series} seriesModel
  651. * @return {module:echarts/view/Chart}
  652. */
  653. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  654. return this._chartsMap[seriesModel.__viewId];
  655. };
  656. var updateMethods = {
  657. prepareAndUpdate: function (payload) {
  658. prepare(this);
  659. updateMethods.update.call(this, payload);
  660. },
  661. /**
  662. * @param {Object} payload
  663. * @private
  664. */
  665. update: function (payload) {
  666. // console.profile && console.profile('update');
  667. var ecModel = this._model;
  668. var api = this._api;
  669. var zr = this._zr;
  670. var coordSysMgr = this._coordSysMgr;
  671. var scheduler = this._scheduler; // update before setOption
  672. if (!ecModel) {
  673. return;
  674. }
  675. scheduler.restoreData(ecModel, payload);
  676. scheduler.performSeriesTasks(ecModel); // TODO
  677. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  678. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  679. // Create new coordinate system each update
  680. // In LineView may save the old coordinate system and use it to get the orignal point
  681. coordSysMgr.create(ecModel, api);
  682. scheduler.performDataProcessorTasks(ecModel, payload); // Current stream render is not supported in data process. So we can update
  683. // stream modes after data processing, where the filtered data is used to
  684. // deteming whether use progressive rendering.
  685. updateStreamModes(this, ecModel); // We update stream modes before coordinate system updated, then the modes info
  686. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  687. // the drawback is the full coord info can not be fetched. Fortunately this full
  688. // coord is not requied in stream mode updater currently.
  689. coordSysMgr.update(ecModel, api);
  690. clearColorPalette(ecModel);
  691. scheduler.performVisualTasks(ecModel, payload);
  692. render(this, ecModel, api, payload); // Set background
  693. var backgroundColor = ecModel.get('backgroundColor') || 'transparent'; // In IE8
  694. if (!env.canvasSupported) {
  695. var colorArr = colorTool.parse(backgroundColor);
  696. backgroundColor = colorTool.stringify(colorArr, 'rgb');
  697. if (colorArr[3] === 0) {
  698. backgroundColor = 'transparent';
  699. }
  700. } else {
  701. zr.setBackgroundColor(backgroundColor);
  702. }
  703. performPostUpdateFuncs(ecModel, api); // console.profile && console.profileEnd('update');
  704. },
  705. /**
  706. * @param {Object} payload
  707. * @private
  708. */
  709. updateTransform: function (payload) {
  710. var ecModel = this._model;
  711. var ecIns = this;
  712. var api = this._api; // update before setOption
  713. if (!ecModel) {
  714. return;
  715. } // ChartView.markUpdateMethod(payload, 'updateTransform');
  716. var componentDirtyList = [];
  717. ecModel.eachComponent(function (componentType, componentModel) {
  718. var componentView = ecIns.getViewOfComponentModel(componentModel);
  719. if (componentView && componentView.__alive) {
  720. if (componentView.updateTransform) {
  721. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  722. result && result.update && componentDirtyList.push(componentView);
  723. } else {
  724. componentDirtyList.push(componentView);
  725. }
  726. }
  727. });
  728. var seriesDirtyMap = zrUtil.createHashMap();
  729. ecModel.eachSeries(function (seriesModel) {
  730. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  731. if (chartView.updateTransform) {
  732. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  733. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  734. } else {
  735. seriesDirtyMap.set(seriesModel.uid, 1);
  736. }
  737. });
  738. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  739. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  740. this._scheduler.performVisualTasks(ecModel, payload, {
  741. setDirty: true,
  742. dirtyMap: seriesDirtyMap
  743. }); // Currently, not call render of components. Geo render cost a lot.
  744. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  745. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  746. performPostUpdateFuncs(ecModel, this._api);
  747. },
  748. /**
  749. * @param {Object} payload
  750. * @private
  751. */
  752. updateView: function (payload) {
  753. var ecModel = this._model; // update before setOption
  754. if (!ecModel) {
  755. return;
  756. }
  757. ChartView.markUpdateMethod(payload, 'updateView');
  758. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  759. this._scheduler.performVisualTasks(ecModel, payload, {
  760. setDirty: true
  761. });
  762. render(this, this._model, this._api, payload);
  763. performPostUpdateFuncs(ecModel, this._api);
  764. },
  765. /**
  766. * @param {Object} payload
  767. * @private
  768. */
  769. updateVisual: function (payload) {
  770. updateMethods.update.call(this, payload); // var ecModel = this._model;
  771. // // update before setOption
  772. // if (!ecModel) {
  773. // return;
  774. // }
  775. // ChartView.markUpdateMethod(payload, 'updateVisual');
  776. // clearColorPalette(ecModel);
  777. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  778. // this._scheduler.performVisualTasks(ecModel, payload, {visualType: 'visual', setDirty: true});
  779. // render(this, this._model, this._api, payload);
  780. // performPostUpdateFuncs(ecModel, this._api);
  781. },
  782. /**
  783. * @param {Object} payload
  784. * @private
  785. */
  786. updateLayout: function (payload) {
  787. updateMethods.update.call(this, payload); // var ecModel = this._model;
  788. // // update before setOption
  789. // if (!ecModel) {
  790. // return;
  791. // }
  792. // ChartView.markUpdateMethod(payload, 'updateLayout');
  793. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  794. // // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  795. // this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  796. // render(this, this._model, this._api, payload);
  797. // performPostUpdateFuncs(ecModel, this._api);
  798. }
  799. };
  800. function prepare(ecIns) {
  801. var ecModel = ecIns._model;
  802. var scheduler = ecIns._scheduler;
  803. scheduler.restorePipelines(ecModel);
  804. scheduler.prepareStageTasks();
  805. prepareView(ecIns, 'component', ecModel, scheduler);
  806. prepareView(ecIns, 'chart', ecModel, scheduler);
  807. scheduler.plan();
  808. }
  809. /**
  810. * @private
  811. */
  812. function updateDirectly(ecIns, method, payload, mainType, subType) {
  813. var ecModel = ecIns._model; // broadcast
  814. if (!mainType) {
  815. // FIXME
  816. // Chart will not be update directly here, except set dirty.
  817. // But there is no such scenario now.
  818. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  819. return;
  820. }
  821. var query = {};
  822. query[mainType + 'Id'] = payload[mainType + 'Id'];
  823. query[mainType + 'Index'] = payload[mainType + 'Index'];
  824. query[mainType + 'Name'] = payload[mainType + 'Name'];
  825. var condition = {
  826. mainType: mainType,
  827. query: query
  828. };
  829. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  830. var excludeSeriesId = payload.excludeSeriesId;
  831. if (excludeSeriesId != null) {
  832. excludeSeriesId = zrUtil.createHashMap(modelUtil.normalizeToArray(excludeSeriesId));
  833. } // If dispatchAction before setOption, do nothing.
  834. ecModel && ecModel.eachComponent(condition, function (model) {
  835. if (!excludeSeriesId || excludeSeriesId.get(model.id) == null) {
  836. callView(ecIns[mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId]);
  837. }
  838. }, ecIns);
  839. function callView(view) {
  840. view && view.__alive && view[method] && view[method](view.__model, ecModel, ecIns._api, payload);
  841. }
  842. }
  843. /**
  844. * Resize the chart
  845. * @param {Object} opts
  846. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  847. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  848. * @param {boolean} [opts.silent=false]
  849. */
  850. echartsProto.resize = function (opts) {
  851. if (this._disposed) {
  852. disposedWarning(this.id);
  853. return;
  854. }
  855. this._zr.resize(opts);
  856. var ecModel = this._model; // Resize loading effect
  857. this._loadingFX && this._loadingFX.resize();
  858. if (!ecModel) {
  859. return;
  860. }
  861. var optionChanged = ecModel.resetOption('media');
  862. var silent = opts && opts.silent;
  863. this[IN_MAIN_PROCESS] = true;
  864. optionChanged && prepare(this);
  865. updateMethods.update.call(this);
  866. this[IN_MAIN_PROCESS] = false;
  867. flushPendingActions.call(this, silent);
  868. triggerUpdatedEvent.call(this, silent);
  869. };
  870. function updateStreamModes(ecIns, ecModel) {
  871. var chartsMap = ecIns._chartsMap;
  872. var scheduler = ecIns._scheduler;
  873. ecModel.eachSeries(function (seriesModel) {
  874. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  875. });
  876. }
  877. /**
  878. * Show loading effect
  879. * @param {string} [name='default']
  880. * @param {Object} [cfg]
  881. */
  882. echartsProto.showLoading = function (name, cfg) {
  883. if (this._disposed) {
  884. disposedWarning(this.id);
  885. return;
  886. }
  887. if (isObject(name)) {
  888. cfg = name;
  889. name = '';
  890. }
  891. name = name || 'default';
  892. this.hideLoading();
  893. if (!loadingEffects[name]) {
  894. return;
  895. }
  896. var el = loadingEffects[name](this._api, cfg);
  897. var zr = this._zr;
  898. this._loadingFX = el;
  899. zr.add(el);
  900. };
  901. /**
  902. * Hide loading effect
  903. */
  904. echartsProto.hideLoading = function () {
  905. if (this._disposed) {
  906. disposedWarning(this.id);
  907. return;
  908. }
  909. this._loadingFX && this._zr.remove(this._loadingFX);
  910. this._loadingFX = null;
  911. };
  912. /**
  913. * @param {Object} eventObj
  914. * @return {Object}
  915. */
  916. echartsProto.makeActionFromEvent = function (eventObj) {
  917. var payload = zrUtil.extend({}, eventObj);
  918. payload.type = eventActionMap[eventObj.type];
  919. return payload;
  920. };
  921. /**
  922. * @pubilc
  923. * @param {Object} payload
  924. * @param {string} [payload.type] Action type
  925. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  926. * @param {boolean} [opt.silent=false] Whether trigger events.
  927. * @param {boolean} [opt.flush=undefined]
  928. * true: Flush immediately, and then pixel in canvas can be fetched
  929. * immediately. Caution: it might affect performance.
  930. * false: Not flush.
  931. * undefined: Auto decide whether perform flush.
  932. */
  933. echartsProto.dispatchAction = function (payload, opt) {
  934. if (this._disposed) {
  935. disposedWarning(this.id);
  936. return;
  937. }
  938. if (!isObject(opt)) {
  939. opt = {
  940. silent: !!opt
  941. };
  942. }
  943. if (!actions[payload.type]) {
  944. return;
  945. } // Avoid dispatch action before setOption. Especially in `connect`.
  946. if (!this._model) {
  947. return;
  948. } // May dispatchAction in rendering procedure
  949. if (this[IN_MAIN_PROCESS]) {
  950. this._pendingActions.push(payload);
  951. return;
  952. }
  953. doDispatchAction.call(this, payload, opt.silent);
  954. if (opt.flush) {
  955. this._zr.flush(true);
  956. } else if (opt.flush !== false && env.browser.weChat) {
  957. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  958. // hang when sliding page (on touch event), which cause that zr does not
  959. // refresh util user interaction finished, which is not expected.
  960. // But `dispatchAction` may be called too frequently when pan on touch
  961. // screen, which impacts performance if do not throttle them.
  962. this._throttledZrFlush();
  963. }
  964. flushPendingActions.call(this, opt.silent);
  965. triggerUpdatedEvent.call(this, opt.silent);
  966. };
  967. function doDispatchAction(payload, silent) {
  968. var payloadType = payload.type;
  969. var escapeConnect = payload.escapeConnect;
  970. var actionWrap = actions[payloadType];
  971. var actionInfo = actionWrap.actionInfo;
  972. var cptType = (actionInfo.update || 'update').split(':');
  973. var updateMethod = cptType.pop();
  974. cptType = cptType[0] != null && parseClassType(cptType[0]);
  975. this[IN_MAIN_PROCESS] = true;
  976. var payloads = [payload];
  977. var batched = false; // Batch action
  978. if (payload.batch) {
  979. batched = true;
  980. payloads = zrUtil.map(payload.batch, function (item) {
  981. item = zrUtil.defaults(zrUtil.extend({}, item), payload);
  982. item.batch = null;
  983. return item;
  984. });
  985. }
  986. var eventObjBatch = [];
  987. var eventObj;
  988. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  989. each(payloads, function (batchItem) {
  990. // Action can specify the event by return it.
  991. eventObj = actionWrap.action(batchItem, this._model, this._api); // Emit event outside
  992. eventObj = eventObj || zrUtil.extend({}, batchItem); // Convert type to eventType
  993. eventObj.type = actionInfo.event || eventObj.type;
  994. eventObjBatch.push(eventObj); // light update does not perform data process, layout and visual.
  995. if (isHighDown) {
  996. // method, payload, mainType, subType
  997. updateDirectly(this, updateMethod, batchItem, 'series');
  998. } else if (cptType) {
  999. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  1000. }
  1001. }, this);
  1002. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  1003. // Still dirty
  1004. if (this[OPTION_UPDATED]) {
  1005. // FIXME Pass payload ?
  1006. prepare(this);
  1007. updateMethods.update.call(this, payload);
  1008. this[OPTION_UPDATED] = false;
  1009. } else {
  1010. updateMethods[updateMethod].call(this, payload);
  1011. }
  1012. } // Follow the rule of action batch
  1013. if (batched) {
  1014. eventObj = {
  1015. type: actionInfo.event || payloadType,
  1016. escapeConnect: escapeConnect,
  1017. batch: eventObjBatch
  1018. };
  1019. } else {
  1020. eventObj = eventObjBatch[0];
  1021. }
  1022. this[IN_MAIN_PROCESS] = false;
  1023. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  1024. }
  1025. function flushPendingActions(silent) {
  1026. var pendingActions = this._pendingActions;
  1027. while (pendingActions.length) {
  1028. var payload = pendingActions.shift();
  1029. doDispatchAction.call(this, payload, silent);
  1030. }
  1031. }
  1032. function triggerUpdatedEvent(silent) {
  1033. !silent && this.trigger('updated');
  1034. }
  1035. /**
  1036. * Event `rendered` is triggered when zr
  1037. * rendered. It is useful for realtime
  1038. * snapshot (reflect animation).
  1039. *
  1040. * Event `finished` is triggered when:
  1041. * (1) zrender rendering finished.
  1042. * (2) initial animation finished.
  1043. * (3) progressive rendering finished.
  1044. * (4) no pending action.
  1045. * (5) no delayed setOption needs to be processed.
  1046. */
  1047. function bindRenderedEvent(zr, ecIns) {
  1048. zr.on('rendered', function () {
  1049. ecIns.trigger('rendered'); // The `finished` event should not be triggered repeatly,
  1050. // so it should only be triggered when rendering indeed happend
  1051. // in zrender. (Consider the case that dipatchAction is keep
  1052. // triggering when mouse move).
  1053. if ( // Although zr is dirty if initial animation is not finished
  1054. // and this checking is called on frame, we also check
  1055. // animation finished for robustness.
  1056. zr.animation.isFinished() && !ecIns[OPTION_UPDATED] && !ecIns._scheduler.unfinished && !ecIns._pendingActions.length) {
  1057. ecIns.trigger('finished');
  1058. }
  1059. });
  1060. }
  1061. /**
  1062. * @param {Object} params
  1063. * @param {number} params.seriesIndex
  1064. * @param {Array|TypedArray} params.data
  1065. */
  1066. echartsProto.appendData = function (params) {
  1067. if (this._disposed) {
  1068. disposedWarning(this.id);
  1069. return;
  1070. }
  1071. var seriesIndex = params.seriesIndex;
  1072. var ecModel = this.getModel();
  1073. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  1074. seriesModel.appendData(params); // Note: `appendData` does not support that update extent of coordinate
  1075. // system, util some scenario require that. In the expected usage of
  1076. // `appendData`, the initial extent of coordinate system should better
  1077. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  1078. // the extent changed while `appendData`, the location of the painted
  1079. // graphic elements have to be changed, which make the usage of
  1080. // `appendData` meaningless.
  1081. this._scheduler.unfinished = true;
  1082. };
  1083. /**
  1084. * Register event
  1085. * @method
  1086. */
  1087. echartsProto.on = createRegisterEventWithLowercaseName('on', false);
  1088. echartsProto.off = createRegisterEventWithLowercaseName('off', false);
  1089. echartsProto.one = createRegisterEventWithLowercaseName('one', false);
  1090. /**
  1091. * Prepare view instances of charts and components
  1092. * @param {module:echarts/model/Global} ecModel
  1093. * @private
  1094. */
  1095. function prepareView(ecIns, type, ecModel, scheduler) {
  1096. var isComponent = type === 'component';
  1097. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  1098. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  1099. var zr = ecIns._zr;
  1100. var api = ecIns._api;
  1101. for (var i = 0; i < viewList.length; i++) {
  1102. viewList[i].__alive = false;
  1103. }
  1104. isComponent ? ecModel.eachComponent(function (componentType, model) {
  1105. componentType !== 'series' && doPrepare(model);
  1106. }) : ecModel.eachSeries(doPrepare);
  1107. function doPrepare(model) {
  1108. // Consider: id same and type changed.
  1109. var viewId = '_ec_' + model.id + '_' + model.type;
  1110. var view = viewMap[viewId];
  1111. if (!view) {
  1112. var classType = parseClassType(model.type);
  1113. var Clazz = isComponent ? ComponentView.getClass(classType.main, classType.sub) : ChartView.getClass(classType.sub);
  1114. view = new Clazz();
  1115. view.init(ecModel, api);
  1116. viewMap[viewId] = view;
  1117. viewList.push(view);
  1118. zr.add(view.group);
  1119. }
  1120. model.__viewId = view.__id = viewId;
  1121. view.__alive = true;
  1122. view.__model = model;
  1123. view.group.__ecComponentInfo = {
  1124. mainType: model.mainType,
  1125. index: model.componentIndex
  1126. };
  1127. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  1128. }
  1129. for (var i = 0; i < viewList.length;) {
  1130. var view = viewList[i];
  1131. if (!view.__alive) {
  1132. !isComponent && view.renderTask.dispose();
  1133. zr.remove(view.group);
  1134. view.dispose(ecModel, api);
  1135. viewList.splice(i, 1);
  1136. delete viewMap[view.__id];
  1137. view.__id = view.group.__ecComponentInfo = null;
  1138. } else {
  1139. i++;
  1140. }
  1141. }
  1142. } // /**
  1143. // * Encode visual infomation from data after data processing
  1144. // *
  1145. // * @param {module:echarts/model/Global} ecModel
  1146. // * @param {object} layout
  1147. // * @param {boolean} [layoutFilter] `true`: only layout,
  1148. // * `false`: only not layout,
  1149. // * `null`/`undefined`: all.
  1150. // * @param {string} taskBaseTag
  1151. // * @private
  1152. // */
  1153. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  1154. // each(visualFuncs, function (visual, index) {
  1155. // var isLayout = visual.isLayout;
  1156. // if (layoutFilter == null
  1157. // || (layoutFilter === false && !isLayout)
  1158. // || (layoutFilter === true && isLayout)
  1159. // ) {
  1160. // visual.func(ecModel, api, payload);
  1161. // }
  1162. // });
  1163. // }
  1164. function clearColorPalette(ecModel) {
  1165. ecModel.clearColorPalette();
  1166. ecModel.eachSeries(function (seriesModel) {
  1167. seriesModel.clearColorPalette();
  1168. });
  1169. }
  1170. function render(ecIns, ecModel, api, payload) {
  1171. renderComponents(ecIns, ecModel, api, payload);
  1172. each(ecIns._chartsViews, function (chart) {
  1173. chart.__alive = false;
  1174. });
  1175. renderSeries(ecIns, ecModel, api, payload); // Remove groups of unrendered charts
  1176. each(ecIns._chartsViews, function (chart) {
  1177. if (!chart.__alive) {
  1178. chart.remove(ecModel, api);
  1179. }
  1180. });
  1181. }
  1182. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  1183. each(dirtyList || ecIns._componentsViews, function (componentView) {
  1184. var componentModel = componentView.__model;
  1185. componentView.render(componentModel, ecModel, api, payload);
  1186. updateZ(componentModel, componentView);
  1187. });
  1188. }
  1189. /**
  1190. * Render each chart and component
  1191. * @private
  1192. */
  1193. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  1194. // Render all charts
  1195. var scheduler = ecIns._scheduler;
  1196. var unfinished;
  1197. ecModel.eachSeries(function (seriesModel) {
  1198. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  1199. chartView.__alive = true;
  1200. var renderTask = chartView.renderTask;
  1201. scheduler.updatePayload(renderTask, payload);
  1202. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  1203. renderTask.dirty();
  1204. }
  1205. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  1206. chartView.group.silent = !!seriesModel.get('silent');
  1207. updateZ(seriesModel, chartView);
  1208. updateBlend(seriesModel, chartView);
  1209. });
  1210. scheduler.unfinished |= unfinished; // If use hover layer
  1211. updateHoverLayerStatus(ecIns, ecModel); // Add aria
  1212. aria(ecIns._zr.dom, ecModel);
  1213. }
  1214. function performPostUpdateFuncs(ecModel, api) {
  1215. each(postUpdateFuncs, function (func) {
  1216. func(ecModel, api);
  1217. });
  1218. }
  1219. var MOUSE_EVENT_NAMES = ['click', 'dblclick', 'mouseover', 'mouseout', 'mousemove', 'mousedown', 'mouseup', 'globalout', 'contextmenu'];
  1220. /**
  1221. * @private
  1222. */
  1223. echartsProto._initEvents = function () {
  1224. each(MOUSE_EVENT_NAMES, function (eveName) {
  1225. var handler = function (e) {
  1226. var ecModel = this.getModel();
  1227. var el = e.target;
  1228. var params;
  1229. var isGlobalOut = eveName === 'globalout'; // no e.target when 'globalout'.
  1230. if (isGlobalOut) {
  1231. params = {};
  1232. } else if (el && el.dataIndex != null) {
  1233. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  1234. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType, el) || {};
  1235. } // If element has custom eventData of components
  1236. else if (el && el.eventData) {
  1237. params = zrUtil.extend({}, el.eventData);
  1238. } // Contract: if params prepared in mouse event,
  1239. // these properties must be specified:
  1240. // {
  1241. // componentType: string (component main type)
  1242. // componentIndex: number
  1243. // }
  1244. // Otherwise event query can not work.
  1245. if (params) {
  1246. var componentType = params.componentType;
  1247. var componentIndex = params.componentIndex; // Special handling for historic reason: when trigger by
  1248. // markLine/markPoint/markArea, the componentType is
  1249. // 'markLine'/'markPoint'/'markArea', but we should better
  1250. // enable them to be queried by seriesIndex, since their
  1251. // option is set in each series.
  1252. if (componentType === 'markLine' || componentType === 'markPoint' || componentType === 'markArea') {
  1253. componentType = 'series';
  1254. componentIndex = params.seriesIndex;
  1255. }
  1256. var model = componentType && componentIndex != null && ecModel.getComponent(componentType, componentIndex);
  1257. var view = model && this[model.mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId];
  1258. params.event = e;
  1259. params.type = eveName;
  1260. this._ecEventProcessor.eventInfo = {
  1261. targetEl: el,
  1262. packedEvent: params,
  1263. model: model,
  1264. view: view
  1265. };
  1266. this.trigger(eveName, params);
  1267. }
  1268. }; // Consider that some component (like tooltip, brush, ...)
  1269. // register zr event handler, but user event handler might
  1270. // do anything, such as call `setOption` or `dispatchAction`,
  1271. // which probably update any of the content and probably
  1272. // cause problem if it is called previous other inner handlers.
  1273. handler.zrEventfulCallAtLast = true;
  1274. this._zr.on(eveName, handler, this);
  1275. }, this);
  1276. each(eventActionMap, function (actionType, eventType) {
  1277. this._messageCenter.on(eventType, function (event) {
  1278. this.trigger(eventType, event);
  1279. }, this);
  1280. }, this);
  1281. };
  1282. /**
  1283. * @return {boolean}
  1284. */
  1285. echartsProto.isDisposed = function () {
  1286. return this._disposed;
  1287. };
  1288. /**
  1289. * Clear
  1290. */
  1291. echartsProto.clear = function () {
  1292. if (this._disposed) {
  1293. disposedWarning(this.id);
  1294. return;
  1295. }
  1296. this.setOption({
  1297. series: []
  1298. }, true);
  1299. };
  1300. /**
  1301. * Dispose instance
  1302. */
  1303. echartsProto.dispose = function () {
  1304. if (this._disposed) {
  1305. disposedWarning(this.id);
  1306. return;
  1307. }
  1308. this._disposed = true;
  1309. modelUtil.setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  1310. var api = this._api;
  1311. var ecModel = this._model;
  1312. each(this._componentsViews, function (component) {
  1313. component.dispose(ecModel, api);
  1314. });
  1315. each(this._chartsViews, function (chart) {
  1316. chart.dispose(ecModel, api);
  1317. }); // Dispose after all views disposed
  1318. this._zr.dispose();
  1319. delete instances[this.id];
  1320. };
  1321. zrUtil.mixin(ECharts, Eventful);
  1322. function disposedWarning(id) {}
  1323. function updateHoverLayerStatus(ecIns, ecModel) {
  1324. var zr = ecIns._zr;
  1325. var storage = zr.storage;
  1326. var elCount = 0;
  1327. storage.traverse(function (el) {
  1328. elCount++;
  1329. });
  1330. if (elCount > ecModel.get('hoverLayerThreshold') && !env.node) {
  1331. ecModel.eachSeries(function (seriesModel) {
  1332. if (seriesModel.preventUsingHoverLayer) {
  1333. return;
  1334. }
  1335. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  1336. if (chartView.__alive) {
  1337. chartView.group.traverse(function (el) {
  1338. // Don't switch back.
  1339. el.useHoverLayer = true;
  1340. });
  1341. }
  1342. });
  1343. }
  1344. }
  1345. /**
  1346. * Update chart progressive and blend.
  1347. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  1348. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  1349. */
  1350. function updateBlend(seriesModel, chartView) {
  1351. var blendMode = seriesModel.get('blendMode') || null;
  1352. chartView.group.traverse(function (el) {
  1353. // FIXME marker and other components
  1354. if (!el.isGroup) {
  1355. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  1356. if (el.style.blend !== blendMode) {
  1357. el.setStyle('blend', blendMode);
  1358. }
  1359. }
  1360. if (el.eachPendingDisplayable) {
  1361. el.eachPendingDisplayable(function (displayable) {
  1362. displayable.setStyle('blend', blendMode);
  1363. });
  1364. }
  1365. });
  1366. }
  1367. /**
  1368. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  1369. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  1370. */
  1371. function updateZ(model, view) {
  1372. var z = model.get('z');
  1373. var zlevel = model.get('zlevel'); // Set z and zlevel
  1374. view.group.traverse(function (el) {
  1375. if (el.type !== 'group') {
  1376. z != null && (el.z = z);
  1377. zlevel != null && (el.zlevel = zlevel);
  1378. }
  1379. });
  1380. }
  1381. function createExtensionAPI(ecInstance) {
  1382. var coordSysMgr = ecInstance._coordSysMgr;
  1383. return zrUtil.extend(new ExtensionAPI(ecInstance), {
  1384. // Inject methods
  1385. getCoordinateSystems: zrUtil.bind(coordSysMgr.getCoordinateSystems, coordSysMgr),
  1386. getComponentByElement: function (el) {
  1387. while (el) {
  1388. var modelInfo = el.__ecComponentInfo;
  1389. if (modelInfo != null) {
  1390. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  1391. }
  1392. el = el.parent;
  1393. }
  1394. }
  1395. });
  1396. }
  1397. /**
  1398. * @class
  1399. * Usage of query:
  1400. * `chart.on('click', query, handler);`
  1401. * The `query` can be:
  1402. * + The component type query string, only `mainType` or `mainType.subType`,
  1403. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  1404. * + The component query object, like:
  1405. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  1406. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  1407. * + The data query object, like:
  1408. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  1409. * + The other query object (cmponent customized query), like:
  1410. * `{element: 'some'}` (only available in custom series).
  1411. *
  1412. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  1413. * same as there is no such prop in the `query` object.
  1414. */
  1415. function EventProcessor() {
  1416. // These info required: targetEl, packedEvent, model, view
  1417. this.eventInfo;
  1418. }
  1419. EventProcessor.prototype = {
  1420. constructor: EventProcessor,
  1421. normalizeQuery: function (query) {
  1422. var cptQuery = {};
  1423. var dataQuery = {};
  1424. var otherQuery = {}; // `query` is `mainType` or `mainType.subType` of component.
  1425. if (zrUtil.isString(query)) {
  1426. var condCptType = parseClassType(query); // `.main` and `.sub` may be ''.
  1427. cptQuery.mainType = condCptType.main || null;
  1428. cptQuery.subType = condCptType.sub || null;
  1429. } // `query` is an object, convert to {mainType, index, name, id}.
  1430. else {
  1431. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  1432. // can not be used in `compomentModel.filterForExposedEvent`.
  1433. var suffixes = ['Index', 'Name', 'Id'];
  1434. var dataKeys = {
  1435. name: 1,
  1436. dataIndex: 1,
  1437. dataType: 1
  1438. };
  1439. zrUtil.each(query, function (val, key) {
  1440. var reserved = false;
  1441. for (var i = 0; i < suffixes.length; i++) {
  1442. var propSuffix = suffixes[i];
  1443. var suffixPos = key.lastIndexOf(propSuffix);
  1444. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  1445. var mainType = key.slice(0, suffixPos); // Consider `dataIndex`.
  1446. if (mainType !== 'data') {
  1447. cptQuery.mainType = mainType;
  1448. cptQuery[propSuffix.toLowerCase()] = val;
  1449. reserved = true;
  1450. }
  1451. }
  1452. }
  1453. if (dataKeys.hasOwnProperty(key)) {
  1454. dataQuery[key] = val;
  1455. reserved = true;
  1456. }
  1457. if (!reserved) {
  1458. otherQuery[key] = val;
  1459. }
  1460. });
  1461. }
  1462. return {
  1463. cptQuery: cptQuery,
  1464. dataQuery: dataQuery,
  1465. otherQuery: otherQuery
  1466. };
  1467. },
  1468. filter: function (eventType, query, args) {
  1469. // They should be assigned before each trigger call.
  1470. var eventInfo = this.eventInfo;
  1471. if (!eventInfo) {
  1472. return true;
  1473. }
  1474. var targetEl = eventInfo.targetEl;
  1475. var packedEvent = eventInfo.packedEvent;
  1476. var model = eventInfo.model;
  1477. var view = eventInfo.view; // For event like 'globalout'.
  1478. if (!model || !view) {
  1479. return true;
  1480. }
  1481. var cptQuery = query.cptQuery;
  1482. var dataQuery = query.dataQuery;
  1483. 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));
  1484. function check(query, host, prop, propOnHost) {
  1485. return query[prop] == null || host[propOnHost || prop] === query[prop];
  1486. }
  1487. },
  1488. afterTrigger: function () {
  1489. // Make sure the eventInfo wont be used in next trigger.
  1490. this.eventInfo = null;
  1491. }
  1492. };
  1493. /**
  1494. * @type {Object} key: actionType.
  1495. * @inner
  1496. */
  1497. var actions = {};
  1498. /**
  1499. * Map eventType to actionType
  1500. * @type {Object}
  1501. */
  1502. var eventActionMap = {};
  1503. /**
  1504. * Data processor functions of each stage
  1505. * @type {Array.<Object.<string, Function>>}
  1506. * @inner
  1507. */
  1508. var dataProcessorFuncs = [];
  1509. /**
  1510. * @type {Array.<Function>}
  1511. * @inner
  1512. */
  1513. var optionPreprocessorFuncs = [];
  1514. /**
  1515. * @type {Array.<Function>}
  1516. * @inner
  1517. */
  1518. var postUpdateFuncs = [];
  1519. /**
  1520. * Visual encoding functions of each stage
  1521. * @type {Array.<Object.<string, Function>>}
  1522. */
  1523. var visualFuncs = [];
  1524. /**
  1525. * Theme storage
  1526. * @type {Object.<key, Object>}
  1527. */
  1528. var themeStorage = {};
  1529. /**
  1530. * Loading effects
  1531. */
  1532. var loadingEffects = {};
  1533. var instances = {};
  1534. var connectedGroups = {};
  1535. var idBase = new Date() - 0;
  1536. var groupIdBase = new Date() - 0;
  1537. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  1538. function enableConnect(chart) {
  1539. var STATUS_PENDING = 0;
  1540. var STATUS_UPDATING = 1;
  1541. var STATUS_UPDATED = 2;
  1542. var STATUS_KEY = '__connectUpdateStatus';
  1543. function updateConnectedChartsStatus(charts, status) {
  1544. for (var i = 0; i < charts.length; i++) {
  1545. var otherChart = charts[i];
  1546. otherChart[STATUS_KEY] = status;
  1547. }
  1548. }
  1549. each(eventActionMap, function (actionType, eventType) {
  1550. chart._messageCenter.on(eventType, function (event) {
  1551. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  1552. if (event && event.escapeConnect) {
  1553. return;
  1554. }
  1555. var action = chart.makeActionFromEvent(event);
  1556. var otherCharts = [];
  1557. each(instances, function (otherChart) {
  1558. if (otherChart !== chart && otherChart.group === chart.group) {
  1559. otherCharts.push(otherChart);
  1560. }
  1561. });
  1562. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  1563. each(otherCharts, function (otherChart) {
  1564. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  1565. otherChart.dispatchAction(action);
  1566. }
  1567. });
  1568. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  1569. }
  1570. });
  1571. });
  1572. }
  1573. /**
  1574. * @param {HTMLElement} dom
  1575. * @param {Object} [theme]
  1576. * @param {Object} opts
  1577. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  1578. * @param {string} [opts.renderer] Can choose 'canvas' or 'svg' to render the chart.
  1579. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  1580. * Can be 'auto' (the same as null/undefined)
  1581. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  1582. * Can be 'auto' (the same as null/undefined)
  1583. */
  1584. function init(dom, theme, opts) {
  1585. var existInstance = getInstanceByDom(dom);
  1586. if (existInstance) {
  1587. return existInstance;
  1588. }
  1589. var chart = new ECharts(dom, theme, opts);
  1590. chart.id = 'ec_' + idBase++;
  1591. instances[chart.id] = chart;
  1592. modelUtil.setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  1593. enableConnect(chart);
  1594. return chart;
  1595. }
  1596. /**
  1597. * @return {string|Array.<module:echarts~ECharts>} groupId
  1598. */
  1599. function connect(groupId) {
  1600. // Is array of charts
  1601. if (zrUtil.isArray(groupId)) {
  1602. var charts = groupId;
  1603. groupId = null; // If any chart has group
  1604. each(charts, function (chart) {
  1605. if (chart.group != null) {
  1606. groupId = chart.group;
  1607. }
  1608. });
  1609. groupId = groupId || 'g_' + groupIdBase++;
  1610. each(charts, function (chart) {
  1611. chart.group = groupId;
  1612. });
  1613. }
  1614. connectedGroups[groupId] = true;
  1615. return groupId;
  1616. }
  1617. /**
  1618. * @DEPRECATED
  1619. * @return {string} groupId
  1620. */
  1621. function disConnect(groupId) {
  1622. connectedGroups[groupId] = false;
  1623. }
  1624. /**
  1625. * @return {string} groupId
  1626. */
  1627. var disconnect = disConnect;
  1628. /**
  1629. * Dispose a chart instance
  1630. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  1631. */
  1632. function dispose(chart) {
  1633. if (typeof chart === 'string') {
  1634. chart = instances[chart];
  1635. } else if (!(chart instanceof ECharts)) {
  1636. // Try to treat as dom
  1637. chart = getInstanceByDom(chart);
  1638. }
  1639. if (chart instanceof ECharts && !chart.isDisposed()) {
  1640. chart.dispose();
  1641. }
  1642. }
  1643. /**
  1644. * @param {HTMLElement} dom
  1645. * @return {echarts~ECharts}
  1646. */
  1647. function getInstanceByDom(dom) {
  1648. return instances[modelUtil.getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  1649. }
  1650. /**
  1651. * @param {string} key
  1652. * @return {echarts~ECharts}
  1653. */
  1654. function getInstanceById(key) {
  1655. return instances[key];
  1656. }
  1657. /**
  1658. * Register theme
  1659. */
  1660. function registerTheme(name, theme) {
  1661. themeStorage[name] = theme;
  1662. }
  1663. /**
  1664. * Register option preprocessor
  1665. * @param {Function} preprocessorFunc
  1666. */
  1667. function registerPreprocessor(preprocessorFunc) {
  1668. optionPreprocessorFuncs.push(preprocessorFunc);
  1669. }
  1670. /**
  1671. * @param {number} [priority=1000]
  1672. * @param {Object|Function} processor
  1673. */
  1674. function registerProcessor(priority, processor) {
  1675. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  1676. }
  1677. /**
  1678. * Register postUpdater
  1679. * @param {Function} postUpdateFunc
  1680. */
  1681. function registerPostUpdate(postUpdateFunc) {
  1682. postUpdateFuncs.push(postUpdateFunc);
  1683. }
  1684. /**
  1685. * Usage:
  1686. * registerAction('someAction', 'someEvent', function () { ... });
  1687. * registerAction('someAction', function () { ... });
  1688. * registerAction(
  1689. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  1690. * function () { ... }
  1691. * );
  1692. *
  1693. * @param {(string|Object)} actionInfo
  1694. * @param {string} actionInfo.type
  1695. * @param {string} [actionInfo.event]
  1696. * @param {string} [actionInfo.update]
  1697. * @param {string} [eventName]
  1698. * @param {Function} action
  1699. */
  1700. function registerAction(actionInfo, eventName, action) {
  1701. if (typeof eventName === 'function') {
  1702. action = eventName;
  1703. eventName = '';
  1704. }
  1705. var actionType = isObject(actionInfo) ? actionInfo.type : [actionInfo, actionInfo = {
  1706. event: eventName
  1707. }][0]; // Event name is all lowercase
  1708. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  1709. eventName = actionInfo.event; // Validate action type and event name.
  1710. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  1711. if (!actions[actionType]) {
  1712. actions[actionType] = {
  1713. action: action,
  1714. actionInfo: actionInfo
  1715. };
  1716. }
  1717. eventActionMap[eventName] = actionType;
  1718. }
  1719. /**
  1720. * @param {string} type
  1721. * @param {*} CoordinateSystem
  1722. */
  1723. function registerCoordinateSystem(type, CoordinateSystem) {
  1724. CoordinateSystemManager.register(type, CoordinateSystem);
  1725. }
  1726. /**
  1727. * Get dimensions of specified coordinate system.
  1728. * @param {string} type
  1729. * @return {Array.<string|Object>}
  1730. */
  1731. function getCoordinateSystemDimensions(type) {
  1732. var coordSysCreator = CoordinateSystemManager.get(type);
  1733. if (coordSysCreator) {
  1734. return coordSysCreator.getDimensionsInfo ? coordSysCreator.getDimensionsInfo() : coordSysCreator.dimensions.slice();
  1735. }
  1736. }
  1737. /**
  1738. * Layout is a special stage of visual encoding
  1739. * Most visual encoding like color are common for different chart
  1740. * But each chart has it's own layout algorithm
  1741. *
  1742. * @param {number} [priority=1000]
  1743. * @param {Function} layoutTask
  1744. */
  1745. function registerLayout(priority, layoutTask) {
  1746. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  1747. }
  1748. /**
  1749. * @param {number} [priority=3000]
  1750. * @param {module:echarts/stream/Task} visualTask
  1751. */
  1752. function registerVisual(priority, visualTask) {
  1753. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  1754. }
  1755. /**
  1756. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  1757. */
  1758. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  1759. if (isFunction(priority) || isObject(priority)) {
  1760. fn = priority;
  1761. priority = defaultPriority;
  1762. }
  1763. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  1764. stageHandler.__prio = priority;
  1765. stageHandler.__raw = fn;
  1766. targetList.push(stageHandler);
  1767. return stageHandler;
  1768. }
  1769. /**
  1770. * @param {string} name
  1771. */
  1772. function registerLoading(name, loadingFx) {
  1773. loadingEffects[name] = loadingFx;
  1774. }
  1775. /**
  1776. * @param {Object} opts
  1777. * @param {string} [superClass]
  1778. */
  1779. function extendComponentModel(opts
  1780. /*, superClass*/
  1781. ) {
  1782. // var Clazz = ComponentModel;
  1783. // if (superClass) {
  1784. // var classType = parseClassType(superClass);
  1785. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  1786. // }
  1787. return ComponentModel.extend(opts);
  1788. }
  1789. /**
  1790. * @param {Object} opts
  1791. * @param {string} [superClass]
  1792. */
  1793. function extendComponentView(opts
  1794. /*, superClass*/
  1795. ) {
  1796. // var Clazz = ComponentView;
  1797. // if (superClass) {
  1798. // var classType = parseClassType(superClass);
  1799. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  1800. // }
  1801. return ComponentView.extend(opts);
  1802. }
  1803. /**
  1804. * @param {Object} opts
  1805. * @param {string} [superClass]
  1806. */
  1807. function extendSeriesModel(opts
  1808. /*, superClass*/
  1809. ) {
  1810. // var Clazz = SeriesModel;
  1811. // if (superClass) {
  1812. // superClass = 'series.' + superClass.replace('series.', '');
  1813. // var classType = parseClassType(superClass);
  1814. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  1815. // }
  1816. return SeriesModel.extend(opts);
  1817. }
  1818. /**
  1819. * @param {Object} opts
  1820. * @param {string} [superClass]
  1821. */
  1822. function extendChartView(opts
  1823. /*, superClass*/
  1824. ) {
  1825. // var Clazz = ChartView;
  1826. // if (superClass) {
  1827. // superClass = superClass.replace('series.', '');
  1828. // var classType = parseClassType(superClass);
  1829. // Clazz = ChartView.getClass(classType.main, true);
  1830. // }
  1831. return ChartView.extend(opts);
  1832. }
  1833. /**
  1834. * ZRender need a canvas context to do measureText.
  1835. * But in node environment canvas may be created by node-canvas.
  1836. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  1837. *
  1838. * Be careful of using it in the browser.
  1839. *
  1840. * @param {Function} creator
  1841. * @example
  1842. * var Canvas = require('canvas');
  1843. * var echarts = require('echarts');
  1844. * echarts.setCanvasCreator(function () {
  1845. * // Small size is enough.
  1846. * return new Canvas(32, 32);
  1847. * });
  1848. */
  1849. function setCanvasCreator(creator) {
  1850. zrUtil.$override('createCanvas', creator);
  1851. }
  1852. /**
  1853. * @param {string} mapName
  1854. * @param {Array.<Object>|Object|string} geoJson
  1855. * @param {Object} [specialAreas]
  1856. *
  1857. * @example GeoJSON
  1858. * $.get('USA.json', function (geoJson) {
  1859. * echarts.registerMap('USA', geoJson);
  1860. * // Or
  1861. * echarts.registerMap('USA', {
  1862. * geoJson: geoJson,
  1863. * specialAreas: {}
  1864. * })
  1865. * });
  1866. *
  1867. * $.get('airport.svg', function (svg) {
  1868. * echarts.registerMap('airport', {
  1869. * svg: svg
  1870. * }
  1871. * });
  1872. *
  1873. * echarts.registerMap('eu', [
  1874. * {svg: eu-topographic.svg},
  1875. * {geoJSON: eu.json}
  1876. * ])
  1877. */
  1878. function registerMap(mapName, geoJson, specialAreas) {
  1879. mapDataStorage.registerMap(mapName, geoJson, specialAreas);
  1880. }
  1881. /**
  1882. * @param {string} mapName
  1883. * @return {Object}
  1884. */
  1885. function getMap(mapName) {
  1886. // For backward compatibility, only return the first one.
  1887. var records = mapDataStorage.retrieveMap(mapName);
  1888. return records && records[0] && {
  1889. geoJson: records[0].geoJSON,
  1890. specialAreas: records[0].specialAreas
  1891. };
  1892. }
  1893. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  1894. registerPreprocessor(backwardCompat);
  1895. registerProcessor(PRIORITY_PROCESSOR_DATASTACK, dataStack);
  1896. registerLoading('default', loadingDefault); // Default actions
  1897. registerAction({
  1898. type: 'highlight',
  1899. event: 'highlight',
  1900. update: 'highlight'
  1901. }, zrUtil.noop);
  1902. registerAction({
  1903. type: 'downplay',
  1904. event: 'downplay',
  1905. update: 'downplay'
  1906. }, zrUtil.noop); // Default theme
  1907. registerTheme('light', lightTheme);
  1908. registerTheme('dark', darkTheme); // For backward compatibility, where the namespace `dataTool` will
  1909. // be mounted on `echarts` is the extension `dataTool` is imported.
  1910. var dataTool = {};
  1911. exports.version = version;
  1912. exports.dependencies = dependencies;
  1913. exports.PRIORITY = PRIORITY;
  1914. exports.init = init;
  1915. exports.connect = connect;
  1916. exports.disConnect = disConnect;
  1917. exports.disconnect = disconnect;
  1918. exports.dispose = dispose;
  1919. exports.getInstanceByDom = getInstanceByDom;
  1920. exports.getInstanceById = getInstanceById;
  1921. exports.registerTheme = registerTheme;
  1922. exports.registerPreprocessor = registerPreprocessor;
  1923. exports.registerProcessor = registerProcessor;
  1924. exports.registerPostUpdate = registerPostUpdate;
  1925. exports.registerAction = registerAction;
  1926. exports.registerCoordinateSystem = registerCoordinateSystem;
  1927. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  1928. exports.registerLayout = registerLayout;
  1929. exports.registerVisual = registerVisual;
  1930. exports.registerLoading = registerLoading;
  1931. exports.extendComponentModel = extendComponentModel;
  1932. exports.extendComponentView = extendComponentView;
  1933. exports.extendSeriesModel = extendSeriesModel;
  1934. exports.extendChartView = extendChartView;
  1935. exports.setCanvasCreator = setCanvasCreator;
  1936. exports.registerMap = registerMap;
  1937. exports.getMap = getMap;
  1938. exports.dataTool = dataTool;
  1939. var ___ec_export = require("./export");
  1940. (function () {
  1941. for (var key in ___ec_export) {
  1942. if (___ec_export.hasOwnProperty(key)) {
  1943. exports[key] = ___ec_export[key];
  1944. }
  1945. }
  1946. })();