You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

54001 lines
1.5 MiB

  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (factory((global.echarts = {})));
  5. }(this, (function (exports) { 'use strict';
  6. // (1) The code `if (__DEV__) ...` can be removed by build tool.
  7. // (2) If intend to use `__DEV__`, this module should be imported. Use a global
  8. // variable `__DEV__` may cause that miss the declaration (see #6535), or the
  9. // declaration is behind of the using position (for example in `Model.extent`,
  10. // And tools like rollup can not analysis the dependency if not import).
  11. var dev;
  12. // In browser
  13. if (typeof window !== 'undefined') {
  14. dev = window.__DEV__;
  15. }
  16. // In node
  17. else if (typeof global !== 'undefined') {
  18. dev = global.__DEV__;
  19. }
  20. if (typeof dev === 'undefined') {
  21. dev = true;
  22. }
  23. var __DEV__ = dev;
  24. /**
  25. * zrender: 生成唯一id
  26. *
  27. * @author errorrik (errorrik@gmail.com)
  28. */
  29. var idStart = 0x0907;
  30. var guid = function () {
  31. return idStart++;
  32. };
  33. /**
  34. * echarts设备环境识别
  35. *
  36. * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。
  37. * @author firede[firede@firede.us]
  38. * @desc thanks zepto.
  39. */
  40. var env = {};
  41. if (typeof wx !== 'undefined') {
  42. // In Weixin Application
  43. env = {
  44. browser: {},
  45. os: {},
  46. node: false,
  47. wxa: true, // Weixin Application
  48. canvasSupported: true,
  49. svgSupported: false,
  50. touchEventsSupported: true
  51. };
  52. }
  53. else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  54. // In worker
  55. env = {
  56. browser: {},
  57. os: {},
  58. node: false,
  59. worker: true,
  60. canvasSupported: true
  61. };
  62. }
  63. else if (typeof navigator === 'undefined') {
  64. // In node
  65. env = {
  66. browser: {},
  67. os: {},
  68. node: true,
  69. worker: false,
  70. // Assume canvas is supported
  71. canvasSupported: true,
  72. svgSupported: true
  73. };
  74. }
  75. else {
  76. env = detect(navigator.userAgent);
  77. }
  78. var env$1 = env;
  79. // Zepto.js
  80. // (c) 2010-2013 Thomas Fuchs
  81. // Zepto.js may be freely distributed under the MIT license.
  82. function detect(ua) {
  83. var os = {};
  84. var browser = {};
  85. // var webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/);
  86. // var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
  87. // var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  88. // var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
  89. // var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
  90. // var webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/);
  91. // var touchpad = webos && ua.match(/TouchPad/);
  92. // var kindle = ua.match(/Kindle\/([\d.]+)/);
  93. // var silk = ua.match(/Silk\/([\d._]+)/);
  94. // var blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/);
  95. // var bb10 = ua.match(/(BB10).*Version\/([\d.]+)/);
  96. // var rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/);
  97. // var playbook = ua.match(/PlayBook/);
  98. // var chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/);
  99. var firefox = ua.match(/Firefox\/([\d.]+)/);
  100. // var safari = webkit && ua.match(/Mobile\//) && !chrome;
  101. // var webview = ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/) && !chrome;
  102. var ie = ua.match(/MSIE\s([\d.]+)/)
  103. // IE 11 Trident/7.0; rv:11.0
  104. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  105. var edge = ua.match(/Edge\/([\d.]+)/); // IE 12 and 12+
  106. var weChat = (/micromessenger/i).test(ua);
  107. // Todo: clean this up with a better OS/browser seperation:
  108. // - discern (more) between multiple browsers on android
  109. // - decide if kindle fire in silk mode is android or not
  110. // - Firefox on Android doesn't specify the Android version
  111. // - possibly devide in os, device and browser hashes
  112. // if (browser.webkit = !!webkit) browser.version = webkit[1];
  113. // if (android) os.android = true, os.version = android[2];
  114. // if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.');
  115. // if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.');
  116. // if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null;
  117. // if (webos) os.webos = true, os.version = webos[2];
  118. // if (touchpad) os.touchpad = true;
  119. // if (blackberry) os.blackberry = true, os.version = blackberry[2];
  120. // if (bb10) os.bb10 = true, os.version = bb10[2];
  121. // if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2];
  122. // if (playbook) browser.playbook = true;
  123. // if (kindle) os.kindle = true, os.version = kindle[1];
  124. // if (silk) browser.silk = true, browser.version = silk[1];
  125. // if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true;
  126. // if (chrome) browser.chrome = true, browser.version = chrome[1];
  127. if (firefox) {
  128. browser.firefox = true;
  129. browser.version = firefox[1];
  130. }
  131. // if (safari && (ua.match(/Safari/) || !!os.ios)) browser.safari = true;
  132. // if (webview) browser.webview = true;
  133. if (ie) {
  134. browser.ie = true;
  135. browser.version = ie[1];
  136. }
  137. if (edge) {
  138. browser.edge = true;
  139. browser.version = edge[1];
  140. }
  141. // It is difficult to detect WeChat in Win Phone precisely, because ua can
  142. // not be set on win phone. So we do not consider Win Phone.
  143. if (weChat) {
  144. browser.weChat = true;
  145. }
  146. // os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) ||
  147. // (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/)));
  148. // os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos ||
  149. // (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) ||
  150. // (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/))));
  151. return {
  152. browser: browser,
  153. os: os,
  154. node: false,
  155. // 原生canvas支持,改极端点了
  156. // canvasSupported : !(browser.ie && parseFloat(browser.version) < 9)
  157. canvasSupported: !!document.createElement('canvas').getContext,
  158. svgSupported: typeof SVGRect !== 'undefined',
  159. // works on most browsers
  160. // IE10/11 does not support touch event, and MS Edge supports them but not by
  161. // default, so we dont check navigator.maxTouchPoints for them here.
  162. touchEventsSupported: 'ontouchstart' in window && !browser.ie && !browser.edge,
  163. // <http://caniuse.com/#search=pointer%20event>.
  164. pointerEventsSupported: 'onpointerdown' in window
  165. // Firefox supports pointer but not by default, only MS browsers are reliable on pointer
  166. // events currently. So we dont use that on other browsers unless tested sufficiently.
  167. // Although IE 10 supports pointer event, it use old style and is different from the
  168. // standard. So we exclude that. (IE 10 is hardly used on touch device)
  169. && (browser.edge || (browser.ie && browser.version >= 11))
  170. // passiveSupported: detectPassiveSupport()
  171. };
  172. }
  173. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
  174. // function detectPassiveSupport() {
  175. // // Test via a getter in the options object to see if the passive property is accessed
  176. // var supportsPassive = false;
  177. // try {
  178. // var opts = Object.defineProperty({}, 'passive', {
  179. // get: function() {
  180. // supportsPassive = true;
  181. // }
  182. // });
  183. // window.addEventListener('testPassive', function() {}, opts);
  184. // } catch (e) {
  185. // }
  186. // return supportsPassive;
  187. // }
  188. /**
  189. * @module zrender/core/util
  190. */
  191. // 用于处理merge时无法遍历Date等对象的问题
  192. var BUILTIN_OBJECT = {
  193. '[object Function]': 1,
  194. '[object RegExp]': 1,
  195. '[object Date]': 1,
  196. '[object Error]': 1,
  197. '[object CanvasGradient]': 1,
  198. '[object CanvasPattern]': 1,
  199. // For node-canvas
  200. '[object Image]': 1,
  201. '[object Canvas]': 1
  202. };
  203. var TYPED_ARRAY = {
  204. '[object Int8Array]': 1,
  205. '[object Uint8Array]': 1,
  206. '[object Uint8ClampedArray]': 1,
  207. '[object Int16Array]': 1,
  208. '[object Uint16Array]': 1,
  209. '[object Int32Array]': 1,
  210. '[object Uint32Array]': 1,
  211. '[object Float32Array]': 1,
  212. '[object Float64Array]': 1
  213. };
  214. var objToString = Object.prototype.toString;
  215. var arrayProto = Array.prototype;
  216. var nativeForEach = arrayProto.forEach;
  217. var nativeFilter = arrayProto.filter;
  218. var nativeSlice = arrayProto.slice;
  219. var nativeMap = arrayProto.map;
  220. var nativeReduce = arrayProto.reduce;
  221. // Avoid assign to an exported variable, for transforming to cjs.
  222. var methods = {};
  223. function $override(name, fn) {
  224. // Clear ctx instance for different environment
  225. if (name === 'createCanvas') {
  226. _ctx = null;
  227. }
  228. methods[name] = fn;
  229. }
  230. /**
  231. * Those data types can be cloned:
  232. * Plain object, Array, TypedArray, number, string, null, undefined.
  233. * Those data types will be assgined using the orginal data:
  234. * BUILTIN_OBJECT
  235. * Instance of user defined class will be cloned to a plain object, without
  236. * properties in prototype.
  237. * Other data types is not supported (not sure what will happen).
  238. *
  239. * Caution: do not support clone Date, for performance consideration.
  240. * (There might be a large number of date in `series.data`).
  241. * So date should not be modified in and out of echarts.
  242. *
  243. * @param {*} source
  244. * @return {*} new
  245. */
  246. function clone(source) {
  247. if (source == null || typeof source != 'object') {
  248. return source;
  249. }
  250. var result = source;
  251. var typeStr = objToString.call(source);
  252. if (typeStr === '[object Array]') {
  253. if (!isPrimitive(source)) {
  254. result = [];
  255. for (var i = 0, len = source.length; i < len; i++) {
  256. result[i] = clone(source[i]);
  257. }
  258. }
  259. }
  260. else if (TYPED_ARRAY[typeStr]) {
  261. if (!isPrimitive(source)) {
  262. var Ctor = source.constructor;
  263. if (source.constructor.from) {
  264. result = Ctor.from(source);
  265. }
  266. else {
  267. result = new Ctor(source.length);
  268. for (var i = 0, len = source.length; i < len; i++) {
  269. result[i] = clone(source[i]);
  270. }
  271. }
  272. }
  273. }
  274. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  275. result = {};
  276. for (var key in source) {
  277. if (source.hasOwnProperty(key)) {
  278. result[key] = clone(source[key]);
  279. }
  280. }
  281. }
  282. return result;
  283. }
  284. /**
  285. * @memberOf module:zrender/core/util
  286. * @param {*} target
  287. * @param {*} source
  288. * @param {boolean} [overwrite=false]
  289. */
  290. function merge(target, source, overwrite) {
  291. // We should escapse that source is string
  292. // and enter for ... in ...
  293. if (!isObject$1(source) || !isObject$1(target)) {
  294. return overwrite ? clone(source) : target;
  295. }
  296. for (var key in source) {
  297. if (source.hasOwnProperty(key)) {
  298. var targetProp = target[key];
  299. var sourceProp = source[key];
  300. if (isObject$1(sourceProp)
  301. && isObject$1(targetProp)
  302. && !isArray(sourceProp)
  303. && !isArray(targetProp)
  304. && !isDom(sourceProp)
  305. && !isDom(targetProp)
  306. && !isBuiltInObject(sourceProp)
  307. && !isBuiltInObject(targetProp)
  308. && !isPrimitive(sourceProp)
  309. && !isPrimitive(targetProp)
  310. ) {
  311. // 如果需要递归覆盖,就递归调用merge
  312. merge(targetProp, sourceProp, overwrite);
  313. }
  314. else if (overwrite || !(key in target)) {
  315. // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况
  316. // NOTE,在 target[key] 不存在的时候也是直接覆盖
  317. target[key] = clone(source[key], true);
  318. }
  319. }
  320. }
  321. return target;
  322. }
  323. /**
  324. * @param {Array} targetAndSources The first item is target, and the rests are source.
  325. * @param {boolean} [overwrite=false]
  326. * @return {*} target
  327. */
  328. function mergeAll(targetAndSources, overwrite) {
  329. var result = targetAndSources[0];
  330. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  331. result = merge(result, targetAndSources[i], overwrite);
  332. }
  333. return result;
  334. }
  335. /**
  336. * @param {*} target
  337. * @param {*} source
  338. * @memberOf module:zrender/core/util
  339. */
  340. function extend(target, source) {
  341. for (var key in source) {
  342. if (source.hasOwnProperty(key)) {
  343. target[key] = source[key];
  344. }
  345. }
  346. return target;
  347. }
  348. /**
  349. * @param {*} target
  350. * @param {*} source
  351. * @param {boolean} [overlay=false]
  352. * @memberOf module:zrender/core/util
  353. */
  354. function defaults(target, source, overlay) {
  355. for (var key in source) {
  356. if (source.hasOwnProperty(key)
  357. && (overlay ? source[key] != null : target[key] == null)
  358. ) {
  359. target[key] = source[key];
  360. }
  361. }
  362. return target;
  363. }
  364. var createCanvas = function () {
  365. return methods.createCanvas();
  366. };
  367. methods.createCanvas = function () {
  368. return document.createElement('canvas');
  369. };
  370. // FIXME
  371. var _ctx;
  372. function getContext() {
  373. if (!_ctx) {
  374. // Use util.createCanvas instead of createCanvas
  375. // because createCanvas may be overwritten in different environment
  376. _ctx = createCanvas().getContext('2d');
  377. }
  378. return _ctx;
  379. }
  380. /**
  381. * 查询数组中元素的index
  382. * @memberOf module:zrender/core/util
  383. */
  384. function indexOf(array, value) {
  385. if (array) {
  386. if (array.indexOf) {
  387. return array.indexOf(value);
  388. }
  389. for (var i = 0, len = array.length; i < len; i++) {
  390. if (array[i] === value) {
  391. return i;
  392. }
  393. }
  394. }
  395. return -1;
  396. }
  397. /**
  398. * 构造类继承关系
  399. *
  400. * @memberOf module:zrender/core/util
  401. * @param {Function} clazz 源类
  402. * @param {Function} baseClazz 基类
  403. */
  404. function inherits(clazz, baseClazz) {
  405. var clazzPrototype = clazz.prototype;
  406. function F() {}
  407. F.prototype = baseClazz.prototype;
  408. clazz.prototype = new F();
  409. for (var prop in clazzPrototype) {
  410. clazz.prototype[prop] = clazzPrototype[prop];
  411. }
  412. clazz.prototype.constructor = clazz;
  413. clazz.superClass = baseClazz;
  414. }
  415. /**
  416. * @memberOf module:zrender/core/util
  417. * @param {Object|Function} target
  418. * @param {Object|Function} sorce
  419. * @param {boolean} overlay
  420. */
  421. function mixin(target, source, overlay) {
  422. target = 'prototype' in target ? target.prototype : target;
  423. source = 'prototype' in source ? source.prototype : source;
  424. defaults(target, source, overlay);
  425. }
  426. /**
  427. * Consider typed array.
  428. * @param {Array|TypedArray} data
  429. */
  430. function isArrayLike(data) {
  431. if (! data) {
  432. return;
  433. }
  434. if (typeof data == 'string') {
  435. return false;
  436. }
  437. return typeof data.length == 'number';
  438. }
  439. /**
  440. * 数组或对象遍历
  441. * @memberOf module:zrender/core/util
  442. * @param {Object|Array} obj
  443. * @param {Function} cb
  444. * @param {*} [context]
  445. */
  446. function each$1(obj, cb, context) {
  447. if (!(obj && cb)) {
  448. return;
  449. }
  450. if (obj.forEach && obj.forEach === nativeForEach) {
  451. obj.forEach(cb, context);
  452. }
  453. else if (obj.length === +obj.length) {
  454. for (var i = 0, len = obj.length; i < len; i++) {
  455. cb.call(context, obj[i], i, obj);
  456. }
  457. }
  458. else {
  459. for (var key in obj) {
  460. if (obj.hasOwnProperty(key)) {
  461. cb.call(context, obj[key], key, obj);
  462. }
  463. }
  464. }
  465. }
  466. /**
  467. * 数组映射
  468. * @memberOf module:zrender/core/util
  469. * @param {Array} obj
  470. * @param {Function} cb
  471. * @param {*} [context]
  472. * @return {Array}
  473. */
  474. function map(obj, cb, context) {
  475. if (!(obj && cb)) {
  476. return;
  477. }
  478. if (obj.map && obj.map === nativeMap) {
  479. return obj.map(cb, context);
  480. }
  481. else {
  482. var result = [];
  483. for (var i = 0, len = obj.length; i < len; i++) {
  484. result.push(cb.call(context, obj[i], i, obj));
  485. }
  486. return result;
  487. }
  488. }
  489. /**
  490. * @memberOf module:zrender/core/util
  491. * @param {Array} obj
  492. * @param {Function} cb
  493. * @param {Object} [memo]
  494. * @param {*} [context]
  495. * @return {Array}
  496. */
  497. function reduce(obj, cb, memo, context) {
  498. if (!(obj && cb)) {
  499. return;
  500. }
  501. if (obj.reduce && obj.reduce === nativeReduce) {
  502. return obj.reduce(cb, memo, context);
  503. }
  504. else {
  505. for (var i = 0, len = obj.length; i < len; i++) {
  506. memo = cb.call(context, memo, obj[i], i, obj);
  507. }
  508. return memo;
  509. }
  510. }
  511. /**
  512. * 数组过滤
  513. * @memberOf module:zrender/core/util
  514. * @param {Array} obj
  515. * @param {Function} cb
  516. * @param {*} [context]
  517. * @return {Array}
  518. */
  519. function filter(obj, cb, context) {
  520. if (!(obj && cb)) {
  521. return;
  522. }
  523. if (obj.filter && obj.filter === nativeFilter) {
  524. return obj.filter(cb, context);
  525. }
  526. else {
  527. var result = [];
  528. for (var i = 0, len = obj.length; i < len; i++) {
  529. if (cb.call(context, obj[i], i, obj)) {
  530. result.push(obj[i]);
  531. }
  532. }
  533. return result;
  534. }
  535. }
  536. /**
  537. * 数组项查找
  538. * @memberOf module:zrender/core/util
  539. * @param {Array} obj
  540. * @param {Function} cb
  541. * @param {*} [context]
  542. * @return {*}
  543. */
  544. function find(obj, cb, context) {
  545. if (!(obj && cb)) {
  546. return;
  547. }
  548. for (var i = 0, len = obj.length; i < len; i++) {
  549. if (cb.call(context, obj[i], i, obj)) {
  550. return obj[i];
  551. }
  552. }
  553. }
  554. /**
  555. * @memberOf module:zrender/core/util
  556. * @param {Function} func
  557. * @param {*} context
  558. * @return {Function}
  559. */
  560. function bind(func, context) {
  561. var args = nativeSlice.call(arguments, 2);
  562. return function () {
  563. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  564. };
  565. }
  566. /**
  567. * @memberOf module:zrender/core/util
  568. * @param {Function} func
  569. * @return {Function}
  570. */
  571. function curry(func) {
  572. var args = nativeSlice.call(arguments, 1);
  573. return function () {
  574. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  575. };
  576. }
  577. /**
  578. * @memberOf module:zrender/core/util
  579. * @param {*} value
  580. * @return {boolean}
  581. */
  582. function isArray(value) {
  583. return objToString.call(value) === '[object Array]';
  584. }
  585. /**
  586. * @memberOf module:zrender/core/util
  587. * @param {*} value
  588. * @return {boolean}
  589. */
  590. function isFunction$1(value) {
  591. return typeof value === 'function';
  592. }
  593. /**
  594. * @memberOf module:zrender/core/util
  595. * @param {*} value
  596. * @return {boolean}
  597. */
  598. function isString(value) {
  599. return objToString.call(value) === '[object String]';
  600. }
  601. /**
  602. * @memberOf module:zrender/core/util
  603. * @param {*} value
  604. * @return {boolean}
  605. */
  606. function isObject$1(value) {
  607. // Avoid a V8 JIT bug in Chrome 19-20.
  608. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  609. var type = typeof value;
  610. return type === 'function' || (!!value && type == 'object');
  611. }
  612. /**
  613. * @memberOf module:zrender/core/util
  614. * @param {*} value
  615. * @return {boolean}
  616. */
  617. function isBuiltInObject(value) {
  618. return !!BUILTIN_OBJECT[objToString.call(value)];
  619. }
  620. /**
  621. * @memberOf module:zrender/core/util
  622. * @param {*} value
  623. * @return {boolean}
  624. */
  625. function isTypedArray(value) {
  626. return !!TYPED_ARRAY[objToString.call(value)];
  627. }
  628. /**
  629. * @memberOf module:zrender/core/util
  630. * @param {*} value
  631. * @return {boolean}
  632. */
  633. function isDom(value) {
  634. return typeof value === 'object'
  635. && typeof value.nodeType === 'number'
  636. && typeof value.ownerDocument === 'object';
  637. }
  638. /**
  639. * Whether is exactly NaN. Notice isNaN('a') returns true.
  640. * @param {*} value
  641. * @return {boolean}
  642. */
  643. function eqNaN(value) {
  644. return value !== value;
  645. }
  646. /**
  647. * If value1 is not null, then return value1, otherwise judget rest of values.
  648. * Low performance.
  649. * @memberOf module:zrender/core/util
  650. * @return {*} Final value
  651. */
  652. function retrieve(values) {
  653. for (var i = 0, len = arguments.length; i < len; i++) {
  654. if (arguments[i] != null) {
  655. return arguments[i];
  656. }
  657. }
  658. }
  659. function retrieve2(value0, value1) {
  660. return value0 != null
  661. ? value0
  662. : value1;
  663. }
  664. function retrieve3(value0, value1, value2) {
  665. return value0 != null
  666. ? value0
  667. : value1 != null
  668. ? value1
  669. : value2;
  670. }
  671. /**
  672. * @memberOf module:zrender/core/util
  673. * @param {Array} arr
  674. * @param {number} startIndex
  675. * @param {number} endIndex
  676. * @return {Array}
  677. */
  678. function slice() {
  679. return Function.call.apply(nativeSlice, arguments);
  680. }
  681. /**
  682. * Normalize css liked array configuration
  683. * e.g.
  684. * 3 => [3, 3, 3, 3]
  685. * [4, 2] => [4, 2, 4, 2]
  686. * [4, 3, 2] => [4, 3, 2, 3]
  687. * @param {number|Array.<number>} val
  688. * @return {Array.<number>}
  689. */
  690. function normalizeCssArray(val) {
  691. if (typeof (val) === 'number') {
  692. return [val, val, val, val];
  693. }
  694. var len = val.length;
  695. if (len === 2) {
  696. // vertical | horizontal
  697. return [val[0], val[1], val[0], val[1]];
  698. }
  699. else if (len === 3) {
  700. // top | horizontal | bottom
  701. return [val[0], val[1], val[2], val[1]];
  702. }
  703. return val;
  704. }
  705. /**
  706. * @memberOf module:zrender/core/util
  707. * @param {boolean} condition
  708. * @param {string} message
  709. */
  710. function assert$1(condition, message) {
  711. if (!condition) {
  712. throw new Error(message);
  713. }
  714. }
  715. /**
  716. * @memberOf module:zrender/core/util
  717. * @param {string} str string to be trimed
  718. * @return {string} trimed string
  719. */
  720. function trim(str) {
  721. if (str == null) {
  722. return null;
  723. }
  724. else if (typeof str.trim === 'function') {
  725. return str.trim();
  726. }
  727. else {
  728. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  729. }
  730. }
  731. var primitiveKey = '__ec_primitive__';
  732. /**
  733. * Set an object as primitive to be ignored traversing children in clone or merge
  734. */
  735. function setAsPrimitive(obj) {
  736. obj[primitiveKey] = true;
  737. }
  738. function isPrimitive(obj) {
  739. return obj[primitiveKey];
  740. }
  741. /**
  742. * @constructor
  743. * @param {Object} obj Only apply `ownProperty`.
  744. */
  745. function HashMap(obj) {
  746. var isArr = isArray(obj);
  747. var thisMap = this;
  748. (obj instanceof HashMap)
  749. ? obj.each(visit)
  750. : (obj && each$1(obj, visit));
  751. function visit(value, key) {
  752. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  753. }
  754. }
  755. // Add prefix to avoid conflict with Object.prototype.
  756. HashMap.prototype = {
  757. constructor: HashMap,
  758. // Do not provide `has` method to avoid defining what is `has`.
  759. // (We usually treat `null` and `undefined` as the same, different
  760. // from ES6 Map).
  761. get: function (key) {
  762. return this.hasOwnProperty(key) ? this[key] : null;
  763. },
  764. set: function (key, value) {
  765. // Comparing with invocation chaining, `return value` is more commonly
  766. // used in this case: `var someVal = map.set('a', genVal());`
  767. return (this[key] = value);
  768. },
  769. // Although util.each can be performed on this hashMap directly, user
  770. // should not use the exposed keys, who are prefixed.
  771. each: function (cb, context) {
  772. context !== void 0 && (cb = bind(cb, context));
  773. for (var key in this) {
  774. this.hasOwnProperty(key) && cb(this[key], key);
  775. }
  776. },
  777. // Do not use this method if performance sensitive.
  778. removeKey: function (key) {
  779. delete this[key];
  780. }
  781. };
  782. function createHashMap(obj) {
  783. return new HashMap(obj);
  784. }
  785. function concatArray(a, b) {
  786. var newArray = new a.constructor(a.length + b.length);
  787. for (var i = 0; i < a.length; i++) {
  788. newArray[i] = a[i];
  789. }
  790. var offset = a.length;
  791. for (i = 0; i < b.length; i++) {
  792. newArray[i + offset] = b[i];
  793. }
  794. return newArray;
  795. }
  796. function noop() {}
  797. var zrUtil = (Object.freeze || Object)({
  798. $override: $override,
  799. clone: clone,
  800. merge: merge,
  801. mergeAll: mergeAll,
  802. extend: extend,
  803. defaults: defaults,
  804. createCanvas: createCanvas,
  805. getContext: getContext,
  806. indexOf: indexOf,
  807. inherits: inherits,
  808. mixin: mixin,
  809. isArrayLike: isArrayLike,
  810. each: each$1,
  811. map: map,
  812. reduce: reduce,
  813. filter: filter,
  814. find: find,
  815. bind: bind,
  816. curry: curry,
  817. isArray: isArray,
  818. isFunction: isFunction$1,
  819. isString: isString,
  820. isObject: isObject$1,
  821. isBuiltInObject: isBuiltInObject,
  822. isTypedArray: isTypedArray,
  823. isDom: isDom,
  824. eqNaN: eqNaN,
  825. retrieve: retrieve,
  826. retrieve2: retrieve2,
  827. retrieve3: retrieve3,
  828. slice: slice,
  829. normalizeCssArray: normalizeCssArray,
  830. assert: assert$1,
  831. trim: trim,
  832. setAsPrimitive: setAsPrimitive,
  833. isPrimitive: isPrimitive,
  834. createHashMap: createHashMap,
  835. concatArray: concatArray,
  836. noop: noop
  837. });
  838. var ArrayCtor = typeof Float32Array === 'undefined'
  839. ? Array
  840. : Float32Array;
  841. /**
  842. * 创建一个向量
  843. * @param {number} [x=0]
  844. * @param {number} [y=0]
  845. * @return {Vector2}
  846. */
  847. function create(x, y) {
  848. var out = new ArrayCtor(2);
  849. if (x == null) {
  850. x = 0;
  851. }
  852. if (y == null) {
  853. y = 0;
  854. }
  855. out[0] = x;
  856. out[1] = y;
  857. return out;
  858. }
  859. /**
  860. * 复制向量数据
  861. * @param {Vector2} out
  862. * @param {Vector2} v
  863. * @return {Vector2}
  864. */
  865. function copy(out, v) {
  866. out[0] = v[0];
  867. out[1] = v[1];
  868. return out;
  869. }
  870. /**
  871. * 克隆一个向量
  872. * @param {Vector2} v
  873. * @return {Vector2}
  874. */
  875. function clone$1(v) {
  876. var out = new ArrayCtor(2);
  877. out[0] = v[0];
  878. out[1] = v[1];
  879. return out;
  880. }
  881. /**
  882. * 设置向量的两个项
  883. * @param {Vector2} out
  884. * @param {number} a
  885. * @param {number} b
  886. * @return {Vector2} 结果
  887. */
  888. function set(out, a, b) {
  889. out[0] = a;
  890. out[1] = b;
  891. return out;
  892. }
  893. /**
  894. * 向量相加
  895. * @param {Vector2} out
  896. * @param {Vector2} v1
  897. * @param {Vector2} v2
  898. */
  899. function add(out, v1, v2) {
  900. out[0] = v1[0] + v2[0];
  901. out[1] = v1[1] + v2[1];
  902. return out;
  903. }
  904. /**
  905. * 向量缩放后相加
  906. * @param {Vector2} out
  907. * @param {Vector2} v1
  908. * @param {Vector2} v2
  909. * @param {number} a
  910. */
  911. function scaleAndAdd(out, v1, v2, a) {
  912. out[0] = v1[0] + v2[0] * a;
  913. out[1] = v1[1] + v2[1] * a;
  914. return out;
  915. }
  916. /**
  917. * 向量相减
  918. * @param {Vector2} out
  919. * @param {Vector2} v1
  920. * @param {Vector2} v2
  921. */
  922. function sub(out, v1, v2) {
  923. out[0] = v1[0] - v2[0];
  924. out[1] = v1[1] - v2[1];
  925. return out;
  926. }
  927. /**
  928. * 向量长度
  929. * @param {Vector2} v
  930. * @return {number}
  931. */
  932. function len(v) {
  933. return Math.sqrt(lenSquare(v));
  934. }
  935. var length = len; // jshint ignore:line
  936. /**
  937. * 向量长度平方
  938. * @param {Vector2} v
  939. * @return {number}
  940. */
  941. function lenSquare(v) {
  942. return v[0] * v[0] + v[1] * v[1];
  943. }
  944. var lengthSquare = lenSquare;
  945. /**
  946. * 向量乘法
  947. * @param {Vector2} out
  948. * @param {Vector2} v1
  949. * @param {Vector2} v2
  950. */
  951. function mul(out, v1, v2) {
  952. out[0] = v1[0] * v2[0];
  953. out[1] = v1[1] * v2[1];
  954. return out;
  955. }
  956. /**
  957. * 向量除法
  958. * @param {Vector2} out
  959. * @param {Vector2} v1
  960. * @param {Vector2} v2
  961. */
  962. function div(out, v1, v2) {
  963. out[0] = v1[0] / v2[0];
  964. out[1] = v1[1] / v2[1];
  965. return out;
  966. }
  967. /**
  968. * 向量点乘
  969. * @param {Vector2} v1
  970. * @param {Vector2} v2
  971. * @return {number}
  972. */
  973. function dot(v1, v2) {
  974. return v1[0] * v2[0] + v1[1] * v2[1];
  975. }
  976. /**
  977. * 向量缩放
  978. * @param {Vector2} out
  979. * @param {Vector2} v
  980. * @param {number} s
  981. */
  982. function scale(out, v, s) {
  983. out[0] = v[0] * s;
  984. out[1] = v[1] * s;
  985. return out;
  986. }
  987. /**
  988. * 向量归一化
  989. * @param {Vector2} out
  990. * @param {Vector2} v
  991. */
  992. function normalize(out, v) {
  993. var d = len(v);
  994. if (d === 0) {
  995. out[0] = 0;
  996. out[1] = 0;
  997. }
  998. else {
  999. out[0] = v[0] / d;
  1000. out[1] = v[1] / d;
  1001. }
  1002. return out;
  1003. }
  1004. /**
  1005. * 计算向量间距离
  1006. * @param {Vector2} v1
  1007. * @param {Vector2} v2
  1008. * @return {number}
  1009. */
  1010. function distance(v1, v2) {
  1011. return Math.sqrt(
  1012. (v1[0] - v2[0]) * (v1[0] - v2[0])
  1013. + (v1[1] - v2[1]) * (v1[1] - v2[1])
  1014. );
  1015. }
  1016. var dist = distance;
  1017. /**
  1018. * 向量距离平方
  1019. * @param {Vector2} v1
  1020. * @param {Vector2} v2
  1021. * @return {number}
  1022. */
  1023. function distanceSquare(v1, v2) {
  1024. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  1025. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  1026. }
  1027. var distSquare = distanceSquare;
  1028. /**
  1029. * 求负向量
  1030. * @param {Vector2} out
  1031. * @param {Vector2} v
  1032. */
  1033. function negate(out, v) {
  1034. out[0] = -v[0];
  1035. out[1] = -v[1];
  1036. return out;
  1037. }
  1038. /**
  1039. * 插值两个点
  1040. * @param {Vector2} out
  1041. * @param {Vector2} v1
  1042. * @param {Vector2} v2
  1043. * @param {number} t
  1044. */
  1045. function lerp(out, v1, v2, t) {
  1046. out[0] = v1[0] + t * (v2[0] - v1[0]);
  1047. out[1] = v1[1] + t * (v2[1] - v1[1]);
  1048. return out;
  1049. }
  1050. /**
  1051. * 矩阵左乘向量
  1052. * @param {Vector2} out
  1053. * @param {Vector2} v
  1054. * @param {Vector2} m
  1055. */
  1056. function applyTransform(out, v, m) {
  1057. var x = v[0];
  1058. var y = v[1];
  1059. out[0] = m[0] * x + m[2] * y + m[4];
  1060. out[1] = m[1] * x + m[3] * y + m[5];
  1061. return out;
  1062. }
  1063. /**
  1064. * 求两个向量最小值
  1065. * @param {Vector2} out
  1066. * @param {Vector2} v1
  1067. * @param {Vector2} v2
  1068. */
  1069. function min(out, v1, v2) {
  1070. out[0] = Math.min(v1[0], v2[0]);
  1071. out[1] = Math.min(v1[1], v2[1]);
  1072. return out;
  1073. }
  1074. /**
  1075. * 求两个向量最大值
  1076. * @param {Vector2} out
  1077. * @param {Vector2} v1
  1078. * @param {Vector2} v2
  1079. */
  1080. function max(out, v1, v2) {
  1081. out[0] = Math.max(v1[0], v2[0]);
  1082. out[1] = Math.max(v1[1], v2[1]);
  1083. return out;
  1084. }
  1085. var vector = (Object.freeze || Object)({
  1086. create: create,
  1087. copy: copy,
  1088. clone: clone$1,
  1089. set: set,
  1090. add: add,
  1091. scaleAndAdd: scaleAndAdd,
  1092. sub: sub,
  1093. len: len,
  1094. length: length,
  1095. lenSquare: lenSquare,
  1096. lengthSquare: lengthSquare,
  1097. mul: mul,
  1098. div: div,
  1099. dot: dot,
  1100. scale: scale,
  1101. normalize: normalize,
  1102. distance: distance,
  1103. dist: dist,
  1104. distanceSquare: distanceSquare,
  1105. distSquare: distSquare,
  1106. negate: negate,
  1107. lerp: lerp,
  1108. applyTransform: applyTransform,
  1109. min: min,
  1110. max: max
  1111. });
  1112. // TODO Draggable for group
  1113. // FIXME Draggable on element which has parent rotation or scale
  1114. function Draggable() {
  1115. this.on('mousedown', this._dragStart, this);
  1116. this.on('mousemove', this._drag, this);
  1117. this.on('mouseup', this._dragEnd, this);
  1118. this.on('globalout', this._dragEnd, this);
  1119. // this._dropTarget = null;
  1120. // this._draggingTarget = null;
  1121. // this._x = 0;
  1122. // this._y = 0;
  1123. }
  1124. Draggable.prototype = {
  1125. constructor: Draggable,
  1126. _dragStart: function (e) {
  1127. var draggingTarget = e.target;
  1128. if (draggingTarget && draggingTarget.draggable) {
  1129. this._draggingTarget = draggingTarget;
  1130. draggingTarget.dragging = true;
  1131. this._x = e.offsetX;
  1132. this._y = e.offsetY;
  1133. this.dispatchToElement(param(draggingTarget, e), 'dragstart', e.event);
  1134. }
  1135. },
  1136. _drag: function (e) {
  1137. var draggingTarget = this._draggingTarget;
  1138. if (draggingTarget) {
  1139. var x = e.offsetX;
  1140. var y = e.offsetY;
  1141. var dx = x - this._x;
  1142. var dy = y - this._y;
  1143. this._x = x;
  1144. this._y = y;
  1145. draggingTarget.drift(dx, dy, e);
  1146. this.dispatchToElement(param(draggingTarget, e), 'drag', e.event);
  1147. var dropTarget = this.findHover(x, y, draggingTarget).target;
  1148. var lastDropTarget = this._dropTarget;
  1149. this._dropTarget = dropTarget;
  1150. if (draggingTarget !== dropTarget) {
  1151. if (lastDropTarget && dropTarget !== lastDropTarget) {
  1152. this.dispatchToElement(param(lastDropTarget, e), 'dragleave', e.event);
  1153. }
  1154. if (dropTarget && dropTarget !== lastDropTarget) {
  1155. this.dispatchToElement(param(dropTarget, e), 'dragenter', e.event);
  1156. }
  1157. }
  1158. }
  1159. },
  1160. _dragEnd: function (e) {
  1161. var draggingTarget = this._draggingTarget;
  1162. if (draggingTarget) {
  1163. draggingTarget.dragging = false;
  1164. }
  1165. this.dispatchToElement(param(draggingTarget, e), 'dragend', e.event);
  1166. if (this._dropTarget) {
  1167. this.dispatchToElement(param(this._dropTarget, e), 'drop', e.event);
  1168. }
  1169. this._draggingTarget = null;
  1170. this._dropTarget = null;
  1171. }
  1172. };
  1173. function param(target, e) {
  1174. return {target: target, topTarget: e && e.topTarget};
  1175. }
  1176. /**
  1177. * 事件扩展
  1178. * @module zrender/mixin/Eventful
  1179. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1180. * pissang (https://www.github.com/pissang)
  1181. */
  1182. var arrySlice = Array.prototype.slice;
  1183. /**
  1184. * 事件分发器
  1185. * @alias module:zrender/mixin/Eventful
  1186. * @constructor
  1187. */
  1188. var Eventful = function () {
  1189. this._$handlers = {};
  1190. };
  1191. Eventful.prototype = {
  1192. constructor: Eventful,
  1193. /**
  1194. * 单次触发绑定,trigger后销毁
  1195. *
  1196. * @param {string} event 事件名
  1197. * @param {Function} handler 响应函数
  1198. * @param {Object} context
  1199. */
  1200. one: function (event, handler, context) {
  1201. var _h = this._$handlers;
  1202. if (!handler || !event) {
  1203. return this;
  1204. }
  1205. if (!_h[event]) {
  1206. _h[event] = [];
  1207. }
  1208. for (var i = 0; i < _h[event].length; i++) {
  1209. if (_h[event][i].h === handler) {
  1210. return this;
  1211. }
  1212. }
  1213. _h[event].push({
  1214. h: handler,
  1215. one: true,
  1216. ctx: context || this
  1217. });
  1218. return this;
  1219. },
  1220. /**
  1221. * 绑定事件
  1222. * @param {string} event 事件名
  1223. * @param {Function} handler 事件处理函数
  1224. * @param {Object} [context]
  1225. */
  1226. on: function (event, handler, context) {
  1227. var _h = this._$handlers;
  1228. if (!handler || !event) {
  1229. return this;
  1230. }
  1231. if (!_h[event]) {
  1232. _h[event] = [];
  1233. }
  1234. for (var i = 0; i < _h[event].length; i++) {
  1235. if (_h[event][i].h === handler) {
  1236. return this;
  1237. }
  1238. }
  1239. _h[event].push({
  1240. h: handler,
  1241. one: false,
  1242. ctx: context || this
  1243. });
  1244. return this;
  1245. },
  1246. /**
  1247. * 是否绑定了事件
  1248. * @param {string} event
  1249. * @return {boolean}
  1250. */
  1251. isSilent: function (event) {
  1252. var _h = this._$handlers;
  1253. return _h[event] && _h[event].length;
  1254. },
  1255. /**
  1256. * 解绑事件
  1257. * @param {string} event 事件名
  1258. * @param {Function} [handler] 事件处理函数
  1259. */
  1260. off: function (event, handler) {
  1261. var _h = this._$handlers;
  1262. if (!event) {
  1263. this._$handlers = {};
  1264. return this;
  1265. }
  1266. if (handler) {
  1267. if (_h[event]) {
  1268. var newList = [];
  1269. for (var i = 0, l = _h[event].length; i < l; i++) {
  1270. if (_h[event][i]['h'] != handler) {
  1271. newList.push(_h[event][i]);
  1272. }
  1273. }
  1274. _h[event] = newList;
  1275. }
  1276. if (_h[event] && _h[event].length === 0) {
  1277. delete _h[event];
  1278. }
  1279. }
  1280. else {
  1281. delete _h[event];
  1282. }
  1283. return this;
  1284. },
  1285. /**
  1286. * 事件分发
  1287. *
  1288. * @param {string} type 事件类型
  1289. */
  1290. trigger: function (type) {
  1291. if (this._$handlers[type]) {
  1292. var args = arguments;
  1293. var argLen = args.length;
  1294. if (argLen > 3) {
  1295. args = arrySlice.call(args, 1);
  1296. }
  1297. var _h = this._$handlers[type];
  1298. var len = _h.length;
  1299. for (var i = 0; i < len;) {
  1300. // Optimize advise from backbone
  1301. switch (argLen) {
  1302. case 1:
  1303. _h[i]['h'].call(_h[i]['ctx']);
  1304. break;
  1305. case 2:
  1306. _h[i]['h'].call(_h[i]['ctx'], args[1]);
  1307. break;
  1308. case 3:
  1309. _h[i]['h'].call(_h[i]['ctx'], args[1], args[2]);
  1310. break;
  1311. default:
  1312. // have more than 2 given arguments
  1313. _h[i]['h'].apply(_h[i]['ctx'], args);
  1314. break;
  1315. }
  1316. if (_h[i]['one']) {
  1317. _h.splice(i, 1);
  1318. len--;
  1319. }
  1320. else {
  1321. i++;
  1322. }
  1323. }
  1324. }
  1325. return this;
  1326. },
  1327. /**
  1328. * 带有context的事件分发, 最后一个参数是事件回调的context
  1329. * @param {string} type 事件类型
  1330. */
  1331. triggerWithContext: function (type) {
  1332. if (this._$handlers[type]) {
  1333. var args = arguments;
  1334. var argLen = args.length;
  1335. if (argLen > 4) {
  1336. args = arrySlice.call(args, 1, args.length - 1);
  1337. }
  1338. var ctx = args[args.length - 1];
  1339. var _h = this._$handlers[type];
  1340. var len = _h.length;
  1341. for (var i = 0; i < len;) {
  1342. // Optimize advise from backbone
  1343. switch (argLen) {
  1344. case 1:
  1345. _h[i]['h'].call(ctx);
  1346. break;
  1347. case 2:
  1348. _h[i]['h'].call(ctx, args[1]);
  1349. break;
  1350. case 3:
  1351. _h[i]['h'].call(ctx, args[1], args[2]);
  1352. break;
  1353. default:
  1354. // have more than 2 given arguments
  1355. _h[i]['h'].apply(ctx, args);
  1356. break;
  1357. }
  1358. if (_h[i]['one']) {
  1359. _h.splice(i, 1);
  1360. len--;
  1361. }
  1362. else {
  1363. i++;
  1364. }
  1365. }
  1366. }
  1367. return this;
  1368. }
  1369. };
  1370. var SILENT = 'silent';
  1371. function makeEventPacket(eveType, targetInfo, event) {
  1372. return {
  1373. type: eveType,
  1374. event: event,
  1375. // target can only be an element that is not silent.
  1376. target: targetInfo.target,
  1377. // topTarget can be a silent element.
  1378. topTarget: targetInfo.topTarget,
  1379. cancelBubble: false,
  1380. offsetX: event.zrX,
  1381. offsetY: event.zrY,
  1382. gestureEvent: event.gestureEvent,
  1383. pinchX: event.pinchX,
  1384. pinchY: event.pinchY,
  1385. pinchScale: event.pinchScale,
  1386. wheelDelta: event.zrDelta,
  1387. zrByTouch: event.zrByTouch,
  1388. which: event.which
  1389. };
  1390. }
  1391. function EmptyProxy () {}
  1392. EmptyProxy.prototype.dispose = function () {};
  1393. var handlerNames = [
  1394. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1395. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1396. ];
  1397. /**
  1398. * @alias module:zrender/Handler
  1399. * @constructor
  1400. * @extends module:zrender/mixin/Eventful
  1401. * @param {module:zrender/Storage} storage Storage instance.
  1402. * @param {module:zrender/Painter} painter Painter instance.
  1403. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  1404. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  1405. */
  1406. var Handler = function(storage, painter, proxy, painterRoot) {
  1407. Eventful.call(this);
  1408. this.storage = storage;
  1409. this.painter = painter;
  1410. this.painterRoot = painterRoot;
  1411. proxy = proxy || new EmptyProxy();
  1412. /**
  1413. * Proxy of event. can be Dom, WebGLSurface, etc.
  1414. */
  1415. this.proxy = null;
  1416. /**
  1417. * {target, topTarget, x, y}
  1418. * @private
  1419. * @type {Object}
  1420. */
  1421. this._hovered = {};
  1422. /**
  1423. * @private
  1424. * @type {Date}
  1425. */
  1426. this._lastTouchMoment;
  1427. /**
  1428. * @private
  1429. * @type {number}
  1430. */
  1431. this._lastX;
  1432. /**
  1433. * @private
  1434. * @type {number}
  1435. */
  1436. this._lastY;
  1437. Draggable.call(this);
  1438. this.setHandlerProxy(proxy);
  1439. };
  1440. Handler.prototype = {
  1441. constructor: Handler,
  1442. setHandlerProxy: function (proxy) {
  1443. if (this.proxy) {
  1444. this.proxy.dispose();
  1445. }
  1446. if (proxy) {
  1447. each$1(handlerNames, function (name) {
  1448. proxy.on && proxy.on(name, this[name], this);
  1449. }, this);
  1450. // Attach handler
  1451. proxy.handler = this;
  1452. }
  1453. this.proxy = proxy;
  1454. },
  1455. mousemove: function (event) {
  1456. var x = event.zrX;
  1457. var y = event.zrY;
  1458. var lastHovered = this._hovered;
  1459. var lastHoveredTarget = lastHovered.target;
  1460. // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  1461. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  1462. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  1463. // See #6198.
  1464. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  1465. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  1466. lastHoveredTarget = lastHovered.target;
  1467. }
  1468. var hovered = this._hovered = this.findHover(x, y);
  1469. var hoveredTarget = hovered.target;
  1470. var proxy = this.proxy;
  1471. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  1472. // Mouse out on previous hovered element
  1473. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1474. this.dispatchToElement(lastHovered, 'mouseout', event);
  1475. }
  1476. // Mouse moving on one element
  1477. this.dispatchToElement(hovered, 'mousemove', event);
  1478. // Mouse over on a new element
  1479. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1480. this.dispatchToElement(hovered, 'mouseover', event);
  1481. }
  1482. },
  1483. mouseout: function (event) {
  1484. this.dispatchToElement(this._hovered, 'mouseout', event);
  1485. // There might be some doms created by upper layer application
  1486. // at the same level of painter.getViewportRoot() (e.g., tooltip
  1487. // dom created by echarts), where 'globalout' event should not
  1488. // be triggered when mouse enters these doms. (But 'mouseout'
  1489. // should be triggered at the original hovered element as usual).
  1490. var element = event.toElement || event.relatedTarget;
  1491. var innerDom;
  1492. do {
  1493. element = element && element.parentNode;
  1494. }
  1495. while (element && element.nodeType != 9 && !(
  1496. innerDom = element === this.painterRoot
  1497. ));
  1498. !innerDom && this.trigger('globalout', {event: event});
  1499. },
  1500. /**
  1501. * Resize
  1502. */
  1503. resize: function (event) {
  1504. this._hovered = {};
  1505. },
  1506. /**
  1507. * Dispatch event
  1508. * @param {string} eventName
  1509. * @param {event=} eventArgs
  1510. */
  1511. dispatch: function (eventName, eventArgs) {
  1512. var handler = this[eventName];
  1513. handler && handler.call(this, eventArgs);
  1514. },
  1515. /**
  1516. * Dispose
  1517. */
  1518. dispose: function () {
  1519. this.proxy.dispose();
  1520. this.storage =
  1521. this.proxy =
  1522. this.painter = null;
  1523. },
  1524. /**
  1525. * 设置默认的cursor style
  1526. * @param {string} [cursorStyle='default'] 例如 crosshair
  1527. */
  1528. setCursorStyle: function (cursorStyle) {
  1529. var proxy = this.proxy;
  1530. proxy.setCursor && proxy.setCursor(cursorStyle);
  1531. },
  1532. /**
  1533. * 事件分发代理
  1534. *
  1535. * @private
  1536. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  1537. * @param {string} eventName 事件名称
  1538. * @param {Object} event 事件对象
  1539. */
  1540. dispatchToElement: function (targetInfo, eventName, event) {
  1541. targetInfo = targetInfo || {};
  1542. var el = targetInfo.target;
  1543. if (el && el.silent) {
  1544. return;
  1545. }
  1546. var eventHandler = 'on' + eventName;
  1547. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  1548. while (el) {
  1549. el[eventHandler]
  1550. && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  1551. el.trigger(eventName, eventPacket);
  1552. el = el.parent;
  1553. if (eventPacket.cancelBubble) {
  1554. break;
  1555. }
  1556. }
  1557. if (!eventPacket.cancelBubble) {
  1558. // 冒泡到顶级 zrender 对象
  1559. this.trigger(eventName, eventPacket);
  1560. // 分发事件到用户自定义层
  1561. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  1562. this.painter && this.painter.eachOtherLayer(function (layer) {
  1563. if (typeof(layer[eventHandler]) == 'function') {
  1564. layer[eventHandler].call(layer, eventPacket);
  1565. }
  1566. if (layer.trigger) {
  1567. layer.trigger(eventName, eventPacket);
  1568. }
  1569. });
  1570. }
  1571. },
  1572. /**
  1573. * @private
  1574. * @param {number} x
  1575. * @param {number} y
  1576. * @param {module:zrender/graphic/Displayable} exclude
  1577. * @return {model:zrender/Element}
  1578. * @method
  1579. */
  1580. findHover: function(x, y, exclude) {
  1581. var list = this.storage.getDisplayList();
  1582. var out = {x: x, y: y};
  1583. for (var i = list.length - 1; i >= 0 ; i--) {
  1584. var hoverCheckResult;
  1585. if (list[i] !== exclude
  1586. // getDisplayList may include ignored item in VML mode
  1587. && !list[i].ignore
  1588. && (hoverCheckResult = isHover(list[i], x, y))
  1589. ) {
  1590. !out.topTarget && (out.topTarget = list[i]);
  1591. if (hoverCheckResult !== SILENT) {
  1592. out.target = list[i];
  1593. break;
  1594. }
  1595. }
  1596. }
  1597. return out;
  1598. }
  1599. };
  1600. // Common handlers
  1601. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  1602. Handler.prototype[name] = function (event) {
  1603. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  1604. var hovered = this.findHover(event.zrX, event.zrY);
  1605. var hoveredTarget = hovered.target;
  1606. if (name === 'mousedown') {
  1607. this._downEl = hoveredTarget;
  1608. this._downPoint = [event.zrX, event.zrY];
  1609. // In case click triggered before mouseup
  1610. this._upEl = hoveredTarget;
  1611. }
  1612. else if (name === 'mouseup') {
  1613. this._upEl = hoveredTarget;
  1614. }
  1615. else if (name === 'click') {
  1616. if (this._downEl !== this._upEl
  1617. // Original click event is triggered on the whole canvas element,
  1618. // including the case that `mousedown` - `mousemove` - `mouseup`,
  1619. // which should be filtered, otherwise it will bring trouble to
  1620. // pan and zoom.
  1621. || !this._downPoint
  1622. // Arbitrary value
  1623. || dist(this._downPoint, [event.zrX, event.zrY]) > 4
  1624. ) {
  1625. return;
  1626. }
  1627. this._downPoint = null;
  1628. }
  1629. this.dispatchToElement(hovered, name, event);
  1630. };
  1631. });
  1632. function isHover(displayable, x, y) {
  1633. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  1634. var el = displayable;
  1635. var isSilent;
  1636. while (el) {
  1637. // If clipped by ancestor.
  1638. // FIXME: If clipPath has neither stroke nor fill,
  1639. // el.clipPath.contain(x, y) will always return false.
  1640. if (el.clipPath && !el.clipPath.contain(x, y)) {
  1641. return false;
  1642. }
  1643. if (el.silent) {
  1644. isSilent = true;
  1645. }
  1646. el = el.parent;
  1647. }
  1648. return isSilent ? SILENT : true;
  1649. }
  1650. return false;
  1651. }
  1652. mixin(Handler, Eventful);
  1653. mixin(Handler, Draggable);
  1654. /**
  1655. * 3x2矩阵操作类
  1656. * @exports zrender/tool/matrix
  1657. */
  1658. var ArrayCtor$1 = typeof Float32Array === 'undefined'
  1659. ? Array
  1660. : Float32Array;
  1661. /**
  1662. * Create a identity matrix.
  1663. * @return {Float32Array|Array.<number>}
  1664. */
  1665. function create$1() {
  1666. var out = new ArrayCtor$1(6);
  1667. identity(out);
  1668. return out;
  1669. }
  1670. /**
  1671. * 设置矩阵为单位矩阵
  1672. * @param {Float32Array|Array.<number>} out
  1673. */
  1674. function identity(out) {
  1675. out[0] = 1;
  1676. out[1] = 0;
  1677. out[2] = 0;
  1678. out[3] = 1;
  1679. out[4] = 0;
  1680. out[5] = 0;
  1681. return out;
  1682. }
  1683. /**
  1684. * 复制矩阵
  1685. * @param {Float32Array|Array.<number>} out
  1686. * @param {Float32Array|Array.<number>} m
  1687. */
  1688. function copy$1(out, m) {
  1689. out[0] = m[0];
  1690. out[1] = m[1];
  1691. out[2] = m[2];
  1692. out[3] = m[3];
  1693. out[4] = m[4];
  1694. out[5] = m[5];
  1695. return out;
  1696. }
  1697. /**
  1698. * 矩阵相乘
  1699. * @param {Float32Array|Array.<number>} out
  1700. * @param {Float32Array|Array.<number>} m1
  1701. * @param {Float32Array|Array.<number>} m2
  1702. */
  1703. function mul$1(out, m1, m2) {
  1704. // Consider matrix.mul(m, m2, m);
  1705. // where out is the same as m2.
  1706. // So use temp variable to escape error.
  1707. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  1708. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  1709. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  1710. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  1711. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  1712. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  1713. out[0] = out0;
  1714. out[1] = out1;
  1715. out[2] = out2;
  1716. out[3] = out3;
  1717. out[4] = out4;
  1718. out[5] = out5;
  1719. return out;
  1720. }
  1721. /**
  1722. * 平移变换
  1723. * @param {Float32Array|Array.<number>} out
  1724. * @param {Float32Array|Array.<number>} a
  1725. * @param {Float32Array|Array.<number>} v
  1726. */
  1727. function translate(out, a, v) {
  1728. out[0] = a[0];
  1729. out[1] = a[1];
  1730. out[2] = a[2];
  1731. out[3] = a[3];
  1732. out[4] = a[4] + v[0];
  1733. out[5] = a[5] + v[1];
  1734. return out;
  1735. }
  1736. /**
  1737. * 旋转变换
  1738. * @param {Float32Array|Array.<number>} out
  1739. * @param {Float32Array|Array.<number>} a
  1740. * @param {number} rad
  1741. */
  1742. function rotate(out, a, rad) {
  1743. var aa = a[0];
  1744. var ac = a[2];
  1745. var atx = a[4];
  1746. var ab = a[1];
  1747. var ad = a[3];
  1748. var aty = a[5];
  1749. var st = Math.sin(rad);
  1750. var ct = Math.cos(rad);
  1751. out[0] = aa * ct + ab * st;
  1752. out[1] = -aa * st + ab * ct;
  1753. out[2] = ac * ct + ad * st;
  1754. out[3] = -ac * st + ct * ad;
  1755. out[4] = ct * atx + st * aty;
  1756. out[5] = ct * aty - st * atx;
  1757. return out;
  1758. }
  1759. /**
  1760. * 缩放变换
  1761. * @param {Float32Array|Array.<number>} out
  1762. * @param {Float32Array|Array.<number>} a
  1763. * @param {Float32Array|Array.<number>} v
  1764. */
  1765. function scale$1(out, a, v) {
  1766. var vx = v[0];
  1767. var vy = v[1];
  1768. out[0] = a[0] * vx;
  1769. out[1] = a[1] * vy;
  1770. out[2] = a[2] * vx;
  1771. out[3] = a[3] * vy;
  1772. out[4] = a[4] * vx;
  1773. out[5] = a[5] * vy;
  1774. return out;
  1775. }
  1776. /**
  1777. * 求逆矩阵
  1778. * @param {Float32Array|Array.<number>} out
  1779. * @param {Float32Array|Array.<number>} a
  1780. */
  1781. function invert(out, a) {
  1782. var aa = a[0];
  1783. var ac = a[2];
  1784. var atx = a[4];
  1785. var ab = a[1];
  1786. var ad = a[3];
  1787. var aty = a[5];
  1788. var det = aa * ad - ab * ac;
  1789. if (!det) {
  1790. return null;
  1791. }
  1792. det = 1.0 / det;
  1793. out[0] = ad * det;
  1794. out[1] = -ab * det;
  1795. out[2] = -ac * det;
  1796. out[3] = aa * det;
  1797. out[4] = (ac * aty - ad * atx) * det;
  1798. out[5] = (ab * atx - aa * aty) * det;
  1799. return out;
  1800. }
  1801. /**
  1802. * Clone a new matrix.
  1803. * @param {Float32Array|Array.<number>} a
  1804. */
  1805. function clone$2(a) {
  1806. var b = create$1();
  1807. copy$1(b, a);
  1808. return b;
  1809. }
  1810. var matrix = (Object.freeze || Object)({
  1811. create: create$1,
  1812. identity: identity,
  1813. copy: copy$1,
  1814. mul: mul$1,
  1815. translate: translate,
  1816. rotate: rotate,
  1817. scale: scale$1,
  1818. invert: invert,
  1819. clone: clone$2
  1820. });
  1821. /**
  1822. * 提供变换扩展
  1823. * @module zrender/mixin/Transformable
  1824. * @author pissang (https://www.github.com/pissang)
  1825. */
  1826. var mIdentity = identity;
  1827. var EPSILON = 5e-5;
  1828. function isNotAroundZero(val) {
  1829. return val > EPSILON || val < -EPSILON;
  1830. }
  1831. /**
  1832. * @alias module:zrender/mixin/Transformable
  1833. * @constructor
  1834. */
  1835. var Transformable = function (opts) {
  1836. opts = opts || {};
  1837. // If there are no given position, rotation, scale
  1838. if (!opts.position) {
  1839. /**
  1840. * 平移
  1841. * @type {Array.<number>}
  1842. * @default [0, 0]
  1843. */
  1844. this.position = [0, 0];
  1845. }
  1846. if (opts.rotation == null) {
  1847. /**
  1848. * 旋转
  1849. * @type {Array.<number>}
  1850. * @default 0
  1851. */
  1852. this.rotation = 0;
  1853. }
  1854. if (!opts.scale) {
  1855. /**
  1856. * 缩放
  1857. * @type {Array.<number>}
  1858. * @default [1, 1]
  1859. */
  1860. this.scale = [1, 1];
  1861. }
  1862. /**
  1863. * 旋转和缩放的原点
  1864. * @type {Array.<number>}
  1865. * @default null
  1866. */
  1867. this.origin = this.origin || null;
  1868. };
  1869. var transformableProto = Transformable.prototype;
  1870. transformableProto.transform = null;
  1871. /**
  1872. * 判断是否需要有坐标变换
  1873. * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵
  1874. */
  1875. transformableProto.needLocalTransform = function () {
  1876. return isNotAroundZero(this.rotation)
  1877. || isNotAroundZero(this.position[0])
  1878. || isNotAroundZero(this.position[1])
  1879. || isNotAroundZero(this.scale[0] - 1)
  1880. || isNotAroundZero(this.scale[1] - 1);
  1881. };
  1882. transformableProto.updateTransform = function () {
  1883. var parent = this.parent;
  1884. var parentHasTransform = parent && parent.transform;
  1885. var needLocalTransform = this.needLocalTransform();
  1886. var m = this.transform;
  1887. if (!(needLocalTransform || parentHasTransform)) {
  1888. m && mIdentity(m);
  1889. return;
  1890. }
  1891. m = m || create$1();
  1892. if (needLocalTransform) {
  1893. this.getLocalTransform(m);
  1894. }
  1895. else {
  1896. mIdentity(m);
  1897. }
  1898. // 应用父节点变换
  1899. if (parentHasTransform) {
  1900. if (needLocalTransform) {
  1901. mul$1(m, parent.transform, m);
  1902. }
  1903. else {
  1904. copy$1(m, parent.transform);
  1905. }
  1906. }
  1907. // 保存这个变换矩阵
  1908. this.transform = m;
  1909. this.invTransform = this.invTransform || create$1();
  1910. invert(this.invTransform, m);
  1911. };
  1912. transformableProto.getLocalTransform = function (m) {
  1913. return Transformable.getLocalTransform(this, m);
  1914. };
  1915. /**
  1916. * 将自己的transform应用到context上
  1917. * @param {CanvasRenderingContext2D} ctx
  1918. */
  1919. transformableProto.setTransform = function (ctx) {
  1920. var m = this.transform;
  1921. var dpr = ctx.dpr || 1;
  1922. if (m) {
  1923. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  1924. }
  1925. else {
  1926. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  1927. }
  1928. };
  1929. transformableProto.restoreTransform = function (ctx) {
  1930. var dpr = ctx.dpr || 1;
  1931. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  1932. };
  1933. var tmpTransform = [];
  1934. /**
  1935. * 分解`transform`矩阵到`position`, `rotation`, `scale`
  1936. */
  1937. transformableProto.decomposeTransform = function () {
  1938. if (!this.transform) {
  1939. return;
  1940. }
  1941. var parent = this.parent;
  1942. var m = this.transform;
  1943. if (parent && parent.transform) {
  1944. // Get local transform and decompose them to position, scale, rotation
  1945. mul$1(tmpTransform, parent.invTransform, m);
  1946. m = tmpTransform;
  1947. }
  1948. var sx = m[0] * m[0] + m[1] * m[1];
  1949. var sy = m[2] * m[2] + m[3] * m[3];
  1950. var position = this.position;
  1951. var scale$$1 = this.scale;
  1952. if (isNotAroundZero(sx - 1)) {
  1953. sx = Math.sqrt(sx);
  1954. }
  1955. if (isNotAroundZero(sy - 1)) {
  1956. sy = Math.sqrt(sy);
  1957. }
  1958. if (m[0] < 0) {
  1959. sx = -sx;
  1960. }
  1961. if (m[3] < 0) {
  1962. sy = -sy;
  1963. }
  1964. position[0] = m[4];
  1965. position[1] = m[5];
  1966. scale$$1[0] = sx;
  1967. scale$$1[1] = sy;
  1968. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  1969. };
  1970. /**
  1971. * Get global scale
  1972. * @return {Array.<number>}
  1973. */
  1974. transformableProto.getGlobalScale = function () {
  1975. var m = this.transform;
  1976. if (!m) {
  1977. return [1, 1];
  1978. }
  1979. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  1980. var sy = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  1981. if (m[0] < 0) {
  1982. sx = -sx;
  1983. }
  1984. if (m[3] < 0) {
  1985. sy = -sy;
  1986. }
  1987. return [sx, sy];
  1988. };
  1989. /**
  1990. * 变换坐标位置到 shape 的局部坐标空间
  1991. * @method
  1992. * @param {number} x
  1993. * @param {number} y
  1994. * @return {Array.<number>}
  1995. */
  1996. transformableProto.transformCoordToLocal = function (x, y) {
  1997. var v2 = [x, y];
  1998. var invTransform = this.invTransform;
  1999. if (invTransform) {
  2000. applyTransform(v2, v2, invTransform);
  2001. }
  2002. return v2;
  2003. };
  2004. /**
  2005. * 变换局部坐标位置到全局坐标空间
  2006. * @method
  2007. * @param {number} x
  2008. * @param {number} y
  2009. * @return {Array.<number>}
  2010. */
  2011. transformableProto.transformCoordToGlobal = function (x, y) {
  2012. var v2 = [x, y];
  2013. var transform = this.transform;
  2014. if (transform) {
  2015. applyTransform(v2, v2, transform);
  2016. }
  2017. return v2;
  2018. };
  2019. /**
  2020. * @static
  2021. * @param {Object} target
  2022. * @param {Array.<number>} target.origin
  2023. * @param {number} target.rotation
  2024. * @param {Array.<number>} target.position
  2025. * @param {Array.<number>} [m]
  2026. */
  2027. Transformable.getLocalTransform = function (target, m) {
  2028. m = m || [];
  2029. mIdentity(m);
  2030. var origin = target.origin;
  2031. var scale$$1 = target.scale || [1, 1];
  2032. var rotation = target.rotation || 0;
  2033. var position = target.position || [0, 0];
  2034. if (origin) {
  2035. // Translate to origin
  2036. m[4] -= origin[0];
  2037. m[5] -= origin[1];
  2038. }
  2039. scale$1(m, m, scale$$1);
  2040. if (rotation) {
  2041. rotate(m, m, rotation);
  2042. }
  2043. if (origin) {
  2044. // Translate back from origin
  2045. m[4] += origin[0];
  2046. m[5] += origin[1];
  2047. }
  2048. m[4] += position[0];
  2049. m[5] += position[1];
  2050. return m;
  2051. };
  2052. /**
  2053. * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js
  2054. * @see http://sole.github.io/tween.js/examples/03_graphs.html
  2055. * @exports zrender/animation/easing
  2056. */
  2057. var easing = {
  2058. /**
  2059. * @param {number} k
  2060. * @return {number}
  2061. */
  2062. linear: function (k) {
  2063. return k;
  2064. },
  2065. /**
  2066. * @param {number} k
  2067. * @return {number}
  2068. */
  2069. quadraticIn: function (k) {
  2070. return k * k;
  2071. },
  2072. /**
  2073. * @param {number} k
  2074. * @return {number}
  2075. */
  2076. quadraticOut: function (k) {
  2077. return k * (2 - k);
  2078. },
  2079. /**
  2080. * @param {number} k
  2081. * @return {number}
  2082. */
  2083. quadraticInOut: function (k) {
  2084. if ((k *= 2) < 1) {
  2085. return 0.5 * k * k;
  2086. }
  2087. return -0.5 * (--k * (k - 2) - 1);
  2088. },
  2089. // 三次方的缓动(t^3)
  2090. /**
  2091. * @param {number} k
  2092. * @return {number}
  2093. */
  2094. cubicIn: function (k) {
  2095. return k * k * k;
  2096. },
  2097. /**
  2098. * @param {number} k
  2099. * @return {number}
  2100. */
  2101. cubicOut: function (k) {
  2102. return --k * k * k + 1;
  2103. },
  2104. /**
  2105. * @param {number} k
  2106. * @return {number}
  2107. */
  2108. cubicInOut: function (k) {
  2109. if ((k *= 2) < 1) {
  2110. return 0.5 * k * k * k;
  2111. }
  2112. return 0.5 * ((k -= 2) * k * k + 2);
  2113. },
  2114. // 四次方的缓动(t^4)
  2115. /**
  2116. * @param {number} k
  2117. * @return {number}
  2118. */
  2119. quarticIn: function (k) {
  2120. return k * k * k * k;
  2121. },
  2122. /**
  2123. * @param {number} k
  2124. * @return {number}
  2125. */
  2126. quarticOut: function (k) {
  2127. return 1 - (--k * k * k * k);
  2128. },
  2129. /**
  2130. * @param {number} k
  2131. * @return {number}
  2132. */
  2133. quarticInOut: function (k) {
  2134. if ((k *= 2) < 1) {
  2135. return 0.5 * k * k * k * k;
  2136. }
  2137. return -0.5 * ((k -= 2) * k * k * k - 2);
  2138. },
  2139. // 五次方的缓动(t^5)
  2140. /**
  2141. * @param {number} k
  2142. * @return {number}
  2143. */
  2144. quinticIn: function (k) {
  2145. return k * k * k * k * k;
  2146. },
  2147. /**
  2148. * @param {number} k
  2149. * @return {number}
  2150. */
  2151. quinticOut: function (k) {
  2152. return --k * k * k * k * k + 1;
  2153. },
  2154. /**
  2155. * @param {number} k
  2156. * @return {number}
  2157. */
  2158. quinticInOut: function (k) {
  2159. if ((k *= 2) < 1) {
  2160. return 0.5 * k * k * k * k * k;
  2161. }
  2162. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2163. },
  2164. // 正弦曲线的缓动(sin(t))
  2165. /**
  2166. * @param {number} k
  2167. * @return {number}
  2168. */
  2169. sinusoidalIn: function (k) {
  2170. return 1 - Math.cos(k * Math.PI / 2);
  2171. },
  2172. /**
  2173. * @param {number} k
  2174. * @return {number}
  2175. */
  2176. sinusoidalOut: function (k) {
  2177. return Math.sin(k * Math.PI / 2);
  2178. },
  2179. /**
  2180. * @param {number} k
  2181. * @return {number}
  2182. */
  2183. sinusoidalInOut: function (k) {
  2184. return 0.5 * (1 - Math.cos(Math.PI * k));
  2185. },
  2186. // 指数曲线的缓动(2^t)
  2187. /**
  2188. * @param {number} k
  2189. * @return {number}
  2190. */
  2191. exponentialIn: function (k) {
  2192. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2193. },
  2194. /**
  2195. * @param {number} k
  2196. * @return {number}
  2197. */
  2198. exponentialOut: function (k) {
  2199. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2200. },
  2201. /**
  2202. * @param {number} k
  2203. * @return {number}
  2204. */
  2205. exponentialInOut: function (k) {
  2206. if (k === 0) {
  2207. return 0;
  2208. }
  2209. if (k === 1) {
  2210. return 1;
  2211. }
  2212. if ((k *= 2) < 1) {
  2213. return 0.5 * Math.pow(1024, k - 1);
  2214. }
  2215. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2216. },
  2217. // 圆形曲线的缓动(sqrt(1-t^2))
  2218. /**
  2219. * @param {number} k
  2220. * @return {number}
  2221. */
  2222. circularIn: function (k) {
  2223. return 1 - Math.sqrt(1 - k * k);
  2224. },
  2225. /**
  2226. * @param {number} k
  2227. * @return {number}
  2228. */
  2229. circularOut: function (k) {
  2230. return Math.sqrt(1 - (--k * k));
  2231. },
  2232. /**
  2233. * @param {number} k
  2234. * @return {number}
  2235. */
  2236. circularInOut: function (k) {
  2237. if ((k *= 2) < 1) {
  2238. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2239. }
  2240. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2241. },
  2242. // 创建类似于弹簧在停止前来回振荡的动画
  2243. /**
  2244. * @param {number} k
  2245. * @return {number}
  2246. */
  2247. elasticIn: function (k) {
  2248. var s;
  2249. var a = 0.1;
  2250. var p = 0.4;
  2251. if (k === 0) {
  2252. return 0;
  2253. }
  2254. if (k === 1) {
  2255. return 1;
  2256. }
  2257. if (!a || a < 1) {
  2258. a = 1; s = p / 4;
  2259. }
  2260. else {
  2261. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2262. }
  2263. return -(a * Math.pow(2, 10 * (k -= 1)) *
  2264. Math.sin((k - s) * (2 * Math.PI) / p));
  2265. },
  2266. /**
  2267. * @param {number} k
  2268. * @return {number}
  2269. */
  2270. elasticOut: function (k) {
  2271. var s;
  2272. var a = 0.1;
  2273. var p = 0.4;
  2274. if (k === 0) {
  2275. return 0;
  2276. }
  2277. if (k === 1) {
  2278. return 1;
  2279. }
  2280. if (!a || a < 1) {
  2281. a = 1; s = p / 4;
  2282. }
  2283. else {
  2284. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2285. }
  2286. return (a * Math.pow(2, -10 * k) *
  2287. Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  2288. },
  2289. /**
  2290. * @param {number} k
  2291. * @return {number}
  2292. */
  2293. elasticInOut: function (k) {
  2294. var s;
  2295. var a = 0.1;
  2296. var p = 0.4;
  2297. if (k === 0) {
  2298. return 0;
  2299. }
  2300. if (k === 1) {
  2301. return 1;
  2302. }
  2303. if (!a || a < 1) {
  2304. a = 1; s = p / 4;
  2305. }
  2306. else {
  2307. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2308. }
  2309. if ((k *= 2) < 1) {
  2310. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  2311. * Math.sin((k - s) * (2 * Math.PI) / p));
  2312. }
  2313. return a * Math.pow(2, -10 * (k -= 1))
  2314. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2315. },
  2316. // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动
  2317. /**
  2318. * @param {number} k
  2319. * @return {number}
  2320. */
  2321. backIn: function (k) {
  2322. var s = 1.70158;
  2323. return k * k * ((s + 1) * k - s);
  2324. },
  2325. /**
  2326. * @param {number} k
  2327. * @return {number}
  2328. */
  2329. backOut: function (k) {
  2330. var s = 1.70158;
  2331. return --k * k * ((s + 1) * k + s) + 1;
  2332. },
  2333. /**
  2334. * @param {number} k
  2335. * @return {number}
  2336. */
  2337. backInOut: function (k) {
  2338. var s = 1.70158 * 1.525;
  2339. if ((k *= 2) < 1) {
  2340. return 0.5 * (k * k * ((s + 1) * k - s));
  2341. }
  2342. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  2343. },
  2344. // 创建弹跳效果
  2345. /**
  2346. * @param {number} k
  2347. * @return {number}
  2348. */
  2349. bounceIn: function (k) {
  2350. return 1 - easing.bounceOut(1 - k);
  2351. },
  2352. /**
  2353. * @param {number} k
  2354. * @return {number}
  2355. */
  2356. bounceOut: function (k) {
  2357. if (k < (1 / 2.75)) {
  2358. return 7.5625 * k * k;
  2359. }
  2360. else if (k < (2 / 2.75)) {
  2361. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  2362. }
  2363. else if (k < (2.5 / 2.75)) {
  2364. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  2365. }
  2366. else {
  2367. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  2368. }
  2369. },
  2370. /**
  2371. * @param {number} k
  2372. * @return {number}
  2373. */
  2374. bounceInOut: function (k) {
  2375. if (k < 0.5) {
  2376. return easing.bounceIn(k * 2) * 0.5;
  2377. }
  2378. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  2379. }
  2380. };
  2381. /**
  2382. * 动画主控制器
  2383. * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件
  2384. * @config life(1000) 动画时长
  2385. * @config delay(0) 动画延迟时间
  2386. * @config loop(true)
  2387. * @config gap(0) 循环的间隔时间
  2388. * @config onframe
  2389. * @config easing(optional)
  2390. * @config ondestroy(optional)
  2391. * @config onrestart(optional)
  2392. *
  2393. * TODO pause
  2394. */
  2395. function Clip(options) {
  2396. this._target = options.target;
  2397. // 生命周期
  2398. this._life = options.life || 1000;
  2399. // 延时
  2400. this._delay = options.delay || 0;
  2401. // 开始时间
  2402. // this._startTime = new Date().getTime() + this._delay;// 单位毫秒
  2403. this._initialized = false;
  2404. // 是否循环
  2405. this.loop = options.loop == null ? false : options.loop;
  2406. this.gap = options.gap || 0;
  2407. this.easing = options.easing || 'Linear';
  2408. this.onframe = options.onframe;
  2409. this.ondestroy = options.ondestroy;
  2410. this.onrestart = options.onrestart;
  2411. this._pausedTime = 0;
  2412. this._paused = false;
  2413. }
  2414. Clip.prototype = {
  2415. constructor: Clip,
  2416. step: function (globalTime, deltaTime) {
  2417. // Set startTime on first step, or _startTime may has milleseconds different between clips
  2418. // PENDING
  2419. if (!this._initialized) {
  2420. this._startTime = globalTime + this._delay;
  2421. this._initialized = true;
  2422. }
  2423. if (this._paused) {
  2424. this._pausedTime += deltaTime;
  2425. return;
  2426. }
  2427. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  2428. // 还没开始
  2429. if (percent < 0) {
  2430. return;
  2431. }
  2432. percent = Math.min(percent, 1);
  2433. var easing$$1 = this.easing;
  2434. var easingFunc = typeof easing$$1 == 'string' ? easing[easing$$1] : easing$$1;
  2435. var schedule = typeof easingFunc === 'function'
  2436. ? easingFunc(percent)
  2437. : percent;
  2438. this.fire('frame', schedule);
  2439. // 结束
  2440. if (percent == 1) {
  2441. if (this.loop) {
  2442. this.restart (globalTime);
  2443. // 重新开始周期
  2444. // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件
  2445. return 'restart';
  2446. }
  2447. // 动画完成将这个控制器标识为待删除
  2448. // 在Animation.update中进行批量删除
  2449. this._needsRemove = true;
  2450. return 'destroy';
  2451. }
  2452. return null;
  2453. },
  2454. restart: function (globalTime) {
  2455. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  2456. this._startTime = globalTime - remainder + this.gap;
  2457. this._pausedTime = 0;
  2458. this._needsRemove = false;
  2459. },
  2460. fire: function (eventType, arg) {
  2461. eventType = 'on' + eventType;
  2462. if (this[eventType]) {
  2463. this[eventType](this._target, arg);
  2464. }
  2465. },
  2466. pause: function () {
  2467. this._paused = true;
  2468. },
  2469. resume: function () {
  2470. this._paused = false;
  2471. }
  2472. };
  2473. // Simple LRU cache use doubly linked list
  2474. // @module zrender/core/LRU
  2475. /**
  2476. * Simple double linked list. Compared with array, it has O(1) remove operation.
  2477. * @constructor
  2478. */
  2479. var LinkedList = function () {
  2480. /**
  2481. * @type {module:zrender/core/LRU~Entry}
  2482. */
  2483. this.head = null;
  2484. /**
  2485. * @type {module:zrender/core/LRU~Entry}
  2486. */
  2487. this.tail = null;
  2488. this._len = 0;
  2489. };
  2490. var linkedListProto = LinkedList.prototype;
  2491. /**
  2492. * Insert a new value at the tail
  2493. * @param {} val
  2494. * @return {module:zrender/core/LRU~Entry}
  2495. */
  2496. linkedListProto.insert = function (val) {
  2497. var entry = new Entry(val);
  2498. this.insertEntry(entry);
  2499. return entry;
  2500. };
  2501. /**
  2502. * Insert an entry at the tail
  2503. * @param {module:zrender/core/LRU~Entry} entry
  2504. */
  2505. linkedListProto.insertEntry = function (entry) {
  2506. if (!this.head) {
  2507. this.head = this.tail = entry;
  2508. }
  2509. else {
  2510. this.tail.next = entry;
  2511. entry.prev = this.tail;
  2512. entry.next = null;
  2513. this.tail = entry;
  2514. }
  2515. this._len++;
  2516. };
  2517. /**
  2518. * Remove entry.
  2519. * @param {module:zrender/core/LRU~Entry} entry
  2520. */
  2521. linkedListProto.remove = function (entry) {
  2522. var prev = entry.prev;
  2523. var next = entry.next;
  2524. if (prev) {
  2525. prev.next = next;
  2526. }
  2527. else {
  2528. // Is head
  2529. this.head = next;
  2530. }
  2531. if (next) {
  2532. next.prev = prev;
  2533. }
  2534. else {
  2535. // Is tail
  2536. this.tail = prev;
  2537. }
  2538. entry.next = entry.prev = null;
  2539. this._len--;
  2540. };
  2541. /**
  2542. * @return {number}
  2543. */
  2544. linkedListProto.len = function () {
  2545. return this._len;
  2546. };
  2547. /**
  2548. * Clear list
  2549. */
  2550. linkedListProto.clear = function () {
  2551. this.head = this.tail = null;
  2552. this._len = 0;
  2553. };
  2554. /**
  2555. * @constructor
  2556. * @param {} val
  2557. */
  2558. var Entry = function (val) {
  2559. /**
  2560. * @type {}
  2561. */
  2562. this.value = val;
  2563. /**
  2564. * @type {module:zrender/core/LRU~Entry}
  2565. */
  2566. this.next;
  2567. /**
  2568. * @type {module:zrender/core/LRU~Entry}
  2569. */
  2570. this.prev;
  2571. };
  2572. /**
  2573. * LRU Cache
  2574. * @constructor
  2575. * @alias module:zrender/core/LRU
  2576. */
  2577. var LRU = function (maxSize) {
  2578. this._list = new LinkedList();
  2579. this._map = {};
  2580. this._maxSize = maxSize || 10;
  2581. this._lastRemovedEntry = null;
  2582. };
  2583. var LRUProto = LRU.prototype;
  2584. /**
  2585. * @param {string} key
  2586. * @param {} value
  2587. * @return {} Removed value
  2588. */
  2589. LRUProto.put = function (key, value) {
  2590. var list = this._list;
  2591. var map = this._map;
  2592. var removed = null;
  2593. if (map[key] == null) {
  2594. var len = list.len();
  2595. // Reuse last removed entry
  2596. var entry = this._lastRemovedEntry;
  2597. if (len >= this._maxSize && len > 0) {
  2598. // Remove the least recently used
  2599. var leastUsedEntry = list.head;
  2600. list.remove(leastUsedEntry);
  2601. delete map[leastUsedEntry.key];
  2602. removed = leastUsedEntry.value;
  2603. this._lastRemovedEntry = leastUsedEntry;
  2604. }
  2605. if (entry) {
  2606. entry.value = value;
  2607. }
  2608. else {
  2609. entry = new Entry(value);
  2610. }
  2611. entry.key = key;
  2612. list.insertEntry(entry);
  2613. map[key] = entry;
  2614. }
  2615. return removed;
  2616. };
  2617. /**
  2618. * @param {string} key
  2619. * @return {}
  2620. */
  2621. LRUProto.get = function (key) {
  2622. var entry = this._map[key];
  2623. var list = this._list;
  2624. if (entry != null) {
  2625. // Put the latest used entry in the tail
  2626. if (entry !== list.tail) {
  2627. list.remove(entry);
  2628. list.insertEntry(entry);
  2629. }
  2630. return entry.value;
  2631. }
  2632. };
  2633. /**
  2634. * Clear the cache
  2635. */
  2636. LRUProto.clear = function () {
  2637. this._list.clear();
  2638. this._map = {};
  2639. };
  2640. var kCSSColorTable = {
  2641. 'transparent': [0,0,0,0], 'aliceblue': [240,248,255,1],
  2642. 'antiquewhite': [250,235,215,1], 'aqua': [0,255,255,1],
  2643. 'aquamarine': [127,255,212,1], 'azure': [240,255,255,1],
  2644. 'beige': [245,245,220,1], 'bisque': [255,228,196,1],
  2645. 'black': [0,0,0,1], 'blanchedalmond': [255,235,205,1],
  2646. 'blue': [0,0,255,1], 'blueviolet': [138,43,226,1],
  2647. 'brown': [165,42,42,1], 'burlywood': [222,184,135,1],
  2648. 'cadetblue': [95,158,160,1], 'chartreuse': [127,255,0,1],
  2649. 'chocolate': [210,105,30,1], 'coral': [255,127,80,1],
  2650. 'cornflowerblue': [100,149,237,1], 'cornsilk': [255,248,220,1],
  2651. 'crimson': [220,20,60,1], 'cyan': [0,255,255,1],
  2652. 'darkblue': [0,0,139,1], 'darkcyan': [0,139,139,1],
  2653. 'darkgoldenrod': [184,134,11,1], 'darkgray': [169,169,169,1],
  2654. 'darkgreen': [0,100,0,1], 'darkgrey': [169,169,169,1],
  2655. 'darkkhaki': [189,183,107,1], 'darkmagenta': [139,0,139,1],
  2656. 'darkolivegreen': [85,107,47,1], 'darkorange': [255,140,0,1],
  2657. 'darkorchid': [153,50,204,1], 'darkred': [139,0,0,1],
  2658. 'darksalmon': [233,150,122,1], 'darkseagreen': [143,188,143,1],
  2659. 'darkslateblue': [72,61,139,1], 'darkslategray': [47,79,79,1],
  2660. 'darkslategrey': [47,79,79,1], 'darkturquoise': [0,206,209,1],
  2661. 'darkviolet': [148,0,211,1], 'deeppink': [255,20,147,1],
  2662. 'deepskyblue': [0,191,255,1], 'dimgray': [105,105,105,1],
  2663. 'dimgrey': [105,105,105,1], 'dodgerblue': [30,144,255,1],
  2664. 'firebrick': [178,34,34,1], 'floralwhite': [255,250,240,1],
  2665. 'forestgreen': [34,139,34,1], 'fuchsia': [255,0,255,1],
  2666. 'gainsboro': [220,220,220,1], 'ghostwhite': [248,248,255,1],
  2667. 'gold': [255,215,0,1], 'goldenrod': [218,165,32,1],
  2668. 'gray': [128,128,128,1], 'green': [0,128,0,1],
  2669. 'greenyellow': [173,255,47,1], 'grey': [128,128,128,1],
  2670. 'honeydew': [240,255,240,1], 'hotpink': [255,105,180,1],
  2671. 'indianred': [205,92,92,1], 'indigo': [75,0,130,1],
  2672. 'ivory': [255,255,240,1], 'khaki': [240,230,140,1],
  2673. 'lavender': [230,230,250,1], 'lavenderblush': [255,240,245,1],
  2674. 'lawngreen': [124,252,0,1], 'lemonchiffon': [255,250,205,1],
  2675. 'lightblue': [173,216,230,1], 'lightcoral': [240,128,128,1],
  2676. 'lightcyan': [224,255,255,1], 'lightgoldenrodyellow': [250,250,210,1],
  2677. 'lightgray': [211,211,211,1], 'lightgreen': [144,238,144,1],
  2678. 'lightgrey': [211,211,211,1], 'lightpink': [255,182,193,1],
  2679. 'lightsalmon': [255,160,122,1], 'lightseagreen': [32,178,170,1],
  2680. 'lightskyblue': [135,206,250,1], 'lightslategray': [119,136,153,1],
  2681. 'lightslategrey': [119,136,153,1], 'lightsteelblue': [176,196,222,1],
  2682. 'lightyellow': [255,255,224,1], 'lime': [0,255,0,1],
  2683. 'limegreen': [50,205,50,1], 'linen': [250,240,230,1],
  2684. 'magenta': [255,0,255,1], 'maroon': [128,0,0,1],
  2685. 'mediumaquamarine': [102,205,170,1], 'mediumblue': [0,0,205,1],
  2686. 'mediumorchid': [186,85,211,1], 'mediumpurple': [147,112,219,1],
  2687. 'mediumseagreen': [60,179,113,1], 'mediumslateblue': [123,104,238,1],
  2688. 'mediumspringgreen': [0,250,154,1], 'mediumturquoise': [72,209,204,1],
  2689. 'mediumvioletred': [199,21,133,1], 'midnightblue': [25,25,112,1],
  2690. 'mintcream': [245,255,250,1], 'mistyrose': [255,228,225,1],
  2691. 'moccasin': [255,228,181,1], 'navajowhite': [255,222,173,1],
  2692. 'navy': [0,0,128,1], 'oldlace': [253,245,230,1],
  2693. 'olive': [128,128,0,1], 'olivedrab': [107,142,35,1],
  2694. 'orange': [255,165,0,1], 'orangered': [255,69,0,1],
  2695. 'orchid': [218,112,214,1], 'palegoldenrod': [238,232,170,1],
  2696. 'palegreen': [152,251,152,1], 'paleturquoise': [175,238,238,1],
  2697. 'palevioletred': [219,112,147,1], 'papayawhip': [255,239,213,1],
  2698. 'peachpuff': [255,218,185,1], 'peru': [205,133,63,1],
  2699. 'pink': [255,192,203,1], 'plum': [221,160,221,1],
  2700. 'powderblue': [176,224,230,1], 'purple': [128,0,128,1],
  2701. 'red': [255,0,0,1], 'rosybrown': [188,143,143,1],
  2702. 'royalblue': [65,105,225,1], 'saddlebrown': [139,69,19,1],
  2703. 'salmon': [250,128,114,1], 'sandybrown': [244,164,96,1],
  2704. 'seagreen': [46,139,87,1], 'seashell': [255,245,238,1],
  2705. 'sienna': [160,82,45,1], 'silver': [192,192,192,1],
  2706. 'skyblue': [135,206,235,1], 'slateblue': [106,90,205,1],
  2707. 'slategray': [112,128,144,1], 'slategrey': [112,128,144,1],
  2708. 'snow': [255,250,250,1], 'springgreen': [0,255,127,1],
  2709. 'steelblue': [70,130,180,1], 'tan': [210,180,140,1],
  2710. 'teal': [0,128,128,1], 'thistle': [216,191,216,1],
  2711. 'tomato': [255,99,71,1], 'turquoise': [64,224,208,1],
  2712. 'violet': [238,130,238,1], 'wheat': [245,222,179,1],
  2713. 'white': [255,255,255,1], 'whitesmoke': [245,245,245,1],
  2714. 'yellow': [255,255,0,1], 'yellowgreen': [154,205,50,1]
  2715. };
  2716. function clampCssByte(i) { // Clamp to integer 0 .. 255.
  2717. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  2718. return i < 0 ? 0 : i > 255 ? 255 : i;
  2719. }
  2720. function clampCssAngle(i) { // Clamp to integer 0 .. 360.
  2721. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  2722. return i < 0 ? 0 : i > 360 ? 360 : i;
  2723. }
  2724. function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
  2725. return f < 0 ? 0 : f > 1 ? 1 : f;
  2726. }
  2727. function parseCssInt(str) { // int or percentage.
  2728. if (str.length && str.charAt(str.length - 1) === '%') {
  2729. return clampCssByte(parseFloat(str) / 100 * 255);
  2730. }
  2731. return clampCssByte(parseInt(str, 10));
  2732. }
  2733. function parseCssFloat(str) { // float or percentage.
  2734. if (str.length && str.charAt(str.length - 1) === '%') {
  2735. return clampCssFloat(parseFloat(str) / 100);
  2736. }
  2737. return clampCssFloat(parseFloat(str));
  2738. }
  2739. function cssHueToRgb(m1, m2, h) {
  2740. if (h < 0) {
  2741. h += 1;
  2742. }
  2743. else if (h > 1) {
  2744. h -= 1;
  2745. }
  2746. if (h * 6 < 1) {
  2747. return m1 + (m2 - m1) * h * 6;
  2748. }
  2749. if (h * 2 < 1) {
  2750. return m2;
  2751. }
  2752. if (h * 3 < 2) {
  2753. return m1 + (m2 - m1) * (2/3 - h) * 6;
  2754. }
  2755. return m1;
  2756. }
  2757. function lerpNumber(a, b, p) {
  2758. return a + (b - a) * p;
  2759. }
  2760. function setRgba(out, r, g, b, a) {
  2761. out[0] = r; out[1] = g; out[2] = b; out[3] = a;
  2762. return out;
  2763. }
  2764. function copyRgba(out, a) {
  2765. out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3];
  2766. return out;
  2767. }
  2768. var colorCache = new LRU(20);
  2769. var lastRemovedArr = null;
  2770. function putToCache(colorStr, rgbaArr) {
  2771. // Reuse removed array
  2772. if (lastRemovedArr) {
  2773. copyRgba(lastRemovedArr, rgbaArr);
  2774. }
  2775. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  2776. }
  2777. /**
  2778. * @param {string} colorStr
  2779. * @param {Array.<number>} out
  2780. * @return {Array.<number>}
  2781. * @memberOf module:zrender/util/color
  2782. */
  2783. function parse(colorStr, rgbaArr) {
  2784. if (!colorStr) {
  2785. return;
  2786. }
  2787. rgbaArr = rgbaArr || [];
  2788. var cached = colorCache.get(colorStr);
  2789. if (cached) {
  2790. return copyRgba(rgbaArr, cached);
  2791. }
  2792. // colorStr may be not string
  2793. colorStr = colorStr + '';
  2794. // Remove all whitespace, not compliant, but should just be more accepting.
  2795. var str = colorStr.replace(/ /g, '').toLowerCase();
  2796. // Color keywords (and transparent) lookup.
  2797. if (str in kCSSColorTable) {
  2798. copyRgba(rgbaArr, kCSSColorTable[str]);
  2799. putToCache(colorStr, rgbaArr);
  2800. return rgbaArr;
  2801. }
  2802. // #abc and #abc123 syntax.
  2803. if (str.charAt(0) === '#') {
  2804. if (str.length === 4) {
  2805. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  2806. if (!(iv >= 0 && iv <= 0xfff)) {
  2807. setRgba(rgbaArr, 0, 0, 0, 1);
  2808. return; // Covers NaN.
  2809. }
  2810. setRgba(rgbaArr,
  2811. ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
  2812. (iv & 0xf0) | ((iv & 0xf0) >> 4),
  2813. (iv & 0xf) | ((iv & 0xf) << 4),
  2814. 1
  2815. );
  2816. putToCache(colorStr, rgbaArr);
  2817. return rgbaArr;
  2818. }
  2819. else if (str.length === 7) {
  2820. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  2821. if (!(iv >= 0 && iv <= 0xffffff)) {
  2822. setRgba(rgbaArr, 0, 0, 0, 1);
  2823. return; // Covers NaN.
  2824. }
  2825. setRgba(rgbaArr,
  2826. (iv & 0xff0000) >> 16,
  2827. (iv & 0xff00) >> 8,
  2828. iv & 0xff,
  2829. 1
  2830. );
  2831. putToCache(colorStr, rgbaArr);
  2832. return rgbaArr;
  2833. }
  2834. return;
  2835. }
  2836. var op = str.indexOf('('), ep = str.indexOf(')');
  2837. if (op !== -1 && ep + 1 === str.length) {
  2838. var fname = str.substr(0, op);
  2839. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  2840. var alpha = 1; // To allow case fallthrough.
  2841. switch (fname) {
  2842. case 'rgba':
  2843. if (params.length !== 4) {
  2844. setRgba(rgbaArr, 0, 0, 0, 1);
  2845. return;
  2846. }
  2847. alpha = parseCssFloat(params.pop()); // jshint ignore:line
  2848. // Fall through.
  2849. case 'rgb':
  2850. if (params.length !== 3) {
  2851. setRgba(rgbaArr, 0, 0, 0, 1);
  2852. return;
  2853. }
  2854. setRgba(rgbaArr,
  2855. parseCssInt(params[0]),
  2856. parseCssInt(params[1]),
  2857. parseCssInt(params[2]),
  2858. alpha
  2859. );
  2860. putToCache(colorStr, rgbaArr);
  2861. return rgbaArr;
  2862. case 'hsla':
  2863. if (params.length !== 4) {
  2864. setRgba(rgbaArr, 0, 0, 0, 1);
  2865. return;
  2866. }
  2867. params[3] = parseCssFloat(params[3]);
  2868. hsla2rgba(params, rgbaArr);
  2869. putToCache(colorStr, rgbaArr);
  2870. return rgbaArr;
  2871. case 'hsl':
  2872. if (params.length !== 3) {
  2873. setRgba(rgbaArr, 0, 0, 0, 1);
  2874. return;
  2875. }
  2876. hsla2rgba(params, rgbaArr);
  2877. putToCache(colorStr, rgbaArr);
  2878. return rgbaArr;
  2879. default:
  2880. return;
  2881. }
  2882. }
  2883. setRgba(rgbaArr, 0, 0, 0, 1);
  2884. return;
  2885. }
  2886. /**
  2887. * @param {Array.<number>} hsla
  2888. * @param {Array.<number>} rgba
  2889. * @return {Array.<number>} rgba
  2890. */
  2891. function hsla2rgba(hsla, rgba) {
  2892. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
  2893. // NOTE(deanm): According to the CSS spec s/l should only be
  2894. // percentages, but we don't bother and let float or percentage.
  2895. var s = parseCssFloat(hsla[1]);
  2896. var l = parseCssFloat(hsla[2]);
  2897. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  2898. var m1 = l * 2 - m2;
  2899. rgba = rgba || [];
  2900. setRgba(rgba,
  2901. clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
  2902. clampCssByte(cssHueToRgb(m1, m2, h) * 255),
  2903. clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255),
  2904. 1
  2905. );
  2906. if (hsla.length === 4) {
  2907. rgba[3] = hsla[3];
  2908. }
  2909. return rgba;
  2910. }
  2911. /**
  2912. * @param {Array.<number>} rgba
  2913. * @return {Array.<number>} hsla
  2914. */
  2915. function rgba2hsla(rgba) {
  2916. if (!rgba) {
  2917. return;
  2918. }
  2919. // RGB from 0 to 255
  2920. var R = rgba[0] / 255;
  2921. var G = rgba[1] / 255;
  2922. var B = rgba[2] / 255;
  2923. var vMin = Math.min(R, G, B); // Min. value of RGB
  2924. var vMax = Math.max(R, G, B); // Max. value of RGB
  2925. var delta = vMax - vMin; // Delta RGB value
  2926. var L = (vMax + vMin) / 2;
  2927. var H;
  2928. var S;
  2929. // HSL results from 0 to 1
  2930. if (delta === 0) {
  2931. H = 0;
  2932. S = 0;
  2933. }
  2934. else {
  2935. if (L < 0.5) {
  2936. S = delta / (vMax + vMin);
  2937. }
  2938. else {
  2939. S = delta / (2 - vMax - vMin);
  2940. }
  2941. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  2942. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  2943. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  2944. if (R === vMax) {
  2945. H = deltaB - deltaG;
  2946. }
  2947. else if (G === vMax) {
  2948. H = (1 / 3) + deltaR - deltaB;
  2949. }
  2950. else if (B === vMax) {
  2951. H = (2 / 3) + deltaG - deltaR;
  2952. }
  2953. if (H < 0) {
  2954. H += 1;
  2955. }
  2956. if (H > 1) {
  2957. H -= 1;
  2958. }
  2959. }
  2960. var hsla = [H * 360, S, L];
  2961. if (rgba[3] != null) {
  2962. hsla.push(rgba[3]);
  2963. }
  2964. return hsla;
  2965. }
  2966. /**
  2967. * @param {string} color
  2968. * @param {number} level
  2969. * @return {string}
  2970. * @memberOf module:zrender/util/color
  2971. */
  2972. function lift(color, level) {
  2973. var colorArr = parse(color);
  2974. if (colorArr) {
  2975. for (var i = 0; i < 3; i++) {
  2976. if (level < 0) {
  2977. colorArr[i] = colorArr[i] * (1 - level) | 0;
  2978. }
  2979. else {
  2980. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  2981. }
  2982. if (colorArr[i] > 255) {
  2983. colorArr[i] = 255;
  2984. }
  2985. else if (color[i] < 0) {
  2986. colorArr[i] = 0;
  2987. }
  2988. }
  2989. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  2990. }
  2991. }
  2992. /**
  2993. * @param {string} color
  2994. * @return {string}
  2995. * @memberOf module:zrender/util/color
  2996. */
  2997. function toHex(color) {
  2998. var colorArr = parse(color);
  2999. if (colorArr) {
  3000. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  3001. }
  3002. }
  3003. /**
  3004. * Map value to color. Faster than lerp methods because color is represented by rgba array.
  3005. * @param {number} normalizedValue A float between 0 and 1.
  3006. * @param {Array.<Array.<number>>} colors List of rgba color array
  3007. * @param {Array.<number>} [out] Mapped gba color array
  3008. * @return {Array.<number>} will be null/undefined if input illegal.
  3009. */
  3010. function fastLerp(normalizedValue, colors, out) {
  3011. if (!(colors && colors.length)
  3012. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3013. ) {
  3014. return;
  3015. }
  3016. out = out || [];
  3017. var value = normalizedValue * (colors.length - 1);
  3018. var leftIndex = Math.floor(value);
  3019. var rightIndex = Math.ceil(value);
  3020. var leftColor = colors[leftIndex];
  3021. var rightColor = colors[rightIndex];
  3022. var dv = value - leftIndex;
  3023. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3024. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3025. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3026. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3027. return out;
  3028. }
  3029. /**
  3030. * @deprecated
  3031. */
  3032. var fastMapToColor = fastLerp;
  3033. /**
  3034. * @param {number} normalizedValue A float between 0 and 1.
  3035. * @param {Array.<string>} colors Color list.
  3036. * @param {boolean=} fullOutput Default false.
  3037. * @return {(string|Object)} Result color. If fullOutput,
  3038. * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
  3039. * @memberOf module:zrender/util/color
  3040. */
  3041. function lerp$1(normalizedValue, colors, fullOutput) {
  3042. if (!(colors && colors.length)
  3043. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3044. ) {
  3045. return;
  3046. }
  3047. var value = normalizedValue * (colors.length - 1);
  3048. var leftIndex = Math.floor(value);
  3049. var rightIndex = Math.ceil(value);
  3050. var leftColor = parse(colors[leftIndex]);
  3051. var rightColor = parse(colors[rightIndex]);
  3052. var dv = value - leftIndex;
  3053. var color = stringify(
  3054. [
  3055. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  3056. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  3057. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  3058. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  3059. ],
  3060. 'rgba'
  3061. );
  3062. return fullOutput
  3063. ? {
  3064. color: color,
  3065. leftIndex: leftIndex,
  3066. rightIndex: rightIndex,
  3067. value: value
  3068. }
  3069. : color;
  3070. }
  3071. /**
  3072. * @deprecated
  3073. */
  3074. var mapToColor = lerp$1;
  3075. /**
  3076. * @param {string} color
  3077. * @param {number=} h 0 ~ 360, ignore when null.
  3078. * @param {number=} s 0 ~ 1, ignore when null.
  3079. * @param {number=} l 0 ~ 1, ignore when null.
  3080. * @return {string} Color string in rgba format.
  3081. * @memberOf module:zrender/util/color
  3082. */
  3083. function modifyHSL(color, h, s, l) {
  3084. color = parse(color);
  3085. if (color) {
  3086. color = rgba2hsla(color);
  3087. h != null && (color[0] = clampCssAngle(h));
  3088. s != null && (color[1] = parseCssFloat(s));
  3089. l != null && (color[2] = parseCssFloat(l));
  3090. return stringify(hsla2rgba(color), 'rgba');
  3091. }
  3092. }
  3093. /**
  3094. * @param {string} color
  3095. * @param {number=} alpha 0 ~ 1
  3096. * @return {string} Color string in rgba format.
  3097. * @memberOf module:zrender/util/color
  3098. */
  3099. function modifyAlpha(color, alpha) {
  3100. color = parse(color);
  3101. if (color && alpha != null) {
  3102. color[3] = clampCssFloat(alpha);
  3103. return stringify(color, 'rgba');
  3104. }
  3105. }
  3106. /**
  3107. * @param {Array.<number>} arrColor like [12,33,44,0.4]
  3108. * @param {string} type 'rgba', 'hsva', ...
  3109. * @return {string} Result color. (If input illegal, return undefined).
  3110. */
  3111. function stringify(arrColor, type) {
  3112. if (!arrColor || !arrColor.length) {
  3113. return;
  3114. }
  3115. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3116. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3117. colorStr += ',' + arrColor[3];
  3118. }
  3119. return type + '(' + colorStr + ')';
  3120. }
  3121. var color = (Object.freeze || Object)({
  3122. parse: parse,
  3123. lift: lift,
  3124. toHex: toHex,
  3125. fastLerp: fastLerp,
  3126. fastMapToColor: fastMapToColor,
  3127. lerp: lerp$1,
  3128. mapToColor: mapToColor,
  3129. modifyHSL: modifyHSL,
  3130. modifyAlpha: modifyAlpha,
  3131. stringify: stringify
  3132. });
  3133. /**
  3134. * @module echarts/animation/Animator
  3135. */
  3136. var arraySlice = Array.prototype.slice;
  3137. function defaultGetter(target, key) {
  3138. return target[key];
  3139. }
  3140. function defaultSetter(target, key, value) {
  3141. target[key] = value;
  3142. }
  3143. /**
  3144. * @param {number} p0
  3145. * @param {number} p1
  3146. * @param {number} percent
  3147. * @return {number}
  3148. */
  3149. function interpolateNumber(p0, p1, percent) {
  3150. return (p1 - p0) * percent + p0;
  3151. }
  3152. /**
  3153. * @param {string} p0
  3154. * @param {string} p1
  3155. * @param {number} percent
  3156. * @return {string}
  3157. */
  3158. function interpolateString(p0, p1, percent) {
  3159. return percent > 0.5 ? p1 : p0;
  3160. }
  3161. /**
  3162. * @param {Array} p0
  3163. * @param {Array} p1
  3164. * @param {number} percent
  3165. * @param {Array} out
  3166. * @param {number} arrDim
  3167. */
  3168. function interpolateArray(p0, p1, percent, out, arrDim) {
  3169. var len = p0.length;
  3170. if (arrDim == 1) {
  3171. for (var i = 0; i < len; i++) {
  3172. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3173. }
  3174. }
  3175. else {
  3176. var len2 = len && p0[0].length;
  3177. for (var i = 0; i < len; i++) {
  3178. for (var j = 0; j < len2; j++) {
  3179. out[i][j] = interpolateNumber(
  3180. p0[i][j], p1[i][j], percent
  3181. );
  3182. }
  3183. }
  3184. }
  3185. }
  3186. // arr0 is source array, arr1 is target array.
  3187. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1
  3188. function fillArr(arr0, arr1, arrDim) {
  3189. var arr0Len = arr0.length;
  3190. var arr1Len = arr1.length;
  3191. if (arr0Len !== arr1Len) {
  3192. // FIXME Not work for TypedArray
  3193. var isPreviousLarger = arr0Len > arr1Len;
  3194. if (isPreviousLarger) {
  3195. // Cut the previous
  3196. arr0.length = arr1Len;
  3197. }
  3198. else {
  3199. // Fill the previous
  3200. for (var i = arr0Len; i < arr1Len; i++) {
  3201. arr0.push(
  3202. arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i])
  3203. );
  3204. }
  3205. }
  3206. }
  3207. // Handling NaN value
  3208. var len2 = arr0[0] && arr0[0].length;
  3209. for (var i = 0; i < arr0.length; i++) {
  3210. if (arrDim === 1) {
  3211. if (isNaN(arr0[i])) {
  3212. arr0[i] = arr1[i];
  3213. }
  3214. }
  3215. else {
  3216. for (var j = 0; j < len2; j++) {
  3217. if (isNaN(arr0[i][j])) {
  3218. arr0[i][j] = arr1[i][j];
  3219. }
  3220. }
  3221. }
  3222. }
  3223. }
  3224. /**
  3225. * @param {Array} arr0
  3226. * @param {Array} arr1
  3227. * @param {number} arrDim
  3228. * @return {boolean}
  3229. */
  3230. function isArraySame(arr0, arr1, arrDim) {
  3231. if (arr0 === arr1) {
  3232. return true;
  3233. }
  3234. var len = arr0.length;
  3235. if (len !== arr1.length) {
  3236. return false;
  3237. }
  3238. if (arrDim === 1) {
  3239. for (var i = 0; i < len; i++) {
  3240. if (arr0[i] !== arr1[i]) {
  3241. return false;
  3242. }
  3243. }
  3244. }
  3245. else {
  3246. var len2 = arr0[0].length;
  3247. for (var i = 0; i < len; i++) {
  3248. for (var j = 0; j < len2; j++) {
  3249. if (arr0[i][j] !== arr1[i][j]) {
  3250. return false;
  3251. }
  3252. }
  3253. }
  3254. }
  3255. return true;
  3256. }
  3257. /**
  3258. * Catmull Rom interpolate array
  3259. * @param {Array} p0
  3260. * @param {Array} p1
  3261. * @param {Array} p2
  3262. * @param {Array} p3
  3263. * @param {number} t
  3264. * @param {number} t2
  3265. * @param {number} t3
  3266. * @param {Array} out
  3267. * @param {number} arrDim
  3268. */
  3269. function catmullRomInterpolateArray(
  3270. p0, p1, p2, p3, t, t2, t3, out, arrDim
  3271. ) {
  3272. var len = p0.length;
  3273. if (arrDim == 1) {
  3274. for (var i = 0; i < len; i++) {
  3275. out[i] = catmullRomInterpolate(
  3276. p0[i], p1[i], p2[i], p3[i], t, t2, t3
  3277. );
  3278. }
  3279. }
  3280. else {
  3281. var len2 = p0[0].length;
  3282. for (var i = 0; i < len; i++) {
  3283. for (var j = 0; j < len2; j++) {
  3284. out[i][j] = catmullRomInterpolate(
  3285. p0[i][j], p1[i][j], p2[i][j], p3[i][j],
  3286. t, t2, t3
  3287. );
  3288. }
  3289. }
  3290. }
  3291. }
  3292. /**
  3293. * Catmull Rom interpolate number
  3294. * @param {number} p0
  3295. * @param {number} p1
  3296. * @param {number} p2
  3297. * @param {number} p3
  3298. * @param {number} t
  3299. * @param {number} t2
  3300. * @param {number} t3
  3301. * @return {number}
  3302. */
  3303. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  3304. var v0 = (p2 - p0) * 0.5;
  3305. var v1 = (p3 - p1) * 0.5;
  3306. return (2 * (p1 - p2) + v0 + v1) * t3
  3307. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  3308. + v0 * t + p1;
  3309. }
  3310. function cloneValue(value) {
  3311. if (isArrayLike(value)) {
  3312. var len = value.length;
  3313. if (isArrayLike(value[0])) {
  3314. var ret = [];
  3315. for (var i = 0; i < len; i++) {
  3316. ret.push(arraySlice.call(value[i]));
  3317. }
  3318. return ret;
  3319. }
  3320. return arraySlice.call(value);
  3321. }
  3322. return value;
  3323. }
  3324. function rgba2String(rgba) {
  3325. rgba[0] = Math.floor(rgba[0]);
  3326. rgba[1] = Math.floor(rgba[1]);
  3327. rgba[2] = Math.floor(rgba[2]);
  3328. return 'rgba(' + rgba.join(',') + ')';
  3329. }
  3330. function getArrayDim(keyframes) {
  3331. var lastValue = keyframes[keyframes.length - 1].value;
  3332. return isArrayLike(lastValue && lastValue[0]) ? 2 : 1;
  3333. }
  3334. function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) {
  3335. var getter = animator._getter;
  3336. var setter = animator._setter;
  3337. var useSpline = easing === 'spline';
  3338. var trackLen = keyframes.length;
  3339. if (!trackLen) {
  3340. return;
  3341. }
  3342. // Guess data type
  3343. var firstVal = keyframes[0].value;
  3344. var isValueArray = isArrayLike(firstVal);
  3345. var isValueColor = false;
  3346. var isValueString = false;
  3347. // For vertices morphing
  3348. var arrDim = isValueArray ? getArrayDim(keyframes) : 0;
  3349. var trackMaxTime;
  3350. // Sort keyframe as ascending
  3351. keyframes.sort(function(a, b) {
  3352. return a.time - b.time;
  3353. });
  3354. trackMaxTime = keyframes[trackLen - 1].time;
  3355. // Percents of each keyframe
  3356. var kfPercents = [];
  3357. // Value of each keyframe
  3358. var kfValues = [];
  3359. var prevValue = keyframes[0].value;
  3360. var isAllValueEqual = true;
  3361. for (var i = 0; i < trackLen; i++) {
  3362. kfPercents.push(keyframes[i].time / trackMaxTime);
  3363. // Assume value is a color when it is a string
  3364. var value = keyframes[i].value;
  3365. // Check if value is equal, deep check if value is array
  3366. if (!((isValueArray && isArraySame(value, prevValue, arrDim))
  3367. || (!isValueArray && value === prevValue))) {
  3368. isAllValueEqual = false;
  3369. }
  3370. prevValue = value;
  3371. // Try converting a string to a color array
  3372. if (typeof value == 'string') {
  3373. var colorArray = parse(value);
  3374. if (colorArray) {
  3375. value = colorArray;
  3376. isValueColor = true;
  3377. }
  3378. else {
  3379. isValueString = true;
  3380. }
  3381. }
  3382. kfValues.push(value);
  3383. }
  3384. if (!forceAnimate && isAllValueEqual) {
  3385. return;
  3386. }
  3387. var lastValue = kfValues[trackLen - 1];
  3388. // Polyfill array and NaN value
  3389. for (var i = 0; i < trackLen - 1; i++) {
  3390. if (isValueArray) {
  3391. fillArr(kfValues[i], lastValue, arrDim);
  3392. }
  3393. else {
  3394. if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) {
  3395. kfValues[i] = lastValue;
  3396. }
  3397. }
  3398. }
  3399. isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim);
  3400. // Cache the key of last frame to speed up when
  3401. // animation playback is sequency
  3402. var lastFrame = 0;
  3403. var lastFramePercent = 0;
  3404. var start;
  3405. var w;
  3406. var p0;
  3407. var p1;
  3408. var p2;
  3409. var p3;
  3410. if (isValueColor) {
  3411. var rgba = [0, 0, 0, 0];
  3412. }
  3413. var onframe = function (target, percent) {
  3414. // Find the range keyframes
  3415. // kf1-----kf2---------current--------kf3
  3416. // find kf2 and kf3 and do interpolation
  3417. var frame;
  3418. // In the easing function like elasticOut, percent may less than 0
  3419. if (percent < 0) {
  3420. frame = 0;
  3421. }
  3422. else if (percent < lastFramePercent) {
  3423. // Start from next key
  3424. // PENDING start from lastFrame ?
  3425. start = Math.min(lastFrame + 1, trackLen - 1);
  3426. for (frame = start; frame >= 0; frame--) {
  3427. if (kfPercents[frame] <= percent) {
  3428. break;
  3429. }
  3430. }
  3431. // PENDING really need to do this ?
  3432. frame = Math.min(frame, trackLen - 2);
  3433. }
  3434. else {
  3435. for (frame = lastFrame; frame < trackLen; frame++) {
  3436. if (kfPercents[frame] > percent) {
  3437. break;
  3438. }
  3439. }
  3440. frame = Math.min(frame - 1, trackLen - 2);
  3441. }
  3442. lastFrame = frame;
  3443. lastFramePercent = percent;
  3444. var range = (kfPercents[frame + 1] - kfPercents[frame]);
  3445. if (range === 0) {
  3446. return;
  3447. }
  3448. else {
  3449. w = (percent - kfPercents[frame]) / range;
  3450. }
  3451. if (useSpline) {
  3452. p1 = kfValues[frame];
  3453. p0 = kfValues[frame === 0 ? frame : frame - 1];
  3454. p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1];
  3455. p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2];
  3456. if (isValueArray) {
  3457. catmullRomInterpolateArray(
  3458. p0, p1, p2, p3, w, w * w, w * w * w,
  3459. getter(target, propName),
  3460. arrDim
  3461. );
  3462. }
  3463. else {
  3464. var value;
  3465. if (isValueColor) {
  3466. value = catmullRomInterpolateArray(
  3467. p0, p1, p2, p3, w, w * w, w * w * w,
  3468. rgba, 1
  3469. );
  3470. value = rgba2String(rgba);
  3471. }
  3472. else if (isValueString) {
  3473. // String is step(0.5)
  3474. return interpolateString(p1, p2, w);
  3475. }
  3476. else {
  3477. value = catmullRomInterpolate(
  3478. p0, p1, p2, p3, w, w * w, w * w * w
  3479. );
  3480. }
  3481. setter(
  3482. target,
  3483. propName,
  3484. value
  3485. );
  3486. }
  3487. }
  3488. else {
  3489. if (isValueArray) {
  3490. interpolateArray(
  3491. kfValues[frame], kfValues[frame + 1], w,
  3492. getter(target, propName),
  3493. arrDim
  3494. );
  3495. }
  3496. else {
  3497. var value;
  3498. if (isValueColor) {
  3499. interpolateArray(
  3500. kfValues[frame], kfValues[frame + 1], w,
  3501. rgba, 1
  3502. );
  3503. value = rgba2String(rgba);
  3504. }
  3505. else if (isValueString) {
  3506. // String is step(0.5)
  3507. return interpolateString(kfValues[frame], kfValues[frame + 1], w);
  3508. }
  3509. else {
  3510. value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w);
  3511. }
  3512. setter(
  3513. target,
  3514. propName,
  3515. value
  3516. );
  3517. }
  3518. }
  3519. };
  3520. var clip = new Clip({
  3521. target: animator._target,
  3522. life: trackMaxTime,
  3523. loop: animator._loop,
  3524. delay: animator._delay,
  3525. onframe: onframe,
  3526. ondestroy: oneTrackDone
  3527. });
  3528. if (easing && easing !== 'spline') {
  3529. clip.easing = easing;
  3530. }
  3531. return clip;
  3532. }
  3533. /**
  3534. * @alias module:zrender/animation/Animator
  3535. * @constructor
  3536. * @param {Object} target
  3537. * @param {boolean} loop
  3538. * @param {Function} getter
  3539. * @param {Function} setter
  3540. */
  3541. var Animator = function(target, loop, getter, setter) {
  3542. this._tracks = {};
  3543. this._target = target;
  3544. this._loop = loop || false;
  3545. this._getter = getter || defaultGetter;
  3546. this._setter = setter || defaultSetter;
  3547. this._clipCount = 0;
  3548. this._delay = 0;
  3549. this._doneList = [];
  3550. this._onframeList = [];
  3551. this._clipList = [];
  3552. };
  3553. Animator.prototype = {
  3554. /**
  3555. * 设置动画关键帧
  3556. * @param {number} time 关键帧时间,单位是ms
  3557. * @param {Object} props 关键帧的属性值,key-value表示
  3558. * @return {module:zrender/animation/Animator}
  3559. */
  3560. when: function(time /* ms */, props) {
  3561. var tracks = this._tracks;
  3562. for (var propName in props) {
  3563. if (!props.hasOwnProperty(propName)) {
  3564. continue;
  3565. }
  3566. if (!tracks[propName]) {
  3567. tracks[propName] = [];
  3568. // Invalid value
  3569. var value = this._getter(this._target, propName);
  3570. if (value == null) {
  3571. // zrLog('Invalid property ' + propName);
  3572. continue;
  3573. }
  3574. // If time is 0
  3575. // Then props is given initialize value
  3576. // Else
  3577. // Initialize value from current prop value
  3578. if (time !== 0) {
  3579. tracks[propName].push({
  3580. time: 0,
  3581. value: cloneValue(value)
  3582. });
  3583. }
  3584. }
  3585. tracks[propName].push({
  3586. time: time,
  3587. value: props[propName]
  3588. });
  3589. }
  3590. return this;
  3591. },
  3592. /**
  3593. * 添加动画每一帧的回调函数
  3594. * @param {Function} callback
  3595. * @return {module:zrender/animation/Animator}
  3596. */
  3597. during: function (callback) {
  3598. this._onframeList.push(callback);
  3599. return this;
  3600. },
  3601. pause: function () {
  3602. for (var i = 0; i < this._clipList.length; i++) {
  3603. this._clipList[i].pause();
  3604. }
  3605. this._paused = true;
  3606. },
  3607. resume: function () {
  3608. for (var i = 0; i < this._clipList.length; i++) {
  3609. this._clipList[i].resume();
  3610. }
  3611. this._paused = false;
  3612. },
  3613. isPaused: function () {
  3614. return !!this._paused;
  3615. },
  3616. _doneCallback: function () {
  3617. // Clear all tracks
  3618. this._tracks = {};
  3619. // Clear all clips
  3620. this._clipList.length = 0;
  3621. var doneList = this._doneList;
  3622. var len = doneList.length;
  3623. for (var i = 0; i < len; i++) {
  3624. doneList[i].call(this);
  3625. }
  3626. },
  3627. /**
  3628. * 开始执行动画
  3629. * @param {string|Function} [easing]
  3630. * 动画缓动函数,详见{@link module:zrender/animation/easing}
  3631. * @param {boolean} forceAnimate
  3632. * @return {module:zrender/animation/Animator}
  3633. */
  3634. start: function (easing, forceAnimate) {
  3635. var self = this;
  3636. var clipCount = 0;
  3637. var oneTrackDone = function() {
  3638. clipCount--;
  3639. if (!clipCount) {
  3640. self._doneCallback();
  3641. }
  3642. };
  3643. var lastClip;
  3644. for (var propName in this._tracks) {
  3645. if (!this._tracks.hasOwnProperty(propName)) {
  3646. continue;
  3647. }
  3648. var clip = createTrackClip(
  3649. this, easing, oneTrackDone,
  3650. this._tracks[propName], propName, forceAnimate
  3651. );
  3652. if (clip) {
  3653. this._clipList.push(clip);
  3654. clipCount++;
  3655. // If start after added to animation
  3656. if (this.animation) {
  3657. this.animation.addClip(clip);
  3658. }
  3659. lastClip = clip;
  3660. }
  3661. }
  3662. // Add during callback on the last clip
  3663. if (lastClip) {
  3664. var oldOnFrame = lastClip.onframe;
  3665. lastClip.onframe = function (target, percent) {
  3666. oldOnFrame(target, percent);
  3667. for (var i = 0; i < self._onframeList.length; i++) {
  3668. self._onframeList[i](target, percent);
  3669. }
  3670. };
  3671. }
  3672. // This optimization will help the case that in the upper application
  3673. // the view may be refreshed frequently, where animation will be
  3674. // called repeatly but nothing changed.
  3675. if (!clipCount) {
  3676. this._doneCallback();
  3677. }
  3678. return this;
  3679. },
  3680. /**
  3681. * 停止动画
  3682. * @param {boolean} forwardToLast If move to last frame before stop
  3683. */
  3684. stop: function (forwardToLast) {
  3685. var clipList = this._clipList;
  3686. var animation = this.animation;
  3687. for (var i = 0; i < clipList.length; i++) {
  3688. var clip = clipList[i];
  3689. if (forwardToLast) {
  3690. // Move to last frame before stop
  3691. clip.onframe(this._target, 1);
  3692. }
  3693. animation && animation.removeClip(clip);
  3694. }
  3695. clipList.length = 0;
  3696. },
  3697. /**
  3698. * 设置动画延迟开始的时间
  3699. * @param {number} time 单位ms
  3700. * @return {module:zrender/animation/Animator}
  3701. */
  3702. delay: function (time) {
  3703. this._delay = time;
  3704. return this;
  3705. },
  3706. /**
  3707. * 添加动画结束的回调
  3708. * @param {Function} cb
  3709. * @return {module:zrender/animation/Animator}
  3710. */
  3711. done: function(cb) {
  3712. if (cb) {
  3713. this._doneList.push(cb);
  3714. }
  3715. return this;
  3716. },
  3717. /**
  3718. * @return {Array.<module:zrender/animation/Clip>}
  3719. */
  3720. getClips: function () {
  3721. return this._clipList;
  3722. }
  3723. };
  3724. var dpr = 1;
  3725. // If in browser environment
  3726. if (typeof window !== 'undefined') {
  3727. dpr = Math.max(window.devicePixelRatio || 1, 1);
  3728. }
  3729. /**
  3730. * config默认配置项
  3731. * @exports zrender/config
  3732. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  3733. */
  3734. /**
  3735. * debug日志选项:catchBrushException为true下有效
  3736. * 0 : 不生成debug数据,发布用
  3737. * 1 : 异常抛出,调试用
  3738. * 2 : 控制台输出,调试用
  3739. */
  3740. var debugMode = 0;
  3741. // retina 屏幕优化
  3742. var devicePixelRatio = dpr;
  3743. var log = function () {
  3744. };
  3745. if (debugMode === 1) {
  3746. log = function () {
  3747. for (var k in arguments) {
  3748. throw new Error(arguments[k]);
  3749. }
  3750. };
  3751. }
  3752. else if (debugMode > 1) {
  3753. log = function () {
  3754. for (var k in arguments) {
  3755. console.log(arguments[k]);
  3756. }
  3757. };
  3758. }
  3759. var zrLog = log;
  3760. /**
  3761. * @alias modue:zrender/mixin/Animatable
  3762. * @constructor
  3763. */
  3764. var Animatable = function () {
  3765. /**
  3766. * @type {Array.<module:zrender/animation/Animator>}
  3767. * @readOnly
  3768. */
  3769. this.animators = [];
  3770. };
  3771. Animatable.prototype = {
  3772. constructor: Animatable,
  3773. /**
  3774. * 动画
  3775. *
  3776. * @param {string} path The path to fetch value from object, like 'a.b.c'.
  3777. * @param {boolean} [loop] Whether to loop animation.
  3778. * @return {module:zrender/animation/Animator}
  3779. * @example:
  3780. * el.animate('style', false)
  3781. * .when(1000, {x: 10} )
  3782. * .done(function(){ // Animation done })
  3783. * .start()
  3784. */
  3785. animate: function (path, loop) {
  3786. var target;
  3787. var animatingShape = false;
  3788. var el = this;
  3789. var zr = this.__zr;
  3790. if (path) {
  3791. var pathSplitted = path.split('.');
  3792. var prop = el;
  3793. // If animating shape
  3794. animatingShape = pathSplitted[0] === 'shape';
  3795. for (var i = 0, l = pathSplitted.length; i < l; i++) {
  3796. if (!prop) {
  3797. continue;
  3798. }
  3799. prop = prop[pathSplitted[i]];
  3800. }
  3801. if (prop) {
  3802. target = prop;
  3803. }
  3804. }
  3805. else {
  3806. target = el;
  3807. }
  3808. if (!target) {
  3809. zrLog(
  3810. 'Property "'
  3811. + path
  3812. + '" is not existed in element '
  3813. + el.id
  3814. );
  3815. return;
  3816. }
  3817. var animators = el.animators;
  3818. var animator = new Animator(target, loop);
  3819. animator.during(function (target) {
  3820. el.dirty(animatingShape);
  3821. })
  3822. .done(function () {
  3823. // FIXME Animator will not be removed if use `Animator#stop` to stop animation
  3824. animators.splice(indexOf(animators, animator), 1);
  3825. });
  3826. animators.push(animator);
  3827. // If animate after added to the zrender
  3828. if (zr) {
  3829. zr.animation.addAnimator(animator);
  3830. }
  3831. return animator;
  3832. },
  3833. /**
  3834. * 停止动画
  3835. * @param {boolean} forwardToLast If move to last frame before stop
  3836. */
  3837. stopAnimation: function (forwardToLast) {
  3838. var animators = this.animators;
  3839. var len = animators.length;
  3840. for (var i = 0; i < len; i++) {
  3841. animators[i].stop(forwardToLast);
  3842. }
  3843. animators.length = 0;
  3844. return this;
  3845. },
  3846. /**
  3847. * Caution: this method will stop previous animation.
  3848. * So do not use this method to one element twice before
  3849. * animation starts, unless you know what you are doing.
  3850. * @param {Object} target
  3851. * @param {number} [time=500] Time in ms
  3852. * @param {string} [easing='linear']
  3853. * @param {number} [delay=0]
  3854. * @param {Function} [callback]
  3855. * @param {Function} [forceAnimate] Prevent stop animation and callback
  3856. * immediently when target values are the same as current values.
  3857. *
  3858. * @example
  3859. * // Animate position
  3860. * el.animateTo({
  3861. * position: [10, 10]
  3862. * }, function () { // done })
  3863. *
  3864. * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing
  3865. * el.animateTo({
  3866. * shape: {
  3867. * width: 500
  3868. * },
  3869. * style: {
  3870. * fill: 'red'
  3871. * }
  3872. * position: [10, 10]
  3873. * }, 100, 100, 'cubicOut', function () { // done })
  3874. */
  3875. // TODO Return animation key
  3876. animateTo: function (target, time, delay, easing, callback, forceAnimate) {
  3877. // animateTo(target, time, easing, callback);
  3878. if (isString(delay)) {
  3879. callback = easing;
  3880. easing = delay;
  3881. delay = 0;
  3882. }
  3883. // animateTo(target, time, delay, callback);
  3884. else if (isFunction$1(easing)) {
  3885. callback = easing;
  3886. easing = 'linear';
  3887. delay = 0;
  3888. }
  3889. // animateTo(target, time, callback);
  3890. else if (isFunction$1(delay)) {
  3891. callback = delay;
  3892. delay = 0;
  3893. }
  3894. // animateTo(target, callback)
  3895. else if (isFunction$1(time)) {
  3896. callback = time;
  3897. time = 500;
  3898. }
  3899. // animateTo(target)
  3900. else if (!time) {
  3901. time = 500;
  3902. }
  3903. // Stop all previous animations
  3904. this.stopAnimation();
  3905. this._animateToShallow('', this, target, time, delay);
  3906. // Animators may be removed immediately after start
  3907. // if there is nothing to animate
  3908. var animators = this.animators.slice();
  3909. var count = animators.length;
  3910. function done() {
  3911. count--;
  3912. if (!count) {
  3913. callback && callback();
  3914. }
  3915. }
  3916. // No animators. This should be checked before animators[i].start(),
  3917. // because 'done' may be executed immediately if no need to animate.
  3918. if (!count) {
  3919. callback && callback();
  3920. }
  3921. // Start after all animators created
  3922. // Incase any animator is done immediately when all animation properties are not changed
  3923. for (var i = 0; i < animators.length; i++) {
  3924. animators[i]
  3925. .done(done)
  3926. .start(easing, forceAnimate);
  3927. }
  3928. },
  3929. /**
  3930. * @private
  3931. * @param {string} path=''
  3932. * @param {Object} source=this
  3933. * @param {Object} target
  3934. * @param {number} [time=500]
  3935. * @param {number} [delay=0]
  3936. *
  3937. * @example
  3938. * // Animate position
  3939. * el._animateToShallow({
  3940. * position: [10, 10]
  3941. * })
  3942. *
  3943. * // Animate shape, style and position in 100ms, delayed 100ms
  3944. * el._animateToShallow({
  3945. * shape: {
  3946. * width: 500
  3947. * },
  3948. * style: {
  3949. * fill: 'red'
  3950. * }
  3951. * position: [10, 10]
  3952. * }, 100, 100)
  3953. */
  3954. _animateToShallow: function (path, source, target, time, delay) {
  3955. var objShallow = {};
  3956. var propertyCount = 0;
  3957. for (var name in target) {
  3958. if (!target.hasOwnProperty(name)) {
  3959. continue;
  3960. }
  3961. if (source[name] != null) {
  3962. if (isObject$1(target[name]) && !isArrayLike(target[name])) {
  3963. this._animateToShallow(
  3964. path ? path + '.' + name : name,
  3965. source[name],
  3966. target[name],
  3967. time,
  3968. delay
  3969. );
  3970. }
  3971. else {
  3972. objShallow[name] = target[name];
  3973. propertyCount++;
  3974. }
  3975. }
  3976. else if (target[name] != null) {
  3977. // Attr directly if not has property
  3978. // FIXME, if some property not needed for element ?
  3979. if (!path) {
  3980. this.attr(name, target[name]);
  3981. }
  3982. else { // Shape or style
  3983. var props = {};
  3984. props[path] = {};
  3985. props[path][name] = target[name];
  3986. this.attr(props);
  3987. }
  3988. }
  3989. }
  3990. if (propertyCount > 0) {
  3991. this.animate(path, false)
  3992. .when(time == null ? 500 : time, objShallow)
  3993. .delay(delay || 0);
  3994. }
  3995. return this;
  3996. }
  3997. };
  3998. /**
  3999. * @alias module:zrender/Element
  4000. * @constructor
  4001. * @extends {module:zrender/mixin/Animatable}
  4002. * @extends {module:zrender/mixin/Transformable}
  4003. * @extends {module:zrender/mixin/Eventful}
  4004. */
  4005. var Element = function (opts) { // jshint ignore:line
  4006. Transformable.call(this, opts);
  4007. Eventful.call(this, opts);
  4008. Animatable.call(this, opts);
  4009. /**
  4010. * 画布元素ID
  4011. * @type {string}
  4012. */
  4013. this.id = opts.id || guid();
  4014. };
  4015. Element.prototype = {
  4016. /**
  4017. * 元素类型
  4018. * Element type
  4019. * @type {string}
  4020. */
  4021. type: 'element',
  4022. /**
  4023. * 元素名字
  4024. * Element name
  4025. * @type {string}
  4026. */
  4027. name: '',
  4028. /**
  4029. * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值
  4030. * ZRender instance will be assigned when element is associated with zrender
  4031. * @name module:/zrender/Element#__zr
  4032. * @type {module:zrender/ZRender}
  4033. */
  4034. __zr: null,
  4035. /**
  4036. * 图形是否忽略,为true时忽略图形的绘制以及事件触发
  4037. * If ignore drawing and events of the element object
  4038. * @name module:/zrender/Element#ignore
  4039. * @type {boolean}
  4040. * @default false
  4041. */
  4042. ignore: false,
  4043. /**
  4044. * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪
  4045. * 该路径会继承被裁减对象的变换
  4046. * @type {module:zrender/graphic/Path}
  4047. * @see http://www.w3.org/TR/2dcontext/#clipping-region
  4048. * @readOnly
  4049. */
  4050. clipPath: null,
  4051. /**
  4052. * 是否是 Group
  4053. * @type {boolean}
  4054. */
  4055. isGroup: false,
  4056. /**
  4057. * Drift element
  4058. * @param {number} dx dx on the global space
  4059. * @param {number} dy dy on the global space
  4060. */
  4061. drift: function (dx, dy) {
  4062. switch (this.draggable) {
  4063. case 'horizontal':
  4064. dy = 0;
  4065. break;
  4066. case 'vertical':
  4067. dx = 0;
  4068. break;
  4069. }
  4070. var m = this.transform;
  4071. if (!m) {
  4072. m = this.transform = [1, 0, 0, 1, 0, 0];
  4073. }
  4074. m[4] += dx;
  4075. m[5] += dy;
  4076. this.decomposeTransform();
  4077. this.dirty(false);
  4078. },
  4079. /**
  4080. * Hook before update
  4081. */
  4082. beforeUpdate: function () {},
  4083. /**
  4084. * Hook after update
  4085. */
  4086. afterUpdate: function () {},
  4087. /**
  4088. * Update each frame
  4089. */
  4090. update: function () {
  4091. this.updateTransform();
  4092. },
  4093. /**
  4094. * @param {Function} cb
  4095. * @param {} context
  4096. */
  4097. traverse: function (cb, context) {},
  4098. /**
  4099. * @protected
  4100. */
  4101. attrKV: function (key, value) {
  4102. if (key === 'position' || key === 'scale' || key === 'origin') {
  4103. // Copy the array
  4104. if (value) {
  4105. var target = this[key];
  4106. if (!target) {
  4107. target = this[key] = [];
  4108. }
  4109. target[0] = value[0];
  4110. target[1] = value[1];
  4111. }
  4112. }
  4113. else {
  4114. this[key] = value;
  4115. }
  4116. },
  4117. /**
  4118. * Hide the element
  4119. */
  4120. hide: function () {
  4121. this.ignore = true;
  4122. this.__zr && this.__zr.refresh();
  4123. },
  4124. /**
  4125. * Show the element
  4126. */
  4127. show: function () {
  4128. this.ignore = false;
  4129. this.__zr && this.__zr.refresh();
  4130. },
  4131. /**
  4132. * @param {string|Object} key
  4133. * @param {*} value
  4134. */
  4135. attr: function (key, value) {
  4136. if (typeof key === 'string') {
  4137. this.attrKV(key, value);
  4138. }
  4139. else if (isObject$1(key)) {
  4140. for (var name in key) {
  4141. if (key.hasOwnProperty(name)) {
  4142. this.attrKV(name, key[name]);
  4143. }
  4144. }
  4145. }
  4146. this.dirty(false);
  4147. return this;
  4148. },
  4149. /**
  4150. * @param {module:zrender/graphic/Path} clipPath
  4151. */
  4152. setClipPath: function (clipPath) {
  4153. var zr = this.__zr;
  4154. if (zr) {
  4155. clipPath.addSelfToZr(zr);
  4156. }
  4157. // Remove previous clip path
  4158. if (this.clipPath && this.clipPath !== clipPath) {
  4159. this.removeClipPath();
  4160. }
  4161. this.clipPath = clipPath;
  4162. clipPath.__zr = zr;
  4163. clipPath.__clipTarget = this;
  4164. this.dirty(false);
  4165. },
  4166. /**
  4167. */
  4168. removeClipPath: function () {
  4169. var clipPath = this.clipPath;
  4170. if (clipPath) {
  4171. if (clipPath.__zr) {
  4172. clipPath.removeSelfFromZr(clipPath.__zr);
  4173. }
  4174. clipPath.__zr = null;
  4175. clipPath.__clipTarget = null;
  4176. this.clipPath = null;
  4177. this.dirty(false);
  4178. }
  4179. },
  4180. /**
  4181. * Add self from zrender instance.
  4182. * Not recursively because it will be invoked when element added to storage.
  4183. * @param {module:zrender/ZRender} zr
  4184. */
  4185. addSelfToZr: function (zr) {
  4186. this.__zr = zr;
  4187. // 添加动画
  4188. var animators = this.animators;
  4189. if (animators) {
  4190. for (var i = 0; i < animators.length; i++) {
  4191. zr.animation.addAnimator(animators[i]);
  4192. }
  4193. }
  4194. if (this.clipPath) {
  4195. this.clipPath.addSelfToZr(zr);
  4196. }
  4197. },
  4198. /**
  4199. * Remove self from zrender instance.
  4200. * Not recursively because it will be invoked when element added to storage.
  4201. * @param {module:zrender/ZRender} zr
  4202. */
  4203. removeSelfFromZr: function (zr) {
  4204. this.__zr = null;
  4205. // 移除动画
  4206. var animators = this.animators;
  4207. if (animators) {
  4208. for (var i = 0; i < animators.length; i++) {
  4209. zr.animation.removeAnimator(animators[i]);
  4210. }
  4211. }
  4212. if (this.clipPath) {
  4213. this.clipPath.removeSelfFromZr(zr);
  4214. }
  4215. }
  4216. };
  4217. mixin(Element, Animatable);
  4218. mixin(Element, Transformable);
  4219. mixin(Element, Eventful);
  4220. /**
  4221. * @module echarts/core/BoundingRect
  4222. */
  4223. var v2ApplyTransform = applyTransform;
  4224. var mathMin = Math.min;
  4225. var mathMax = Math.max;
  4226. /**
  4227. * @alias module:echarts/core/BoundingRect
  4228. */
  4229. function BoundingRect(x, y, width, height) {
  4230. if (width < 0) {
  4231. x = x + width;
  4232. width = -width;
  4233. }
  4234. if (height < 0) {
  4235. y = y + height;
  4236. height = -height;
  4237. }
  4238. /**
  4239. * @type {number}
  4240. */
  4241. this.x = x;
  4242. /**
  4243. * @type {number}
  4244. */
  4245. this.y = y;
  4246. /**
  4247. * @type {number}
  4248. */
  4249. this.width = width;
  4250. /**
  4251. * @type {number}
  4252. */
  4253. this.height = height;
  4254. }
  4255. BoundingRect.prototype = {
  4256. constructor: BoundingRect,
  4257. /**
  4258. * @param {module:echarts/core/BoundingRect} other
  4259. */
  4260. union: function (other) {
  4261. var x = mathMin(other.x, this.x);
  4262. var y = mathMin(other.y, this.y);
  4263. this.width = mathMax(
  4264. other.x + other.width,
  4265. this.x + this.width
  4266. ) - x;
  4267. this.height = mathMax(
  4268. other.y + other.height,
  4269. this.y + this.height
  4270. ) - y;
  4271. this.x = x;
  4272. this.y = y;
  4273. },
  4274. /**
  4275. * @param {Array.<number>} m
  4276. * @methods
  4277. */
  4278. applyTransform: (function () {
  4279. var lt = [];
  4280. var rb = [];
  4281. var lb = [];
  4282. var rt = [];
  4283. return function (m) {
  4284. // In case usage like this
  4285. // el.getBoundingRect().applyTransform(el.transform)
  4286. // And element has no transform
  4287. if (!m) {
  4288. return;
  4289. }
  4290. lt[0] = lb[0] = this.x;
  4291. lt[1] = rt[1] = this.y;
  4292. rb[0] = rt[0] = this.x + this.width;
  4293. rb[1] = lb[1] = this.y + this.height;
  4294. v2ApplyTransform(lt, lt, m);
  4295. v2ApplyTransform(rb, rb, m);
  4296. v2ApplyTransform(lb, lb, m);
  4297. v2ApplyTransform(rt, rt, m);
  4298. this.x = mathMin(lt[0], rb[0], lb[0], rt[0]);
  4299. this.y = mathMin(lt[1], rb[1], lb[1], rt[1]);
  4300. var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]);
  4301. var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]);
  4302. this.width = maxX - this.x;
  4303. this.height = maxY - this.y;
  4304. };
  4305. })(),
  4306. /**
  4307. * Calculate matrix of transforming from self to target rect
  4308. * @param {module:zrender/core/BoundingRect} b
  4309. * @return {Array.<number>}
  4310. */
  4311. calculateTransform: function (b) {
  4312. var a = this;
  4313. var sx = b.width / a.width;
  4314. var sy = b.height / a.height;
  4315. var m = create$1();
  4316. // 矩阵右乘
  4317. translate(m, m, [-a.x, -a.y]);
  4318. scale$1(m, m, [sx, sy]);
  4319. translate(m, m, [b.x, b.y]);
  4320. return m;
  4321. },
  4322. /**
  4323. * @param {(module:echarts/core/BoundingRect|Object)} b
  4324. * @return {boolean}
  4325. */
  4326. intersect: function (b) {
  4327. if (!b) {
  4328. return false;
  4329. }
  4330. if (!(b instanceof BoundingRect)) {
  4331. // Normalize negative width/height.
  4332. b = BoundingRect.create(b);
  4333. }
  4334. var a = this;
  4335. var ax0 = a.x;
  4336. var ax1 = a.x + a.width;
  4337. var ay0 = a.y;
  4338. var ay1 = a.y + a.height;
  4339. var bx0 = b.x;
  4340. var bx1 = b.x + b.width;
  4341. var by0 = b.y;
  4342. var by1 = b.y + b.height;
  4343. return ! (ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  4344. },
  4345. contain: function (x, y) {
  4346. var rect = this;
  4347. return x >= rect.x
  4348. && x <= (rect.x + rect.width)
  4349. && y >= rect.y
  4350. && y <= (rect.y + rect.height);
  4351. },
  4352. /**
  4353. * @return {module:echarts/core/BoundingRect}
  4354. */
  4355. clone: function () {
  4356. return new BoundingRect(this.x, this.y, this.width, this.height);
  4357. },
  4358. /**
  4359. * Copy from another rect
  4360. */
  4361. copy: function (other) {
  4362. this.x = other.x;
  4363. this.y = other.y;
  4364. this.width = other.width;
  4365. this.height = other.height;
  4366. },
  4367. plain: function () {
  4368. return {
  4369. x: this.x,
  4370. y: this.y,
  4371. width: this.width,
  4372. height: this.height
  4373. };
  4374. }
  4375. };
  4376. /**
  4377. * @param {Object|module:zrender/core/BoundingRect} rect
  4378. * @param {number} rect.x
  4379. * @param {number} rect.y
  4380. * @param {number} rect.width
  4381. * @param {number} rect.height
  4382. * @return {module:zrender/core/BoundingRect}
  4383. */
  4384. BoundingRect.create = function (rect) {
  4385. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  4386. };
  4387. /**
  4388. * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上
  4389. * @module zrender/graphic/Group
  4390. * @example
  4391. * var Group = require('zrender/container/Group');
  4392. * var Circle = require('zrender/graphic/shape/Circle');
  4393. * var g = new Group();
  4394. * g.position[0] = 100;
  4395. * g.position[1] = 100;
  4396. * g.add(new Circle({
  4397. * style: {
  4398. * x: 100,
  4399. * y: 100,
  4400. * r: 20,
  4401. * }
  4402. * }));
  4403. * zr.add(g);
  4404. */
  4405. /**
  4406. * @alias module:zrender/graphic/Group
  4407. * @constructor
  4408. * @extends module:zrender/mixin/Transformable
  4409. * @extends module:zrender/mixin/Eventful
  4410. */
  4411. var Group = function (opts) {
  4412. opts = opts || {};
  4413. Element.call(this, opts);
  4414. for (var key in opts) {
  4415. if (opts.hasOwnProperty(key)) {
  4416. this[key] = opts[key];
  4417. }
  4418. }
  4419. this._children = [];
  4420. this.__storage = null;
  4421. this.__dirty = true;
  4422. };
  4423. Group.prototype = {
  4424. constructor: Group,
  4425. isGroup: true,
  4426. /**
  4427. * @type {string}
  4428. */
  4429. type: 'group',
  4430. /**
  4431. * 所有子孙元素是否响应鼠标事件
  4432. * @name module:/zrender/container/Group#silent
  4433. * @type {boolean}
  4434. * @default false
  4435. */
  4436. silent: false,
  4437. /**
  4438. * @return {Array.<module:zrender/Element>}
  4439. */
  4440. children: function () {
  4441. return this._children.slice();
  4442. },
  4443. /**
  4444. * 获取指定 index 的儿子节点
  4445. * @param {number} idx
  4446. * @return {module:zrender/Element}
  4447. */
  4448. childAt: function (idx) {
  4449. return this._children[idx];
  4450. },
  4451. /**
  4452. * 获取指定名字的儿子节点
  4453. * @param {string} name
  4454. * @return {module:zrender/Element}
  4455. */
  4456. childOfName: function (name) {
  4457. var children = this._children;
  4458. for (var i = 0; i < children.length; i++) {
  4459. if (children[i].name === name) {
  4460. return children[i];
  4461. }
  4462. }
  4463. },
  4464. /**
  4465. * @return {number}
  4466. */
  4467. childCount: function () {
  4468. return this._children.length;
  4469. },
  4470. /**
  4471. * 添加子节点到最后
  4472. * @param {module:zrender/Element} child
  4473. */
  4474. add: function (child) {
  4475. if (child && child !== this && child.parent !== this) {
  4476. this._children.push(child);
  4477. this._doAdd(child);
  4478. }
  4479. return this;
  4480. },
  4481. /**
  4482. * 添加子节点在 nextSibling 之前
  4483. * @param {module:zrender/Element} child
  4484. * @param {module:zrender/Element} nextSibling
  4485. */
  4486. addBefore: function (child, nextSibling) {
  4487. if (child && child !== this && child.parent !== this
  4488. && nextSibling && nextSibling.parent === this) {
  4489. var children = this._children;
  4490. var idx = children.indexOf(nextSibling);
  4491. if (idx >= 0) {
  4492. children.splice(idx, 0, child);
  4493. this._doAdd(child);
  4494. }
  4495. }
  4496. return this;
  4497. },
  4498. _doAdd: function (child) {
  4499. if (child.parent) {
  4500. child.parent.remove(child);
  4501. }
  4502. child.parent = this;
  4503. var storage = this.__storage;
  4504. var zr = this.__zr;
  4505. if (storage && storage !== child.__storage) {
  4506. storage.addToStorage(child);
  4507. if (child instanceof Group) {
  4508. child.addChildrenToStorage(storage);
  4509. }
  4510. }
  4511. zr && zr.refresh();
  4512. },
  4513. /**
  4514. * 移除子节点
  4515. * @param {module:zrender/Element} child
  4516. */
  4517. remove: function (child) {
  4518. var zr = this.__zr;
  4519. var storage = this.__storage;
  4520. var children = this._children;
  4521. var idx = indexOf(children, child);
  4522. if (idx < 0) {
  4523. return this;
  4524. }
  4525. children.splice(idx, 1);
  4526. child.parent = null;
  4527. if (storage) {
  4528. storage.delFromStorage(child);
  4529. if (child instanceof Group) {
  4530. child.delChildrenFromStorage(storage);
  4531. }
  4532. }
  4533. zr && zr.refresh();
  4534. return this;
  4535. },
  4536. /**
  4537. * 移除所有子节点
  4538. */
  4539. removeAll: function () {
  4540. var children = this._children;
  4541. var storage = this.__storage;
  4542. var child;
  4543. var i;
  4544. for (i = 0; i < children.length; i++) {
  4545. child = children[i];
  4546. if (storage) {
  4547. storage.delFromStorage(child);
  4548. if (child instanceof Group) {
  4549. child.delChildrenFromStorage(storage);
  4550. }
  4551. }
  4552. child.parent = null;
  4553. }
  4554. children.length = 0;
  4555. return this;
  4556. },
  4557. /**
  4558. * 遍历所有子节点
  4559. * @param {Function} cb
  4560. * @param {} context
  4561. */
  4562. eachChild: function (cb, context) {
  4563. var children = this._children;
  4564. for (var i = 0; i < children.length; i++) {
  4565. var child = children[i];
  4566. cb.call(context, child, i);
  4567. }
  4568. return this;
  4569. },
  4570. /**
  4571. * 深度优先遍历所有子孙节点
  4572. * @param {Function} cb
  4573. * @param {} context
  4574. */
  4575. traverse: function (cb, context) {
  4576. for (var i = 0; i < this._children.length; i++) {
  4577. var child = this._children[i];
  4578. cb.call(context, child);
  4579. if (child.type === 'group') {
  4580. child.traverse(cb, context);
  4581. }
  4582. }
  4583. return this;
  4584. },
  4585. addChildrenToStorage: function (storage) {
  4586. for (var i = 0; i < this._children.length; i++) {
  4587. var child = this._children[i];
  4588. storage.addToStorage(child);
  4589. if (child instanceof Group) {
  4590. child.addChildrenToStorage(storage);
  4591. }
  4592. }
  4593. },
  4594. delChildrenFromStorage: function (storage) {
  4595. for (var i = 0; i < this._children.length; i++) {
  4596. var child = this._children[i];
  4597. storage.delFromStorage(child);
  4598. if (child instanceof Group) {
  4599. child.delChildrenFromStorage(storage);
  4600. }
  4601. }
  4602. },
  4603. dirty: function () {
  4604. this.__dirty = true;
  4605. this.__zr && this.__zr.refresh();
  4606. return this;
  4607. },
  4608. /**
  4609. * @return {module:zrender/core/BoundingRect}
  4610. */
  4611. getBoundingRect: function (includeChildren) {
  4612. // TODO Caching
  4613. var rect = null;
  4614. var tmpRect = new BoundingRect(0, 0, 0, 0);
  4615. var children = includeChildren || this._children;
  4616. var tmpMat = [];
  4617. for (var i = 0; i < children.length; i++) {
  4618. var child = children[i];
  4619. if (child.ignore || child.invisible) {
  4620. continue;
  4621. }
  4622. var childRect = child.getBoundingRect();
  4623. var transform = child.getLocalTransform(tmpMat);
  4624. // TODO
  4625. // The boundingRect cacluated by transforming original
  4626. // rect may be bigger than the actual bundingRect when rotation
  4627. // is used. (Consider a circle rotated aginst its center, where
  4628. // the actual boundingRect should be the same as that not be
  4629. // rotated.) But we can not find better approach to calculate
  4630. // actual boundingRect yet, considering performance.
  4631. if (transform) {
  4632. tmpRect.copy(childRect);
  4633. tmpRect.applyTransform(transform);
  4634. rect = rect || tmpRect.clone();
  4635. rect.union(tmpRect);
  4636. }
  4637. else {
  4638. rect = rect || childRect.clone();
  4639. rect.union(childRect);
  4640. }
  4641. }
  4642. return rect || tmpRect;
  4643. }
  4644. };
  4645. inherits(Group, Element);
  4646. // https://github.com/mziccard/node-timsort
  4647. var DEFAULT_MIN_MERGE = 32;
  4648. var DEFAULT_MIN_GALLOPING = 7;
  4649. function minRunLength(n) {
  4650. var r = 0;
  4651. while (n >= DEFAULT_MIN_MERGE) {
  4652. r |= n & 1;
  4653. n >>= 1;
  4654. }
  4655. return n + r;
  4656. }
  4657. function makeAscendingRun(array, lo, hi, compare) {
  4658. var runHi = lo + 1;
  4659. if (runHi === hi) {
  4660. return 1;
  4661. }
  4662. if (compare(array[runHi++], array[lo]) < 0) {
  4663. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  4664. runHi++;
  4665. }
  4666. reverseRun(array, lo, runHi);
  4667. }
  4668. else {
  4669. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  4670. runHi++;
  4671. }
  4672. }
  4673. return runHi - lo;
  4674. }
  4675. function reverseRun(array, lo, hi) {
  4676. hi--;
  4677. while (lo < hi) {
  4678. var t = array[lo];
  4679. array[lo++] = array[hi];
  4680. array[hi--] = t;
  4681. }
  4682. }
  4683. function binaryInsertionSort(array, lo, hi, start, compare) {
  4684. if (start === lo) {
  4685. start++;
  4686. }
  4687. for (; start < hi; start++) {
  4688. var pivot = array[start];
  4689. var left = lo;
  4690. var right = start;
  4691. var mid;
  4692. while (left < right) {
  4693. mid = left + right >>> 1;
  4694. if (compare(pivot, array[mid]) < 0) {
  4695. right = mid;
  4696. }
  4697. else {
  4698. left = mid + 1;
  4699. }
  4700. }
  4701. var n = start - left;
  4702. switch (n) {
  4703. case 3:
  4704. array[left + 3] = array[left + 2];
  4705. case 2:
  4706. array[left + 2] = array[left + 1];
  4707. case 1:
  4708. array[left + 1] = array[left];
  4709. break;
  4710. default:
  4711. while (n > 0) {
  4712. array[left + n] = array[left + n - 1];
  4713. n--;
  4714. }
  4715. }
  4716. array[left] = pivot;
  4717. }
  4718. }
  4719. function gallopLeft(value, array, start, length, hint, compare) {
  4720. var lastOffset = 0;
  4721. var maxOffset = 0;
  4722. var offset = 1;
  4723. if (compare(value, array[start + hint]) > 0) {
  4724. maxOffset = length - hint;
  4725. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  4726. lastOffset = offset;
  4727. offset = (offset << 1) + 1;
  4728. if (offset <= 0) {
  4729. offset = maxOffset;
  4730. }
  4731. }
  4732. if (offset > maxOffset) {
  4733. offset = maxOffset;
  4734. }
  4735. lastOffset += hint;
  4736. offset += hint;
  4737. }
  4738. else {
  4739. maxOffset = hint + 1;
  4740. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  4741. lastOffset = offset;
  4742. offset = (offset << 1) + 1;
  4743. if (offset <= 0) {
  4744. offset = maxOffset;
  4745. }
  4746. }
  4747. if (offset > maxOffset) {
  4748. offset = maxOffset;
  4749. }
  4750. var tmp = lastOffset;
  4751. lastOffset = hint - offset;
  4752. offset = hint - tmp;
  4753. }
  4754. lastOffset++;
  4755. while (lastOffset < offset) {
  4756. var m = lastOffset + (offset - lastOffset >>> 1);
  4757. if (compare(value, array[start + m]) > 0) {
  4758. lastOffset = m + 1;
  4759. }
  4760. else {
  4761. offset = m;
  4762. }
  4763. }
  4764. return offset;
  4765. }
  4766. function gallopRight(value, array, start, length, hint, compare) {
  4767. var lastOffset = 0;
  4768. var maxOffset = 0;
  4769. var offset = 1;
  4770. if (compare(value, array[start + hint]) < 0) {
  4771. maxOffset = hint + 1;
  4772. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  4773. lastOffset = offset;
  4774. offset = (offset << 1) + 1;
  4775. if (offset <= 0) {
  4776. offset = maxOffset;
  4777. }
  4778. }
  4779. if (offset > maxOffset) {
  4780. offset = maxOffset;
  4781. }
  4782. var tmp = lastOffset;
  4783. lastOffset = hint - offset;
  4784. offset = hint - tmp;
  4785. }
  4786. else {
  4787. maxOffset = length - hint;
  4788. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  4789. lastOffset = offset;
  4790. offset = (offset << 1) + 1;
  4791. if (offset <= 0) {
  4792. offset = maxOffset;
  4793. }
  4794. }
  4795. if (offset > maxOffset) {
  4796. offset = maxOffset;
  4797. }
  4798. lastOffset += hint;
  4799. offset += hint;
  4800. }
  4801. lastOffset++;
  4802. while (lastOffset < offset) {
  4803. var m = lastOffset + (offset - lastOffset >>> 1);
  4804. if (compare(value, array[start + m]) < 0) {
  4805. offset = m;
  4806. }
  4807. else {
  4808. lastOffset = m + 1;
  4809. }
  4810. }
  4811. return offset;
  4812. }
  4813. function TimSort(array, compare) {
  4814. var minGallop = DEFAULT_MIN_GALLOPING;
  4815. var runStart;
  4816. var runLength;
  4817. var stackSize = 0;
  4818. var tmp = [];
  4819. runStart = [];
  4820. runLength = [];
  4821. function pushRun(_runStart, _runLength) {
  4822. runStart[stackSize] = _runStart;
  4823. runLength[stackSize] = _runLength;
  4824. stackSize += 1;
  4825. }
  4826. function mergeRuns() {
  4827. while (stackSize > 1) {
  4828. var n = stackSize - 2;
  4829. if (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1] || n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1]) {
  4830. if (runLength[n - 1] < runLength[n + 1]) {
  4831. n--;
  4832. }
  4833. }
  4834. else if (runLength[n] > runLength[n + 1]) {
  4835. break;
  4836. }
  4837. mergeAt(n);
  4838. }
  4839. }
  4840. function forceMergeRuns() {
  4841. while (stackSize > 1) {
  4842. var n = stackSize - 2;
  4843. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  4844. n--;
  4845. }
  4846. mergeAt(n);
  4847. }
  4848. }
  4849. function mergeAt(i) {
  4850. var start1 = runStart[i];
  4851. var length1 = runLength[i];
  4852. var start2 = runStart[i + 1];
  4853. var length2 = runLength[i + 1];
  4854. runLength[i] = length1 + length2;
  4855. if (i === stackSize - 3) {
  4856. runStart[i + 1] = runStart[i + 2];
  4857. runLength[i + 1] = runLength[i + 2];
  4858. }
  4859. stackSize--;
  4860. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  4861. start1 += k;
  4862. length1 -= k;
  4863. if (length1 === 0) {
  4864. return;
  4865. }
  4866. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  4867. if (length2 === 0) {
  4868. return;
  4869. }
  4870. if (length1 <= length2) {
  4871. mergeLow(start1, length1, start2, length2);
  4872. }
  4873. else {
  4874. mergeHigh(start1, length1, start2, length2);
  4875. }
  4876. }
  4877. function mergeLow(start1, length1, start2, length2) {
  4878. var i = 0;
  4879. for (i = 0; i < length1; i++) {
  4880. tmp[i] = array[start1 + i];
  4881. }
  4882. var cursor1 = 0;
  4883. var cursor2 = start2;
  4884. var dest = start1;
  4885. array[dest++] = array[cursor2++];
  4886. if (--length2 === 0) {
  4887. for (i = 0; i < length1; i++) {
  4888. array[dest + i] = tmp[cursor1 + i];
  4889. }
  4890. return;
  4891. }
  4892. if (length1 === 1) {
  4893. for (i = 0; i < length2; i++) {
  4894. array[dest + i] = array[cursor2 + i];
  4895. }
  4896. array[dest + length2] = tmp[cursor1];
  4897. return;
  4898. }
  4899. var _minGallop = minGallop;
  4900. var count1, count2, exit;
  4901. while (1) {
  4902. count1 = 0;
  4903. count2 = 0;
  4904. exit = false;
  4905. do {
  4906. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  4907. array[dest++] = array[cursor2++];
  4908. count2++;
  4909. count1 = 0;
  4910. if (--length2 === 0) {
  4911. exit = true;
  4912. break;
  4913. }
  4914. }
  4915. else {
  4916. array[dest++] = tmp[cursor1++];
  4917. count1++;
  4918. count2 = 0;
  4919. if (--length1 === 1) {
  4920. exit = true;
  4921. break;
  4922. }
  4923. }
  4924. } while ((count1 | count2) < _minGallop);
  4925. if (exit) {
  4926. break;
  4927. }
  4928. do {
  4929. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  4930. if (count1 !== 0) {
  4931. for (i = 0; i < count1; i++) {
  4932. array[dest + i] = tmp[cursor1 + i];
  4933. }
  4934. dest += count1;
  4935. cursor1 += count1;
  4936. length1 -= count1;
  4937. if (length1 <= 1) {
  4938. exit = true;
  4939. break;
  4940. }
  4941. }
  4942. array[dest++] = array[cursor2++];
  4943. if (--length2 === 0) {
  4944. exit = true;
  4945. break;
  4946. }
  4947. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  4948. if (count2 !== 0) {
  4949. for (i = 0; i < count2; i++) {
  4950. array[dest + i] = array[cursor2 + i];
  4951. }
  4952. dest += count2;
  4953. cursor2 += count2;
  4954. length2 -= count2;
  4955. if (length2 === 0) {
  4956. exit = true;
  4957. break;
  4958. }
  4959. }
  4960. array[dest++] = tmp[cursor1++];
  4961. if (--length1 === 1) {
  4962. exit = true;
  4963. break;
  4964. }
  4965. _minGallop--;
  4966. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  4967. if (exit) {
  4968. break;
  4969. }
  4970. if (_minGallop < 0) {
  4971. _minGallop = 0;
  4972. }
  4973. _minGallop += 2;
  4974. }
  4975. minGallop = _minGallop;
  4976. minGallop < 1 && (minGallop = 1);
  4977. if (length1 === 1) {
  4978. for (i = 0; i < length2; i++) {
  4979. array[dest + i] = array[cursor2 + i];
  4980. }
  4981. array[dest + length2] = tmp[cursor1];
  4982. }
  4983. else if (length1 === 0) {
  4984. throw new Error();
  4985. // throw new Error('mergeLow preconditions were not respected');
  4986. }
  4987. else {
  4988. for (i = 0; i < length1; i++) {
  4989. array[dest + i] = tmp[cursor1 + i];
  4990. }
  4991. }
  4992. }
  4993. function mergeHigh (start1, length1, start2, length2) {
  4994. var i = 0;
  4995. for (i = 0; i < length2; i++) {
  4996. tmp[i] = array[start2 + i];
  4997. }
  4998. var cursor1 = start1 + length1 - 1;
  4999. var cursor2 = length2 - 1;
  5000. var dest = start2 + length2 - 1;
  5001. var customCursor = 0;
  5002. var customDest = 0;
  5003. array[dest--] = array[cursor1--];
  5004. if (--length1 === 0) {
  5005. customCursor = dest - (length2 - 1);
  5006. for (i = 0; i < length2; i++) {
  5007. array[customCursor + i] = tmp[i];
  5008. }
  5009. return;
  5010. }
  5011. if (length2 === 1) {
  5012. dest -= length1;
  5013. cursor1 -= length1;
  5014. customDest = dest + 1;
  5015. customCursor = cursor1 + 1;
  5016. for (i = length1 - 1; i >= 0; i--) {
  5017. array[customDest + i] = array[customCursor + i];
  5018. }
  5019. array[dest] = tmp[cursor2];
  5020. return;
  5021. }
  5022. var _minGallop = minGallop;
  5023. while (true) {
  5024. var count1 = 0;
  5025. var count2 = 0;
  5026. var exit = false;
  5027. do {
  5028. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  5029. array[dest--] = array[cursor1--];
  5030. count1++;
  5031. count2 = 0;
  5032. if (--length1 === 0) {
  5033. exit = true;
  5034. break;
  5035. }
  5036. }
  5037. else {
  5038. array[dest--] = tmp[cursor2--];
  5039. count2++;
  5040. count1 = 0;
  5041. if (--length2 === 1) {
  5042. exit = true;
  5043. break;
  5044. }
  5045. }
  5046. } while ((count1 | count2) < _minGallop);
  5047. if (exit) {
  5048. break;
  5049. }
  5050. do {
  5051. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  5052. if (count1 !== 0) {
  5053. dest -= count1;
  5054. cursor1 -= count1;
  5055. length1 -= count1;
  5056. customDest = dest + 1;
  5057. customCursor = cursor1 + 1;
  5058. for (i = count1 - 1; i >= 0; i--) {
  5059. array[customDest + i] = array[customCursor + i];
  5060. }
  5061. if (length1 === 0) {
  5062. exit = true;
  5063. break;
  5064. }
  5065. }
  5066. array[dest--] = tmp[cursor2--];
  5067. if (--length2 === 1) {
  5068. exit = true;
  5069. break;
  5070. }
  5071. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  5072. if (count2 !== 0) {
  5073. dest -= count2;
  5074. cursor2 -= count2;
  5075. length2 -= count2;
  5076. customDest = dest + 1;
  5077. customCursor = cursor2 + 1;
  5078. for (i = 0; i < count2; i++) {
  5079. array[customDest + i] = tmp[customCursor + i];
  5080. }
  5081. if (length2 <= 1) {
  5082. exit = true;
  5083. break;
  5084. }
  5085. }
  5086. array[dest--] = array[cursor1--];
  5087. if (--length1 === 0) {
  5088. exit = true;
  5089. break;
  5090. }
  5091. _minGallop--;
  5092. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5093. if (exit) {
  5094. break;
  5095. }
  5096. if (_minGallop < 0) {
  5097. _minGallop = 0;
  5098. }
  5099. _minGallop += 2;
  5100. }
  5101. minGallop = _minGallop;
  5102. if (minGallop < 1) {
  5103. minGallop = 1;
  5104. }
  5105. if (length2 === 1) {
  5106. dest -= length1;
  5107. cursor1 -= length1;
  5108. customDest = dest + 1;
  5109. customCursor = cursor1 + 1;
  5110. for (i = length1 - 1; i >= 0; i--) {
  5111. array[customDest + i] = array[customCursor + i];
  5112. }
  5113. array[dest] = tmp[cursor2];
  5114. }
  5115. else if (length2 === 0) {
  5116. throw new Error();
  5117. // throw new Error('mergeHigh preconditions were not respected');
  5118. }
  5119. else {
  5120. customCursor = dest - (length2 - 1);
  5121. for (i = 0; i < length2; i++) {
  5122. array[customCursor + i] = tmp[i];
  5123. }
  5124. }
  5125. }
  5126. this.mergeRuns = mergeRuns;
  5127. this.forceMergeRuns = forceMergeRuns;
  5128. this.pushRun = pushRun;
  5129. }
  5130. function sort(array, compare, lo, hi) {
  5131. if (!lo) {
  5132. lo = 0;
  5133. }
  5134. if (!hi) {
  5135. hi = array.length;
  5136. }
  5137. var remaining = hi - lo;
  5138. if (remaining < 2) {
  5139. return;
  5140. }
  5141. var runLength = 0;
  5142. if (remaining < DEFAULT_MIN_MERGE) {
  5143. runLength = makeAscendingRun(array, lo, hi, compare);
  5144. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5145. return;
  5146. }
  5147. var ts = new TimSort(array, compare);
  5148. var minRun = minRunLength(remaining);
  5149. do {
  5150. runLength = makeAscendingRun(array, lo, hi, compare);
  5151. if (runLength < minRun) {
  5152. var force = remaining;
  5153. if (force > minRun) {
  5154. force = minRun;
  5155. }
  5156. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5157. runLength = force;
  5158. }
  5159. ts.pushRun(lo, runLength);
  5160. ts.mergeRuns();
  5161. remaining -= runLength;
  5162. lo += runLength;
  5163. } while (remaining !== 0);
  5164. ts.forceMergeRuns();
  5165. }
  5166. // Use timsort because in most case elements are partially sorted
  5167. // https://jsfiddle.net/pissang/jr4x7mdm/8/
  5168. function shapeCompareFunc(a, b) {
  5169. if (a.zlevel === b.zlevel) {
  5170. if (a.z === b.z) {
  5171. // if (a.z2 === b.z2) {
  5172. // // FIXME Slow has renderidx compare
  5173. // // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement
  5174. // // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012
  5175. // return a.__renderidx - b.__renderidx;
  5176. // }
  5177. return a.z2 - b.z2;
  5178. }
  5179. return a.z - b.z;
  5180. }
  5181. return a.zlevel - b.zlevel;
  5182. }
  5183. /**
  5184. * 内容仓库 (M)
  5185. * @alias module:zrender/Storage
  5186. * @constructor
  5187. */
  5188. var Storage = function () { // jshint ignore:line
  5189. this._roots = [];
  5190. this._displayList = [];
  5191. this._displayListLen = 0;
  5192. };
  5193. Storage.prototype = {
  5194. constructor: Storage,
  5195. /**
  5196. * @param {Function} cb
  5197. *
  5198. */
  5199. traverse: function (cb, context) {
  5200. for (var i = 0; i < this._roots.length; i++) {
  5201. this._roots[i].traverse(cb, context);
  5202. }
  5203. },
  5204. /**
  5205. * 返回所有图形的绘制队列
  5206. * @param {boolean} [update=false] 是否在返回前更新该数组
  5207. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效
  5208. *
  5209. * 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList}
  5210. * @return {Array.<module:zrender/graphic/Displayable>}
  5211. */
  5212. getDisplayList: function (update, includeIgnore) {
  5213. includeIgnore = includeIgnore || false;
  5214. if (update) {
  5215. this.updateDisplayList(includeIgnore);
  5216. }
  5217. return this._displayList;
  5218. },
  5219. /**
  5220. * 更新图形的绘制队列。
  5221. * 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,
  5222. * 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列
  5223. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组
  5224. */
  5225. updateDisplayList: function (includeIgnore) {
  5226. this._displayListLen = 0;
  5227. var roots = this._roots;
  5228. var displayList = this._displayList;
  5229. for (var i = 0, len = roots.length; i < len; i++) {
  5230. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  5231. }
  5232. displayList.length = this._displayListLen;
  5233. env$1.canvasSupported && sort(displayList, shapeCompareFunc);
  5234. },
  5235. _updateAndAddDisplayable: function (el, clipPaths, includeIgnore) {
  5236. if (el.ignore && !includeIgnore) {
  5237. return;
  5238. }
  5239. el.beforeUpdate();
  5240. if (el.__dirty) {
  5241. el.update();
  5242. }
  5243. el.afterUpdate();
  5244. var userSetClipPath = el.clipPath;
  5245. if (userSetClipPath) {
  5246. // FIXME 效率影响
  5247. if (clipPaths) {
  5248. clipPaths = clipPaths.slice();
  5249. }
  5250. else {
  5251. clipPaths = [];
  5252. }
  5253. var currentClipPath = userSetClipPath;
  5254. var parentClipPath = el;
  5255. // Recursively add clip path
  5256. while (currentClipPath) {
  5257. // clipPath 的变换是基于使用这个 clipPath 的元素
  5258. currentClipPath.parent = parentClipPath;
  5259. currentClipPath.updateTransform();
  5260. clipPaths.push(currentClipPath);
  5261. parentClipPath = currentClipPath;
  5262. currentClipPath = currentClipPath.clipPath;
  5263. }
  5264. }
  5265. if (el.isGroup) {
  5266. var children = el._children;
  5267. for (var i = 0; i < children.length; i++) {
  5268. var child = children[i];
  5269. // Force to mark as dirty if group is dirty
  5270. // FIXME __dirtyPath ?
  5271. if (el.__dirty) {
  5272. child.__dirty = true;
  5273. }
  5274. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  5275. }
  5276. // Mark group clean here
  5277. el.__dirty = false;
  5278. }
  5279. else {
  5280. el.__clipPaths = clipPaths;
  5281. this._displayList[this._displayListLen++] = el;
  5282. }
  5283. },
  5284. /**
  5285. * 添加图形(Shape)或者组(Group)到根节点
  5286. * @param {module:zrender/Element} el
  5287. */
  5288. addRoot: function (el) {
  5289. if (el.__storage === this) {
  5290. return;
  5291. }
  5292. if (el instanceof Group) {
  5293. el.addChildrenToStorage(this);
  5294. }
  5295. this.addToStorage(el);
  5296. this._roots.push(el);
  5297. },
  5298. /**
  5299. * 删除指定的图形(Shape)或者组(Group)
  5300. * @param {string|Array.<string>} [el] 如果为空清空整个Storage
  5301. */
  5302. delRoot: function (el) {
  5303. if (el == null) {
  5304. // 不指定el清空
  5305. for (var i = 0; i < this._roots.length; i++) {
  5306. var root = this._roots[i];
  5307. if (root instanceof Group) {
  5308. root.delChildrenFromStorage(this);
  5309. }
  5310. }
  5311. this._roots = [];
  5312. this._displayList = [];
  5313. this._displayListLen = 0;
  5314. return;
  5315. }
  5316. if (el instanceof Array) {
  5317. for (var i = 0, l = el.length; i < l; i++) {
  5318. this.delRoot(el[i]);
  5319. }
  5320. return;
  5321. }
  5322. var idx = indexOf(this._roots, el);
  5323. if (idx >= 0) {
  5324. this.delFromStorage(el);
  5325. this._roots.splice(idx, 1);
  5326. if (el instanceof Group) {
  5327. el.delChildrenFromStorage(this);
  5328. }
  5329. }
  5330. },
  5331. addToStorage: function (el) {
  5332. if (el) {
  5333. el.__storage = this;
  5334. el.dirty(false);
  5335. }
  5336. return this;
  5337. },
  5338. delFromStorage: function (el) {
  5339. if (el) {
  5340. el.__storage = null;
  5341. }
  5342. return this;
  5343. },
  5344. /**
  5345. * 清空并且释放Storage
  5346. */
  5347. dispose: function () {
  5348. this._renderList =
  5349. this._roots = null;
  5350. },
  5351. displayableSortFunc: shapeCompareFunc
  5352. };
  5353. var SHADOW_PROPS = {
  5354. 'shadowBlur': 1,
  5355. 'shadowOffsetX': 1,
  5356. 'shadowOffsetY': 1,
  5357. 'textShadowBlur': 1,
  5358. 'textShadowOffsetX': 1,
  5359. 'textShadowOffsetY': 1,
  5360. 'textBoxShadowBlur': 1,
  5361. 'textBoxShadowOffsetX': 1,
  5362. 'textBoxShadowOffsetY': 1
  5363. };
  5364. var fixShadow = function (ctx, propName, value) {
  5365. if (SHADOW_PROPS.hasOwnProperty(propName)) {
  5366. return value *= ctx.dpr;
  5367. }
  5368. return value;
  5369. };
  5370. var STYLE_COMMON_PROPS = [
  5371. ['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'],
  5372. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  5373. ];
  5374. // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
  5375. // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
  5376. var Style = function (opts, host) {
  5377. this.extendFrom(opts, false);
  5378. this.host = host;
  5379. };
  5380. function createLinearGradient(ctx, obj, rect) {
  5381. var x = obj.x == null ? 0 : obj.x;
  5382. var x2 = obj.x2 == null ? 1 : obj.x2;
  5383. var y = obj.y == null ? 0 : obj.y;
  5384. var y2 = obj.y2 == null ? 0 : obj.y2;
  5385. if (!obj.global) {
  5386. x = x * rect.width + rect.x;
  5387. x2 = x2 * rect.width + rect.x;
  5388. y = y * rect.height + rect.y;
  5389. y2 = y2 * rect.height + rect.y;
  5390. }
  5391. // Fix NaN when rect is Infinity
  5392. x = isNaN(x) ? 0 : x;
  5393. x2 = isNaN(x2) ? 1 : x2;
  5394. y = isNaN(y) ? 0 : y;
  5395. y2 = isNaN(y2) ? 0 : y2;
  5396. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  5397. return canvasGradient;
  5398. }
  5399. function createRadialGradient(ctx, obj, rect) {
  5400. var width = rect.width;
  5401. var height = rect.height;
  5402. var min = Math.min(width, height);
  5403. var x = obj.x == null ? 0.5 : obj.x;
  5404. var y = obj.y == null ? 0.5 : obj.y;
  5405. var r = obj.r == null ? 0.5 : obj.r;
  5406. if (!obj.global) {
  5407. x = x * width + rect.x;
  5408. y = y * height + rect.y;
  5409. r = r * min;
  5410. }
  5411. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  5412. return canvasGradient;
  5413. }
  5414. Style.prototype = {
  5415. constructor: Style,
  5416. /**
  5417. * @type {module:zrender/graphic/Displayable}
  5418. */
  5419. host: null,
  5420. /**
  5421. * @type {string}
  5422. */
  5423. fill: '#000',
  5424. /**
  5425. * @type {string}
  5426. */
  5427. stroke: null,
  5428. /**
  5429. * @type {number}
  5430. */
  5431. opacity: 1,
  5432. /**
  5433. * @type {Array.<number>}
  5434. */
  5435. lineDash: null,
  5436. /**
  5437. * @type {number}
  5438. */
  5439. lineDashOffset: 0,
  5440. /**
  5441. * @type {number}
  5442. */
  5443. shadowBlur: 0,
  5444. /**
  5445. * @type {number}
  5446. */
  5447. shadowOffsetX: 0,
  5448. /**
  5449. * @type {number}
  5450. */
  5451. shadowOffsetY: 0,
  5452. /**
  5453. * @type {number}
  5454. */
  5455. lineWidth: 1,
  5456. /**
  5457. * If stroke ignore scale
  5458. * @type {Boolean}
  5459. */
  5460. strokeNoScale: false,
  5461. // Bounding rect text configuration
  5462. // Not affected by element transform
  5463. /**
  5464. * @type {string}
  5465. */
  5466. text: null,
  5467. /**
  5468. * If `fontSize` or `fontFamily` exists, `font` will be reset by
  5469. * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`.
  5470. * So do not visit it directly in upper application (like echarts),
  5471. * but use `contain/text#makeFont` instead.
  5472. * @type {string}
  5473. */
  5474. font: null,
  5475. /**
  5476. * The same as font. Use font please.
  5477. * @deprecated
  5478. * @type {string}
  5479. */
  5480. textFont: null,
  5481. /**
  5482. * It helps merging respectively, rather than parsing an entire font string.
  5483. * @type {string}
  5484. */
  5485. fontStyle: null,
  5486. /**
  5487. * It helps merging respectively, rather than parsing an entire font string.
  5488. * @type {string}
  5489. */
  5490. fontWeight: null,
  5491. /**
  5492. * It helps merging respectively, rather than parsing an entire font string.
  5493. * Should be 12 but not '12px'.
  5494. * @type {number}
  5495. */
  5496. fontSize: null,
  5497. /**
  5498. * It helps merging respectively, rather than parsing an entire font string.
  5499. * @type {string}
  5500. */
  5501. fontFamily: null,
  5502. /**
  5503. * Reserved for special functinality, like 'hr'.
  5504. * @type {string}
  5505. */
  5506. textTag: null,
  5507. /**
  5508. * @type {string}
  5509. */
  5510. textFill: '#000',
  5511. /**
  5512. * @type {string}
  5513. */
  5514. textStroke: null,
  5515. /**
  5516. * @type {number}
  5517. */
  5518. textWidth: null,
  5519. /**
  5520. * Only for textBackground.
  5521. * @type {number}
  5522. */
  5523. textHeight: null,
  5524. /**
  5525. * textStroke may be set as some color as a default
  5526. * value in upper applicaion, where the default value
  5527. * of textStrokeWidth should be 0 to make sure that
  5528. * user can choose to do not use text stroke.
  5529. * @type {number}
  5530. */
  5531. textStrokeWidth: 0,
  5532. /**
  5533. * @type {number}
  5534. */
  5535. textLineHeight: null,
  5536. /**
  5537. * 'inside', 'left', 'right', 'top', 'bottom'
  5538. * [x, y]
  5539. * Based on x, y of rect.
  5540. * @type {string|Array.<number>}
  5541. * @default 'inside'
  5542. */
  5543. textPosition: 'inside',
  5544. /**
  5545. * If not specified, use the boundingRect of a `displayable`.
  5546. * @type {Object}
  5547. */
  5548. textRect: null,
  5549. /**
  5550. * [x, y]
  5551. * @type {Array.<number>}
  5552. */
  5553. textOffset: null,
  5554. /**
  5555. * @type {string}
  5556. */
  5557. textAlign: null,
  5558. /**
  5559. * @type {string}
  5560. */
  5561. textVerticalAlign: null,
  5562. /**
  5563. * @type {number}
  5564. */
  5565. textDistance: 5,
  5566. /**
  5567. * @type {string}
  5568. */
  5569. textShadowColor: 'transparent',
  5570. /**
  5571. * @type {number}
  5572. */
  5573. textShadowBlur: 0,
  5574. /**
  5575. * @type {number}
  5576. */
  5577. textShadowOffsetX: 0,
  5578. /**
  5579. * @type {number}
  5580. */
  5581. textShadowOffsetY: 0,
  5582. /**
  5583. * @type {string}
  5584. */
  5585. textBoxShadowColor: 'transparent',
  5586. /**
  5587. * @type {number}
  5588. */
  5589. textBoxShadowBlur: 0,
  5590. /**
  5591. * @type {number}
  5592. */
  5593. textBoxShadowOffsetX: 0,
  5594. /**
  5595. * @type {number}
  5596. */
  5597. textBoxShadowOffsetY: 0,
  5598. /**
  5599. * Whether transform text.
  5600. * Only useful in Path and Image element
  5601. * @type {boolean}
  5602. */
  5603. transformText: false,
  5604. /**
  5605. * Text rotate around position of Path or Image
  5606. * Only useful in Path and Image element and transformText is false.
  5607. */
  5608. textRotation: 0,
  5609. /**
  5610. * Text origin of text rotation, like [10, 40].
  5611. * Based on x, y of rect.
  5612. * Useful in label rotation of circular symbol.
  5613. * By default, this origin is textPosition.
  5614. * Can be 'center'.
  5615. * @type {string|Array.<number>}
  5616. */
  5617. textOrigin: null,
  5618. /**
  5619. * @type {string}
  5620. */
  5621. textBackgroundColor: null,
  5622. /**
  5623. * @type {string}
  5624. */
  5625. textBorderColor: null,
  5626. /**
  5627. * @type {number}
  5628. */
  5629. textBorderWidth: 0,
  5630. /**
  5631. * @type {number}
  5632. */
  5633. textBorderRadius: 0,
  5634. /**
  5635. * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]`
  5636. * @type {number|Array.<number>}
  5637. */
  5638. textPadding: null,
  5639. /**
  5640. * Text styles for rich text.
  5641. * @type {Object}
  5642. */
  5643. rich: null,
  5644. /**
  5645. * {outerWidth, outerHeight, ellipsis, placeholder}
  5646. * @type {Object}
  5647. */
  5648. truncate: null,
  5649. /**
  5650. * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  5651. * @type {string}
  5652. */
  5653. blend: null,
  5654. /**
  5655. * @param {CanvasRenderingContext2D} ctx
  5656. */
  5657. bind: function (ctx, el, prevEl) {
  5658. var style = this;
  5659. var prevStyle = prevEl && prevEl.style;
  5660. var firstDraw = !prevStyle;
  5661. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  5662. var prop = STYLE_COMMON_PROPS[i];
  5663. var styleName = prop[0];
  5664. if (firstDraw || style[styleName] !== prevStyle[styleName]) {
  5665. // FIXME Invalid property value will cause style leak from previous element.
  5666. ctx[styleName] =
  5667. fixShadow(ctx, styleName, style[styleName] || prop[1]);
  5668. }
  5669. }
  5670. if ((firstDraw || style.fill !== prevStyle.fill)) {
  5671. ctx.fillStyle = style.fill;
  5672. }
  5673. if ((firstDraw || style.stroke !== prevStyle.stroke)) {
  5674. ctx.strokeStyle = style.stroke;
  5675. }
  5676. if ((firstDraw || style.opacity !== prevStyle.opacity)) {
  5677. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  5678. }
  5679. if ((firstDraw || style.blend !== prevStyle.blend)) {
  5680. ctx.globalCompositeOperation = style.blend || 'source-over';
  5681. }
  5682. if (this.hasStroke()) {
  5683. var lineWidth = style.lineWidth;
  5684. ctx.lineWidth = lineWidth / (
  5685. (this.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1
  5686. );
  5687. }
  5688. },
  5689. hasFill: function () {
  5690. var fill = this.fill;
  5691. return fill != null && fill !== 'none';
  5692. },
  5693. hasStroke: function () {
  5694. var stroke = this.stroke;
  5695. return stroke != null && stroke !== 'none' && this.lineWidth > 0;
  5696. },
  5697. /**
  5698. * Extend from other style
  5699. * @param {zrender/graphic/Style} otherStyle
  5700. * @param {boolean} overwrite true: overwrirte any way.
  5701. * false: overwrite only when !target.hasOwnProperty
  5702. * others: overwrite when property is not null/undefined.
  5703. */
  5704. extendFrom: function (otherStyle, overwrite) {
  5705. if (otherStyle) {
  5706. for (var name in otherStyle) {
  5707. if (otherStyle.hasOwnProperty(name)
  5708. && (overwrite === true
  5709. || (
  5710. overwrite === false
  5711. ? !this.hasOwnProperty(name)
  5712. : otherStyle[name] != null
  5713. )
  5714. )
  5715. ) {
  5716. this[name] = otherStyle[name];
  5717. }
  5718. }
  5719. }
  5720. },
  5721. /**
  5722. * Batch setting style with a given object
  5723. * @param {Object|string} obj
  5724. * @param {*} [obj]
  5725. */
  5726. set: function (obj, value) {
  5727. if (typeof obj === 'string') {
  5728. this[obj] = value;
  5729. }
  5730. else {
  5731. this.extendFrom(obj, true);
  5732. }
  5733. },
  5734. /**
  5735. * Clone
  5736. * @return {zrender/graphic/Style} [description]
  5737. */
  5738. clone: function () {
  5739. var newStyle = new this.constructor();
  5740. newStyle.extendFrom(this, true);
  5741. return newStyle;
  5742. },
  5743. getGradient: function (ctx, obj, rect) {
  5744. var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
  5745. var canvasGradient = method(ctx, obj, rect);
  5746. var colorStops = obj.colorStops;
  5747. for (var i = 0; i < colorStops.length; i++) {
  5748. canvasGradient.addColorStop(
  5749. colorStops[i].offset, colorStops[i].color
  5750. );
  5751. }
  5752. return canvasGradient;
  5753. }
  5754. };
  5755. var styleProto = Style.prototype;
  5756. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  5757. var prop = STYLE_COMMON_PROPS[i];
  5758. if (!(prop[0] in styleProto)) {
  5759. styleProto[prop[0]] = prop[1];
  5760. }
  5761. }
  5762. // Provide for others
  5763. Style.getGradient = styleProto.getGradient;
  5764. var Pattern = function (image, repeat) {
  5765. // Should do nothing more in this constructor. Because gradient can be
  5766. // declard by `color: {image: ...}`, where this constructor will not be called.
  5767. this.image = image;
  5768. this.repeat = repeat;
  5769. // Can be cloned
  5770. this.type = 'pattern';
  5771. };
  5772. Pattern.prototype.getCanvasPattern = function (ctx) {
  5773. return ctx.createPattern(this.image, this.repeat || 'repeat');
  5774. };
  5775. /**
  5776. * @module zrender/Layer
  5777. * @author pissang(https://www.github.com/pissang)
  5778. */
  5779. function returnFalse() {
  5780. return false;
  5781. }
  5782. /**
  5783. * 创建dom
  5784. *
  5785. * @inner
  5786. * @param {string} id dom id 待用
  5787. * @param {Painter} painter painter instance
  5788. * @param {number} number
  5789. */
  5790. function createDom(id, painter, dpr) {
  5791. var newDom = createCanvas();
  5792. var width = painter.getWidth();
  5793. var height = painter.getHeight();
  5794. var newDomStyle = newDom.style;
  5795. if (newDomStyle) { // In node or some other non-browser environment
  5796. newDomStyle.position = 'absolute';
  5797. newDomStyle.left = 0;
  5798. newDomStyle.top = 0;
  5799. newDomStyle.width = width + 'px';
  5800. newDomStyle.height = height + 'px';
  5801. newDom.setAttribute('data-zr-dom-id', id);
  5802. }
  5803. newDom.width = width * dpr;
  5804. newDom.height = height * dpr;
  5805. return newDom;
  5806. }
  5807. /**
  5808. * @alias module:zrender/Layer
  5809. * @constructor
  5810. * @extends module:zrender/mixin/Transformable
  5811. * @param {string} id
  5812. * @param {module:zrender/Painter} painter
  5813. * @param {number} [dpr]
  5814. */
  5815. var Layer = function(id, painter, dpr) {
  5816. var dom;
  5817. dpr = dpr || devicePixelRatio;
  5818. if (typeof id === 'string') {
  5819. dom = createDom(id, painter, dpr);
  5820. }
  5821. // Not using isDom because in node it will return false
  5822. else if (isObject$1(id)) {
  5823. dom = id;
  5824. id = dom.id;
  5825. }
  5826. this.id = id;
  5827. this.dom = dom;
  5828. var domStyle = dom.style;
  5829. if (domStyle) { // Not in node
  5830. dom.onselectstart = returnFalse; // 避免页面选中的尴尬
  5831. domStyle['-webkit-user-select'] = 'none';
  5832. domStyle['user-select'] = 'none';
  5833. domStyle['-webkit-touch-callout'] = 'none';
  5834. domStyle['-webkit-tap-highlight-color'] = 'rgba(0,0,0,0)';
  5835. domStyle['padding'] = 0;
  5836. domStyle['margin'] = 0;
  5837. domStyle['border-width'] = 0;
  5838. }
  5839. this.domBack = null;
  5840. this.ctxBack = null;
  5841. this.painter = painter;
  5842. this.config = null;
  5843. // Configs
  5844. /**
  5845. * 每次清空画布的颜色
  5846. * @type {string}
  5847. * @default 0
  5848. */
  5849. this.clearColor = 0;
  5850. /**
  5851. * 是否开启动态模糊
  5852. * @type {boolean}
  5853. * @default false
  5854. */
  5855. this.motionBlur = false;
  5856. /**
  5857. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  5858. * @type {number}
  5859. * @default 0.7
  5860. */
  5861. this.lastFrameAlpha = 0.7;
  5862. /**
  5863. * Layer dpr
  5864. * @type {number}
  5865. */
  5866. this.dpr = dpr;
  5867. };
  5868. Layer.prototype = {
  5869. constructor: Layer,
  5870. __dirty: true,
  5871. __used: false,
  5872. __drawIndex: 0,
  5873. __startIndex: 0,
  5874. __endIndex: 0,
  5875. incremental: false,
  5876. getElementCount: function () {
  5877. return this.__endIndex - this.__startIndex;
  5878. },
  5879. initContext: function () {
  5880. this.ctx = this.dom.getContext('2d');
  5881. this.ctx.dpr = this.dpr;
  5882. },
  5883. createBackBuffer: function () {
  5884. var dpr = this.dpr;
  5885. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  5886. this.ctxBack = this.domBack.getContext('2d');
  5887. if (dpr != 1) {
  5888. this.ctxBack.scale(dpr, dpr);
  5889. }
  5890. },
  5891. /**
  5892. * @param {number} width
  5893. * @param {number} height
  5894. */
  5895. resize: function (width, height) {
  5896. var dpr = this.dpr;
  5897. var dom = this.dom;
  5898. var domStyle = dom.style;
  5899. var domBack = this.domBack;
  5900. if (domStyle) {
  5901. domStyle.width = width + 'px';
  5902. domStyle.height = height + 'px';
  5903. }
  5904. dom.width = width * dpr;
  5905. dom.height = height * dpr;
  5906. if (domBack) {
  5907. domBack.width = width * dpr;
  5908. domBack.height = height * dpr;
  5909. if (dpr != 1) {
  5910. this.ctxBack.scale(dpr, dpr);
  5911. }
  5912. }
  5913. },
  5914. /**
  5915. * 清空该层画布
  5916. * @param {boolean} [clearAll]=false Clear all with out motion blur
  5917. * @param {Color} [clearColor]
  5918. */
  5919. clear: function (clearAll, clearColor) {
  5920. var dom = this.dom;
  5921. var ctx = this.ctx;
  5922. var width = dom.width;
  5923. var height = dom.height;
  5924. var clearColor = clearColor || this.clearColor;
  5925. var haveMotionBLur = this.motionBlur && !clearAll;
  5926. var lastFrameAlpha = this.lastFrameAlpha;
  5927. var dpr = this.dpr;
  5928. if (haveMotionBLur) {
  5929. if (!this.domBack) {
  5930. this.createBackBuffer();
  5931. }
  5932. this.ctxBack.globalCompositeOperation = 'copy';
  5933. this.ctxBack.drawImage(
  5934. dom, 0, 0,
  5935. width / dpr,
  5936. height / dpr
  5937. );
  5938. }
  5939. ctx.clearRect(0, 0, width, height);
  5940. if (clearColor && clearColor !== 'transparent') {
  5941. var clearColorGradientOrPattern;
  5942. // Gradient
  5943. if (clearColor.colorStops) {
  5944. // Cache canvas gradient
  5945. clearColorGradientOrPattern = clearColor.__canvasGradient || Style.getGradient(ctx, clearColor, {
  5946. x: 0,
  5947. y: 0,
  5948. width: width,
  5949. height: height
  5950. });
  5951. clearColor.__canvasGradient = clearColorGradientOrPattern;
  5952. }
  5953. // Pattern
  5954. else if (clearColor.image) {
  5955. clearColorGradientOrPattern = Pattern.prototype.getCanvasPattern.call(clearColor, ctx);
  5956. }
  5957. ctx.save();
  5958. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  5959. ctx.fillRect(0, 0, width, height);
  5960. ctx.restore();
  5961. }
  5962. if (haveMotionBLur) {
  5963. var domBack = this.domBack;
  5964. ctx.save();
  5965. ctx.globalAlpha = lastFrameAlpha;
  5966. ctx.drawImage(domBack, 0, 0, width, height);
  5967. ctx.restore();
  5968. }
  5969. }
  5970. };
  5971. var requestAnimationFrame = (
  5972. typeof window !== 'undefined'
  5973. && (
  5974. (window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  5975. // https://github.com/ecomfe/zrender/issues/189#issuecomment-224919809
  5976. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  5977. || window.mozRequestAnimationFrame
  5978. || window.webkitRequestAnimationFrame
  5979. )
  5980. ) || function (func) {
  5981. setTimeout(func, 16);
  5982. };
  5983. var globalImageCache = new LRU(50);
  5984. /**
  5985. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  5986. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  5987. */
  5988. function findExistImage(newImageOrSrc) {
  5989. if (typeof newImageOrSrc === 'string') {
  5990. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  5991. return cachedImgObj && cachedImgObj.image;
  5992. }
  5993. else {
  5994. return newImageOrSrc;
  5995. }
  5996. }
  5997. /**
  5998. * Caution: User should cache loaded images, but not just count on LRU.
  5999. * Consider if required images more than LRU size, will dead loop occur?
  6000. *
  6001. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6002. * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image.
  6003. * @param {module:zrender/Element} [hostEl] For calling `dirty`.
  6004. * @param {Function} [cb] params: (image, cbPayload)
  6005. * @param {Object} [cbPayload] Payload on cb calling.
  6006. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6007. */
  6008. function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) {
  6009. if (!newImageOrSrc) {
  6010. return image;
  6011. }
  6012. else if (typeof newImageOrSrc === 'string') {
  6013. // Image should not be loaded repeatly.
  6014. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  6015. return image;
  6016. }
  6017. // Only when there is no existent image or existent image src
  6018. // is different, this method is responsible for load.
  6019. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6020. var pendingWrap = {hostEl: hostEl, cb: cb, cbPayload: cbPayload};
  6021. if (cachedImgObj) {
  6022. image = cachedImgObj.image;
  6023. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  6024. }
  6025. else {
  6026. !image && (image = new Image());
  6027. image.onload = imageOnLoad;
  6028. globalImageCache.put(
  6029. newImageOrSrc,
  6030. image.__cachedImgObj = {
  6031. image: image,
  6032. pending: [pendingWrap]
  6033. }
  6034. );
  6035. image.src = image.__zrImageSrc = newImageOrSrc;
  6036. }
  6037. return image;
  6038. }
  6039. // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas
  6040. else {
  6041. return newImageOrSrc;
  6042. }
  6043. }
  6044. function imageOnLoad() {
  6045. var cachedImgObj = this.__cachedImgObj;
  6046. this.onload = this.__cachedImgObj = null;
  6047. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  6048. var pendingWrap = cachedImgObj.pending[i];
  6049. var cb = pendingWrap.cb;
  6050. cb && cb(this, pendingWrap.cbPayload);
  6051. pendingWrap.hostEl.dirty();
  6052. }
  6053. cachedImgObj.pending.length = 0;
  6054. }
  6055. function isImageReady(image) {
  6056. return image && image.width && image.height;
  6057. }
  6058. var textWidthCache = {};
  6059. var textWidthCacheCounter = 0;
  6060. var TEXT_CACHE_MAX = 5000;
  6061. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  6062. var DEFAULT_FONT = '12px sans-serif';
  6063. // Avoid assign to an exported variable, for transforming to cjs.
  6064. var methods$1 = {};
  6065. function $override$1(name, fn) {
  6066. methods$1[name] = fn;
  6067. }
  6068. /**
  6069. * @public
  6070. * @param {string} text
  6071. * @param {string} font
  6072. * @return {number} width
  6073. */
  6074. function getWidth(text, font) {
  6075. font = font || DEFAULT_FONT;
  6076. var key = text + ':' + font;
  6077. if (textWidthCache[key]) {
  6078. return textWidthCache[key];
  6079. }
  6080. var textLines = (text + '').split('\n');
  6081. var width = 0;
  6082. for (var i = 0, l = textLines.length; i < l; i++) {
  6083. // textContain.measureText may be overrided in SVG or VML
  6084. width = Math.max(measureText(textLines[i], font).width, width);
  6085. }
  6086. if (textWidthCacheCounter > TEXT_CACHE_MAX) {
  6087. textWidthCacheCounter = 0;
  6088. textWidthCache = {};
  6089. }
  6090. textWidthCacheCounter++;
  6091. textWidthCache[key] = width;
  6092. return width;
  6093. }
  6094. /**
  6095. * @public
  6096. * @param {string} text
  6097. * @param {string} font
  6098. * @param {string} [textAlign='left']
  6099. * @param {string} [textVerticalAlign='top']
  6100. * @param {Array.<number>} [textPadding]
  6101. * @param {Object} [rich]
  6102. * @param {Object} [truncate]
  6103. * @return {Object} {x, y, width, height, lineHeight}
  6104. */
  6105. function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) {
  6106. return rich
  6107. ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate)
  6108. : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, truncate);
  6109. }
  6110. function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, truncate) {
  6111. var contentBlock = parsePlainText(text, font, textPadding, truncate);
  6112. var outerWidth = getWidth(text, font);
  6113. if (textPadding) {
  6114. outerWidth += textPadding[1] + textPadding[3];
  6115. }
  6116. var outerHeight = contentBlock.outerHeight;
  6117. var x = adjustTextX(0, outerWidth, textAlign);
  6118. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6119. var rect = new BoundingRect(x, y, outerWidth, outerHeight);
  6120. rect.lineHeight = contentBlock.lineHeight;
  6121. return rect;
  6122. }
  6123. function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) {
  6124. var contentBlock = parseRichText(text, {
  6125. rich: rich,
  6126. truncate: truncate,
  6127. font: font,
  6128. textAlign: textAlign,
  6129. textPadding: textPadding
  6130. });
  6131. var outerWidth = contentBlock.outerWidth;
  6132. var outerHeight = contentBlock.outerHeight;
  6133. var x = adjustTextX(0, outerWidth, textAlign);
  6134. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6135. return new BoundingRect(x, y, outerWidth, outerHeight);
  6136. }
  6137. /**
  6138. * @public
  6139. * @param {number} x
  6140. * @param {number} width
  6141. * @param {string} [textAlign='left']
  6142. * @return {number} Adjusted x.
  6143. */
  6144. function adjustTextX(x, width, textAlign) {
  6145. // FIXME Right to left language
  6146. if (textAlign === 'right') {
  6147. x -= width;
  6148. }
  6149. else if (textAlign === 'center') {
  6150. x -= width / 2;
  6151. }
  6152. return x;
  6153. }
  6154. /**
  6155. * @public
  6156. * @param {number} y
  6157. * @param {number} height
  6158. * @param {string} [textVerticalAlign='top']
  6159. * @return {number} Adjusted y.
  6160. */
  6161. function adjustTextY(y, height, textVerticalAlign) {
  6162. if (textVerticalAlign === 'middle') {
  6163. y -= height / 2;
  6164. }
  6165. else if (textVerticalAlign === 'bottom') {
  6166. y -= height;
  6167. }
  6168. return y;
  6169. }
  6170. /**
  6171. * @public
  6172. * @param {stirng} textPosition
  6173. * @param {Object} rect {x, y, width, height}
  6174. * @param {number} distance
  6175. * @return {Object} {x, y, textAlign, textVerticalAlign}
  6176. */
  6177. function adjustTextPositionOnRect(textPosition, rect, distance) {
  6178. var x = rect.x;
  6179. var y = rect.y;
  6180. var height = rect.height;
  6181. var width = rect.width;
  6182. var halfHeight = height / 2;
  6183. var textAlign = 'left';
  6184. var textVerticalAlign = 'top';
  6185. switch (textPosition) {
  6186. case 'left':
  6187. x -= distance;
  6188. y += halfHeight;
  6189. textAlign = 'right';
  6190. textVerticalAlign = 'middle';
  6191. break;
  6192. case 'right':
  6193. x += distance + width;
  6194. y += halfHeight;
  6195. textVerticalAlign = 'middle';
  6196. break;
  6197. case 'top':
  6198. x += width / 2;
  6199. y -= distance;
  6200. textAlign = 'center';
  6201. textVerticalAlign = 'bottom';
  6202. break;
  6203. case 'bottom':
  6204. x += width / 2;
  6205. y += height + distance;
  6206. textAlign = 'center';
  6207. break;
  6208. case 'inside':
  6209. x += width / 2;
  6210. y += halfHeight;
  6211. textAlign = 'center';
  6212. textVerticalAlign = 'middle';
  6213. break;
  6214. case 'insideLeft':
  6215. x += distance;
  6216. y += halfHeight;
  6217. textVerticalAlign = 'middle';
  6218. break;
  6219. case 'insideRight':
  6220. x += width - distance;
  6221. y += halfHeight;
  6222. textAlign = 'right';
  6223. textVerticalAlign = 'middle';
  6224. break;
  6225. case 'insideTop':
  6226. x += width / 2;
  6227. y += distance;
  6228. textAlign = 'center';
  6229. break;
  6230. case 'insideBottom':
  6231. x += width / 2;
  6232. y += height - distance;
  6233. textAlign = 'center';
  6234. textVerticalAlign = 'bottom';
  6235. break;
  6236. case 'insideTopLeft':
  6237. x += distance;
  6238. y += distance;
  6239. break;
  6240. case 'insideTopRight':
  6241. x += width - distance;
  6242. y += distance;
  6243. textAlign = 'right';
  6244. break;
  6245. case 'insideBottomLeft':
  6246. x += distance;
  6247. y += height - distance;
  6248. textVerticalAlign = 'bottom';
  6249. break;
  6250. case 'insideBottomRight':
  6251. x += width - distance;
  6252. y += height - distance;
  6253. textAlign = 'right';
  6254. textVerticalAlign = 'bottom';
  6255. break;
  6256. }
  6257. return {
  6258. x: x,
  6259. y: y,
  6260. textAlign: textAlign,
  6261. textVerticalAlign: textVerticalAlign
  6262. };
  6263. }
  6264. /**
  6265. * Show ellipsis if overflow.
  6266. *
  6267. * @public
  6268. * @param {string} text
  6269. * @param {string} containerWidth
  6270. * @param {string} font
  6271. * @param {number} [ellipsis='...']
  6272. * @param {Object} [options]
  6273. * @param {number} [options.maxIterations=3]
  6274. * @param {number} [options.minChar=0] If truncate result are less
  6275. * then minChar, ellipsis will not show, which is
  6276. * better for user hint in some cases.
  6277. * @param {number} [options.placeholder=''] When all truncated, use the placeholder.
  6278. * @return {string}
  6279. */
  6280. function truncateText(text, containerWidth, font, ellipsis, options) {
  6281. if (!containerWidth) {
  6282. return '';
  6283. }
  6284. var textLines = (text + '').split('\n');
  6285. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  6286. // FIXME
  6287. // It is not appropriate that every line has '...' when truncate multiple lines.
  6288. for (var i = 0, len = textLines.length; i < len; i++) {
  6289. textLines[i] = truncateSingleLine(textLines[i], options);
  6290. }
  6291. return textLines.join('\n');
  6292. }
  6293. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  6294. options = extend({}, options);
  6295. options.font = font;
  6296. var ellipsis = retrieve2(ellipsis, '...');
  6297. options.maxIterations = retrieve2(options.maxIterations, 2);
  6298. var minChar = options.minChar = retrieve2(options.minChar, 0);
  6299. // FIXME
  6300. // Other languages?
  6301. options.cnCharWidth = getWidth('国', font);
  6302. // FIXME
  6303. // Consider proportional font?
  6304. var ascCharWidth = options.ascCharWidth = getWidth('a', font);
  6305. options.placeholder = retrieve2(options.placeholder, '');
  6306. // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'.
  6307. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'.
  6308. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap.
  6309. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  6310. contentWidth -= ascCharWidth;
  6311. }
  6312. var ellipsisWidth = getWidth(ellipsis);
  6313. if (ellipsisWidth > contentWidth) {
  6314. ellipsis = '';
  6315. ellipsisWidth = 0;
  6316. }
  6317. contentWidth = containerWidth - ellipsisWidth;
  6318. options.ellipsis = ellipsis;
  6319. options.ellipsisWidth = ellipsisWidth;
  6320. options.contentWidth = contentWidth;
  6321. options.containerWidth = containerWidth;
  6322. return options;
  6323. }
  6324. function truncateSingleLine(textLine, options) {
  6325. var containerWidth = options.containerWidth;
  6326. var font = options.font;
  6327. var contentWidth = options.contentWidth;
  6328. if (!containerWidth) {
  6329. return '';
  6330. }
  6331. var lineWidth = getWidth(textLine, font);
  6332. if (lineWidth <= containerWidth) {
  6333. return textLine;
  6334. }
  6335. for (var j = 0;; j++) {
  6336. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  6337. textLine += options.ellipsis;
  6338. break;
  6339. }
  6340. var subLength = j === 0
  6341. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  6342. : lineWidth > 0
  6343. ? Math.floor(textLine.length * contentWidth / lineWidth)
  6344. : 0;
  6345. textLine = textLine.substr(0, subLength);
  6346. lineWidth = getWidth(textLine, font);
  6347. }
  6348. if (textLine === '') {
  6349. textLine = options.placeholder;
  6350. }
  6351. return textLine;
  6352. }
  6353. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  6354. var width = 0;
  6355. var i = 0;
  6356. for (var len = text.length; i < len && width < contentWidth; i++) {
  6357. var charCode = text.charCodeAt(i);
  6358. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  6359. }
  6360. return i;
  6361. }
  6362. /**
  6363. * @public
  6364. * @param {string} font
  6365. * @return {number} line height
  6366. */
  6367. function getLineHeight(font) {
  6368. // FIXME A rough approach.
  6369. return getWidth('国', font);
  6370. }
  6371. /**
  6372. * @public
  6373. * @param {string} text
  6374. * @param {string} font
  6375. * @return {Object} width
  6376. */
  6377. function measureText(text, font) {
  6378. return methods$1.measureText(text, font);
  6379. }
  6380. // Avoid assign to an exported variable, for transforming to cjs.
  6381. methods$1.measureText = function (text, font) {
  6382. var ctx = getContext();
  6383. ctx.font = font || DEFAULT_FONT;
  6384. return ctx.measureText(text);
  6385. };
  6386. /**
  6387. * @public
  6388. * @param {string} text
  6389. * @param {string} font
  6390. * @param {Object} [truncate]
  6391. * @return {Object} block: {lineHeight, lines, height, outerHeight}
  6392. * Notice: for performance, do not calculate outerWidth util needed.
  6393. */
  6394. function parsePlainText(text, font, padding, truncate) {
  6395. text != null && (text += '');
  6396. var lineHeight = getLineHeight(font);
  6397. var lines = text ? text.split('\n') : [];
  6398. var height = lines.length * lineHeight;
  6399. var outerHeight = height;
  6400. if (padding) {
  6401. outerHeight += padding[0] + padding[2];
  6402. }
  6403. if (text && truncate) {
  6404. var truncOuterHeight = truncate.outerHeight;
  6405. var truncOuterWidth = truncate.outerWidth;
  6406. if (truncOuterHeight != null && outerHeight > truncOuterHeight) {
  6407. text = '';
  6408. lines = [];
  6409. }
  6410. else if (truncOuterWidth != null) {
  6411. var options = prepareTruncateOptions(
  6412. truncOuterWidth - (padding ? padding[1] + padding[3] : 0),
  6413. font,
  6414. truncate.ellipsis,
  6415. {minChar: truncate.minChar, placeholder: truncate.placeholder}
  6416. );
  6417. // FIXME
  6418. // It is not appropriate that every line has '...' when truncate multiple lines.
  6419. for (var i = 0, len = lines.length; i < len; i++) {
  6420. lines[i] = truncateSingleLine(lines[i], options);
  6421. }
  6422. }
  6423. }
  6424. return {
  6425. lines: lines,
  6426. height: height,
  6427. outerHeight: outerHeight,
  6428. lineHeight: lineHeight
  6429. };
  6430. }
  6431. /**
  6432. * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx'
  6433. * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'.
  6434. *
  6435. * @public
  6436. * @param {string} text
  6437. * @param {Object} style
  6438. * @return {Object} block
  6439. * {
  6440. * width,
  6441. * height,
  6442. * lines: [{
  6443. * lineHeight,
  6444. * width,
  6445. * tokens: [[{
  6446. * styleName,
  6447. * text,
  6448. * width, // include textPadding
  6449. * height, // include textPadding
  6450. * textWidth, // pure text width
  6451. * textHeight, // pure text height
  6452. * lineHeihgt,
  6453. * font,
  6454. * textAlign,
  6455. * textVerticalAlign
  6456. * }], [...], ...]
  6457. * }, ...]
  6458. * }
  6459. * If styleName is undefined, it is plain text.
  6460. */
  6461. function parseRichText(text, style) {
  6462. var contentBlock = {lines: [], width: 0, height: 0};
  6463. text != null && (text += '');
  6464. if (!text) {
  6465. return contentBlock;
  6466. }
  6467. var lastIndex = STYLE_REG.lastIndex = 0;
  6468. var result;
  6469. while ((result = STYLE_REG.exec(text)) != null) {
  6470. var matchedIndex = result.index;
  6471. if (matchedIndex > lastIndex) {
  6472. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex));
  6473. }
  6474. pushTokens(contentBlock, result[2], result[1]);
  6475. lastIndex = STYLE_REG.lastIndex;
  6476. }
  6477. if (lastIndex < text.length) {
  6478. pushTokens(contentBlock, text.substring(lastIndex, text.length));
  6479. }
  6480. var lines = contentBlock.lines;
  6481. var contentHeight = 0;
  6482. var contentWidth = 0;
  6483. // For `textWidth: 100%`
  6484. var pendingList = [];
  6485. var stlPadding = style.textPadding;
  6486. var truncate = style.truncate;
  6487. var truncateWidth = truncate && truncate.outerWidth;
  6488. var truncateHeight = truncate && truncate.outerHeight;
  6489. if (stlPadding) {
  6490. truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]);
  6491. truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]);
  6492. }
  6493. // Calculate layout info of tokens.
  6494. for (var i = 0; i < lines.length; i++) {
  6495. var line = lines[i];
  6496. var lineHeight = 0;
  6497. var lineWidth = 0;
  6498. for (var j = 0; j < line.tokens.length; j++) {
  6499. var token = line.tokens[j];
  6500. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  6501. // textPadding should not inherit from style.
  6502. var textPadding = token.textPadding = tokenStyle.textPadding;
  6503. // textFont has been asigned to font by `normalizeStyle`.
  6504. var font = token.font = tokenStyle.font || style.font;
  6505. // textHeight can be used when textVerticalAlign is specified in token.
  6506. var tokenHeight = token.textHeight = retrieve2(
  6507. // textHeight should not be inherited, consider it can be specified
  6508. // as box height of the block.
  6509. tokenStyle.textHeight, getLineHeight(font)
  6510. );
  6511. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  6512. token.height = tokenHeight;
  6513. token.lineHeight = retrieve3(
  6514. tokenStyle.textLineHeight, style.textLineHeight, tokenHeight
  6515. );
  6516. token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign;
  6517. token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle';
  6518. if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) {
  6519. return {lines: [], width: 0, height: 0};
  6520. }
  6521. token.textWidth = getWidth(token.text, font);
  6522. var tokenWidth = tokenStyle.textWidth;
  6523. var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto';
  6524. // Percent width, can be `100%`, can be used in drawing separate
  6525. // line when box width is needed to be auto.
  6526. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') {
  6527. token.percentWidth = tokenWidth;
  6528. pendingList.push(token);
  6529. tokenWidth = 0;
  6530. // Do not truncate in this case, because there is no user case
  6531. // and it is too complicated.
  6532. }
  6533. else {
  6534. if (tokenWidthNotSpecified) {
  6535. tokenWidth = token.textWidth;
  6536. // FIXME: If image is not loaded and textWidth is not specified, calling
  6537. // `getBoundingRect()` will not get correct result.
  6538. var textBackgroundColor = tokenStyle.textBackgroundColor;
  6539. var bgImg = textBackgroundColor && textBackgroundColor.image;
  6540. // Use cases:
  6541. // (1) If image is not loaded, it will be loaded at render phase and call
  6542. // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded
  6543. // image, and then the right size will be calculated here at the next tick.
  6544. // See `graphic/helper/text.js`.
  6545. // (2) If image loaded, and `textBackgroundColor.image` is image src string,
  6546. // use `imageHelper.findExistImage` to find cached image.
  6547. // `imageHelper.findExistImage` will always be called here before
  6548. // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText`
  6549. // which ensures that image will not be rendered before correct size calcualted.
  6550. if (bgImg) {
  6551. bgImg = findExistImage(bgImg);
  6552. if (isImageReady(bgImg)) {
  6553. tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height);
  6554. }
  6555. }
  6556. }
  6557. var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0;
  6558. tokenWidth += paddingW;
  6559. var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null;
  6560. if (remianTruncWidth != null && remianTruncWidth < tokenWidth) {
  6561. if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) {
  6562. token.text = '';
  6563. token.textWidth = tokenWidth = 0;
  6564. }
  6565. else {
  6566. token.text = truncateText(
  6567. token.text, remianTruncWidth - paddingW, font, truncate.ellipsis,
  6568. {minChar: truncate.minChar}
  6569. );
  6570. token.textWidth = getWidth(token.text, font);
  6571. tokenWidth = token.textWidth + paddingW;
  6572. }
  6573. }
  6574. }
  6575. lineWidth += (token.width = tokenWidth);
  6576. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  6577. }
  6578. line.width = lineWidth;
  6579. line.lineHeight = lineHeight;
  6580. contentHeight += lineHeight;
  6581. contentWidth = Math.max(contentWidth, lineWidth);
  6582. }
  6583. contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth);
  6584. contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight);
  6585. if (stlPadding) {
  6586. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  6587. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  6588. }
  6589. for (var i = 0; i < pendingList.length; i++) {
  6590. var token = pendingList[i];
  6591. var percentWidth = token.percentWidth;
  6592. // Should not base on outerWidth, because token can not be placed out of padding.
  6593. token.width = parseInt(percentWidth, 10) / 100 * contentWidth;
  6594. }
  6595. return contentBlock;
  6596. }
  6597. function pushTokens(block, str, styleName) {
  6598. var isEmptyStr = str === '';
  6599. var strs = str.split('\n');
  6600. var lines = block.lines;
  6601. for (var i = 0; i < strs.length; i++) {
  6602. var text = strs[i];
  6603. var token = {
  6604. styleName: styleName,
  6605. text: text,
  6606. isLineHolder: !text && !isEmptyStr
  6607. };
  6608. // The first token should be appended to the last line.
  6609. if (!i) {
  6610. var tokens = (lines[lines.length - 1] || (lines[0] = {tokens: []})).tokens;
  6611. // Consider cases:
  6612. // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item
  6613. // (which is a placeholder) should be replaced by new token.
  6614. // (2) A image backage, where token likes {a|}.
  6615. // (3) A redundant '' will affect textAlign in line.
  6616. // (4) tokens with the same tplName should not be merged, because
  6617. // they should be displayed in different box (with border and padding).
  6618. var tokensLen = tokens.length;
  6619. (tokensLen === 1 && tokens[0].isLineHolder)
  6620. ? (tokens[0] = token)
  6621. // Consider text is '', only insert when it is the "lineHolder" or
  6622. // "emptyStr". Otherwise a redundant '' will affect textAlign in line.
  6623. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  6624. }
  6625. // Other tokens always start a new line.
  6626. else {
  6627. // If there is '', insert it as a placeholder.
  6628. lines.push({tokens: [token]});
  6629. }
  6630. }
  6631. }
  6632. function makeFont(style) {
  6633. // FIXME in node-canvas fontWeight is before fontStyle
  6634. // Use `fontSize` `fontFamily` to check whether font properties are defined.
  6635. var font = (style.fontSize || style.fontFamily) && [
  6636. style.fontStyle,
  6637. style.fontWeight,
  6638. (style.fontSize || 12) + 'px',
  6639. // If font properties are defined, `fontFamily` should not be ignored.
  6640. style.fontFamily || 'sans-serif'
  6641. ].join(' ');
  6642. return font && trim(font) || style.textFont || style.font;
  6643. }
  6644. function buildPath(ctx, shape) {
  6645. var x = shape.x;
  6646. var y = shape.y;
  6647. var width = shape.width;
  6648. var height = shape.height;
  6649. var r = shape.r;
  6650. var r1;
  6651. var r2;
  6652. var r3;
  6653. var r4;
  6654. // Convert width and height to positive for better borderRadius
  6655. if (width < 0) {
  6656. x = x + width;
  6657. width = -width;
  6658. }
  6659. if (height < 0) {
  6660. y = y + height;
  6661. height = -height;
  6662. }
  6663. if (typeof r === 'number') {
  6664. r1 = r2 = r3 = r4 = r;
  6665. }
  6666. else if (r instanceof Array) {
  6667. if (r.length === 1) {
  6668. r1 = r2 = r3 = r4 = r[0];
  6669. }
  6670. else if (r.length === 2) {
  6671. r1 = r3 = r[0];
  6672. r2 = r4 = r[1];
  6673. }
  6674. else if (r.length === 3) {
  6675. r1 = r[0];
  6676. r2 = r4 = r[1];
  6677. r3 = r[2];
  6678. }
  6679. else {
  6680. r1 = r[0];
  6681. r2 = r[1];
  6682. r3 = r[2];
  6683. r4 = r[3];
  6684. }
  6685. }
  6686. else {
  6687. r1 = r2 = r3 = r4 = 0;
  6688. }
  6689. var total;
  6690. if (r1 + r2 > width) {
  6691. total = r1 + r2;
  6692. r1 *= width / total;
  6693. r2 *= width / total;
  6694. }
  6695. if (r3 + r4 > width) {
  6696. total = r3 + r4;
  6697. r3 *= width / total;
  6698. r4 *= width / total;
  6699. }
  6700. if (r2 + r3 > height) {
  6701. total = r2 + r3;
  6702. r2 *= height / total;
  6703. r3 *= height / total;
  6704. }
  6705. if (r1 + r4 > height) {
  6706. total = r1 + r4;
  6707. r1 *= height / total;
  6708. r4 *= height / total;
  6709. }
  6710. ctx.moveTo(x + r1, y);
  6711. ctx.lineTo(x + width - r2, y);
  6712. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  6713. ctx.lineTo(x + width, y + height - r3);
  6714. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  6715. ctx.lineTo(x + r4, y + height);
  6716. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  6717. ctx.lineTo(x, y + r1);
  6718. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  6719. }
  6720. // TODO: Have not support 'start', 'end' yet.
  6721. var VALID_TEXT_ALIGN = {left: 1, right: 1, center: 1};
  6722. var VALID_TEXT_VERTICAL_ALIGN = {top: 1, bottom: 1, middle: 1};
  6723. /**
  6724. * @param {module:zrender/graphic/Style} style
  6725. * @return {module:zrender/graphic/Style} The input style.
  6726. */
  6727. function normalizeTextStyle(style) {
  6728. normalizeStyle(style);
  6729. each$1(style.rich, normalizeStyle);
  6730. return style;
  6731. }
  6732. function normalizeStyle(style) {
  6733. if (style) {
  6734. style.font = makeFont(style);
  6735. var textAlign = style.textAlign;
  6736. textAlign === 'middle' && (textAlign = 'center');
  6737. style.textAlign = (
  6738. textAlign == null || VALID_TEXT_ALIGN[textAlign]
  6739. ) ? textAlign : 'left';
  6740. // Compatible with textBaseline.
  6741. var textVerticalAlign = style.textVerticalAlign || style.textBaseline;
  6742. textVerticalAlign === 'center' && (textVerticalAlign = 'middle');
  6743. style.textVerticalAlign = (
  6744. textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign]
  6745. ) ? textVerticalAlign : 'top';
  6746. var textPadding = style.textPadding;
  6747. if (textPadding) {
  6748. style.textPadding = normalizeCssArray(style.textPadding);
  6749. }
  6750. }
  6751. }
  6752. /**
  6753. * @param {CanvasRenderingContext2D} ctx
  6754. * @param {string} text
  6755. * @param {module:zrender/graphic/Style} style
  6756. * @param {Object|boolean} [rect] {x, y, width, height}
  6757. * If set false, rect text is not used.
  6758. */
  6759. function renderText(hostEl, ctx, text, style, rect) {
  6760. style.rich
  6761. ? renderRichText(hostEl, ctx, text, style, rect)
  6762. : renderPlainText(hostEl, ctx, text, style, rect);
  6763. }
  6764. function renderPlainText(hostEl, ctx, text, style, rect) {
  6765. var font = setCtx(ctx, 'font', style.font || DEFAULT_FONT);
  6766. var textPadding = style.textPadding;
  6767. var contentBlock = hostEl.__textCotentBlock;
  6768. if (!contentBlock || hostEl.__dirty) {
  6769. contentBlock = hostEl.__textCotentBlock = parsePlainText(
  6770. text, font, textPadding, style.truncate
  6771. );
  6772. }
  6773. var outerHeight = contentBlock.outerHeight;
  6774. var textLines = contentBlock.lines;
  6775. var lineHeight = contentBlock.lineHeight;
  6776. var boxPos = getBoxPosition(outerHeight, style, rect);
  6777. var baseX = boxPos.baseX;
  6778. var baseY = boxPos.baseY;
  6779. var textAlign = boxPos.textAlign;
  6780. var textVerticalAlign = boxPos.textVerticalAlign;
  6781. // Origin of textRotation should be the base point of text drawing.
  6782. applyTextRotation(ctx, style, rect, baseX, baseY);
  6783. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  6784. var textX = baseX;
  6785. var textY = boxY;
  6786. var needDrawBg = needDrawBackground(style);
  6787. if (needDrawBg || textPadding) {
  6788. // Consider performance, do not call getTextWidth util necessary.
  6789. var textWidth = getWidth(text, font);
  6790. var outerWidth = textWidth;
  6791. textPadding && (outerWidth += textPadding[1] + textPadding[3]);
  6792. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  6793. needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  6794. if (textPadding) {
  6795. textX = getTextXForPadding(baseX, textAlign, textPadding);
  6796. textY += textPadding[0];
  6797. }
  6798. }
  6799. setCtx(ctx, 'textAlign', textAlign || 'left');
  6800. // Force baseline to be "middle". Otherwise, if using "top", the
  6801. // text will offset downward a little bit in font "Microsoft YaHei".
  6802. setCtx(ctx, 'textBaseline', 'middle');
  6803. // Always set shadowBlur and shadowOffset to avoid leak from displayable.
  6804. setCtx(ctx, 'shadowBlur', style.textShadowBlur || 0);
  6805. setCtx(ctx, 'shadowColor', style.textShadowColor || 'transparent');
  6806. setCtx(ctx, 'shadowOffsetX', style.textShadowOffsetX || 0);
  6807. setCtx(ctx, 'shadowOffsetY', style.textShadowOffsetY || 0);
  6808. // `textBaseline` is set as 'middle'.
  6809. textY += lineHeight / 2;
  6810. var textStrokeWidth = style.textStrokeWidth;
  6811. var textStroke = getStroke(style.textStroke, textStrokeWidth);
  6812. var textFill = getFill(style.textFill);
  6813. if (textStroke) {
  6814. setCtx(ctx, 'lineWidth', textStrokeWidth);
  6815. setCtx(ctx, 'strokeStyle', textStroke);
  6816. }
  6817. if (textFill) {
  6818. setCtx(ctx, 'fillStyle', textFill);
  6819. }
  6820. for (var i = 0; i < textLines.length; i++) {
  6821. // Fill after stroke so the outline will not cover the main part.
  6822. textStroke && ctx.strokeText(textLines[i], textX, textY);
  6823. textFill && ctx.fillText(textLines[i], textX, textY);
  6824. textY += lineHeight;
  6825. }
  6826. }
  6827. function renderRichText(hostEl, ctx, text, style, rect) {
  6828. var contentBlock = hostEl.__textCotentBlock;
  6829. if (!contentBlock || hostEl.__dirty) {
  6830. contentBlock = hostEl.__textCotentBlock = parseRichText(text, style);
  6831. }
  6832. drawRichText(hostEl, ctx, contentBlock, style, rect);
  6833. }
  6834. function drawRichText(hostEl, ctx, contentBlock, style, rect) {
  6835. var contentWidth = contentBlock.width;
  6836. var outerWidth = contentBlock.outerWidth;
  6837. var outerHeight = contentBlock.outerHeight;
  6838. var textPadding = style.textPadding;
  6839. var boxPos = getBoxPosition(outerHeight, style, rect);
  6840. var baseX = boxPos.baseX;
  6841. var baseY = boxPos.baseY;
  6842. var textAlign = boxPos.textAlign;
  6843. var textVerticalAlign = boxPos.textVerticalAlign;
  6844. // Origin of textRotation should be the base point of text drawing.
  6845. applyTextRotation(ctx, style, rect, baseX, baseY);
  6846. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  6847. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  6848. var xLeft = boxX;
  6849. var lineTop = boxY;
  6850. if (textPadding) {
  6851. xLeft += textPadding[3];
  6852. lineTop += textPadding[0];
  6853. }
  6854. var xRight = xLeft + contentWidth;
  6855. needDrawBackground(style) && drawBackground(
  6856. hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight
  6857. );
  6858. for (var i = 0; i < contentBlock.lines.length; i++) {
  6859. var line = contentBlock.lines[i];
  6860. var tokens = line.tokens;
  6861. var tokenCount = tokens.length;
  6862. var lineHeight = line.lineHeight;
  6863. var usedWidth = line.width;
  6864. var leftIndex = 0;
  6865. var lineXLeft = xLeft;
  6866. var lineXRight = xRight;
  6867. var rightIndex = tokenCount - 1;
  6868. var token;
  6869. while (
  6870. leftIndex < tokenCount
  6871. && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left')
  6872. ) {
  6873. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left');
  6874. usedWidth -= token.width;
  6875. lineXLeft += token.width;
  6876. leftIndex++;
  6877. }
  6878. while (
  6879. rightIndex >= 0
  6880. && (token = tokens[rightIndex], token.textAlign === 'right')
  6881. ) {
  6882. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right');
  6883. usedWidth -= token.width;
  6884. lineXRight -= token.width;
  6885. rightIndex--;
  6886. }
  6887. // The other tokens are placed as textAlign 'center' if there is enough space.
  6888. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2;
  6889. while (leftIndex <= rightIndex) {
  6890. token = tokens[leftIndex];
  6891. // Consider width specified by user, use 'center' rather than 'left'.
  6892. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center');
  6893. lineXLeft += token.width;
  6894. leftIndex++;
  6895. }
  6896. lineTop += lineHeight;
  6897. }
  6898. }
  6899. function applyTextRotation(ctx, style, rect, x, y) {
  6900. // textRotation only apply in RectText.
  6901. if (rect && style.textRotation) {
  6902. var origin = style.textOrigin;
  6903. if (origin === 'center') {
  6904. x = rect.width / 2 + rect.x;
  6905. y = rect.height / 2 + rect.y;
  6906. }
  6907. else if (origin) {
  6908. x = origin[0] + rect.x;
  6909. y = origin[1] + rect.y;
  6910. }
  6911. ctx.translate(x, y);
  6912. // Positive: anticlockwise
  6913. ctx.rotate(-style.textRotation);
  6914. ctx.translate(-x, -y);
  6915. }
  6916. }
  6917. function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) {
  6918. var tokenStyle = style.rich[token.styleName] || {};
  6919. // 'ctx.textBaseline' is always set as 'middle', for sake of
  6920. // the bias of "Microsoft YaHei".
  6921. var textVerticalAlign = token.textVerticalAlign;
  6922. var y = lineTop + lineHeight / 2;
  6923. if (textVerticalAlign === 'top') {
  6924. y = lineTop + token.height / 2;
  6925. }
  6926. else if (textVerticalAlign === 'bottom') {
  6927. y = lineTop + lineHeight - token.height / 2;
  6928. }
  6929. !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground(
  6930. hostEl,
  6931. ctx,
  6932. tokenStyle,
  6933. textAlign === 'right'
  6934. ? x - token.width
  6935. : textAlign === 'center'
  6936. ? x - token.width / 2
  6937. : x,
  6938. y - token.height / 2,
  6939. token.width,
  6940. token.height
  6941. );
  6942. var textPadding = token.textPadding;
  6943. if (textPadding) {
  6944. x = getTextXForPadding(x, textAlign, textPadding);
  6945. y -= token.height / 2 - textPadding[2] - token.textHeight / 2;
  6946. }
  6947. setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0));
  6948. setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent');
  6949. setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0));
  6950. setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0));
  6951. setCtx(ctx, 'textAlign', textAlign);
  6952. // Force baseline to be "middle". Otherwise, if using "top", the
  6953. // text will offset downward a little bit in font "Microsoft YaHei".
  6954. setCtx(ctx, 'textBaseline', 'middle');
  6955. setCtx(ctx, 'font', token.font || DEFAULT_FONT);
  6956. var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth);
  6957. var textFill = getFill(tokenStyle.textFill || style.textFill);
  6958. var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth);
  6959. // Fill after stroke so the outline will not cover the main part.
  6960. if (textStroke) {
  6961. setCtx(ctx, 'lineWidth', textStrokeWidth);
  6962. setCtx(ctx, 'strokeStyle', textStroke);
  6963. ctx.strokeText(token.text, x, y);
  6964. }
  6965. if (textFill) {
  6966. setCtx(ctx, 'fillStyle', textFill);
  6967. ctx.fillText(token.text, x, y);
  6968. }
  6969. }
  6970. function needDrawBackground(style) {
  6971. return style.textBackgroundColor
  6972. || (style.textBorderWidth && style.textBorderColor);
  6973. }
  6974. // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius}
  6975. // shape: {x, y, width, height}
  6976. function drawBackground(hostEl, ctx, style, x, y, width, height) {
  6977. var textBackgroundColor = style.textBackgroundColor;
  6978. var textBorderWidth = style.textBorderWidth;
  6979. var textBorderColor = style.textBorderColor;
  6980. var isPlainBg = isString(textBackgroundColor);
  6981. setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0);
  6982. setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent');
  6983. setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0);
  6984. setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0);
  6985. if (isPlainBg || (textBorderWidth && textBorderColor)) {
  6986. ctx.beginPath();
  6987. var textBorderRadius = style.textBorderRadius;
  6988. if (!textBorderRadius) {
  6989. ctx.rect(x, y, width, height);
  6990. }
  6991. else {
  6992. buildPath(ctx, {
  6993. x: x, y: y, width: width, height: height, r: textBorderRadius
  6994. });
  6995. }
  6996. ctx.closePath();
  6997. }
  6998. if (isPlainBg) {
  6999. setCtx(ctx, 'fillStyle', textBackgroundColor);
  7000. ctx.fill();
  7001. }
  7002. else if (isObject$1(textBackgroundColor)) {
  7003. var image = textBackgroundColor.image;
  7004. image = createOrUpdateImage(
  7005. image, null, hostEl, onBgImageLoaded, textBackgroundColor
  7006. );
  7007. if (image && isImageReady(image)) {
  7008. ctx.drawImage(image, x, y, width, height);
  7009. }
  7010. }
  7011. if (textBorderWidth && textBorderColor) {
  7012. setCtx(ctx, 'lineWidth', textBorderWidth);
  7013. setCtx(ctx, 'strokeStyle', textBorderColor);
  7014. ctx.stroke();
  7015. }
  7016. }
  7017. function onBgImageLoaded(image, textBackgroundColor) {
  7018. // Replace image, so that `contain/text.js#parseRichText`
  7019. // will get correct result in next tick.
  7020. textBackgroundColor.image = image;
  7021. }
  7022. function getBoxPosition(blockHeiht, style, rect) {
  7023. var baseX = style.x || 0;
  7024. var baseY = style.y || 0;
  7025. var textAlign = style.textAlign;
  7026. var textVerticalAlign = style.textVerticalAlign;
  7027. // Text position represented by coord
  7028. if (rect) {
  7029. var textPosition = style.textPosition;
  7030. if (textPosition instanceof Array) {
  7031. // Percent
  7032. baseX = rect.x + parsePercent(textPosition[0], rect.width);
  7033. baseY = rect.y + parsePercent(textPosition[1], rect.height);
  7034. }
  7035. else {
  7036. var res = adjustTextPositionOnRect(
  7037. textPosition, rect, style.textDistance
  7038. );
  7039. baseX = res.x;
  7040. baseY = res.y;
  7041. // Default align and baseline when has textPosition
  7042. textAlign = textAlign || res.textAlign;
  7043. textVerticalAlign = textVerticalAlign || res.textVerticalAlign;
  7044. }
  7045. // textOffset is only support in RectText, otherwise
  7046. // we have to adjust boundingRect for textOffset.
  7047. var textOffset = style.textOffset;
  7048. if (textOffset) {
  7049. baseX += textOffset[0];
  7050. baseY += textOffset[1];
  7051. }
  7052. }
  7053. return {
  7054. baseX: baseX,
  7055. baseY: baseY,
  7056. textAlign: textAlign,
  7057. textVerticalAlign: textVerticalAlign
  7058. };
  7059. }
  7060. function setCtx(ctx, prop, value) {
  7061. ctx[prop] = fixShadow(ctx, prop, value);
  7062. return ctx[prop];
  7063. }
  7064. /**
  7065. * @param {string} [stroke] If specified, do not check style.textStroke.
  7066. * @param {string} [lineWidth] If specified, do not check style.textStroke.
  7067. * @param {number} style
  7068. */
  7069. function getStroke(stroke, lineWidth) {
  7070. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  7071. ? null
  7072. // TODO pattern and gradient?
  7073. : (stroke.image || stroke.colorStops)
  7074. ? '#000'
  7075. : stroke;
  7076. }
  7077. function getFill(fill) {
  7078. return (fill == null || fill === 'none')
  7079. ? null
  7080. // TODO pattern and gradient?
  7081. : (fill.image || fill.colorStops)
  7082. ? '#000'
  7083. : fill;
  7084. }
  7085. function parsePercent(value, maxValue) {
  7086. if (typeof value === 'string') {
  7087. if (value.lastIndexOf('%') >= 0) {
  7088. return parseFloat(value) / 100 * maxValue;
  7089. }
  7090. return parseFloat(value);
  7091. }
  7092. return value;
  7093. }
  7094. function getTextXForPadding(x, textAlign, textPadding) {
  7095. return textAlign === 'right'
  7096. ? (x - textPadding[1])
  7097. : textAlign === 'center'
  7098. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  7099. : (x + textPadding[3]);
  7100. }
  7101. /**
  7102. * @param {string} text
  7103. * @param {module:zrender/Style} style
  7104. * @return {boolean}
  7105. */
  7106. function needDrawText(text, style) {
  7107. return text != null
  7108. && (text
  7109. || style.textBackgroundColor
  7110. || (style.textBorderWidth && style.textBorderColor)
  7111. || style.textPadding
  7112. );
  7113. }
  7114. /**
  7115. * Mixin for drawing text in a element bounding rect
  7116. * @module zrender/mixin/RectText
  7117. */
  7118. var tmpRect$1 = new BoundingRect();
  7119. var RectText = function () {};
  7120. RectText.prototype = {
  7121. constructor: RectText,
  7122. /**
  7123. * Draw text in a rect with specified position.
  7124. * @param {CanvasRenderingContext2D} ctx
  7125. * @param {Object} rect Displayable rect
  7126. */
  7127. drawRectText: function (ctx, rect) {
  7128. var style = this.style;
  7129. rect = style.textRect || rect;
  7130. // Optimize, avoid normalize every time.
  7131. this.__dirty && normalizeTextStyle(style, true);
  7132. var text = style.text;
  7133. // Convert to string
  7134. text != null && (text += '');
  7135. if (!needDrawText(text, style)) {
  7136. return;
  7137. }
  7138. // FIXME
  7139. ctx.save();
  7140. // Transform rect to view space
  7141. var transform = this.transform;
  7142. if (!style.transformText) {
  7143. if (transform) {
  7144. tmpRect$1.copy(rect);
  7145. tmpRect$1.applyTransform(transform);
  7146. rect = tmpRect$1;
  7147. }
  7148. }
  7149. else {
  7150. this.setTransform(ctx);
  7151. }
  7152. // transformText and textRotation can not be used at the same time.
  7153. renderText(this, ctx, text, style, rect);
  7154. ctx.restore();
  7155. }
  7156. };
  7157. /**
  7158. * 可绘制的图形基类
  7159. * Base class of all displayable graphic objects
  7160. * @module zrender/graphic/Displayable
  7161. */
  7162. /**
  7163. * @alias module:zrender/graphic/Displayable
  7164. * @extends module:zrender/Element
  7165. * @extends module:zrender/graphic/mixin/RectText
  7166. */
  7167. function Displayable(opts) {
  7168. opts = opts || {};
  7169. Element.call(this, opts);
  7170. // Extend properties
  7171. for (var name in opts) {
  7172. if (
  7173. opts.hasOwnProperty(name) &&
  7174. name !== 'style'
  7175. ) {
  7176. this[name] = opts[name];
  7177. }
  7178. }
  7179. /**
  7180. * @type {module:zrender/graphic/Style}
  7181. */
  7182. this.style = new Style(opts.style, this);
  7183. this._rect = null;
  7184. // Shapes for cascade clipping.
  7185. this.__clipPaths = [];
  7186. // FIXME Stateful must be mixined after style is setted
  7187. // Stateful.call(this, opts);
  7188. }
  7189. Displayable.prototype = {
  7190. constructor: Displayable,
  7191. type: 'displayable',
  7192. /**
  7193. * Displayable 是否为脏,Painter 中会根据该标记判断是否需要是否需要重新绘制
  7194. * Dirty flag. From which painter will determine if this displayable object needs brush
  7195. * @name module:zrender/graphic/Displayable#__dirty
  7196. * @type {boolean}
  7197. */
  7198. __dirty: true,
  7199. /**
  7200. * 图形是否可见,为true时不绘制图形,但是仍能触发鼠标事件
  7201. * If ignore drawing of the displayable object. Mouse event will still be triggered
  7202. * @name module:/zrender/graphic/Displayable#invisible
  7203. * @type {boolean}
  7204. * @default false
  7205. */
  7206. invisible: false,
  7207. /**
  7208. * @name module:/zrender/graphic/Displayable#z
  7209. * @type {number}
  7210. * @default 0
  7211. */
  7212. z: 0,
  7213. /**
  7214. * @name module:/zrender/graphic/Displayable#z
  7215. * @type {number}
  7216. * @default 0
  7217. */
  7218. z2: 0,
  7219. /**
  7220. * z层level,决定绘画在哪层canvas中
  7221. * @name module:/zrender/graphic/Displayable#zlevel
  7222. * @type {number}
  7223. * @default 0
  7224. */
  7225. zlevel: 0,
  7226. /**
  7227. * 是否可拖拽
  7228. * @name module:/zrender/graphic/Displayable#draggable
  7229. * @type {boolean}
  7230. * @default false
  7231. */
  7232. draggable: false,
  7233. /**
  7234. * 是否正在拖拽
  7235. * @name module:/zrender/graphic/Displayable#draggable
  7236. * @type {boolean}
  7237. * @default false
  7238. */
  7239. dragging: false,
  7240. /**
  7241. * 是否相应鼠标事件
  7242. * @name module:/zrender/graphic/Displayable#silent
  7243. * @type {boolean}
  7244. * @default false
  7245. */
  7246. silent: false,
  7247. /**
  7248. * If enable culling
  7249. * @type {boolean}
  7250. * @default false
  7251. */
  7252. culling: false,
  7253. /**
  7254. * Mouse cursor when hovered
  7255. * @name module:/zrender/graphic/Displayable#cursor
  7256. * @type {string}
  7257. */
  7258. cursor: 'pointer',
  7259. /**
  7260. * If hover area is bounding rect
  7261. * @name module:/zrender/graphic/Displayable#rectHover
  7262. * @type {string}
  7263. */
  7264. rectHover: false,
  7265. /**
  7266. * Render the element progressively when the value >= 0,
  7267. * usefull for large data.
  7268. * @type {boolean}
  7269. */
  7270. progressive: false,
  7271. /**
  7272. * @type {boolean}
  7273. */
  7274. incremental: false,
  7275. // inplace is used with incremental
  7276. inplace: false,
  7277. beforeBrush: function (ctx) {},
  7278. afterBrush: function (ctx) {},
  7279. /**
  7280. * 图形绘制方法
  7281. * @param {CanvasRenderingContext2D} ctx
  7282. */
  7283. // Interface
  7284. brush: function (ctx, prevEl) {},
  7285. /**
  7286. * 获取最小包围盒
  7287. * @return {module:zrender/core/BoundingRect}
  7288. */
  7289. // Interface
  7290. getBoundingRect: function () {},
  7291. /**
  7292. * 判断坐标 x, y 是否在图形上
  7293. * If displayable element contain coord x, y
  7294. * @param {number} x
  7295. * @param {number} y
  7296. * @return {boolean}
  7297. */
  7298. contain: function (x, y) {
  7299. return this.rectContain(x, y);
  7300. },
  7301. /**
  7302. * @param {Function} cb
  7303. * @param {} context
  7304. */
  7305. traverse: function (cb, context) {
  7306. cb.call(context, this);
  7307. },
  7308. /**
  7309. * 判断坐标 x, y 是否在图形的包围盒上
  7310. * If bounding rect of element contain coord x, y
  7311. * @param {number} x
  7312. * @param {number} y
  7313. * @return {boolean}
  7314. */
  7315. rectContain: function (x, y) {
  7316. var coord = this.transformCoordToLocal(x, y);
  7317. var rect = this.getBoundingRect();
  7318. return rect.contain(coord[0], coord[1]);
  7319. },
  7320. /**
  7321. * 标记图形元素为脏,并且在下一帧重绘
  7322. * Mark displayable element dirty and refresh next frame
  7323. */
  7324. dirty: function () {
  7325. this.__dirty = true;
  7326. this._rect = null;
  7327. this.__zr && this.__zr.refresh();
  7328. },
  7329. /**
  7330. * 图形是否会触发事件
  7331. * If displayable object binded any event
  7332. * @return {boolean}
  7333. */
  7334. // TODO, 通过 bind 绑定的事件
  7335. // isSilent: function () {
  7336. // return !(
  7337. // this.hoverable || this.draggable
  7338. // || this.onmousemove || this.onmouseover || this.onmouseout
  7339. // || this.onmousedown || this.onmouseup || this.onclick
  7340. // || this.ondragenter || this.ondragover || this.ondragleave
  7341. // || this.ondrop
  7342. // );
  7343. // },
  7344. /**
  7345. * Alias for animate('style')
  7346. * @param {boolean} loop
  7347. */
  7348. animateStyle: function (loop) {
  7349. return this.animate('style', loop);
  7350. },
  7351. attrKV: function (key, value) {
  7352. if (key !== 'style') {
  7353. Element.prototype.attrKV.call(this, key, value);
  7354. }
  7355. else {
  7356. this.style.set(value);
  7357. }
  7358. },
  7359. /**
  7360. * @param {Object|string} key
  7361. * @param {*} value
  7362. */
  7363. setStyle: function (key, value) {
  7364. this.style.set(key, value);
  7365. this.dirty(false);
  7366. return this;
  7367. },
  7368. /**
  7369. * Use given style object
  7370. * @param {Object} obj
  7371. */
  7372. useStyle: function (obj) {
  7373. this.style = new Style(obj, this);
  7374. this.dirty(false);
  7375. return this;
  7376. }
  7377. };
  7378. inherits(Displayable, Element);
  7379. mixin(Displayable, RectText);
  7380. /**
  7381. * @alias zrender/graphic/Image
  7382. * @extends module:zrender/graphic/Displayable
  7383. * @constructor
  7384. * @param {Object} opts
  7385. */
  7386. function ZImage(opts) {
  7387. Displayable.call(this, opts);
  7388. }
  7389. ZImage.prototype = {
  7390. constructor: ZImage,
  7391. type: 'image',
  7392. brush: function (ctx, prevEl) {
  7393. var style = this.style;
  7394. var src = style.image;
  7395. // Must bind each time
  7396. style.bind(ctx, this, prevEl);
  7397. var image = this._image = createOrUpdateImage(
  7398. src,
  7399. this._image,
  7400. this,
  7401. this.onload
  7402. );
  7403. if (!image || !isImageReady(image)) {
  7404. return;
  7405. }
  7406. // 图片已经加载完成
  7407. // if (image.nodeName.toUpperCase() == 'IMG') {
  7408. // if (!image.complete) {
  7409. // return;
  7410. // }
  7411. // }
  7412. // Else is canvas
  7413. var x = style.x || 0;
  7414. var y = style.y || 0;
  7415. var width = style.width;
  7416. var height = style.height;
  7417. var aspect = image.width / image.height;
  7418. if (width == null && height != null) {
  7419. // Keep image/height ratio
  7420. width = height * aspect;
  7421. }
  7422. else if (height == null && width != null) {
  7423. height = width / aspect;
  7424. }
  7425. else if (width == null && height == null) {
  7426. width = image.width;
  7427. height = image.height;
  7428. }
  7429. // 设置transform
  7430. this.setTransform(ctx);
  7431. if (style.sWidth && style.sHeight) {
  7432. var sx = style.sx || 0;
  7433. var sy = style.sy || 0;
  7434. ctx.drawImage(
  7435. image,
  7436. sx, sy, style.sWidth, style.sHeight,
  7437. x, y, width, height
  7438. );
  7439. }
  7440. else if (style.sx && style.sy) {
  7441. var sx = style.sx;
  7442. var sy = style.sy;
  7443. var sWidth = width - sx;
  7444. var sHeight = height - sy;
  7445. ctx.drawImage(
  7446. image,
  7447. sx, sy, sWidth, sHeight,
  7448. x, y, width, height
  7449. );
  7450. }
  7451. else {
  7452. ctx.drawImage(image, x, y, width, height);
  7453. }
  7454. // Draw rect text
  7455. if (style.text != null) {
  7456. // Only restore transform when needs draw text.
  7457. this.restoreTransform(ctx);
  7458. this.drawRectText(ctx, this.getBoundingRect());
  7459. }
  7460. },
  7461. getBoundingRect: function () {
  7462. var style = this.style;
  7463. if (! this._rect) {
  7464. this._rect = new BoundingRect(
  7465. style.x || 0, style.y || 0, style.width || 0, style.height || 0
  7466. );
  7467. }
  7468. return this._rect;
  7469. }
  7470. };
  7471. inherits(ZImage, Displayable);
  7472. var HOVER_LAYER_ZLEVEL = 1e5;
  7473. var CANVAS_ZLEVEL = 314159;
  7474. var EL_AFTER_INCREMENTAL_INC = 0.01;
  7475. var INCREMENTAL_INC = 0.001;
  7476. function parseInt10(val) {
  7477. return parseInt(val, 10);
  7478. }
  7479. function isLayerValid(layer) {
  7480. if (!layer) {
  7481. return false;
  7482. }
  7483. if (layer.__builtin__) {
  7484. return true;
  7485. }
  7486. if (typeof(layer.resize) !== 'function'
  7487. || typeof(layer.refresh) !== 'function'
  7488. ) {
  7489. return false;
  7490. }
  7491. return true;
  7492. }
  7493. var tmpRect = new BoundingRect(0, 0, 0, 0);
  7494. var viewRect = new BoundingRect(0, 0, 0, 0);
  7495. function isDisplayableCulled(el, width, height) {
  7496. tmpRect.copy(el.getBoundingRect());
  7497. if (el.transform) {
  7498. tmpRect.applyTransform(el.transform);
  7499. }
  7500. viewRect.width = width;
  7501. viewRect.height = height;
  7502. return !tmpRect.intersect(viewRect);
  7503. }
  7504. function isClipPathChanged(clipPaths, prevClipPaths) {
  7505. if (clipPaths == prevClipPaths) { // Can both be null or undefined
  7506. return false;
  7507. }
  7508. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  7509. return true;
  7510. }
  7511. for (var i = 0; i < clipPaths.length; i++) {
  7512. if (clipPaths[i] !== prevClipPaths[i]) {
  7513. return true;
  7514. }
  7515. }
  7516. }
  7517. function doClip(clipPaths, ctx) {
  7518. for (var i = 0; i < clipPaths.length; i++) {
  7519. var clipPath = clipPaths[i];
  7520. clipPath.setTransform(ctx);
  7521. ctx.beginPath();
  7522. clipPath.buildPath(ctx, clipPath.shape);
  7523. ctx.clip();
  7524. // Transform back
  7525. clipPath.restoreTransform(ctx);
  7526. }
  7527. }
  7528. function createRoot(width, height) {
  7529. var domRoot = document.createElement('div');
  7530. // domRoot.onselectstart = returnFalse; // 避免页面选中的尴尬
  7531. domRoot.style.cssText = [
  7532. 'position:relative',
  7533. 'overflow:hidden',
  7534. 'width:' + width + 'px',
  7535. 'height:' + height + 'px',
  7536. 'padding:0',
  7537. 'margin:0',
  7538. 'border-width:0'
  7539. ].join(';') + ';';
  7540. return domRoot;
  7541. }
  7542. /**
  7543. * @alias module:zrender/Painter
  7544. * @constructor
  7545. * @param {HTMLElement} root 绘图容器
  7546. * @param {module:zrender/Storage} storage
  7547. * @param {Object} opts
  7548. */
  7549. var Painter = function (root, storage, opts) {
  7550. this.type = 'canvas';
  7551. // In node environment using node-canvas
  7552. var singleCanvas = !root.nodeName // In node ?
  7553. || root.nodeName.toUpperCase() === 'CANVAS';
  7554. this._opts = opts = extend({}, opts || {});
  7555. /**
  7556. * @type {number}
  7557. */
  7558. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  7559. /**
  7560. * @type {boolean}
  7561. * @private
  7562. */
  7563. this._singleCanvas = singleCanvas;
  7564. /**
  7565. * 绘图容器
  7566. * @type {HTMLElement}
  7567. */
  7568. this.root = root;
  7569. var rootStyle = root.style;
  7570. if (rootStyle) {
  7571. rootStyle['-webkit-tap-highlight-color'] = 'transparent';
  7572. rootStyle['-webkit-user-select'] =
  7573. rootStyle['user-select'] =
  7574. rootStyle['-webkit-touch-callout'] = 'none';
  7575. root.innerHTML = '';
  7576. }
  7577. /**
  7578. * @type {module:zrender/Storage}
  7579. */
  7580. this.storage = storage;
  7581. /**
  7582. * @type {Array.<number>}
  7583. * @private
  7584. */
  7585. var zlevelList = this._zlevelList = [];
  7586. /**
  7587. * @type {Object.<string, module:zrender/Layer>}
  7588. * @private
  7589. */
  7590. var layers = this._layers = {};
  7591. /**
  7592. * @type {Object.<string, Object>}
  7593. * @private
  7594. */
  7595. this._layerConfig = {};
  7596. /**
  7597. * zrender will do compositing when root is a canvas and have multiple zlevels.
  7598. */
  7599. this._needsManuallyCompositing = false;
  7600. if (!singleCanvas) {
  7601. this._width = this._getSize(0);
  7602. this._height = this._getSize(1);
  7603. var domRoot = this._domRoot = createRoot(
  7604. this._width, this._height
  7605. );
  7606. root.appendChild(domRoot);
  7607. }
  7608. else {
  7609. var width = root.width;
  7610. var height = root.height;
  7611. if (opts.width != null) {
  7612. width = opts.width;
  7613. }
  7614. if (opts.height != null) {
  7615. height = opts.height;
  7616. }
  7617. this.dpr = opts.devicePixelRatio || 1;
  7618. // Use canvas width and height directly
  7619. root.width = width * this.dpr;
  7620. root.height = height * this.dpr;
  7621. this._width = width;
  7622. this._height = height;
  7623. // Create layer if only one given canvas
  7624. // Device can be specified to create a high dpi image.
  7625. var mainLayer = new Layer(root, this, this.dpr);
  7626. mainLayer.__builtin__ = true;
  7627. mainLayer.initContext();
  7628. // FIXME Use canvas width and height
  7629. // mainLayer.resize(width, height);
  7630. layers[CANVAS_ZLEVEL] = mainLayer;
  7631. // Not use common zlevel.
  7632. zlevelList.push(CANVAS_ZLEVEL);
  7633. this._domRoot = root;
  7634. }
  7635. /**
  7636. * @type {module:zrender/Layer}
  7637. * @private
  7638. */
  7639. this._hoverlayer = null;
  7640. this._hoverElements = [];
  7641. };
  7642. Painter.prototype = {
  7643. constructor: Painter,
  7644. getType: function () {
  7645. return 'canvas';
  7646. },
  7647. /**
  7648. * If painter use a single canvas
  7649. * @return {boolean}
  7650. */
  7651. isSingleCanvas: function () {
  7652. return this._singleCanvas;
  7653. },
  7654. /**
  7655. * @return {HTMLDivElement}
  7656. */
  7657. getViewportRoot: function () {
  7658. return this._domRoot;
  7659. },
  7660. getViewportRootOffset: function () {
  7661. var viewportRoot = this.getViewportRoot();
  7662. if (viewportRoot) {
  7663. return {
  7664. offsetLeft: viewportRoot.offsetLeft || 0,
  7665. offsetTop: viewportRoot.offsetTop || 0
  7666. };
  7667. }
  7668. },
  7669. /**
  7670. * 刷新
  7671. * @param {boolean} [paintAll=false] 强制绘制所有displayable
  7672. */
  7673. refresh: function (paintAll) {
  7674. var list = this.storage.getDisplayList(true);
  7675. var zlevelList = this._zlevelList;
  7676. this._redrawId = Math.random();
  7677. this._paintList(list, paintAll, this._redrawId);
  7678. // Paint custum layers
  7679. for (var i = 0; i < zlevelList.length; i++) {
  7680. var z = zlevelList[i];
  7681. var layer = this._layers[z];
  7682. if (!layer.__builtin__ && layer.refresh) {
  7683. var clearColor = i === 0 ? this._backgroundColor : null;
  7684. layer.refresh(clearColor);
  7685. }
  7686. }
  7687. this.refreshHover();
  7688. return this;
  7689. },
  7690. addHover: function (el, hoverStyle) {
  7691. if (el.__hoverMir) {
  7692. return;
  7693. }
  7694. var elMirror = new el.constructor({
  7695. style: el.style,
  7696. shape: el.shape
  7697. });
  7698. elMirror.__from = el;
  7699. el.__hoverMir = elMirror;
  7700. elMirror.setStyle(hoverStyle);
  7701. this._hoverElements.push(elMirror);
  7702. },
  7703. removeHover: function (el) {
  7704. var elMirror = el.__hoverMir;
  7705. var hoverElements = this._hoverElements;
  7706. var idx = indexOf(hoverElements, elMirror);
  7707. if (idx >= 0) {
  7708. hoverElements.splice(idx, 1);
  7709. }
  7710. el.__hoverMir = null;
  7711. },
  7712. clearHover: function (el) {
  7713. var hoverElements = this._hoverElements;
  7714. for (var i = 0; i < hoverElements.length; i++) {
  7715. var from = hoverElements[i].__from;
  7716. if (from) {
  7717. from.__hoverMir = null;
  7718. }
  7719. }
  7720. hoverElements.length = 0;
  7721. },
  7722. refreshHover: function () {
  7723. var hoverElements = this._hoverElements;
  7724. var len = hoverElements.length;
  7725. var hoverLayer = this._hoverlayer;
  7726. hoverLayer && hoverLayer.clear();
  7727. if (!len) {
  7728. return;
  7729. }
  7730. sort(hoverElements, this.storage.displayableSortFunc);
  7731. // Use a extream large zlevel
  7732. // FIXME?
  7733. if (!hoverLayer) {
  7734. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  7735. }
  7736. var scope = {};
  7737. hoverLayer.ctx.save();
  7738. for (var i = 0; i < len;) {
  7739. var el = hoverElements[i];
  7740. var originalEl = el.__from;
  7741. // Original el is removed
  7742. // PENDING
  7743. if (!(originalEl && originalEl.__zr)) {
  7744. hoverElements.splice(i, 1);
  7745. originalEl.__hoverMir = null;
  7746. len--;
  7747. continue;
  7748. }
  7749. i++;
  7750. // Use transform
  7751. // FIXME style and shape ?
  7752. if (!originalEl.invisible) {
  7753. el.transform = originalEl.transform;
  7754. el.invTransform = originalEl.invTransform;
  7755. el.__clipPaths = originalEl.__clipPaths;
  7756. // el.
  7757. this._doPaintEl(el, hoverLayer, true, scope);
  7758. }
  7759. }
  7760. hoverLayer.ctx.restore();
  7761. },
  7762. getHoverLayer: function () {
  7763. return this.getLayer(HOVER_LAYER_ZLEVEL);
  7764. },
  7765. _paintList: function (list, paintAll, redrawId) {
  7766. if (this._redrawId !== redrawId) {
  7767. return;
  7768. }
  7769. paintAll = paintAll || false;
  7770. this._updateLayerStatus(list);
  7771. var finished = this._doPaintList(list, paintAll);
  7772. if (this._needsManuallyCompositing) {
  7773. this._compositeManually();
  7774. }
  7775. if (!finished) {
  7776. var self = this;
  7777. requestAnimationFrame(function () {
  7778. self._paintList(list, paintAll, redrawId);
  7779. });
  7780. }
  7781. },
  7782. _compositeManually: function () {
  7783. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  7784. var width = this._domRoot.width;
  7785. var height = this._domRoot.height;
  7786. ctx.clearRect(0, 0, width, height);
  7787. // PENDING, If only builtin layer?
  7788. this.eachBuiltinLayer(function (layer) {
  7789. if (layer.virtual) {
  7790. ctx.drawImage(layer.dom, 0, 0, width, height);
  7791. }
  7792. });
  7793. },
  7794. _doPaintList: function (list, paintAll) {
  7795. var layerList = [];
  7796. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  7797. var zlevel = this._zlevelList[zi];
  7798. var layer = this._layers[zlevel];
  7799. if (layer.__builtin__
  7800. && layer !== this._hoverlayer
  7801. && (layer.__dirty || paintAll)
  7802. ) {
  7803. layerList.push(layer);
  7804. }
  7805. }
  7806. var finished = true;
  7807. for (var k = 0; k < layerList.length; k++) {
  7808. var layer = layerList[k];
  7809. var ctx = layer.ctx;
  7810. var scope = {};
  7811. ctx.save();
  7812. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  7813. var useTimer = !paintAll && layer.incremental && Date.now;
  7814. var startTime = useTimer && Date.now();
  7815. var clearColor = layer.zlevel === this._zlevelList[0]
  7816. ? this._backgroundColor : null;
  7817. // All elements in this layer are cleared.
  7818. if (layer.__startIndex === layer.__endIndex) {
  7819. layer.clear(false, clearColor);
  7820. }
  7821. else if (start === layer.__startIndex) {
  7822. var firstEl = list[start];
  7823. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  7824. layer.clear(false, clearColor);
  7825. }
  7826. }
  7827. if (start === -1) {
  7828. console.error('For some unknown reason. drawIndex is -1');
  7829. start = layer.__startIndex;
  7830. }
  7831. for (var i = start; i < layer.__endIndex; i++) {
  7832. var el = list[i];
  7833. this._doPaintEl(el, layer, paintAll, scope);
  7834. el.__dirty = false;
  7835. if (useTimer) {
  7836. // Date.now can be executed in 13,025,305 ops/second.
  7837. var dTime = Date.now() - startTime;
  7838. // Give 15 millisecond to draw.
  7839. // The rest elements will be drawn in the next frame.
  7840. if (dTime > 15) {
  7841. break;
  7842. }
  7843. }
  7844. }
  7845. layer.__drawIndex = i;
  7846. if (layer.__drawIndex < layer.__endIndex) {
  7847. finished = false;
  7848. }
  7849. if (scope.prevElClipPaths) {
  7850. // Needs restore the state. If last drawn element is in the clipping area.
  7851. ctx.restore();
  7852. }
  7853. ctx.restore();
  7854. }
  7855. if (env$1.wxa) {
  7856. // Flush for weixin application
  7857. each$1(this._layers, function (layer) {
  7858. if (layer && layer.ctx && layer.ctx.draw) {
  7859. layer.ctx.draw();
  7860. }
  7861. });
  7862. }
  7863. return finished;
  7864. },
  7865. _doPaintEl: function (el, currentLayer, forcePaint, scope) {
  7866. var ctx = currentLayer.ctx;
  7867. var m = el.transform;
  7868. if (
  7869. (currentLayer.__dirty || forcePaint)
  7870. // Ignore invisible element
  7871. && !el.invisible
  7872. // Ignore transparent element
  7873. && el.style.opacity !== 0
  7874. // Ignore scale 0 element, in some environment like node-canvas
  7875. // Draw a scale 0 element can cause all following draw wrong
  7876. // And setTransform with scale 0 will cause set back transform failed.
  7877. && !(m && !m[0] && !m[3])
  7878. // Ignore culled element
  7879. && !(el.culling && isDisplayableCulled(el, this._width, this._height))
  7880. ) {
  7881. var clipPaths = el.__clipPaths;
  7882. // Optimize when clipping on group with several elements
  7883. if (!scope.prevElClipPaths
  7884. || isClipPathChanged(clipPaths, scope.prevElClipPaths)
  7885. ) {
  7886. // If has previous clipping state, restore from it
  7887. if (scope.prevElClipPaths) {
  7888. currentLayer.ctx.restore();
  7889. scope.prevElClipPaths = null;
  7890. // Reset prevEl since context has been restored
  7891. scope.prevEl = null;
  7892. }
  7893. // New clipping state
  7894. if (clipPaths) {
  7895. ctx.save();
  7896. doClip(clipPaths, ctx);
  7897. scope.prevElClipPaths = clipPaths;
  7898. }
  7899. }
  7900. el.beforeBrush && el.beforeBrush(ctx);
  7901. el.brush(ctx, scope.prevEl || null);
  7902. scope.prevEl = el;
  7903. el.afterBrush && el.afterBrush(ctx);
  7904. }
  7905. },
  7906. /**
  7907. * 获取 zlevel 所在层,如果不存在则会创建一个新的层
  7908. * @param {number} zlevel
  7909. * @param {boolean} virtual Virtual layer will not be inserted into dom.
  7910. * @return {module:zrender/Layer}
  7911. */
  7912. getLayer: function (zlevel, virtual) {
  7913. if (this._singleCanvas && !this._needsManuallyCompositing) {
  7914. zlevel = CANVAS_ZLEVEL;
  7915. }
  7916. var layer = this._layers[zlevel];
  7917. if (!layer) {
  7918. // Create a new layer
  7919. layer = new Layer('zr_' + zlevel, this, this.dpr);
  7920. layer.zlevel = zlevel;
  7921. layer.__builtin__ = true;
  7922. if (this._layerConfig[zlevel]) {
  7923. merge(layer, this._layerConfig[zlevel], true);
  7924. }
  7925. if (virtual) {
  7926. layer.virtual = virtual;
  7927. }
  7928. this.insertLayer(zlevel, layer);
  7929. // Context is created after dom inserted to document
  7930. // Or excanvas will get 0px clientWidth and clientHeight
  7931. layer.initContext();
  7932. }
  7933. return layer;
  7934. },
  7935. insertLayer: function (zlevel, layer) {
  7936. var layersMap = this._layers;
  7937. var zlevelList = this._zlevelList;
  7938. var len = zlevelList.length;
  7939. var prevLayer = null;
  7940. var i = -1;
  7941. var domRoot = this._domRoot;
  7942. if (layersMap[zlevel]) {
  7943. zrLog('ZLevel ' + zlevel + ' has been used already');
  7944. return;
  7945. }
  7946. // Check if is a valid layer
  7947. if (!isLayerValid(layer)) {
  7948. zrLog('Layer of zlevel ' + zlevel + ' is not valid');
  7949. return;
  7950. }
  7951. if (len > 0 && zlevel > zlevelList[0]) {
  7952. for (i = 0; i < len - 1; i++) {
  7953. if (
  7954. zlevelList[i] < zlevel
  7955. && zlevelList[i + 1] > zlevel
  7956. ) {
  7957. break;
  7958. }
  7959. }
  7960. prevLayer = layersMap[zlevelList[i]];
  7961. }
  7962. zlevelList.splice(i + 1, 0, zlevel);
  7963. layersMap[zlevel] = layer;
  7964. // Vitual layer will not directly show on the screen.
  7965. // (It can be a WebGL layer and assigned to a ZImage element)
  7966. // But it still under management of zrender.
  7967. if (!layer.virtual) {
  7968. if (prevLayer) {
  7969. var prevDom = prevLayer.dom;
  7970. if (prevDom.nextSibling) {
  7971. domRoot.insertBefore(
  7972. layer.dom,
  7973. prevDom.nextSibling
  7974. );
  7975. }
  7976. else {
  7977. domRoot.appendChild(layer.dom);
  7978. }
  7979. }
  7980. else {
  7981. if (domRoot.firstChild) {
  7982. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  7983. }
  7984. else {
  7985. domRoot.appendChild(layer.dom);
  7986. }
  7987. }
  7988. }
  7989. },
  7990. // Iterate each layer
  7991. eachLayer: function (cb, context) {
  7992. var zlevelList = this._zlevelList;
  7993. var z;
  7994. var i;
  7995. for (i = 0; i < zlevelList.length; i++) {
  7996. z = zlevelList[i];
  7997. cb.call(context, this._layers[z], z);
  7998. }
  7999. },
  8000. // Iterate each buildin layer
  8001. eachBuiltinLayer: function (cb, context) {
  8002. var zlevelList = this._zlevelList;
  8003. var layer;
  8004. var z;
  8005. var i;
  8006. for (i = 0; i < zlevelList.length; i++) {
  8007. z = zlevelList[i];
  8008. layer = this._layers[z];
  8009. if (layer.__builtin__) {
  8010. cb.call(context, layer, z);
  8011. }
  8012. }
  8013. },
  8014. // Iterate each other layer except buildin layer
  8015. eachOtherLayer: function (cb, context) {
  8016. var zlevelList = this._zlevelList;
  8017. var layer;
  8018. var z;
  8019. var i;
  8020. for (i = 0; i < zlevelList.length; i++) {
  8021. z = zlevelList[i];
  8022. layer = this._layers[z];
  8023. if (!layer.__builtin__) {
  8024. cb.call(context, layer, z);
  8025. }
  8026. }
  8027. },
  8028. /**
  8029. * 获取所有已创建的层
  8030. * @param {Array.<module:zrender/Layer>} [prevLayer]
  8031. */
  8032. getLayers: function () {
  8033. return this._layers;
  8034. },
  8035. _updateLayerStatus: function (list) {
  8036. this.eachBuiltinLayer(function (layer, z) {
  8037. layer.__dirty = layer.__used = false;
  8038. });
  8039. function updatePrevLayer(idx) {
  8040. if (prevLayer) {
  8041. if (prevLayer.__endIndex !== idx) {
  8042. prevLayer.__dirty = true;
  8043. }
  8044. prevLayer.__endIndex = idx;
  8045. }
  8046. }
  8047. if (this._singleCanvas) {
  8048. for (var i = 1; i < list.length; i++) {
  8049. var el = list[i];
  8050. if (el.zlevel !== list[i - 1].zlevel || el.incremental) {
  8051. this._needsManuallyCompositing = true;
  8052. break;
  8053. }
  8054. }
  8055. }
  8056. var prevLayer = null;
  8057. var incrementalLayerCount = 0;
  8058. for (var i = 0; i < list.length; i++) {
  8059. var el = list[i];
  8060. var zlevel = el.zlevel;
  8061. var layer;
  8062. // PENDING If change one incremental element style ?
  8063. // TODO Where there are non-incremental elements between incremental elements.
  8064. if (el.incremental) {
  8065. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  8066. layer.incremental = true;
  8067. incrementalLayerCount = 1;
  8068. }
  8069. else {
  8070. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  8071. }
  8072. if (!layer.__builtin__) {
  8073. zrLog('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  8074. }
  8075. if (layer !== prevLayer) {
  8076. layer.__used = true;
  8077. if (layer.__startIndex !== i) {
  8078. layer.__dirty = true;
  8079. }
  8080. layer.__startIndex = i;
  8081. if (!layer.incremental) {
  8082. layer.__drawIndex = i;
  8083. }
  8084. else {
  8085. // Mark layer draw index needs to update.
  8086. layer.__drawIndex = -1;
  8087. }
  8088. updatePrevLayer(i);
  8089. prevLayer = layer;
  8090. }
  8091. if (el.__dirty) {
  8092. layer.__dirty = true;
  8093. if (layer.incremental && layer.__drawIndex < 0) {
  8094. // Start draw from the first dirty element.
  8095. layer.__drawIndex = i;
  8096. }
  8097. }
  8098. }
  8099. updatePrevLayer(i);
  8100. this.eachBuiltinLayer(function (layer, z) {
  8101. // Used in last frame but not in this frame. Needs clear
  8102. if (!layer.__used && layer.getElementCount() > 0) {
  8103. layer.__dirty = true;
  8104. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  8105. }
  8106. // For incremental layer. In case start index changed and no elements are dirty.
  8107. if (layer.__dirty && layer.__drawIndex < 0) {
  8108. layer.__drawIndex = layer.__startIndex;
  8109. }
  8110. });
  8111. },
  8112. /**
  8113. * 清除hover层外所有内容
  8114. */
  8115. clear: function () {
  8116. this.eachBuiltinLayer(this._clearLayer);
  8117. return this;
  8118. },
  8119. _clearLayer: function (layer) {
  8120. layer.clear();
  8121. },
  8122. setBackgroundColor: function (backgroundColor) {
  8123. this._backgroundColor = backgroundColor;
  8124. },
  8125. /**
  8126. * 修改指定zlevel的绘制参数
  8127. *
  8128. * @param {string} zlevel
  8129. * @param {Object} config 配置对象
  8130. * @param {string} [config.clearColor=0] 每次清空画布的颜色
  8131. * @param {string} [config.motionBlur=false] 是否开启动态模糊
  8132. * @param {number} [config.lastFrameAlpha=0.7]
  8133. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  8134. */
  8135. configLayer: function (zlevel, config) {
  8136. if (config) {
  8137. var layerConfig = this._layerConfig;
  8138. if (!layerConfig[zlevel]) {
  8139. layerConfig[zlevel] = config;
  8140. }
  8141. else {
  8142. merge(layerConfig[zlevel], config, true);
  8143. }
  8144. for (var i = 0; i < this._zlevelList.length; i++) {
  8145. var _zlevel = this._zlevelList[i];
  8146. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  8147. var layer = this._layers[_zlevel];
  8148. merge(layer, layerConfig[zlevel], true);
  8149. }
  8150. }
  8151. }
  8152. },
  8153. /**
  8154. * 删除指定层
  8155. * @param {number} zlevel 层所在的zlevel
  8156. */
  8157. delLayer: function (zlevel) {
  8158. var layers = this._layers;
  8159. var zlevelList = this._zlevelList;
  8160. var layer = layers[zlevel];
  8161. if (!layer) {
  8162. return;
  8163. }
  8164. layer.dom.parentNode.removeChild(layer.dom);
  8165. delete layers[zlevel];
  8166. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  8167. },
  8168. /**
  8169. * 区域大小变化后重绘
  8170. */
  8171. resize: function (width, height) {
  8172. if (!this._domRoot.style) { // Maybe in node or worker
  8173. if (width == null || height == null) {
  8174. return;
  8175. }
  8176. this._width = width;
  8177. this._height = height;
  8178. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  8179. }
  8180. else {
  8181. var domRoot = this._domRoot;
  8182. // FIXME Why ?
  8183. domRoot.style.display = 'none';
  8184. // Save input w/h
  8185. var opts = this._opts;
  8186. width != null && (opts.width = width);
  8187. height != null && (opts.height = height);
  8188. width = this._getSize(0);
  8189. height = this._getSize(1);
  8190. domRoot.style.display = '';
  8191. // 优化没有实际改变的resize
  8192. if (this._width != width || height != this._height) {
  8193. domRoot.style.width = width + 'px';
  8194. domRoot.style.height = height + 'px';
  8195. for (var id in this._layers) {
  8196. if (this._layers.hasOwnProperty(id)) {
  8197. this._layers[id].resize(width, height);
  8198. }
  8199. }
  8200. each$1(this._progressiveLayers, function (layer) {
  8201. layer.resize(width, height);
  8202. });
  8203. this.refresh(true);
  8204. }
  8205. this._width = width;
  8206. this._height = height;
  8207. }
  8208. return this;
  8209. },
  8210. /**
  8211. * 清除单独的一个层
  8212. * @param {number} zlevel
  8213. */
  8214. clearLayer: function (zlevel) {
  8215. var layer = this._layers[zlevel];
  8216. if (layer) {
  8217. layer.clear();
  8218. }
  8219. },
  8220. /**
  8221. * 释放
  8222. */
  8223. dispose: function () {
  8224. this.root.innerHTML = '';
  8225. this.root =
  8226. this.storage =
  8227. this._domRoot =
  8228. this._layers = null;
  8229. },
  8230. /**
  8231. * Get canvas which has all thing rendered
  8232. * @param {Object} opts
  8233. * @param {string} [opts.backgroundColor]
  8234. * @param {number} [opts.pixelRatio]
  8235. */
  8236. getRenderedCanvas: function (opts) {
  8237. opts = opts || {};
  8238. if (this._singleCanvas && !this._compositeManually) {
  8239. return this._layers[CANVAS_ZLEVEL].dom;
  8240. }
  8241. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  8242. imageLayer.initContext();
  8243. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  8244. if (opts.pixelRatio <= this.dpr) {
  8245. this.refresh();
  8246. var width = imageLayer.dom.width;
  8247. var height = imageLayer.dom.height;
  8248. var ctx = imageLayer.ctx;
  8249. this.eachLayer(function (layer) {
  8250. if (layer.__builtin__) {
  8251. ctx.drawImage(layer.dom, 0, 0, width, height);
  8252. }
  8253. else if (layer.renderToCanvas) {
  8254. imageLayer.ctx.save();
  8255. layer.renderToCanvas(imageLayer.ctx);
  8256. imageLayer.ctx.restore();
  8257. }
  8258. });
  8259. }
  8260. else {
  8261. // PENDING, echarts-gl and incremental rendering.
  8262. var scope = {};
  8263. var displayList = this.storage.getDisplayList(true);
  8264. for (var i = 0; i < displayList.length; i++) {
  8265. var el = displayList[i];
  8266. this._doPaintEl(el, imageLayer, true, scope);
  8267. }
  8268. }
  8269. return imageLayer.dom;
  8270. },
  8271. /**
  8272. * 获取绘图区域宽度
  8273. */
  8274. getWidth: function () {
  8275. return this._width;
  8276. },
  8277. /**
  8278. * 获取绘图区域高度
  8279. */
  8280. getHeight: function () {
  8281. return this._height;
  8282. },
  8283. _getSize: function (whIdx) {
  8284. var opts = this._opts;
  8285. var wh = ['width', 'height'][whIdx];
  8286. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  8287. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  8288. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  8289. if (opts[wh] != null && opts[wh] !== 'auto') {
  8290. return parseFloat(opts[wh]);
  8291. }
  8292. var root = this.root;
  8293. // IE8 does not support getComputedStyle, but it use VML.
  8294. var stl = document.defaultView.getComputedStyle(root);
  8295. return (
  8296. (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  8297. - (parseInt10(stl[plt]) || 0)
  8298. - (parseInt10(stl[prb]) || 0)
  8299. ) | 0;
  8300. },
  8301. pathToImage: function (path, dpr) {
  8302. dpr = dpr || this.dpr;
  8303. var canvas = document.createElement('canvas');
  8304. var ctx = canvas.getContext('2d');
  8305. var rect = path.getBoundingRect();
  8306. var style = path.style;
  8307. var shadowBlurSize = style.shadowBlur * dpr;
  8308. var shadowOffsetX = style.shadowOffsetX * dpr;
  8309. var shadowOffsetY = style.shadowOffsetY * dpr;
  8310. var lineWidth = style.hasStroke() ? style.lineWidth : 0;
  8311. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  8312. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  8313. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  8314. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  8315. var width = rect.width + leftMargin + rightMargin;
  8316. var height = rect.height + topMargin + bottomMargin;
  8317. canvas.width = width * dpr;
  8318. canvas.height = height * dpr;
  8319. ctx.scale(dpr, dpr);
  8320. ctx.clearRect(0, 0, width, height);
  8321. ctx.dpr = dpr;
  8322. var pathTransform = {
  8323. position: path.position,
  8324. rotation: path.rotation,
  8325. scale: path.scale
  8326. };
  8327. path.position = [leftMargin - rect.x, topMargin - rect.y];
  8328. path.rotation = 0;
  8329. path.scale = [1, 1];
  8330. path.updateTransform();
  8331. if (path) {
  8332. path.brush(ctx);
  8333. }
  8334. var ImageShape = ZImage;
  8335. var imgShape = new ImageShape({
  8336. style: {
  8337. x: 0,
  8338. y: 0,
  8339. image: canvas
  8340. }
  8341. });
  8342. if (pathTransform.position != null) {
  8343. imgShape.position = path.position = pathTransform.position;
  8344. }
  8345. if (pathTransform.rotation != null) {
  8346. imgShape.rotation = path.rotation = pathTransform.rotation;
  8347. }
  8348. if (pathTransform.scale != null) {
  8349. imgShape.scale = path.scale = pathTransform.scale;
  8350. }
  8351. return imgShape;
  8352. }
  8353. };
  8354. /**
  8355. * 事件辅助类
  8356. * @module zrender/core/event
  8357. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  8358. */
  8359. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  8360. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  8361. function getBoundingClientRect(el) {
  8362. // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect
  8363. return el.getBoundingClientRect ? el.getBoundingClientRect() : {left: 0, top: 0};
  8364. }
  8365. // `calculate` is optional, default false
  8366. function clientToLocal(el, e, out, calculate) {
  8367. out = out || {};
  8368. // According to the W3C Working Draft, offsetX and offsetY should be relative
  8369. // to the padding edge of the target element. The only browser using this convention
  8370. // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does
  8371. // not support the properties.
  8372. // (see http://www.jacklmoore.com/notes/mouse-position/)
  8373. // In zr painter.dom, padding edge equals to border edge.
  8374. // FIXME
  8375. // When mousemove event triggered on ec tooltip, target is not zr painter.dom, and
  8376. // offsetX/Y is relative to e.target, where the calculation of zrX/Y via offsetX/Y
  8377. // is too complex. So css-transfrom dont support in this case temporarily.
  8378. if (calculate || !env$1.canvasSupported) {
  8379. defaultGetZrXY(el, e, out);
  8380. }
  8381. // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned
  8382. // ancestor element, so we should make sure el is positioned (e.g., not position:static).
  8383. // BTW1, Webkit don't return the same results as FF in non-simple cases (like add
  8384. // zoom-factor, overflow / opacity layers, transforms ...)
  8385. // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d.
  8386. // <https://bugs.jquery.com/ticket/8523#comment:14>
  8387. // BTW3, In ff, offsetX/offsetY is always 0.
  8388. else if (env$1.browser.firefox && e.layerX != null && e.layerX !== e.offsetX) {
  8389. out.zrX = e.layerX;
  8390. out.zrY = e.layerY;
  8391. }
  8392. // For IE6+, chrome, safari, opera. (When will ff support offsetX?)
  8393. else if (e.offsetX != null) {
  8394. out.zrX = e.offsetX;
  8395. out.zrY = e.offsetY;
  8396. }
  8397. // For some other device, e.g., IOS safari.
  8398. else {
  8399. defaultGetZrXY(el, e, out);
  8400. }
  8401. return out;
  8402. }
  8403. function defaultGetZrXY(el, e, out) {
  8404. // This well-known method below does not support css transform.
  8405. var box = getBoundingClientRect(el);
  8406. out.zrX = e.clientX - box.left;
  8407. out.zrY = e.clientY - box.top;
  8408. }
  8409. /**
  8410. * 如果存在第三方嵌入的一些dom触发的事件,或touch事件,需要转换一下事件坐标.
  8411. * `calculate` is optional, default false.
  8412. */
  8413. function normalizeEvent(el, e, calculate) {
  8414. e = e || window.event;
  8415. if (e.zrX != null) {
  8416. return e;
  8417. }
  8418. var eventType = e.type;
  8419. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  8420. if (!isTouch) {
  8421. clientToLocal(el, e, e, calculate);
  8422. e.zrDelta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
  8423. }
  8424. else {
  8425. var touch = eventType != 'touchend'
  8426. ? e.targetTouches[0]
  8427. : e.changedTouches[0];
  8428. touch && clientToLocal(el, touch, e, calculate);
  8429. }
  8430. // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0;
  8431. // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js
  8432. // If e.which has been defined, if may be readonly,
  8433. // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  8434. var button = e.button;
  8435. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  8436. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  8437. }
  8438. return e;
  8439. }
  8440. /**
  8441. * @param {HTMLElement} el
  8442. * @param {string} name
  8443. * @param {Function} handler
  8444. */
  8445. function addEventListener(el, name, handler) {
  8446. if (isDomLevel2) {
  8447. // Reproduct the console warning:
  8448. // [Violation] Added non-passive event listener to a scroll-blocking <some> event.
  8449. // Consider marking event handler as 'passive' to make the page more responsive.
  8450. // Just set console log level: verbose in chrome dev tool.
  8451. // then the warning log will be printed when addEventListener called.
  8452. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
  8453. // We have not yet found a neat way to using passive. Because in zrender the dom event
  8454. // listener delegate all of the upper events of element. Some of those events need
  8455. // to prevent default. For example, the feature `preventDefaultMouseMove` of echarts.
  8456. // Before passive can be adopted, these issues should be considered:
  8457. // (1) Whether and how a zrender user specifies an event listener passive. And by default,
  8458. // passive or not.
  8459. // (2) How to tread that some zrender event listener is passive, and some is not. If
  8460. // we use other way but not preventDefault of mousewheel and touchmove, browser
  8461. // compatibility should be handled.
  8462. // var opts = (env.passiveSupported && name === 'mousewheel')
  8463. // ? {passive: true}
  8464. // // By default, the third param of el.addEventListener is `capture: false`.
  8465. // : void 0;
  8466. // el.addEventListener(name, handler /* , opts */);
  8467. el.addEventListener(name, handler);
  8468. }
  8469. else {
  8470. el.attachEvent('on' + name, handler);
  8471. }
  8472. }
  8473. function removeEventListener(el, name, handler) {
  8474. if (isDomLevel2) {
  8475. el.removeEventListener(name, handler);
  8476. }
  8477. else {
  8478. el.detachEvent('on' + name, handler);
  8479. }
  8480. }
  8481. /**
  8482. * preventDefault and stopPropagation.
  8483. * Notice: do not do that in zrender. Upper application
  8484. * do that if necessary.
  8485. *
  8486. * @memberOf module:zrender/core/event
  8487. * @method
  8488. * @param {Event} e : event对象
  8489. */
  8490. var stop = isDomLevel2
  8491. ? function (e) {
  8492. e.preventDefault();
  8493. e.stopPropagation();
  8494. e.cancelBubble = true;
  8495. }
  8496. : function (e) {
  8497. e.returnValue = false;
  8498. e.cancelBubble = true;
  8499. };
  8500. function notLeftMouse(e) {
  8501. // If e.which is undefined, considered as left mouse event.
  8502. return e.which > 1;
  8503. }
  8504. /**
  8505. * 动画主类, 调度和管理所有动画控制器
  8506. *
  8507. * @module zrender/animation/Animation
  8508. * @author pissang(https://github.com/pissang)
  8509. */
  8510. // TODO Additive animation
  8511. // http://iosoteric.com/additive-animations-animatewithduration-in-ios-8/
  8512. // https://developer.apple.com/videos/wwdc2014/#236
  8513. /**
  8514. * @typedef {Object} IZRenderStage
  8515. * @property {Function} update
  8516. */
  8517. /**
  8518. * @alias module:zrender/animation/Animation
  8519. * @constructor
  8520. * @param {Object} [options]
  8521. * @param {Function} [options.onframe]
  8522. * @param {IZRenderStage} [options.stage]
  8523. * @example
  8524. * var animation = new Animation();
  8525. * var obj = {
  8526. * x: 100,
  8527. * y: 100
  8528. * };
  8529. * animation.animate(node.position)
  8530. * .when(1000, {
  8531. * x: 500,
  8532. * y: 500
  8533. * })
  8534. * .when(2000, {
  8535. * x: 100,
  8536. * y: 100
  8537. * })
  8538. * .start('spline');
  8539. */
  8540. var Animation = function (options) {
  8541. options = options || {};
  8542. this.stage = options.stage || {};
  8543. this.onframe = options.onframe || function() {};
  8544. // private properties
  8545. this._clips = [];
  8546. this._running = false;
  8547. this._time;
  8548. this._pausedTime;
  8549. this._pauseStart;
  8550. this._paused = false;
  8551. Eventful.call(this);
  8552. };
  8553. Animation.prototype = {
  8554. constructor: Animation,
  8555. /**
  8556. * 添加 clip
  8557. * @param {module:zrender/animation/Clip} clip
  8558. */
  8559. addClip: function (clip) {
  8560. this._clips.push(clip);
  8561. },
  8562. /**
  8563. * 添加 animator
  8564. * @param {module:zrender/animation/Animator} animator
  8565. */
  8566. addAnimator: function (animator) {
  8567. animator.animation = this;
  8568. var clips = animator.getClips();
  8569. for (var i = 0; i < clips.length; i++) {
  8570. this.addClip(clips[i]);
  8571. }
  8572. },
  8573. /**
  8574. * 删除动画片段
  8575. * @param {module:zrender/animation/Clip} clip
  8576. */
  8577. removeClip: function(clip) {
  8578. var idx = indexOf(this._clips, clip);
  8579. if (idx >= 0) {
  8580. this._clips.splice(idx, 1);
  8581. }
  8582. },
  8583. /**
  8584. * 删除动画片段
  8585. * @param {module:zrender/animation/Animator} animator
  8586. */
  8587. removeAnimator: function (animator) {
  8588. var clips = animator.getClips();
  8589. for (var i = 0; i < clips.length; i++) {
  8590. this.removeClip(clips[i]);
  8591. }
  8592. animator.animation = null;
  8593. },
  8594. _update: function() {
  8595. var time = new Date().getTime() - this._pausedTime;
  8596. var delta = time - this._time;
  8597. var clips = this._clips;
  8598. var len = clips.length;
  8599. var deferredEvents = [];
  8600. var deferredClips = [];
  8601. for (var i = 0; i < len; i++) {
  8602. var clip = clips[i];
  8603. var e = clip.step(time, delta);
  8604. // Throw out the events need to be called after
  8605. // stage.update, like destroy
  8606. if (e) {
  8607. deferredEvents.push(e);
  8608. deferredClips.push(clip);
  8609. }
  8610. }
  8611. // Remove the finished clip
  8612. for (var i = 0; i < len;) {
  8613. if (clips[i]._needsRemove) {
  8614. clips[i] = clips[len - 1];
  8615. clips.pop();
  8616. len--;
  8617. }
  8618. else {
  8619. i++;
  8620. }
  8621. }
  8622. len = deferredEvents.length;
  8623. for (var i = 0; i < len; i++) {
  8624. deferredClips[i].fire(deferredEvents[i]);
  8625. }
  8626. this._time = time;
  8627. this.onframe(delta);
  8628. // 'frame' should be triggered before stage, because upper application
  8629. // depends on the sequence (e.g., echarts-stream and finish
  8630. // event judge)
  8631. this.trigger('frame', delta);
  8632. if (this.stage.update) {
  8633. this.stage.update();
  8634. }
  8635. },
  8636. _startLoop: function () {
  8637. var self = this;
  8638. this._running = true;
  8639. function step() {
  8640. if (self._running) {
  8641. requestAnimationFrame(step);
  8642. !self._paused && self._update();
  8643. }
  8644. }
  8645. requestAnimationFrame(step);
  8646. },
  8647. /**
  8648. * Start animation.
  8649. */
  8650. start: function () {
  8651. this._time = new Date().getTime();
  8652. this._pausedTime = 0;
  8653. this._startLoop();
  8654. },
  8655. /**
  8656. * Stop animation.
  8657. */
  8658. stop: function () {
  8659. this._running = false;
  8660. },
  8661. /**
  8662. * Pause animation.
  8663. */
  8664. pause: function () {
  8665. if (!this._paused) {
  8666. this._pauseStart = new Date().getTime();
  8667. this._paused = true;
  8668. }
  8669. },
  8670. /**
  8671. * Resume animation.
  8672. */
  8673. resume: function () {
  8674. if (this._paused) {
  8675. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  8676. this._paused = false;
  8677. }
  8678. },
  8679. /**
  8680. * Clear animation.
  8681. */
  8682. clear: function () {
  8683. this._clips = [];
  8684. },
  8685. /**
  8686. * Whether animation finished.
  8687. */
  8688. isFinished: function () {
  8689. return !this._clips.length;
  8690. },
  8691. /**
  8692. * Creat animator for a target, whose props can be animated.
  8693. *
  8694. * @param {Object} target
  8695. * @param {Object} options
  8696. * @param {boolean} [options.loop=false] Whether loop animation.
  8697. * @param {Function} [options.getter=null] Get value from target.
  8698. * @param {Function} [options.setter=null] Set value to target.
  8699. * @return {module:zrender/animation/Animation~Animator}
  8700. */
  8701. // TODO Gap
  8702. animate: function (target, options) {
  8703. options = options || {};
  8704. var animator = new Animator(
  8705. target,
  8706. options.loop,
  8707. options.getter,
  8708. options.setter
  8709. );
  8710. this.addAnimator(animator);
  8711. return animator;
  8712. }
  8713. };
  8714. mixin(Animation, Eventful);
  8715. /**
  8716. * Only implements needed gestures for mobile.
  8717. */
  8718. var GestureMgr = function () {
  8719. /**
  8720. * @private
  8721. * @type {Array.<Object>}
  8722. */
  8723. this._track = [];
  8724. };
  8725. GestureMgr.prototype = {
  8726. constructor: GestureMgr,
  8727. recognize: function (event, target, root) {
  8728. this._doTrack(event, target, root);
  8729. return this._recognize(event);
  8730. },
  8731. clear: function () {
  8732. this._track.length = 0;
  8733. return this;
  8734. },
  8735. _doTrack: function (event, target, root) {
  8736. var touches = event.touches;
  8737. if (!touches) {
  8738. return;
  8739. }
  8740. var trackItem = {
  8741. points: [],
  8742. touches: [],
  8743. target: target,
  8744. event: event
  8745. };
  8746. for (var i = 0, len = touches.length; i < len; i++) {
  8747. var touch = touches[i];
  8748. var pos = clientToLocal(root, touch, {});
  8749. trackItem.points.push([pos.zrX, pos.zrY]);
  8750. trackItem.touches.push(touch);
  8751. }
  8752. this._track.push(trackItem);
  8753. },
  8754. _recognize: function (event) {
  8755. for (var eventName in recognizers) {
  8756. if (recognizers.hasOwnProperty(eventName)) {
  8757. var gestureInfo = recognizers[eventName](this._track, event);
  8758. if (gestureInfo) {
  8759. return gestureInfo;
  8760. }
  8761. }
  8762. }
  8763. }
  8764. };
  8765. function dist$1(pointPair) {
  8766. var dx = pointPair[1][0] - pointPair[0][0];
  8767. var dy = pointPair[1][1] - pointPair[0][1];
  8768. return Math.sqrt(dx * dx + dy * dy);
  8769. }
  8770. function center(pointPair) {
  8771. return [
  8772. (pointPair[0][0] + pointPair[1][0]) / 2,
  8773. (pointPair[0][1] + pointPair[1][1]) / 2
  8774. ];
  8775. }
  8776. var recognizers = {
  8777. pinch: function (track, event) {
  8778. var trackLen = track.length;
  8779. if (!trackLen) {
  8780. return;
  8781. }
  8782. var pinchEnd = (track[trackLen - 1] || {}).points;
  8783. var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd;
  8784. if (pinchPre
  8785. && pinchPre.length > 1
  8786. && pinchEnd
  8787. && pinchEnd.length > 1
  8788. ) {
  8789. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  8790. !isFinite(pinchScale) && (pinchScale = 1);
  8791. event.pinchScale = pinchScale;
  8792. var pinchCenter = center(pinchEnd);
  8793. event.pinchX = pinchCenter[0];
  8794. event.pinchY = pinchCenter[1];
  8795. return {
  8796. type: 'pinch',
  8797. target: track[0].target,
  8798. event: event
  8799. };
  8800. }
  8801. }
  8802. // Only pinch currently.
  8803. };
  8804. var TOUCH_CLICK_DELAY = 300;
  8805. var mouseHandlerNames = [
  8806. 'click', 'dblclick', 'mousewheel', 'mouseout',
  8807. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  8808. ];
  8809. var touchHandlerNames = [
  8810. 'touchstart', 'touchend', 'touchmove'
  8811. ];
  8812. var pointerEventNames = {
  8813. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  8814. };
  8815. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  8816. var nm = name.replace('mouse', 'pointer');
  8817. return pointerEventNames[nm] ? nm : name;
  8818. });
  8819. function eventNameFix(name) {
  8820. return (name === 'mousewheel' && env$1.browser.firefox) ? 'DOMMouseScroll' : name;
  8821. }
  8822. function processGesture(proxy, event, stage) {
  8823. var gestureMgr = proxy._gestureMgr;
  8824. stage === 'start' && gestureMgr.clear();
  8825. var gestureInfo = gestureMgr.recognize(
  8826. event,
  8827. proxy.handler.findHover(event.zrX, event.zrY, null).target,
  8828. proxy.dom
  8829. );
  8830. stage === 'end' && gestureMgr.clear();
  8831. // Do not do any preventDefault here. Upper application do that if necessary.
  8832. if (gestureInfo) {
  8833. var type = gestureInfo.type;
  8834. event.gestureEvent = type;
  8835. proxy.handler.dispatchToElement({target: gestureInfo.target}, type, gestureInfo.event);
  8836. }
  8837. }
  8838. // function onMSGestureChange(proxy, event) {
  8839. // if (event.translationX || event.translationY) {
  8840. // // mousemove is carried by MSGesture to reduce the sensitivity.
  8841. // proxy.handler.dispatchToElement(event.target, 'mousemove', event);
  8842. // }
  8843. // if (event.scale !== 1) {
  8844. // event.pinchX = event.offsetX;
  8845. // event.pinchY = event.offsetY;
  8846. // event.pinchScale = event.scale;
  8847. // proxy.handler.dispatchToElement(event.target, 'pinch', event);
  8848. // }
  8849. // }
  8850. /**
  8851. * Prevent mouse event from being dispatched after Touch Events action
  8852. * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js>
  8853. * 1. Mobile browsers dispatch mouse events 300ms after touchend.
  8854. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms
  8855. * Result: Blocking Mouse Events for 700ms.
  8856. */
  8857. function setTouchTimer(instance) {
  8858. instance._touching = true;
  8859. clearTimeout(instance._touchTimer);
  8860. instance._touchTimer = setTimeout(function () {
  8861. instance._touching = false;
  8862. }, 700);
  8863. }
  8864. var domHandlers = {
  8865. /**
  8866. * Mouse move handler
  8867. * @inner
  8868. * @param {Event} event
  8869. */
  8870. mousemove: function (event) {
  8871. event = normalizeEvent(this.dom, event);
  8872. this.trigger('mousemove', event);
  8873. },
  8874. /**
  8875. * Mouse out handler
  8876. * @inner
  8877. * @param {Event} event
  8878. */
  8879. mouseout: function (event) {
  8880. event = normalizeEvent(this.dom, event);
  8881. var element = event.toElement || event.relatedTarget;
  8882. if (element != this.dom) {
  8883. while (element && element.nodeType != 9) {
  8884. // 忽略包含在root中的dom引起的mouseOut
  8885. if (element === this.dom) {
  8886. return;
  8887. }
  8888. element = element.parentNode;
  8889. }
  8890. }
  8891. this.trigger('mouseout', event);
  8892. },
  8893. /**
  8894. * Touch开始响应函数
  8895. * @inner
  8896. * @param {Event} event
  8897. */
  8898. touchstart: function (event) {
  8899. // Default mouse behaviour should not be disabled here.
  8900. // For example, page may needs to be slided.
  8901. event = normalizeEvent(this.dom, event);
  8902. // Mark touch, which is useful in distinguish touch and
  8903. // mouse event in upper applicatoin.
  8904. event.zrByTouch = true;
  8905. this._lastTouchMoment = new Date();
  8906. processGesture(this, event, 'start');
  8907. // In touch device, trigger `mousemove`(`mouseover`) should
  8908. // be triggered, and must before `mousedown` triggered.
  8909. domHandlers.mousemove.call(this, event);
  8910. domHandlers.mousedown.call(this, event);
  8911. setTouchTimer(this);
  8912. },
  8913. /**
  8914. * Touch移动响应函数
  8915. * @inner
  8916. * @param {Event} event
  8917. */
  8918. touchmove: function (event) {
  8919. event = normalizeEvent(this.dom, event);
  8920. // Mark touch, which is useful in distinguish touch and
  8921. // mouse event in upper applicatoin.
  8922. event.zrByTouch = true;
  8923. processGesture(this, event, 'change');
  8924. // Mouse move should always be triggered no matter whether
  8925. // there is gestrue event, because mouse move and pinch may
  8926. // be used at the same time.
  8927. domHandlers.mousemove.call(this, event);
  8928. setTouchTimer(this);
  8929. },
  8930. /**
  8931. * Touch结束响应函数
  8932. * @inner
  8933. * @param {Event} event
  8934. */
  8935. touchend: function (event) {
  8936. event = normalizeEvent(this.dom, event);
  8937. // Mark touch, which is useful in distinguish touch and
  8938. // mouse event in upper applicatoin.
  8939. event.zrByTouch = true;
  8940. processGesture(this, event, 'end');
  8941. domHandlers.mouseup.call(this, event);
  8942. // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is
  8943. // triggered in `touchstart`. This seems to be illogical, but by this mechanism,
  8944. // we can conveniently implement "hover style" in both PC and touch device just
  8945. // by listening to `mouseover` to add "hover style" and listening to `mouseout`
  8946. // to remove "hover style" on an element, without any additional code for
  8947. // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover
  8948. // style" will remain for user view)
  8949. // click event should always be triggered no matter whether
  8950. // there is gestrue event. System click can not be prevented.
  8951. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) {
  8952. domHandlers.click.call(this, event);
  8953. }
  8954. setTouchTimer(this);
  8955. },
  8956. pointerdown: function (event) {
  8957. domHandlers.mousedown.call(this, event);
  8958. // if (useMSGuesture(this, event)) {
  8959. // this._msGesture.addPointer(event.pointerId);
  8960. // }
  8961. },
  8962. pointermove: function (event) {
  8963. // FIXME
  8964. // pointermove is so sensitive that it always triggered when
  8965. // tap(click) on touch screen, which affect some judgement in
  8966. // upper application. So, we dont support mousemove on MS touch
  8967. // device yet.
  8968. if (!isPointerFromTouch(event)) {
  8969. domHandlers.mousemove.call(this, event);
  8970. }
  8971. },
  8972. pointerup: function (event) {
  8973. domHandlers.mouseup.call(this, event);
  8974. },
  8975. pointerout: function (event) {
  8976. // pointerout will be triggered when tap on touch screen
  8977. // (IE11+/Edge on MS Surface) after click event triggered,
  8978. // which is inconsistent with the mousout behavior we defined
  8979. // in touchend. So we unify them.
  8980. // (check domHandlers.touchend for detailed explanation)
  8981. if (!isPointerFromTouch(event)) {
  8982. domHandlers.mouseout.call(this, event);
  8983. }
  8984. }
  8985. };
  8986. function isPointerFromTouch(event) {
  8987. var pointerType = event.pointerType;
  8988. return pointerType === 'pen' || pointerType === 'touch';
  8989. }
  8990. // function useMSGuesture(handlerProxy, event) {
  8991. // return isPointerFromTouch(event) && !!handlerProxy._msGesture;
  8992. // }
  8993. // Common handlers
  8994. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  8995. domHandlers[name] = function (event) {
  8996. event = normalizeEvent(this.dom, event);
  8997. this.trigger(name, event);
  8998. };
  8999. });
  9000. /**
  9001. * 为控制类实例初始化dom 事件处理函数
  9002. *
  9003. * @inner
  9004. * @param {module:zrender/Handler} instance 控制类实例
  9005. */
  9006. function initDomHandler(instance) {
  9007. each$1(touchHandlerNames, function (name) {
  9008. instance._handlers[name] = bind(domHandlers[name], instance);
  9009. });
  9010. each$1(pointerHandlerNames, function (name) {
  9011. instance._handlers[name] = bind(domHandlers[name], instance);
  9012. });
  9013. each$1(mouseHandlerNames, function (name) {
  9014. instance._handlers[name] = makeMouseHandler(domHandlers[name], instance);
  9015. });
  9016. function makeMouseHandler(fn, instance) {
  9017. return function () {
  9018. if (instance._touching) {
  9019. return;
  9020. }
  9021. return fn.apply(instance, arguments);
  9022. };
  9023. }
  9024. }
  9025. function HandlerDomProxy(dom) {
  9026. Eventful.call(this);
  9027. this.dom = dom;
  9028. /**
  9029. * @private
  9030. * @type {boolean}
  9031. */
  9032. this._touching = false;
  9033. /**
  9034. * @private
  9035. * @type {number}
  9036. */
  9037. this._touchTimer;
  9038. /**
  9039. * @private
  9040. * @type {module:zrender/core/GestureMgr}
  9041. */
  9042. this._gestureMgr = new GestureMgr();
  9043. this._handlers = {};
  9044. initDomHandler(this);
  9045. if (env$1.pointerEventsSupported) { // Only IE11+/Edge
  9046. // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240),
  9047. // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event
  9048. // at the same time.
  9049. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on
  9050. // screen, which do not occurs in pointer event.
  9051. // So we use pointer event to both detect touch gesture and mouse behavior.
  9052. mountHandlers(pointerHandlerNames, this);
  9053. // FIXME
  9054. // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable,
  9055. // which does not prevent defuault behavior occasionally (which may cause view port
  9056. // zoomed in but use can not zoom it back). And event.preventDefault() does not work.
  9057. // So we have to not to use MSGesture and not to support touchmove and pinch on MS
  9058. // touch screen. And we only support click behavior on MS touch screen now.
  9059. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+.
  9060. // We dont support touch on IE on win7.
  9061. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx>
  9062. // if (typeof MSGesture === 'function') {
  9063. // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line
  9064. // dom.addEventListener('MSGestureChange', onMSGestureChange);
  9065. // }
  9066. }
  9067. else {
  9068. if (env$1.touchEventsSupported) {
  9069. mountHandlers(touchHandlerNames, this);
  9070. // Handler of 'mouseout' event is needed in touch mode, which will be mounted below.
  9071. // addEventListener(root, 'mouseout', this._mouseoutHandler);
  9072. }
  9073. // 1. Considering some devices that both enable touch and mouse event (like on MS Surface
  9074. // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise
  9075. // mouse event can not be handle in those devices.
  9076. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent
  9077. // mouseevent after touch event triggered, see `setTouchTimer`.
  9078. mountHandlers(mouseHandlerNames, this);
  9079. }
  9080. function mountHandlers(handlerNames, instance) {
  9081. each$1(handlerNames, function (name) {
  9082. addEventListener(dom, eventNameFix(name), instance._handlers[name]);
  9083. }, instance);
  9084. }
  9085. }
  9086. var handlerDomProxyProto = HandlerDomProxy.prototype;
  9087. handlerDomProxyProto.dispose = function () {
  9088. var handlerNames = mouseHandlerNames.concat(touchHandlerNames);
  9089. for (var i = 0; i < handlerNames.length; i++) {
  9090. var name = handlerNames[i];
  9091. removeEventListener(this.dom, eventNameFix(name), this._handlers[name]);
  9092. }
  9093. };
  9094. handlerDomProxyProto.setCursor = function (cursorStyle) {
  9095. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  9096. };
  9097. mixin(HandlerDomProxy, Eventful);
  9098. /*!
  9099. * ZRender, a high performance 2d drawing library.
  9100. *
  9101. * Copyright (c) 2013, Baidu Inc.
  9102. * All rights reserved.
  9103. *
  9104. * LICENSE
  9105. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  9106. */
  9107. var useVML = !env$1.canvasSupported;
  9108. var painterCtors = {
  9109. canvas: Painter
  9110. };
  9111. var instances$1 = {}; // ZRender实例map索引
  9112. /**
  9113. * @type {string}
  9114. */
  9115. var version$1 = '4.0.3';
  9116. /**
  9117. * Initializing a zrender instance
  9118. * @param {HTMLElement} dom
  9119. * @param {Object} opts
  9120. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9121. * @param {number} [opts.devicePixelRatio]
  9122. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9123. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9124. * @return {module:zrender/ZRender}
  9125. */
  9126. function init$1(dom, opts) {
  9127. var zr = new ZRender(guid(), dom, opts);
  9128. instances$1[zr.id] = zr;
  9129. return zr;
  9130. }
  9131. /**
  9132. * Dispose zrender instance
  9133. * @param {module:zrender/ZRender} zr
  9134. */
  9135. function dispose$1(zr) {
  9136. if (zr) {
  9137. zr.dispose();
  9138. }
  9139. else {
  9140. for (var key in instances$1) {
  9141. if (instances$1.hasOwnProperty(key)) {
  9142. instances$1[key].dispose();
  9143. }
  9144. }
  9145. instances$1 = {};
  9146. }
  9147. return this;
  9148. }
  9149. /**
  9150. * Get zrender instance by id
  9151. * @param {string} id zrender instance id
  9152. * @return {module:zrender/ZRender}
  9153. */
  9154. function getInstance(id) {
  9155. return instances$1[id];
  9156. }
  9157. function registerPainter(name, Ctor) {
  9158. painterCtors[name] = Ctor;
  9159. }
  9160. function delInstance(id) {
  9161. delete instances$1[id];
  9162. }
  9163. /**
  9164. * @module zrender/ZRender
  9165. */
  9166. /**
  9167. * @constructor
  9168. * @alias module:zrender/ZRender
  9169. * @param {string} id
  9170. * @param {HTMLElement} dom
  9171. * @param {Object} opts
  9172. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9173. * @param {number} [opts.devicePixelRatio]
  9174. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  9175. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  9176. */
  9177. var ZRender = function (id, dom, opts) {
  9178. opts = opts || {};
  9179. /**
  9180. * @type {HTMLDomElement}
  9181. */
  9182. this.dom = dom;
  9183. /**
  9184. * @type {string}
  9185. */
  9186. this.id = id;
  9187. var self = this;
  9188. var storage = new Storage();
  9189. var rendererType = opts.renderer;
  9190. // TODO WebGL
  9191. if (useVML) {
  9192. if (!painterCtors.vml) {
  9193. throw new Error('You need to require \'zrender/vml/vml\' to support IE8');
  9194. }
  9195. rendererType = 'vml';
  9196. }
  9197. else if (!rendererType || !painterCtors[rendererType]) {
  9198. rendererType = 'canvas';
  9199. }
  9200. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  9201. this.storage = storage;
  9202. this.painter = painter;
  9203. var handerProxy = (!env$1.node && !env$1.worker) ? new HandlerDomProxy(painter.getViewportRoot()) : null;
  9204. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  9205. /**
  9206. * @type {module:zrender/animation/Animation}
  9207. */
  9208. this.animation = new Animation({
  9209. stage: {
  9210. update: bind(this.flush, this)
  9211. }
  9212. });
  9213. this.animation.start();
  9214. /**
  9215. * @type {boolean}
  9216. * @private
  9217. */
  9218. this._needsRefresh;
  9219. // 修改 storage.delFromStorage, 每次删除元素之前删除动画
  9220. // FIXME 有点ugly
  9221. var oldDelFromStorage = storage.delFromStorage;
  9222. var oldAddToStorage = storage.addToStorage;
  9223. storage.delFromStorage = function (el) {
  9224. oldDelFromStorage.call(storage, el);
  9225. el && el.removeSelfFromZr(self);
  9226. };
  9227. storage.addToStorage = function (el) {
  9228. oldAddToStorage.call(storage, el);
  9229. el.addSelfToZr(self);
  9230. };
  9231. };
  9232. ZRender.prototype = {
  9233. constructor: ZRender,
  9234. /**
  9235. * 获取实例唯一标识
  9236. * @return {string}
  9237. */
  9238. getId: function () {
  9239. return this.id;
  9240. },
  9241. /**
  9242. * 添加元素
  9243. * @param {module:zrender/Element} el
  9244. */
  9245. add: function (el) {
  9246. this.storage.addRoot(el);
  9247. this._needsRefresh = true;
  9248. },
  9249. /**
  9250. * 删除元素
  9251. * @param {module:zrender/Element} el
  9252. */
  9253. remove: function (el) {
  9254. this.storage.delRoot(el);
  9255. this._needsRefresh = true;
  9256. },
  9257. /**
  9258. * Change configuration of layer
  9259. * @param {string} zLevel
  9260. * @param {Object} config
  9261. * @param {string} [config.clearColor=0] Clear color
  9262. * @param {string} [config.motionBlur=false] If enable motion blur
  9263. * @param {number} [config.lastFrameAlpha=0.7] Motion blur factor. Larger value cause longer trailer
  9264. */
  9265. configLayer: function (zLevel, config) {
  9266. if (this.painter.configLayer) {
  9267. this.painter.configLayer(zLevel, config);
  9268. }
  9269. this._needsRefresh = true;
  9270. },
  9271. /**
  9272. * Set background color
  9273. * @param {string} backgroundColor
  9274. */
  9275. setBackgroundColor: function (backgroundColor) {
  9276. if (this.painter.setBackgroundColor) {
  9277. this.painter.setBackgroundColor(backgroundColor);
  9278. }
  9279. this._needsRefresh = true;
  9280. },
  9281. /**
  9282. * Repaint the canvas immediately
  9283. */
  9284. refreshImmediately: function () {
  9285. // var start = new Date();
  9286. // Clear needsRefresh ahead to avoid something wrong happens in refresh
  9287. // Or it will cause zrender refreshes again and again.
  9288. this._needsRefresh = false;
  9289. this.painter.refresh();
  9290. /**
  9291. * Avoid trigger zr.refresh in Element#beforeUpdate hook
  9292. */
  9293. this._needsRefresh = false;
  9294. // var end = new Date();
  9295. // var log = document.getElementById('log');
  9296. // if (log) {
  9297. // log.innerHTML = log.innerHTML + '<br>' + (end - start);
  9298. // }
  9299. },
  9300. /**
  9301. * Mark and repaint the canvas in the next frame of browser
  9302. */
  9303. refresh: function() {
  9304. this._needsRefresh = true;
  9305. },
  9306. /**
  9307. * Perform all refresh
  9308. */
  9309. flush: function () {
  9310. var triggerRendered;
  9311. if (this._needsRefresh) {
  9312. triggerRendered = true;
  9313. this.refreshImmediately();
  9314. }
  9315. if (this._needsRefreshHover) {
  9316. triggerRendered = true;
  9317. this.refreshHoverImmediately();
  9318. }
  9319. triggerRendered && this.trigger('rendered');
  9320. },
  9321. /**
  9322. * Add element to hover layer
  9323. * @param {module:zrender/Element} el
  9324. * @param {Object} style
  9325. */
  9326. addHover: function (el, style) {
  9327. if (this.painter.addHover) {
  9328. this.painter.addHover(el, style);
  9329. this.refreshHover();
  9330. }
  9331. },
  9332. /**
  9333. * Add element from hover layer
  9334. * @param {module:zrender/Element} el
  9335. */
  9336. removeHover: function (el) {
  9337. if (this.painter.removeHover) {
  9338. this.painter.removeHover(el);
  9339. this.refreshHover();
  9340. }
  9341. },
  9342. /**
  9343. * Clear all hover elements in hover layer
  9344. * @param {module:zrender/Element} el
  9345. */
  9346. clearHover: function () {
  9347. if (this.painter.clearHover) {
  9348. this.painter.clearHover();
  9349. this.refreshHover();
  9350. }
  9351. },
  9352. /**
  9353. * Refresh hover in next frame
  9354. */
  9355. refreshHover: function () {
  9356. this._needsRefreshHover = true;
  9357. },
  9358. /**
  9359. * Refresh hover immediately
  9360. */
  9361. refreshHoverImmediately: function () {
  9362. this._needsRefreshHover = false;
  9363. this.painter.refreshHover && this.painter.refreshHover();
  9364. },
  9365. /**
  9366. * Resize the canvas.
  9367. * Should be invoked when container size is changed
  9368. * @param {Object} [opts]
  9369. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9370. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9371. */
  9372. resize: function(opts) {
  9373. opts = opts || {};
  9374. this.painter.resize(opts.width, opts.height);
  9375. this.handler.resize();
  9376. },
  9377. /**
  9378. * Stop and clear all animation immediately
  9379. */
  9380. clearAnimation: function () {
  9381. this.animation.clear();
  9382. },
  9383. /**
  9384. * Get container width
  9385. */
  9386. getWidth: function() {
  9387. return this.painter.getWidth();
  9388. },
  9389. /**
  9390. * Get container height
  9391. */
  9392. getHeight: function() {
  9393. return this.painter.getHeight();
  9394. },
  9395. /**
  9396. * Export the canvas as Base64 URL
  9397. * @param {string} type
  9398. * @param {string} [backgroundColor='#fff']
  9399. * @return {string} Base64 URL
  9400. */
  9401. // toDataURL: function(type, backgroundColor) {
  9402. // return this.painter.getRenderedCanvas({
  9403. // backgroundColor: backgroundColor
  9404. // }).toDataURL(type);
  9405. // },
  9406. /**
  9407. * Converting a path to image.
  9408. * It has much better performance of drawing image rather than drawing a vector path.
  9409. * @param {module:zrender/graphic/Path} e
  9410. * @param {number} width
  9411. * @param {number} height
  9412. */
  9413. pathToImage: function(e, dpr) {
  9414. return this.painter.pathToImage(e, dpr);
  9415. },
  9416. /**
  9417. * Set default cursor
  9418. * @param {string} [cursorStyle='default'] 例如 crosshair
  9419. */
  9420. setCursorStyle: function (cursorStyle) {
  9421. this.handler.setCursorStyle(cursorStyle);
  9422. },
  9423. /**
  9424. * Find hovered element
  9425. * @param {number} x
  9426. * @param {number} y
  9427. * @return {Object} {target, topTarget}
  9428. */
  9429. findHover: function (x, y) {
  9430. return this.handler.findHover(x, y);
  9431. },
  9432. /**
  9433. * Bind event
  9434. *
  9435. * @param {string} eventName Event name
  9436. * @param {Function} eventHandler Handler function
  9437. * @param {Object} [context] Context object
  9438. */
  9439. on: function(eventName, eventHandler, context) {
  9440. this.handler.on(eventName, eventHandler, context);
  9441. },
  9442. /**
  9443. * Unbind event
  9444. * @param {string} eventName Event name
  9445. * @param {Function} [eventHandler] Handler function
  9446. */
  9447. off: function(eventName, eventHandler) {
  9448. this.handler.off(eventName, eventHandler);
  9449. },
  9450. /**
  9451. * Trigger event manually
  9452. *
  9453. * @param {string} eventName Event name
  9454. * @param {event=} event Event object
  9455. */
  9456. trigger: function (eventName, event) {
  9457. this.handler.trigger(eventName, event);
  9458. },
  9459. /**
  9460. * Clear all objects and the canvas.
  9461. */
  9462. clear: function () {
  9463. this.storage.delRoot();
  9464. this.painter.clear();
  9465. },
  9466. /**
  9467. * Dispose self.
  9468. */
  9469. dispose: function () {
  9470. this.animation.stop();
  9471. this.clear();
  9472. this.storage.dispose();
  9473. this.painter.dispose();
  9474. this.handler.dispose();
  9475. this.animation =
  9476. this.storage =
  9477. this.painter =
  9478. this.handler = null;
  9479. delInstance(this.id);
  9480. }
  9481. };
  9482. var zrender = (Object.freeze || Object)({
  9483. version: version$1,
  9484. init: init$1,
  9485. dispose: dispose$1,
  9486. getInstance: getInstance,
  9487. registerPainter: registerPainter
  9488. });
  9489. var each$2 = each$1;
  9490. var isObject$2 = isObject$1;
  9491. var isArray$1 = isArray;
  9492. /**
  9493. * Make the name displayable. But we should
  9494. * make sure it is not duplicated with user
  9495. * specified name, so use '\0';
  9496. */
  9497. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  9498. /**
  9499. * If value is not array, then translate it to array.
  9500. * @param {*} value
  9501. * @return {Array} [value] or value
  9502. */
  9503. function normalizeToArray(value) {
  9504. return value instanceof Array
  9505. ? value
  9506. : value == null
  9507. ? []
  9508. : [value];
  9509. }
  9510. /**
  9511. * Sync default option between normal and emphasis like `position` and `show`
  9512. * In case some one will write code like
  9513. * label: {
  9514. * show: false,
  9515. * position: 'outside',
  9516. * fontSize: 18
  9517. * },
  9518. * emphasis: {
  9519. * label: { show: true }
  9520. * }
  9521. * @param {Object} opt
  9522. * @param {string} key
  9523. * @param {Array.<string>} subOpts
  9524. */
  9525. function defaultEmphasis(opt, key, subOpts) {
  9526. if (opt) {
  9527. opt[key] = opt[key] || {};
  9528. opt.emphasis = opt.emphasis || {};
  9529. opt.emphasis[key] = opt.emphasis[key] || {};
  9530. // Default emphasis option from normal
  9531. for (var i = 0, len = subOpts.length; i < len; i++) {
  9532. var subOptName = subOpts[i];
  9533. if (!opt.emphasis[key].hasOwnProperty(subOptName)
  9534. && opt[key].hasOwnProperty(subOptName)
  9535. ) {
  9536. opt.emphasis[key][subOptName] = opt[key][subOptName];
  9537. }
  9538. }
  9539. }
  9540. }
  9541. var TEXT_STYLE_OPTIONS = [
  9542. 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  9543. 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth',
  9544. 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline',
  9545. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY',
  9546. 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY',
  9547. 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding'
  9548. ];
  9549. // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  9550. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  9551. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  9552. // // FIXME: deprecated, check and remove it.
  9553. // 'textStyle'
  9554. // ]);
  9555. /**
  9556. * The method do not ensure performance.
  9557. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9558. * This helper method retieves value from data.
  9559. * @param {string|number|Date|Array|Object} dataItem
  9560. * @return {number|string|Date|Array.<number|string|Date>}
  9561. */
  9562. function getDataItemValue(dataItem) {
  9563. return (isObject$2(dataItem) && !isArray$1(dataItem) && !(dataItem instanceof Date))
  9564. ? dataItem.value : dataItem;
  9565. }
  9566. /**
  9567. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9568. * This helper method determine if dataItem has extra option besides value
  9569. * @param {string|number|Date|Array|Object} dataItem
  9570. */
  9571. function isDataItemOption(dataItem) {
  9572. return isObject$2(dataItem)
  9573. && !(dataItem instanceof Array);
  9574. // // markLine data can be array
  9575. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  9576. }
  9577. /**
  9578. * Mapping to exists for merge.
  9579. *
  9580. * @public
  9581. * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists
  9582. * @param {Object|Array.<Object>} newCptOptions
  9583. * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9584. * index of which is the same as exists.
  9585. */
  9586. function mappingToExists(exists, newCptOptions) {
  9587. // Mapping by the order by original option (but not order of
  9588. // new option) in merge mode. Because we should ensure
  9589. // some specified index (like xAxisIndex) is consistent with
  9590. // original option, which is easy to understand, espatially in
  9591. // media query. And in most case, merge option is used to
  9592. // update partial option but not be expected to change order.
  9593. newCptOptions = (newCptOptions || []).slice();
  9594. var result = map(exists || [], function (obj, index) {
  9595. return {exist: obj};
  9596. });
  9597. // Mapping by id or name if specified.
  9598. each$2(newCptOptions, function (cptOption, index) {
  9599. if (!isObject$2(cptOption)) {
  9600. return;
  9601. }
  9602. // id has highest priority.
  9603. for (var i = 0; i < result.length; i++) {
  9604. if (!result[i].option // Consider name: two map to one.
  9605. && cptOption.id != null
  9606. && result[i].exist.id === cptOption.id + ''
  9607. ) {
  9608. result[i].option = cptOption;
  9609. newCptOptions[index] = null;
  9610. return;
  9611. }
  9612. }
  9613. for (var i = 0; i < result.length; i++) {
  9614. var exist = result[i].exist;
  9615. if (!result[i].option // Consider name: two map to one.
  9616. // Can not match when both ids exist but different.
  9617. && (exist.id == null || cptOption.id == null)
  9618. && cptOption.name != null
  9619. && !isIdInner(cptOption)
  9620. && !isIdInner(exist)
  9621. && exist.name === cptOption.name + ''
  9622. ) {
  9623. result[i].option = cptOption;
  9624. newCptOptions[index] = null;
  9625. return;
  9626. }
  9627. }
  9628. });
  9629. // Otherwise mapping by index.
  9630. each$2(newCptOptions, function (cptOption, index) {
  9631. if (!isObject$2(cptOption)) {
  9632. return;
  9633. }
  9634. var i = 0;
  9635. for (; i < result.length; i++) {
  9636. var exist = result[i].exist;
  9637. if (!result[i].option
  9638. // Existing model that already has id should be able to
  9639. // mapped to (because after mapping performed model may
  9640. // be assigned with a id, whish should not affect next
  9641. // mapping), except those has inner id.
  9642. && !isIdInner(exist)
  9643. // Caution:
  9644. // Do not overwrite id. But name can be overwritten,
  9645. // because axis use name as 'show label text'.
  9646. // 'exist' always has id and name and we dont
  9647. // need to check it.
  9648. && cptOption.id == null
  9649. ) {
  9650. result[i].option = cptOption;
  9651. break;
  9652. }
  9653. }
  9654. if (i >= result.length) {
  9655. result.push({option: cptOption});
  9656. }
  9657. });
  9658. return result;
  9659. }
  9660. /**
  9661. * Make id and name for mapping result (result of mappingToExists)
  9662. * into `keyInfo` field.
  9663. *
  9664. * @public
  9665. * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9666. * which order is the same as exists.
  9667. * @return {Array.<Object>} The input.
  9668. */
  9669. function makeIdAndName(mapResult) {
  9670. // We use this id to hash component models and view instances
  9671. // in echarts. id can be specified by user, or auto generated.
  9672. // The id generation rule ensures new view instance are able
  9673. // to mapped to old instance when setOption are called in
  9674. // no-merge mode. So we generate model id by name and plus
  9675. // type in view id.
  9676. // name can be duplicated among components, which is convenient
  9677. // to specify multi components (like series) by one name.
  9678. // Ensure that each id is distinct.
  9679. var idMap = createHashMap();
  9680. each$2(mapResult, function (item, index) {
  9681. var existCpt = item.exist;
  9682. existCpt && idMap.set(existCpt.id, item);
  9683. });
  9684. each$2(mapResult, function (item, index) {
  9685. var opt = item.option;
  9686. assert$1(
  9687. !opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item,
  9688. 'id duplicates: ' + (opt && opt.id)
  9689. );
  9690. opt && opt.id != null && idMap.set(opt.id, item);
  9691. !item.keyInfo && (item.keyInfo = {});
  9692. });
  9693. // Make name and id.
  9694. each$2(mapResult, function (item, index) {
  9695. var existCpt = item.exist;
  9696. var opt = item.option;
  9697. var keyInfo = item.keyInfo;
  9698. if (!isObject$2(opt)) {
  9699. return;
  9700. }
  9701. // name can be overwitten. Consider case: axis.name = '20km'.
  9702. // But id generated by name will not be changed, which affect
  9703. // only in that case: setOption with 'not merge mode' and view
  9704. // instance will be recreated, which can be accepted.
  9705. keyInfo.name = opt.name != null
  9706. ? opt.name + ''
  9707. : existCpt
  9708. ? existCpt.name
  9709. // Avoid diffferent series has the same name,
  9710. // because name may be used like in color pallet.
  9711. : DUMMY_COMPONENT_NAME_PREFIX + index;
  9712. if (existCpt) {
  9713. keyInfo.id = existCpt.id;
  9714. }
  9715. else if (opt.id != null) {
  9716. keyInfo.id = opt.id + '';
  9717. }
  9718. else {
  9719. // Consider this situatoin:
  9720. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  9721. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  9722. // Series with the same name between optionA and optionB
  9723. // should be mapped.
  9724. var idNum = 0;
  9725. do {
  9726. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  9727. }
  9728. while (idMap.get(keyInfo.id));
  9729. }
  9730. idMap.set(keyInfo.id, item);
  9731. });
  9732. }
  9733. function isNameSpecified(componentModel) {
  9734. var name = componentModel.name;
  9735. // Is specified when `indexOf` get -1 or > 0.
  9736. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  9737. }
  9738. /**
  9739. * @public
  9740. * @param {Object} cptOption
  9741. * @return {boolean}
  9742. */
  9743. function isIdInner(cptOption) {
  9744. return isObject$2(cptOption)
  9745. && cptOption.id
  9746. && (cptOption.id + '').indexOf('\0_ec_\0') === 0;
  9747. }
  9748. /**
  9749. * A helper for removing duplicate items between batchA and batchB,
  9750. * and in themselves, and categorize by series.
  9751. *
  9752. * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  9753. * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  9754. * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB]
  9755. */
  9756. /**
  9757. * @param {module:echarts/data/List} data
  9758. * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  9759. * each of which can be Array or primary type.
  9760. * @return {number|Array.<number>} dataIndex If not found, return undefined/null.
  9761. */
  9762. function queryDataIndex(data, payload) {
  9763. if (payload.dataIndexInside != null) {
  9764. return payload.dataIndexInside;
  9765. }
  9766. else if (payload.dataIndex != null) {
  9767. return isArray(payload.dataIndex)
  9768. ? map(payload.dataIndex, function (value) {
  9769. return data.indexOfRawIndex(value);
  9770. })
  9771. : data.indexOfRawIndex(payload.dataIndex);
  9772. }
  9773. else if (payload.name != null) {
  9774. return isArray(payload.name)
  9775. ? map(payload.name, function (value) {
  9776. return data.indexOfName(value);
  9777. })
  9778. : data.indexOfName(payload.name);
  9779. }
  9780. }
  9781. /**
  9782. * Enable property storage to any host object.
  9783. * Notice: Serialization is not supported.
  9784. *
  9785. * For example:
  9786. * var inner = zrUitl.makeInner();
  9787. *
  9788. * function some1(hostObj) {
  9789. * inner(hostObj).someProperty = 1212;
  9790. * ...
  9791. * }
  9792. * function some2() {
  9793. * var fields = inner(this);
  9794. * fields.someProperty1 = 1212;
  9795. * fields.someProperty2 = 'xx';
  9796. * ...
  9797. * }
  9798. *
  9799. * @return {Function}
  9800. */
  9801. function makeInner() {
  9802. // Consider different scope by es module import.
  9803. var key = '__\0ec_inner_' + innerUniqueIndex++ + '_' + Math.random().toFixed(5);
  9804. return function (hostObj) {
  9805. return hostObj[key] || (hostObj[key] = {});
  9806. };
  9807. }
  9808. var innerUniqueIndex = 0;
  9809. /**
  9810. * @param {module:echarts/model/Global} ecModel
  9811. * @param {string|Object} finder
  9812. * If string, e.g., 'geo', means {geoIndex: 0}.
  9813. * If Object, could contain some of these properties below:
  9814. * {
  9815. * seriesIndex, seriesId, seriesName,
  9816. * geoIndex, geoId, geoName,
  9817. * bmapIndex, bmapId, bmapName,
  9818. * xAxisIndex, xAxisId, xAxisName,
  9819. * yAxisIndex, yAxisId, yAxisName,
  9820. * gridIndex, gridId, gridName,
  9821. * ... (can be extended)
  9822. * }
  9823. * Each properties can be number|string|Array.<number>|Array.<string>
  9824. * For example, a finder could be
  9825. * {
  9826. * seriesIndex: 3,
  9827. * geoId: ['aa', 'cc'],
  9828. * gridName: ['xx', 'rr']
  9829. * }
  9830. * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify)
  9831. * If nothing or null/undefined specified, return nothing.
  9832. * @param {Object} [opt]
  9833. * @param {string} [opt.defaultMainType]
  9834. * @param {Array.<string>} [opt.includeMainTypes]
  9835. * @return {Object} result like:
  9836. * {
  9837. * seriesModels: [seriesModel1, seriesModel2],
  9838. * seriesModel: seriesModel1, // The first model
  9839. * geoModels: [geoModel1, geoModel2],
  9840. * geoModel: geoModel1, // The first model
  9841. * ...
  9842. * }
  9843. */
  9844. function parseFinder(ecModel, finder, opt) {
  9845. if (isString(finder)) {
  9846. var obj = {};
  9847. obj[finder + 'Index'] = 0;
  9848. finder = obj;
  9849. }
  9850. var defaultMainType = opt && opt.defaultMainType;
  9851. if (defaultMainType
  9852. && !has(finder, defaultMainType + 'Index')
  9853. && !has(finder, defaultMainType + 'Id')
  9854. && !has(finder, defaultMainType + 'Name')
  9855. ) {
  9856. finder[defaultMainType + 'Index'] = 0;
  9857. }
  9858. var result = {};
  9859. each$2(finder, function (value, key) {
  9860. var value = finder[key];
  9861. // Exclude 'dataIndex' and other illgal keys.
  9862. if (key === 'dataIndex' || key === 'dataIndexInside') {
  9863. result[key] = value;
  9864. return;
  9865. }
  9866. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  9867. var mainType = parsedKey[1];
  9868. var queryType = (parsedKey[2] || '').toLowerCase();
  9869. if (!mainType
  9870. || !queryType
  9871. || value == null
  9872. || (queryType === 'index' && value === 'none')
  9873. || (opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0)
  9874. ) {
  9875. return;
  9876. }
  9877. var queryParam = {mainType: mainType};
  9878. if (queryType !== 'index' || value !== 'all') {
  9879. queryParam[queryType] = value;
  9880. }
  9881. var models = ecModel.queryComponents(queryParam);
  9882. result[mainType + 'Models'] = models;
  9883. result[mainType + 'Model'] = models[0];
  9884. });
  9885. return result;
  9886. }
  9887. function has(obj, prop) {
  9888. return obj && obj.hasOwnProperty(prop);
  9889. }
  9890. function setAttribute(dom, key, value) {
  9891. dom.setAttribute
  9892. ? dom.setAttribute(key, value)
  9893. : (dom[key] = value);
  9894. }
  9895. function getAttribute(dom, key) {
  9896. return dom.getAttribute
  9897. ? dom.getAttribute(key)
  9898. : dom[key];
  9899. }
  9900. var TYPE_DELIMITER = '.';
  9901. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  9902. /**
  9903. * Notice, parseClassType('') should returns {main: '', sub: ''}
  9904. * @public
  9905. */
  9906. function parseClassType$1(componentType) {
  9907. var ret = {main: '', sub: ''};
  9908. if (componentType) {
  9909. componentType = componentType.split(TYPE_DELIMITER);
  9910. ret.main = componentType[0] || '';
  9911. ret.sub = componentType[1] || '';
  9912. }
  9913. return ret;
  9914. }
  9915. /**
  9916. * @public
  9917. */
  9918. function checkClassType(componentType) {
  9919. assert$1(
  9920. /^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType),
  9921. 'componentType "' + componentType + '" illegal'
  9922. );
  9923. }
  9924. /**
  9925. * @public
  9926. */
  9927. function enableClassExtend(RootClass, mandatoryMethods) {
  9928. RootClass.$constructor = RootClass;
  9929. RootClass.extend = function (proto) {
  9930. if (__DEV__) {
  9931. each$1(mandatoryMethods, function (method) {
  9932. if (!proto[method]) {
  9933. console.warn(
  9934. 'Method `' + method + '` should be implemented'
  9935. + (proto.type ? ' in ' + proto.type : '') + '.'
  9936. );
  9937. }
  9938. });
  9939. }
  9940. var superClass = this;
  9941. var ExtendedClass = function () {
  9942. if (!proto.$constructor) {
  9943. superClass.apply(this, arguments);
  9944. }
  9945. else {
  9946. proto.$constructor.apply(this, arguments);
  9947. }
  9948. };
  9949. extend(ExtendedClass.prototype, proto);
  9950. ExtendedClass.extend = this.extend;
  9951. ExtendedClass.superCall = superCall;
  9952. ExtendedClass.superApply = superApply;
  9953. inherits(ExtendedClass, this);
  9954. ExtendedClass.superClass = superClass;
  9955. return ExtendedClass;
  9956. };
  9957. }
  9958. var classBase = 0;
  9959. /**
  9960. * Can not use instanceof, consider different scope by
  9961. * cross domain or es module import in ec extensions.
  9962. * Mount a method "isInstance()" to Clz.
  9963. */
  9964. function enableClassCheck(Clz) {
  9965. var classAttr = ['__\0is_clz', classBase++, Math.random().toFixed(3)].join('_');
  9966. Clz.prototype[classAttr] = true;
  9967. if (__DEV__) {
  9968. assert$1(!Clz.isInstance, 'The method "is" can not be defined.');
  9969. }
  9970. Clz.isInstance = function (obj) {
  9971. return !!(obj && obj[classAttr]);
  9972. };
  9973. }
  9974. // superCall should have class info, which can not be fetch from 'this'.
  9975. // Consider this case:
  9976. // class A has method f,
  9977. // class B inherits class A, overrides method f, f call superApply('f'),
  9978. // class C inherits class B, do not overrides method f,
  9979. // then when method of class C is called, dead loop occured.
  9980. function superCall(context, methodName) {
  9981. var args = slice(arguments, 2);
  9982. return this.superClass.prototype[methodName].apply(context, args);
  9983. }
  9984. function superApply(context, methodName, args) {
  9985. return this.superClass.prototype[methodName].apply(context, args);
  9986. }
  9987. /**
  9988. * @param {Object} entity
  9989. * @param {Object} options
  9990. * @param {boolean} [options.registerWhenExtend]
  9991. * @public
  9992. */
  9993. function enableClassManagement(entity, options) {
  9994. options = options || {};
  9995. /**
  9996. * Component model classes
  9997. * key: componentType,
  9998. * value:
  9999. * componentClass, when componentType is 'xxx'
  10000. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  10001. * @type {Object}
  10002. */
  10003. var storage = {};
  10004. entity.registerClass = function (Clazz, componentType) {
  10005. if (componentType) {
  10006. checkClassType(componentType);
  10007. componentType = parseClassType$1(componentType);
  10008. if (!componentType.sub) {
  10009. if (__DEV__) {
  10010. if (storage[componentType.main]) {
  10011. console.warn(componentType.main + ' exists.');
  10012. }
  10013. }
  10014. storage[componentType.main] = Clazz;
  10015. }
  10016. else if (componentType.sub !== IS_CONTAINER) {
  10017. var container = makeContainer(componentType);
  10018. container[componentType.sub] = Clazz;
  10019. }
  10020. }
  10021. return Clazz;
  10022. };
  10023. entity.getClass = function (componentMainType, subType, throwWhenNotFound) {
  10024. var Clazz = storage[componentMainType];
  10025. if (Clazz && Clazz[IS_CONTAINER]) {
  10026. Clazz = subType ? Clazz[subType] : null;
  10027. }
  10028. if (throwWhenNotFound && !Clazz) {
  10029. throw new Error(
  10030. !subType
  10031. ? componentMainType + '.' + 'type should be specified.'
  10032. : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.'
  10033. );
  10034. }
  10035. return Clazz;
  10036. };
  10037. entity.getClassesByMainType = function (componentType) {
  10038. componentType = parseClassType$1(componentType);
  10039. var result = [];
  10040. var obj = storage[componentType.main];
  10041. if (obj && obj[IS_CONTAINER]) {
  10042. each$1(obj, function (o, type) {
  10043. type !== IS_CONTAINER && result.push(o);
  10044. });
  10045. }
  10046. else {
  10047. result.push(obj);
  10048. }
  10049. return result;
  10050. };
  10051. entity.hasClass = function (componentType) {
  10052. // Just consider componentType.main.
  10053. componentType = parseClassType$1(componentType);
  10054. return !!storage[componentType.main];
  10055. };
  10056. /**
  10057. * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx']
  10058. */
  10059. entity.getAllClassMainTypes = function () {
  10060. var types = [];
  10061. each$1(storage, function (obj, type) {
  10062. types.push(type);
  10063. });
  10064. return types;
  10065. };
  10066. /**
  10067. * If a main type is container and has sub types
  10068. * @param {string} mainType
  10069. * @return {boolean}
  10070. */
  10071. entity.hasSubTypes = function (componentType) {
  10072. componentType = parseClassType$1(componentType);
  10073. var obj = storage[componentType.main];
  10074. return obj && obj[IS_CONTAINER];
  10075. };
  10076. entity.parseClassType = parseClassType$1;
  10077. function makeContainer(componentType) {
  10078. var container = storage[componentType.main];
  10079. if (!container || !container[IS_CONTAINER]) {
  10080. container = storage[componentType.main] = {};
  10081. container[IS_CONTAINER] = true;
  10082. }
  10083. return container;
  10084. }
  10085. if (options.registerWhenExtend) {
  10086. var originalExtend = entity.extend;
  10087. if (originalExtend) {
  10088. entity.extend = function (proto) {
  10089. var ExtendedClass = originalExtend.call(this, proto);
  10090. return entity.registerClass(ExtendedClass, proto.type);
  10091. };
  10092. }
  10093. }
  10094. return entity;
  10095. }
  10096. /**
  10097. * @param {string|Array.<string>} properties
  10098. */
  10099. // TODO Parse shadow style
  10100. // TODO Only shallow path support
  10101. var makeStyleMapper = function (properties) {
  10102. // Normalize
  10103. for (var i = 0; i < properties.length; i++) {
  10104. if (!properties[i][1]) {
  10105. properties[i][1] = properties[i][0];
  10106. }
  10107. }
  10108. return function (model, excludes, includes) {
  10109. var style = {};
  10110. for (var i = 0; i < properties.length; i++) {
  10111. var propName = properties[i][1];
  10112. if ((excludes && indexOf(excludes, propName) >= 0)
  10113. || (includes && indexOf(includes, propName) < 0)
  10114. ) {
  10115. continue;
  10116. }
  10117. var val = model.getShallow(propName);
  10118. if (val != null) {
  10119. style[properties[i][0]] = val;
  10120. }
  10121. }
  10122. return style;
  10123. };
  10124. };
  10125. var getLineStyle = makeStyleMapper(
  10126. [
  10127. ['lineWidth', 'width'],
  10128. ['stroke', 'color'],
  10129. ['opacity'],
  10130. ['shadowBlur'],
  10131. ['shadowOffsetX'],
  10132. ['shadowOffsetY'],
  10133. ['shadowColor']
  10134. ]
  10135. );
  10136. var lineStyleMixin = {
  10137. getLineStyle: function (excludes) {
  10138. var style = getLineStyle(this, excludes);
  10139. var lineDash = this.getLineDash(style.lineWidth);
  10140. lineDash && (style.lineDash = lineDash);
  10141. return style;
  10142. },
  10143. getLineDash: function (lineWidth) {
  10144. if (lineWidth == null) {
  10145. lineWidth = 1;
  10146. }
  10147. var lineType = this.get('type');
  10148. var dotSize = Math.max(lineWidth, 2);
  10149. var dashSize = lineWidth * 4;
  10150. return (lineType === 'solid' || lineType == null) ? null
  10151. : (lineType === 'dashed' ? [dashSize, dashSize] : [dotSize, dotSize]);
  10152. }
  10153. };
  10154. var getAreaStyle = makeStyleMapper(
  10155. [
  10156. ['fill', 'color'],
  10157. ['shadowBlur'],
  10158. ['shadowOffsetX'],
  10159. ['shadowOffsetY'],
  10160. ['opacity'],
  10161. ['shadowColor']
  10162. ]
  10163. );
  10164. var areaStyleMixin = {
  10165. getAreaStyle: function (excludes, includes) {
  10166. return getAreaStyle(this, excludes, includes);
  10167. }
  10168. };
  10169. /**
  10170. * 曲线辅助模块
  10171. * @module zrender/core/curve
  10172. * @author pissang(https://www.github.com/pissang)
  10173. */
  10174. var mathPow = Math.pow;
  10175. var mathSqrt$2 = Math.sqrt;
  10176. var EPSILON$1 = 1e-8;
  10177. var EPSILON_NUMERIC = 1e-4;
  10178. var THREE_SQRT = mathSqrt$2(3);
  10179. var ONE_THIRD = 1 / 3;
  10180. // 临时变量
  10181. var _v0 = create();
  10182. var _v1 = create();
  10183. var _v2 = create();
  10184. function isAroundZero(val) {
  10185. return val > -EPSILON$1 && val < EPSILON$1;
  10186. }
  10187. function isNotAroundZero$1(val) {
  10188. return val > EPSILON$1 || val < -EPSILON$1;
  10189. }
  10190. /**
  10191. * 计算三次贝塞尔值
  10192. * @memberOf module:zrender/core/curve
  10193. * @param {number} p0
  10194. * @param {number} p1
  10195. * @param {number} p2
  10196. * @param {number} p3
  10197. * @param {number} t
  10198. * @return {number}
  10199. */
  10200. function cubicAt(p0, p1, p2, p3, t) {
  10201. var onet = 1 - t;
  10202. return onet * onet * (onet * p0 + 3 * t * p1)
  10203. + t * t * (t * p3 + 3 * onet * p2);
  10204. }
  10205. /**
  10206. * 计算三次贝塞尔导数值
  10207. * @memberOf module:zrender/core/curve
  10208. * @param {number} p0
  10209. * @param {number} p1
  10210. * @param {number} p2
  10211. * @param {number} p3
  10212. * @param {number} t
  10213. * @return {number}
  10214. */
  10215. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  10216. var onet = 1 - t;
  10217. return 3 * (
  10218. ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  10219. + (p3 - p2) * t * t
  10220. );
  10221. }
  10222. /**
  10223. * 计算三次贝塞尔方程根,使用盛金公式
  10224. * @memberOf module:zrender/core/curve
  10225. * @param {number} p0
  10226. * @param {number} p1
  10227. * @param {number} p2
  10228. * @param {number} p3
  10229. * @param {number} val
  10230. * @param {Array.<number>} roots
  10231. * @return {number} 有效根数目
  10232. */
  10233. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  10234. // Evaluate roots of cubic functions
  10235. var a = p3 + 3 * (p1 - p2) - p0;
  10236. var b = 3 * (p2 - p1 * 2 + p0);
  10237. var c = 3 * (p1 - p0);
  10238. var d = p0 - val;
  10239. var A = b * b - 3 * a * c;
  10240. var B = b * c - 9 * a * d;
  10241. var C = c * c - 3 * b * d;
  10242. var n = 0;
  10243. if (isAroundZero(A) && isAroundZero(B)) {
  10244. if (isAroundZero(b)) {
  10245. roots[0] = 0;
  10246. }
  10247. else {
  10248. var t1 = -c / b; //t1, t2, t3, b is not zero
  10249. if (t1 >= 0 && t1 <= 1) {
  10250. roots[n++] = t1;
  10251. }
  10252. }
  10253. }
  10254. else {
  10255. var disc = B * B - 4 * A * C;
  10256. if (isAroundZero(disc)) {
  10257. var K = B / A;
  10258. var t1 = -b / a + K; // t1, a is not zero
  10259. var t2 = -K / 2; // t2, t3
  10260. if (t1 >= 0 && t1 <= 1) {
  10261. roots[n++] = t1;
  10262. }
  10263. if (t2 >= 0 && t2 <= 1) {
  10264. roots[n++] = t2;
  10265. }
  10266. }
  10267. else if (disc > 0) {
  10268. var discSqrt = mathSqrt$2(disc);
  10269. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  10270. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  10271. if (Y1 < 0) {
  10272. Y1 = -mathPow(-Y1, ONE_THIRD);
  10273. }
  10274. else {
  10275. Y1 = mathPow(Y1, ONE_THIRD);
  10276. }
  10277. if (Y2 < 0) {
  10278. Y2 = -mathPow(-Y2, ONE_THIRD);
  10279. }
  10280. else {
  10281. Y2 = mathPow(Y2, ONE_THIRD);
  10282. }
  10283. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  10284. if (t1 >= 0 && t1 <= 1) {
  10285. roots[n++] = t1;
  10286. }
  10287. }
  10288. else {
  10289. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  10290. var theta = Math.acos(T) / 3;
  10291. var ASqrt = mathSqrt$2(A);
  10292. var tmp = Math.cos(theta);
  10293. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  10294. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  10295. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  10296. if (t1 >= 0 && t1 <= 1) {
  10297. roots[n++] = t1;
  10298. }
  10299. if (t2 >= 0 && t2 <= 1) {
  10300. roots[n++] = t2;
  10301. }
  10302. if (t3 >= 0 && t3 <= 1) {
  10303. roots[n++] = t3;
  10304. }
  10305. }
  10306. }
  10307. return n;
  10308. }
  10309. /**
  10310. * 计算三次贝塞尔方程极限值的位置
  10311. * @memberOf module:zrender/core/curve
  10312. * @param {number} p0
  10313. * @param {number} p1
  10314. * @param {number} p2
  10315. * @param {number} p3
  10316. * @param {Array.<number>} extrema
  10317. * @return {number} 有效数目
  10318. */
  10319. function cubicExtrema(p0, p1, p2, p3, extrema) {
  10320. var b = 6 * p2 - 12 * p1 + 6 * p0;
  10321. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  10322. var c = 3 * p1 - 3 * p0;
  10323. var n = 0;
  10324. if (isAroundZero(a)) {
  10325. if (isNotAroundZero$1(b)) {
  10326. var t1 = -c / b;
  10327. if (t1 >= 0 && t1 <=1) {
  10328. extrema[n++] = t1;
  10329. }
  10330. }
  10331. }
  10332. else {
  10333. var disc = b * b - 4 * a * c;
  10334. if (isAroundZero(disc)) {
  10335. extrema[0] = -b / (2 * a);
  10336. }
  10337. else if (disc > 0) {
  10338. var discSqrt = mathSqrt$2(disc);
  10339. var t1 = (-b + discSqrt) / (2 * a);
  10340. var t2 = (-b - discSqrt) / (2 * a);
  10341. if (t1 >= 0 && t1 <= 1) {
  10342. extrema[n++] = t1;
  10343. }
  10344. if (t2 >= 0 && t2 <= 1) {
  10345. extrema[n++] = t2;
  10346. }
  10347. }
  10348. }
  10349. return n;
  10350. }
  10351. /**
  10352. * 细分三次贝塞尔曲线
  10353. * @memberOf module:zrender/core/curve
  10354. * @param {number} p0
  10355. * @param {number} p1
  10356. * @param {number} p2
  10357. * @param {number} p3
  10358. * @param {number} t
  10359. * @param {Array.<number>} out
  10360. */
  10361. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  10362. var p01 = (p1 - p0) * t + p0;
  10363. var p12 = (p2 - p1) * t + p1;
  10364. var p23 = (p3 - p2) * t + p2;
  10365. var p012 = (p12 - p01) * t + p01;
  10366. var p123 = (p23 - p12) * t + p12;
  10367. var p0123 = (p123 - p012) * t + p012;
  10368. // Seg0
  10369. out[0] = p0;
  10370. out[1] = p01;
  10371. out[2] = p012;
  10372. out[3] = p0123;
  10373. // Seg1
  10374. out[4] = p0123;
  10375. out[5] = p123;
  10376. out[6] = p23;
  10377. out[7] = p3;
  10378. }
  10379. /**
  10380. * 投射点到三次贝塞尔曲线上,返回投射距离。
  10381. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10382. * @param {number} x0
  10383. * @param {number} y0
  10384. * @param {number} x1
  10385. * @param {number} y1
  10386. * @param {number} x2
  10387. * @param {number} y2
  10388. * @param {number} x3
  10389. * @param {number} y3
  10390. * @param {number} x
  10391. * @param {number} y
  10392. * @param {Array.<number>} [out] 投射点
  10393. * @return {number}
  10394. */
  10395. function cubicProjectPoint(
  10396. x0, y0, x1, y1, x2, y2, x3, y3,
  10397. x, y, out
  10398. ) {
  10399. // http://pomax.github.io/bezierinfo/#projections
  10400. var t;
  10401. var interval = 0.005;
  10402. var d = Infinity;
  10403. var prev;
  10404. var next;
  10405. var d1;
  10406. var d2;
  10407. _v0[0] = x;
  10408. _v0[1] = y;
  10409. // 先粗略估计一下可能的最小距离的 t 值
  10410. // PENDING
  10411. for (var _t = 0; _t < 1; _t += 0.05) {
  10412. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  10413. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  10414. d1 = distSquare(_v0, _v1);
  10415. if (d1 < d) {
  10416. t = _t;
  10417. d = d1;
  10418. }
  10419. }
  10420. d = Infinity;
  10421. // At most 32 iteration
  10422. for (var i = 0; i < 32; i++) {
  10423. if (interval < EPSILON_NUMERIC) {
  10424. break;
  10425. }
  10426. prev = t - interval;
  10427. next = t + interval;
  10428. // t - interval
  10429. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  10430. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  10431. d1 = distSquare(_v1, _v0);
  10432. if (prev >= 0 && d1 < d) {
  10433. t = prev;
  10434. d = d1;
  10435. }
  10436. else {
  10437. // t + interval
  10438. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  10439. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  10440. d2 = distSquare(_v2, _v0);
  10441. if (next <= 1 && d2 < d) {
  10442. t = next;
  10443. d = d2;
  10444. }
  10445. else {
  10446. interval *= 0.5;
  10447. }
  10448. }
  10449. }
  10450. // t
  10451. if (out) {
  10452. out[0] = cubicAt(x0, x1, x2, x3, t);
  10453. out[1] = cubicAt(y0, y1, y2, y3, t);
  10454. }
  10455. // console.log(interval, i);
  10456. return mathSqrt$2(d);
  10457. }
  10458. /**
  10459. * 计算二次方贝塞尔值
  10460. * @param {number} p0
  10461. * @param {number} p1
  10462. * @param {number} p2
  10463. * @param {number} t
  10464. * @return {number}
  10465. */
  10466. function quadraticAt(p0, p1, p2, t) {
  10467. var onet = 1 - t;
  10468. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  10469. }
  10470. /**
  10471. * 计算二次方贝塞尔导数值
  10472. * @param {number} p0
  10473. * @param {number} p1
  10474. * @param {number} p2
  10475. * @param {number} t
  10476. * @return {number}
  10477. */
  10478. function quadraticDerivativeAt(p0, p1, p2, t) {
  10479. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  10480. }
  10481. /**
  10482. * 计算二次方贝塞尔方程根
  10483. * @param {number} p0
  10484. * @param {number} p1
  10485. * @param {number} p2
  10486. * @param {number} t
  10487. * @param {Array.<number>} roots
  10488. * @return {number} 有效根数目
  10489. */
  10490. function quadraticRootAt(p0, p1, p2, val, roots) {
  10491. var a = p0 - 2 * p1 + p2;
  10492. var b = 2 * (p1 - p0);
  10493. var c = p0 - val;
  10494. var n = 0;
  10495. if (isAroundZero(a)) {
  10496. if (isNotAroundZero$1(b)) {
  10497. var t1 = -c / b;
  10498. if (t1 >= 0 && t1 <= 1) {
  10499. roots[n++] = t1;
  10500. }
  10501. }
  10502. }
  10503. else {
  10504. var disc = b * b - 4 * a * c;
  10505. if (isAroundZero(disc)) {
  10506. var t1 = -b / (2 * a);
  10507. if (t1 >= 0 && t1 <= 1) {
  10508. roots[n++] = t1;
  10509. }
  10510. }
  10511. else if (disc > 0) {
  10512. var discSqrt = mathSqrt$2(disc);
  10513. var t1 = (-b + discSqrt) / (2 * a);
  10514. var t2 = (-b - discSqrt) / (2 * a);
  10515. if (t1 >= 0 && t1 <= 1) {
  10516. roots[n++] = t1;
  10517. }
  10518. if (t2 >= 0 && t2 <= 1) {
  10519. roots[n++] = t2;
  10520. }
  10521. }
  10522. }
  10523. return n;
  10524. }
  10525. /**
  10526. * 计算二次贝塞尔方程极限值
  10527. * @memberOf module:zrender/core/curve
  10528. * @param {number} p0
  10529. * @param {number} p1
  10530. * @param {number} p2
  10531. * @return {number}
  10532. */
  10533. function quadraticExtremum(p0, p1, p2) {
  10534. var divider = p0 + p2 - 2 * p1;
  10535. if (divider === 0) {
  10536. // p1 is center of p0 and p2
  10537. return 0.5;
  10538. }
  10539. else {
  10540. return (p0 - p1) / divider;
  10541. }
  10542. }
  10543. /**
  10544. * 细分二次贝塞尔曲线
  10545. * @memberOf module:zrender/core/curve
  10546. * @param {number} p0
  10547. * @param {number} p1
  10548. * @param {number} p2
  10549. * @param {number} t
  10550. * @param {Array.<number>} out
  10551. */
  10552. function quadraticSubdivide(p0, p1, p2, t, out) {
  10553. var p01 = (p1 - p0) * t + p0;
  10554. var p12 = (p2 - p1) * t + p1;
  10555. var p012 = (p12 - p01) * t + p01;
  10556. // Seg0
  10557. out[0] = p0;
  10558. out[1] = p01;
  10559. out[2] = p012;
  10560. // Seg1
  10561. out[3] = p012;
  10562. out[4] = p12;
  10563. out[5] = p2;
  10564. }
  10565. /**
  10566. * 投射点到二次贝塞尔曲线上,返回投射距离。
  10567. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10568. * @param {number} x0
  10569. * @param {number} y0
  10570. * @param {number} x1
  10571. * @param {number} y1
  10572. * @param {number} x2
  10573. * @param {number} y2
  10574. * @param {number} x
  10575. * @param {number} y
  10576. * @param {Array.<number>} out 投射点
  10577. * @return {number}
  10578. */
  10579. function quadraticProjectPoint(
  10580. x0, y0, x1, y1, x2, y2,
  10581. x, y, out
  10582. ) {
  10583. // http://pomax.github.io/bezierinfo/#projections
  10584. var t;
  10585. var interval = 0.005;
  10586. var d = Infinity;
  10587. _v0[0] = x;
  10588. _v0[1] = y;
  10589. // 先粗略估计一下可能的最小距离的 t 值
  10590. // PENDING
  10591. for (var _t = 0; _t < 1; _t += 0.05) {
  10592. _v1[0] = quadraticAt(x0, x1, x2, _t);
  10593. _v1[1] = quadraticAt(y0, y1, y2, _t);
  10594. var d1 = distSquare(_v0, _v1);
  10595. if (d1 < d) {
  10596. t = _t;
  10597. d = d1;
  10598. }
  10599. }
  10600. d = Infinity;
  10601. // At most 32 iteration
  10602. for (var i = 0; i < 32; i++) {
  10603. if (interval < EPSILON_NUMERIC) {
  10604. break;
  10605. }
  10606. var prev = t - interval;
  10607. var next = t + interval;
  10608. // t - interval
  10609. _v1[0] = quadraticAt(x0, x1, x2, prev);
  10610. _v1[1] = quadraticAt(y0, y1, y2, prev);
  10611. var d1 = distSquare(_v1, _v0);
  10612. if (prev >= 0 && d1 < d) {
  10613. t = prev;
  10614. d = d1;
  10615. }
  10616. else {
  10617. // t + interval
  10618. _v2[0] = quadraticAt(x0, x1, x2, next);
  10619. _v2[1] = quadraticAt(y0, y1, y2, next);
  10620. var d2 = distSquare(_v2, _v0);
  10621. if (next <= 1 && d2 < d) {
  10622. t = next;
  10623. d = d2;
  10624. }
  10625. else {
  10626. interval *= 0.5;
  10627. }
  10628. }
  10629. }
  10630. // t
  10631. if (out) {
  10632. out[0] = quadraticAt(x0, x1, x2, t);
  10633. out[1] = quadraticAt(y0, y1, y2, t);
  10634. }
  10635. // console.log(interval, i);
  10636. return mathSqrt$2(d);
  10637. }
  10638. /**
  10639. * @author Yi Shen(https://github.com/pissang)
  10640. */
  10641. var mathMin$3 = Math.min;
  10642. var mathMax$3 = Math.max;
  10643. var mathSin$2 = Math.sin;
  10644. var mathCos$2 = Math.cos;
  10645. var PI2 = Math.PI * 2;
  10646. var start = create();
  10647. var end = create();
  10648. var extremity = create();
  10649. /**
  10650. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  10651. * @module zrender/core/bbox
  10652. * @param {Array<Object>} points 顶点数组
  10653. * @param {number} min
  10654. * @param {number} max
  10655. */
  10656. function fromPoints(points, min$$1, max$$1) {
  10657. if (points.length === 0) {
  10658. return;
  10659. }
  10660. var p = points[0];
  10661. var left = p[0];
  10662. var right = p[0];
  10663. var top = p[1];
  10664. var bottom = p[1];
  10665. var i;
  10666. for (i = 1; i < points.length; i++) {
  10667. p = points[i];
  10668. left = mathMin$3(left, p[0]);
  10669. right = mathMax$3(right, p[0]);
  10670. top = mathMin$3(top, p[1]);
  10671. bottom = mathMax$3(bottom, p[1]);
  10672. }
  10673. min$$1[0] = left;
  10674. min$$1[1] = top;
  10675. max$$1[0] = right;
  10676. max$$1[1] = bottom;
  10677. }
  10678. /**
  10679. * @memberOf module:zrender/core/bbox
  10680. * @param {number} x0
  10681. * @param {number} y0
  10682. * @param {number} x1
  10683. * @param {number} y1
  10684. * @param {Array.<number>} min
  10685. * @param {Array.<number>} max
  10686. */
  10687. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  10688. min$$1[0] = mathMin$3(x0, x1);
  10689. min$$1[1] = mathMin$3(y0, y1);
  10690. max$$1[0] = mathMax$3(x0, x1);
  10691. max$$1[1] = mathMax$3(y0, y1);
  10692. }
  10693. var xDim = [];
  10694. var yDim = [];
  10695. /**
  10696. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  10697. * @memberOf module:zrender/core/bbox
  10698. * @param {number} x0
  10699. * @param {number} y0
  10700. * @param {number} x1
  10701. * @param {number} y1
  10702. * @param {number} x2
  10703. * @param {number} y2
  10704. * @param {number} x3
  10705. * @param {number} y3
  10706. * @param {Array.<number>} min
  10707. * @param {Array.<number>} max
  10708. */
  10709. function fromCubic(
  10710. x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1
  10711. ) {
  10712. var cubicExtrema$$1 = cubicExtrema;
  10713. var cubicAt$$1 = cubicAt;
  10714. var i;
  10715. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  10716. min$$1[0] = Infinity;
  10717. min$$1[1] = Infinity;
  10718. max$$1[0] = -Infinity;
  10719. max$$1[1] = -Infinity;
  10720. for (i = 0; i < n; i++) {
  10721. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  10722. min$$1[0] = mathMin$3(x, min$$1[0]);
  10723. max$$1[0] = mathMax$3(x, max$$1[0]);
  10724. }
  10725. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  10726. for (i = 0; i < n; i++) {
  10727. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  10728. min$$1[1] = mathMin$3(y, min$$1[1]);
  10729. max$$1[1] = mathMax$3(y, max$$1[1]);
  10730. }
  10731. min$$1[0] = mathMin$3(x0, min$$1[0]);
  10732. max$$1[0] = mathMax$3(x0, max$$1[0]);
  10733. min$$1[0] = mathMin$3(x3, min$$1[0]);
  10734. max$$1[0] = mathMax$3(x3, max$$1[0]);
  10735. min$$1[1] = mathMin$3(y0, min$$1[1]);
  10736. max$$1[1] = mathMax$3(y0, max$$1[1]);
  10737. min$$1[1] = mathMin$3(y3, min$$1[1]);
  10738. max$$1[1] = mathMax$3(y3, max$$1[1]);
  10739. }
  10740. /**
  10741. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  10742. * @memberOf module:zrender/core/bbox
  10743. * @param {number} x0
  10744. * @param {number} y0
  10745. * @param {number} x1
  10746. * @param {number} y1
  10747. * @param {number} x2
  10748. * @param {number} y2
  10749. * @param {Array.<number>} min
  10750. * @param {Array.<number>} max
  10751. */
  10752. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  10753. var quadraticExtremum$$1 = quadraticExtremum;
  10754. var quadraticAt$$1 = quadraticAt;
  10755. // Find extremities, where derivative in x dim or y dim is zero
  10756. var tx =
  10757. mathMax$3(
  10758. mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0
  10759. );
  10760. var ty =
  10761. mathMax$3(
  10762. mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0
  10763. );
  10764. var x = quadraticAt$$1(x0, x1, x2, tx);
  10765. var y = quadraticAt$$1(y0, y1, y2, ty);
  10766. min$$1[0] = mathMin$3(x0, x2, x);
  10767. min$$1[1] = mathMin$3(y0, y2, y);
  10768. max$$1[0] = mathMax$3(x0, x2, x);
  10769. max$$1[1] = mathMax$3(y0, y2, y);
  10770. }
  10771. /**
  10772. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  10773. * @method
  10774. * @memberOf module:zrender/core/bbox
  10775. * @param {number} x
  10776. * @param {number} y
  10777. * @param {number} rx
  10778. * @param {number} ry
  10779. * @param {number} startAngle
  10780. * @param {number} endAngle
  10781. * @param {number} anticlockwise
  10782. * @param {Array.<number>} min
  10783. * @param {Array.<number>} max
  10784. */
  10785. function fromArc(
  10786. x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1
  10787. ) {
  10788. var vec2Min = min;
  10789. var vec2Max = max;
  10790. var diff = Math.abs(startAngle - endAngle);
  10791. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  10792. // Is a circle
  10793. min$$1[0] = x - rx;
  10794. min$$1[1] = y - ry;
  10795. max$$1[0] = x + rx;
  10796. max$$1[1] = y + ry;
  10797. return;
  10798. }
  10799. start[0] = mathCos$2(startAngle) * rx + x;
  10800. start[1] = mathSin$2(startAngle) * ry + y;
  10801. end[0] = mathCos$2(endAngle) * rx + x;
  10802. end[1] = mathSin$2(endAngle) * ry + y;
  10803. vec2Min(min$$1, start, end);
  10804. vec2Max(max$$1, start, end);
  10805. // Thresh to [0, Math.PI * 2]
  10806. startAngle = startAngle % (PI2);
  10807. if (startAngle < 0) {
  10808. startAngle = startAngle + PI2;
  10809. }
  10810. endAngle = endAngle % (PI2);
  10811. if (endAngle < 0) {
  10812. endAngle = endAngle + PI2;
  10813. }
  10814. if (startAngle > endAngle && !anticlockwise) {
  10815. endAngle += PI2;
  10816. }
  10817. else if (startAngle < endAngle && anticlockwise) {
  10818. startAngle += PI2;
  10819. }
  10820. if (anticlockwise) {
  10821. var tmp = endAngle;
  10822. endAngle = startAngle;
  10823. startAngle = tmp;
  10824. }
  10825. // var number = 0;
  10826. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  10827. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  10828. if (angle > startAngle) {
  10829. extremity[0] = mathCos$2(angle) * rx + x;
  10830. extremity[1] = mathSin$2(angle) * ry + y;
  10831. vec2Min(min$$1, extremity, min$$1);
  10832. vec2Max(max$$1, extremity, max$$1);
  10833. }
  10834. }
  10835. }
  10836. /**
  10837. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  10838. * 可以用于 isInsidePath 判断以及获取boundingRect
  10839. *
  10840. * @module zrender/core/PathProxy
  10841. * @author Yi Shen (http://www.github.com/pissang)
  10842. */
  10843. // TODO getTotalLength, getPointAtLength
  10844. var CMD = {
  10845. M: 1,
  10846. L: 2,
  10847. C: 3,
  10848. Q: 4,
  10849. A: 5,
  10850. Z: 6,
  10851. // Rect
  10852. R: 7
  10853. };
  10854. // var CMD_MEM_SIZE = {
  10855. // M: 3,
  10856. // L: 3,
  10857. // C: 7,
  10858. // Q: 5,
  10859. // A: 9,
  10860. // R: 5,
  10861. // Z: 1
  10862. // };
  10863. var min$1 = [];
  10864. var max$1 = [];
  10865. var min2 = [];
  10866. var max2 = [];
  10867. var mathMin$2 = Math.min;
  10868. var mathMax$2 = Math.max;
  10869. var mathCos$1 = Math.cos;
  10870. var mathSin$1 = Math.sin;
  10871. var mathSqrt$1 = Math.sqrt;
  10872. var mathAbs = Math.abs;
  10873. var hasTypedArray = typeof Float32Array != 'undefined';
  10874. /**
  10875. * @alias module:zrender/core/PathProxy
  10876. * @constructor
  10877. */
  10878. var PathProxy = function (notSaveData) {
  10879. this._saveData = !(notSaveData || false);
  10880. if (this._saveData) {
  10881. /**
  10882. * Path data. Stored as flat array
  10883. * @type {Array.<Object>}
  10884. */
  10885. this.data = [];
  10886. }
  10887. this._ctx = null;
  10888. };
  10889. /**
  10890. * 快速计算Path包围盒(并不是最小包围盒)
  10891. * @return {Object}
  10892. */
  10893. PathProxy.prototype = {
  10894. constructor: PathProxy,
  10895. _xi: 0,
  10896. _yi: 0,
  10897. _x0: 0,
  10898. _y0: 0,
  10899. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  10900. _ux: 0,
  10901. _uy: 0,
  10902. _len: 0,
  10903. _lineDash: null,
  10904. _dashOffset: 0,
  10905. _dashIdx: 0,
  10906. _dashSum: 0,
  10907. /**
  10908. * @readOnly
  10909. */
  10910. setScale: function (sx, sy) {
  10911. this._ux = mathAbs(1 / devicePixelRatio / sx) || 0;
  10912. this._uy = mathAbs(1 / devicePixelRatio / sy) || 0;
  10913. },
  10914. getContext: function () {
  10915. return this._ctx;
  10916. },
  10917. /**
  10918. * @param {CanvasRenderingContext2D} ctx
  10919. * @return {module:zrender/core/PathProxy}
  10920. */
  10921. beginPath: function (ctx) {
  10922. this._ctx = ctx;
  10923. ctx && ctx.beginPath();
  10924. ctx && (this.dpr = ctx.dpr);
  10925. // Reset
  10926. if (this._saveData) {
  10927. this._len = 0;
  10928. }
  10929. if (this._lineDash) {
  10930. this._lineDash = null;
  10931. this._dashOffset = 0;
  10932. }
  10933. return this;
  10934. },
  10935. /**
  10936. * @param {number} x
  10937. * @param {number} y
  10938. * @return {module:zrender/core/PathProxy}
  10939. */
  10940. moveTo: function (x, y) {
  10941. this.addData(CMD.M, x, y);
  10942. this._ctx && this._ctx.moveTo(x, y);
  10943. // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  10944. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  10945. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  10946. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  10947. this._x0 = x;
  10948. this._y0 = y;
  10949. this._xi = x;
  10950. this._yi = y;
  10951. return this;
  10952. },
  10953. /**
  10954. * @param {number} x
  10955. * @param {number} y
  10956. * @return {module:zrender/core/PathProxy}
  10957. */
  10958. lineTo: function (x, y) {
  10959. var exceedUnit = mathAbs(x - this._xi) > this._ux
  10960. || mathAbs(y - this._yi) > this._uy
  10961. // Force draw the first segment
  10962. || this._len < 5;
  10963. this.addData(CMD.L, x, y);
  10964. if (this._ctx && exceedUnit) {
  10965. this._needsDash() ? this._dashedLineTo(x, y)
  10966. : this._ctx.lineTo(x, y);
  10967. }
  10968. if (exceedUnit) {
  10969. this._xi = x;
  10970. this._yi = y;
  10971. }
  10972. return this;
  10973. },
  10974. /**
  10975. * @param {number} x1
  10976. * @param {number} y1
  10977. * @param {number} x2
  10978. * @param {number} y2
  10979. * @param {number} x3
  10980. * @param {number} y3
  10981. * @return {module:zrender/core/PathProxy}
  10982. */
  10983. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  10984. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  10985. if (this._ctx) {
  10986. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  10987. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  10988. }
  10989. this._xi = x3;
  10990. this._yi = y3;
  10991. return this;
  10992. },
  10993. /**
  10994. * @param {number} x1
  10995. * @param {number} y1
  10996. * @param {number} x2
  10997. * @param {number} y2
  10998. * @return {module:zrender/core/PathProxy}
  10999. */
  11000. quadraticCurveTo: function (x1, y1, x2, y2) {
  11001. this.addData(CMD.Q, x1, y1, x2, y2);
  11002. if (this._ctx) {
  11003. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2)
  11004. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  11005. }
  11006. this._xi = x2;
  11007. this._yi = y2;
  11008. return this;
  11009. },
  11010. /**
  11011. * @param {number} cx
  11012. * @param {number} cy
  11013. * @param {number} r
  11014. * @param {number} startAngle
  11015. * @param {number} endAngle
  11016. * @param {boolean} anticlockwise
  11017. * @return {module:zrender/core/PathProxy}
  11018. */
  11019. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  11020. this.addData(
  11021. CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1
  11022. );
  11023. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  11024. this._xi = mathCos$1(endAngle) * r + cx;
  11025. this._yi = mathSin$1(endAngle) * r + cx;
  11026. return this;
  11027. },
  11028. // TODO
  11029. arcTo: function (x1, y1, x2, y2, radius) {
  11030. if (this._ctx) {
  11031. this._ctx.arcTo(x1, y1, x2, y2, radius);
  11032. }
  11033. return this;
  11034. },
  11035. // TODO
  11036. rect: function (x, y, w, h) {
  11037. this._ctx && this._ctx.rect(x, y, w, h);
  11038. this.addData(CMD.R, x, y, w, h);
  11039. return this;
  11040. },
  11041. /**
  11042. * @return {module:zrender/core/PathProxy}
  11043. */
  11044. closePath: function () {
  11045. this.addData(CMD.Z);
  11046. var ctx = this._ctx;
  11047. var x0 = this._x0;
  11048. var y0 = this._y0;
  11049. if (ctx) {
  11050. this._needsDash() && this._dashedLineTo(x0, y0);
  11051. ctx.closePath();
  11052. }
  11053. this._xi = x0;
  11054. this._yi = y0;
  11055. return this;
  11056. },
  11057. /**
  11058. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  11059. * stroke 同样
  11060. * @param {CanvasRenderingContext2D} ctx
  11061. * @return {module:zrender/core/PathProxy}
  11062. */
  11063. fill: function (ctx) {
  11064. ctx && ctx.fill();
  11065. this.toStatic();
  11066. },
  11067. /**
  11068. * @param {CanvasRenderingContext2D} ctx
  11069. * @return {module:zrender/core/PathProxy}
  11070. */
  11071. stroke: function (ctx) {
  11072. ctx && ctx.stroke();
  11073. this.toStatic();
  11074. },
  11075. /**
  11076. * 必须在其它绘制命令前调用
  11077. * Must be invoked before all other path drawing methods
  11078. * @return {module:zrender/core/PathProxy}
  11079. */
  11080. setLineDash: function (lineDash) {
  11081. if (lineDash instanceof Array) {
  11082. this._lineDash = lineDash;
  11083. this._dashIdx = 0;
  11084. var lineDashSum = 0;
  11085. for (var i = 0; i < lineDash.length; i++) {
  11086. lineDashSum += lineDash[i];
  11087. }
  11088. this._dashSum = lineDashSum;
  11089. }
  11090. return this;
  11091. },
  11092. /**
  11093. * 必须在其它绘制命令前调用
  11094. * Must be invoked before all other path drawing methods
  11095. * @return {module:zrender/core/PathProxy}
  11096. */
  11097. setLineDashOffset: function (offset) {
  11098. this._dashOffset = offset;
  11099. return this;
  11100. },
  11101. /**
  11102. *
  11103. * @return {boolean}
  11104. */
  11105. len: function () {
  11106. return this._len;
  11107. },
  11108. /**
  11109. * 直接设置 Path 数据
  11110. */
  11111. setData: function (data) {
  11112. var len$$1 = data.length;
  11113. if (! (this.data && this.data.length == len$$1) && hasTypedArray) {
  11114. this.data = new Float32Array(len$$1);
  11115. }
  11116. for (var i = 0; i < len$$1; i++) {
  11117. this.data[i] = data[i];
  11118. }
  11119. this._len = len$$1;
  11120. },
  11121. /**
  11122. * 添加子路径
  11123. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  11124. */
  11125. appendPath: function (path) {
  11126. if (!(path instanceof Array)) {
  11127. path = [path];
  11128. }
  11129. var len$$1 = path.length;
  11130. var appendSize = 0;
  11131. var offset = this._len;
  11132. for (var i = 0; i < len$$1; i++) {
  11133. appendSize += path[i].len();
  11134. }
  11135. if (hasTypedArray && (this.data instanceof Float32Array)) {
  11136. this.data = new Float32Array(offset + appendSize);
  11137. }
  11138. for (var i = 0; i < len$$1; i++) {
  11139. var appendPathData = path[i].data;
  11140. for (var k = 0; k < appendPathData.length; k++) {
  11141. this.data[offset++] = appendPathData[k];
  11142. }
  11143. }
  11144. this._len = offset;
  11145. },
  11146. /**
  11147. * 填充 Path 数据。
  11148. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  11149. */
  11150. addData: function (cmd) {
  11151. if (!this._saveData) {
  11152. return;
  11153. }
  11154. var data = this.data;
  11155. if (this._len + arguments.length > data.length) {
  11156. // 因为之前的数组已经转换成静态的 Float32Array
  11157. // 所以不够用时需要扩展一个新的动态数组
  11158. this._expandData();
  11159. data = this.data;
  11160. }
  11161. for (var i = 0; i < arguments.length; i++) {
  11162. data[this._len++] = arguments[i];
  11163. }
  11164. this._prevCmd = cmd;
  11165. },
  11166. _expandData: function () {
  11167. // Only if data is Float32Array
  11168. if (!(this.data instanceof Array)) {
  11169. var newData = [];
  11170. for (var i = 0; i < this._len; i++) {
  11171. newData[i] = this.data[i];
  11172. }
  11173. this.data = newData;
  11174. }
  11175. },
  11176. /**
  11177. * If needs js implemented dashed line
  11178. * @return {boolean}
  11179. * @private
  11180. */
  11181. _needsDash: function () {
  11182. return this._lineDash;
  11183. },
  11184. _dashedLineTo: function (x1, y1) {
  11185. var dashSum = this._dashSum;
  11186. var offset = this._dashOffset;
  11187. var lineDash = this._lineDash;
  11188. var ctx = this._ctx;
  11189. var x0 = this._xi;
  11190. var y0 = this._yi;
  11191. var dx = x1 - x0;
  11192. var dy = y1 - y0;
  11193. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  11194. var x = x0;
  11195. var y = y0;
  11196. var dash;
  11197. var nDash = lineDash.length;
  11198. var idx;
  11199. dx /= dist$$1;
  11200. dy /= dist$$1;
  11201. if (offset < 0) {
  11202. // Convert to positive offset
  11203. offset = dashSum + offset;
  11204. }
  11205. offset %= dashSum;
  11206. x -= offset * dx;
  11207. y -= offset * dy;
  11208. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  11209. || (dx == 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  11210. idx = this._dashIdx;
  11211. dash = lineDash[idx];
  11212. x += dx * dash;
  11213. y += dy * dash;
  11214. this._dashIdx = (idx + 1) % nDash;
  11215. // Skip positive offset
  11216. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  11217. continue;
  11218. }
  11219. ctx[idx % 2 ? 'moveTo' : 'lineTo'](
  11220. dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1),
  11221. dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1)
  11222. );
  11223. }
  11224. // Offset for next lineTo
  11225. dx = x - x1;
  11226. dy = y - y1;
  11227. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11228. },
  11229. // Not accurate dashed line to
  11230. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  11231. var dashSum = this._dashSum;
  11232. var offset = this._dashOffset;
  11233. var lineDash = this._lineDash;
  11234. var ctx = this._ctx;
  11235. var x0 = this._xi;
  11236. var y0 = this._yi;
  11237. var t;
  11238. var dx;
  11239. var dy;
  11240. var cubicAt$$1 = cubicAt;
  11241. var bezierLen = 0;
  11242. var idx = this._dashIdx;
  11243. var nDash = lineDash.length;
  11244. var x;
  11245. var y;
  11246. var tmpLen = 0;
  11247. if (offset < 0) {
  11248. // Convert to positive offset
  11249. offset = dashSum + offset;
  11250. }
  11251. offset %= dashSum;
  11252. // Bezier approx length
  11253. for (t = 0; t < 1; t += 0.1) {
  11254. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1)
  11255. - cubicAt$$1(x0, x1, x2, x3, t);
  11256. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1)
  11257. - cubicAt$$1(y0, y1, y2, y3, t);
  11258. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  11259. }
  11260. // Find idx after add offset
  11261. for (; idx < nDash; idx++) {
  11262. tmpLen += lineDash[idx];
  11263. if (tmpLen > offset) {
  11264. break;
  11265. }
  11266. }
  11267. t = (tmpLen - offset) / bezierLen;
  11268. while (t <= 1) {
  11269. x = cubicAt$$1(x0, x1, x2, x3, t);
  11270. y = cubicAt$$1(y0, y1, y2, y3, t);
  11271. // Use line to approximate dashed bezier
  11272. // Bad result if dash is long
  11273. idx % 2 ? ctx.moveTo(x, y)
  11274. : ctx.lineTo(x, y);
  11275. t += lineDash[idx] / bezierLen;
  11276. idx = (idx + 1) % nDash;
  11277. }
  11278. // Finish the last segment and calculate the new offset
  11279. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  11280. dx = x3 - x;
  11281. dy = y3 - y;
  11282. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11283. },
  11284. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  11285. // Convert quadratic to cubic using degree elevation
  11286. var x3 = x2;
  11287. var y3 = y2;
  11288. x2 = (x2 + 2 * x1) / 3;
  11289. y2 = (y2 + 2 * y1) / 3;
  11290. x1 = (this._xi + 2 * x1) / 3;
  11291. y1 = (this._yi + 2 * y1) / 3;
  11292. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  11293. },
  11294. /**
  11295. * 转成静态的 Float32Array 减少堆内存占用
  11296. * Convert dynamic array to static Float32Array
  11297. */
  11298. toStatic: function () {
  11299. var data = this.data;
  11300. if (data instanceof Array) {
  11301. data.length = this._len;
  11302. if (hasTypedArray) {
  11303. this.data = new Float32Array(data);
  11304. }
  11305. }
  11306. },
  11307. /**
  11308. * @return {module:zrender/core/BoundingRect}
  11309. */
  11310. getBoundingRect: function () {
  11311. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  11312. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  11313. var data = this.data;
  11314. var xi = 0;
  11315. var yi = 0;
  11316. var x0 = 0;
  11317. var y0 = 0;
  11318. for (var i = 0; i < data.length;) {
  11319. var cmd = data[i++];
  11320. if (i == 1) {
  11321. // 如果第一个命令是 L, C, Q
  11322. // 则 previous point 同绘制命令的第一个 point
  11323. //
  11324. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11325. xi = data[i];
  11326. yi = data[i + 1];
  11327. x0 = xi;
  11328. y0 = yi;
  11329. }
  11330. switch (cmd) {
  11331. case CMD.M:
  11332. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11333. // 在 closePath 的时候使用
  11334. x0 = data[i++];
  11335. y0 = data[i++];
  11336. xi = x0;
  11337. yi = y0;
  11338. min2[0] = x0;
  11339. min2[1] = y0;
  11340. max2[0] = x0;
  11341. max2[1] = y0;
  11342. break;
  11343. case CMD.L:
  11344. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  11345. xi = data[i++];
  11346. yi = data[i++];
  11347. break;
  11348. case CMD.C:
  11349. fromCubic(
  11350. xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11351. min2, max2
  11352. );
  11353. xi = data[i++];
  11354. yi = data[i++];
  11355. break;
  11356. case CMD.Q:
  11357. fromQuadratic(
  11358. xi, yi, data[i++], data[i++], data[i], data[i + 1],
  11359. min2, max2
  11360. );
  11361. xi = data[i++];
  11362. yi = data[i++];
  11363. break;
  11364. case CMD.A:
  11365. // TODO Arc 判断的开销比较大
  11366. var cx = data[i++];
  11367. var cy = data[i++];
  11368. var rx = data[i++];
  11369. var ry = data[i++];
  11370. var startAngle = data[i++];
  11371. var endAngle = data[i++] + startAngle;
  11372. // TODO Arc 旋转
  11373. var psi = data[i++];
  11374. var anticlockwise = 1 - data[i++];
  11375. if (i == 1) {
  11376. // 直接使用 arc 命令
  11377. // 第一个命令起点还未定义
  11378. x0 = mathCos$1(startAngle) * rx + cx;
  11379. y0 = mathSin$1(startAngle) * ry + cy;
  11380. }
  11381. fromArc(
  11382. cx, cy, rx, ry, startAngle, endAngle,
  11383. anticlockwise, min2, max2
  11384. );
  11385. xi = mathCos$1(endAngle) * rx + cx;
  11386. yi = mathSin$1(endAngle) * ry + cy;
  11387. break;
  11388. case CMD.R:
  11389. x0 = xi = data[i++];
  11390. y0 = yi = data[i++];
  11391. var width = data[i++];
  11392. var height = data[i++];
  11393. // Use fromLine
  11394. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  11395. break;
  11396. case CMD.Z:
  11397. xi = x0;
  11398. yi = y0;
  11399. break;
  11400. }
  11401. // Union
  11402. min(min$1, min$1, min2);
  11403. max(max$1, max$1, max2);
  11404. }
  11405. // No data
  11406. if (i === 0) {
  11407. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  11408. }
  11409. return new BoundingRect(
  11410. min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]
  11411. );
  11412. },
  11413. /**
  11414. * Rebuild path from current data
  11415. * Rebuild path will not consider javascript implemented line dash.
  11416. * @param {CanvasRenderingContext2D} ctx
  11417. */
  11418. rebuildPath: function (ctx) {
  11419. var d = this.data;
  11420. var x0, y0;
  11421. var xi, yi;
  11422. var x, y;
  11423. var ux = this._ux;
  11424. var uy = this._uy;
  11425. var len$$1 = this._len;
  11426. for (var i = 0; i < len$$1;) {
  11427. var cmd = d[i++];
  11428. if (i == 1) {
  11429. // 如果第一个命令是 L, C, Q
  11430. // 则 previous point 同绘制命令的第一个 point
  11431. //
  11432. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11433. xi = d[i];
  11434. yi = d[i + 1];
  11435. x0 = xi;
  11436. y0 = yi;
  11437. }
  11438. switch (cmd) {
  11439. case CMD.M:
  11440. x0 = xi = d[i++];
  11441. y0 = yi = d[i++];
  11442. ctx.moveTo(xi, yi);
  11443. break;
  11444. case CMD.L:
  11445. x = d[i++];
  11446. y = d[i++];
  11447. // Not draw too small seg between
  11448. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  11449. ctx.lineTo(x, y);
  11450. xi = x;
  11451. yi = y;
  11452. }
  11453. break;
  11454. case CMD.C:
  11455. ctx.bezierCurveTo(
  11456. d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]
  11457. );
  11458. xi = d[i - 2];
  11459. yi = d[i - 1];
  11460. break;
  11461. case CMD.Q:
  11462. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  11463. xi = d[i - 2];
  11464. yi = d[i - 1];
  11465. break;
  11466. case CMD.A:
  11467. var cx = d[i++];
  11468. var cy = d[i++];
  11469. var rx = d[i++];
  11470. var ry = d[i++];
  11471. var theta = d[i++];
  11472. var dTheta = d[i++];
  11473. var psi = d[i++];
  11474. var fs = d[i++];
  11475. var r = (rx > ry) ? rx : ry;
  11476. var scaleX = (rx > ry) ? 1 : rx / ry;
  11477. var scaleY = (rx > ry) ? ry / rx : 1;
  11478. var isEllipse = Math.abs(rx - ry) > 1e-3;
  11479. var endAngle = theta + dTheta;
  11480. if (isEllipse) {
  11481. ctx.translate(cx, cy);
  11482. ctx.rotate(psi);
  11483. ctx.scale(scaleX, scaleY);
  11484. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  11485. ctx.scale(1 / scaleX, 1 / scaleY);
  11486. ctx.rotate(-psi);
  11487. ctx.translate(-cx, -cy);
  11488. }
  11489. else {
  11490. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  11491. }
  11492. if (i == 1) {
  11493. // 直接使用 arc 命令
  11494. // 第一个命令起点还未定义
  11495. x0 = mathCos$1(theta) * rx + cx;
  11496. y0 = mathSin$1(theta) * ry + cy;
  11497. }
  11498. xi = mathCos$1(endAngle) * rx + cx;
  11499. yi = mathSin$1(endAngle) * ry + cy;
  11500. break;
  11501. case CMD.R:
  11502. x0 = xi = d[i];
  11503. y0 = yi = d[i + 1];
  11504. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  11505. break;
  11506. case CMD.Z:
  11507. ctx.closePath();
  11508. xi = x0;
  11509. yi = y0;
  11510. }
  11511. }
  11512. }
  11513. };
  11514. PathProxy.CMD = CMD;
  11515. /**
  11516. * 线段包含判断
  11517. * @param {number} x0
  11518. * @param {number} y0
  11519. * @param {number} x1
  11520. * @param {number} y1
  11521. * @param {number} lineWidth
  11522. * @param {number} x
  11523. * @param {number} y
  11524. * @return {boolean}
  11525. */
  11526. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  11527. if (lineWidth === 0) {
  11528. return false;
  11529. }
  11530. var _l = lineWidth;
  11531. var _a = 0;
  11532. var _b = x0;
  11533. // Quick reject
  11534. if (
  11535. (y > y0 + _l && y > y1 + _l)
  11536. || (y < y0 - _l && y < y1 - _l)
  11537. || (x > x0 + _l && x > x1 + _l)
  11538. || (x < x0 - _l && x < x1 - _l)
  11539. ) {
  11540. return false;
  11541. }
  11542. if (x0 !== x1) {
  11543. _a = (y0 - y1) / (x0 - x1);
  11544. _b = (x0 * y1 - x1 * y0) / (x0 - x1) ;
  11545. }
  11546. else {
  11547. return Math.abs(x - x0) <= _l / 2;
  11548. }
  11549. var tmp = _a * x - y + _b;
  11550. var _s = tmp * tmp / (_a * _a + 1);
  11551. return _s <= _l / 2 * _l / 2;
  11552. }
  11553. /**
  11554. * 三次贝塞尔曲线描边包含判断
  11555. * @param {number} x0
  11556. * @param {number} y0
  11557. * @param {number} x1
  11558. * @param {number} y1
  11559. * @param {number} x2
  11560. * @param {number} y2
  11561. * @param {number} x3
  11562. * @param {number} y3
  11563. * @param {number} lineWidth
  11564. * @param {number} x
  11565. * @param {number} y
  11566. * @return {boolean}
  11567. */
  11568. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  11569. if (lineWidth === 0) {
  11570. return false;
  11571. }
  11572. var _l = lineWidth;
  11573. // Quick reject
  11574. if (
  11575. (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  11576. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  11577. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  11578. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)
  11579. ) {
  11580. return false;
  11581. }
  11582. var d = cubicProjectPoint(
  11583. x0, y0, x1, y1, x2, y2, x3, y3,
  11584. x, y, null
  11585. );
  11586. return d <= _l / 2;
  11587. }
  11588. /**
  11589. * 二次贝塞尔曲线描边包含判断
  11590. * @param {number} x0
  11591. * @param {number} y0
  11592. * @param {number} x1
  11593. * @param {number} y1
  11594. * @param {number} x2
  11595. * @param {number} y2
  11596. * @param {number} lineWidth
  11597. * @param {number} x
  11598. * @param {number} y
  11599. * @return {boolean}
  11600. */
  11601. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  11602. if (lineWidth === 0) {
  11603. return false;
  11604. }
  11605. var _l = lineWidth;
  11606. // Quick reject
  11607. if (
  11608. (y > y0 + _l && y > y1 + _l && y > y2 + _l)
  11609. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  11610. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  11611. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)
  11612. ) {
  11613. return false;
  11614. }
  11615. var d = quadraticProjectPoint(
  11616. x0, y0, x1, y1, x2, y2,
  11617. x, y, null
  11618. );
  11619. return d <= _l / 2;
  11620. }
  11621. var PI2$3 = Math.PI * 2;
  11622. function normalizeRadian(angle) {
  11623. angle %= PI2$3;
  11624. if (angle < 0) {
  11625. angle += PI2$3;
  11626. }
  11627. return angle;
  11628. }
  11629. var PI2$2 = Math.PI * 2;
  11630. /**
  11631. * 圆弧描边包含判断
  11632. * @param {number} cx
  11633. * @param {number} cy
  11634. * @param {number} r
  11635. * @param {number} startAngle
  11636. * @param {number} endAngle
  11637. * @param {boolean} anticlockwise
  11638. * @param {number} lineWidth
  11639. * @param {number} x
  11640. * @param {number} y
  11641. * @return {Boolean}
  11642. */
  11643. function containStroke$4(
  11644. cx, cy, r, startAngle, endAngle, anticlockwise,
  11645. lineWidth, x, y
  11646. ) {
  11647. if (lineWidth === 0) {
  11648. return false;
  11649. }
  11650. var _l = lineWidth;
  11651. x -= cx;
  11652. y -= cy;
  11653. var d = Math.sqrt(x * x + y * y);
  11654. if ((d - _l > r) || (d + _l < r)) {
  11655. return false;
  11656. }
  11657. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  11658. // Is a circle
  11659. return true;
  11660. }
  11661. if (anticlockwise) {
  11662. var tmp = startAngle;
  11663. startAngle = normalizeRadian(endAngle);
  11664. endAngle = normalizeRadian(tmp);
  11665. } else {
  11666. startAngle = normalizeRadian(startAngle);
  11667. endAngle = normalizeRadian(endAngle);
  11668. }
  11669. if (startAngle > endAngle) {
  11670. endAngle += PI2$2;
  11671. }
  11672. var angle = Math.atan2(y, x);
  11673. if (angle < 0) {
  11674. angle += PI2$2;
  11675. }
  11676. return (angle >= startAngle && angle <= endAngle)
  11677. || (angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle);
  11678. }
  11679. function windingLine(x0, y0, x1, y1, x, y) {
  11680. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  11681. return 0;
  11682. }
  11683. // Ignore horizontal line
  11684. if (y1 === y0) {
  11685. return 0;
  11686. }
  11687. var dir = y1 < y0 ? 1 : -1;
  11688. var t = (y - y0) / (y1 - y0);
  11689. // Avoid winding error when intersection point is the connect point of two line of polygon
  11690. if (t === 1 || t === 0) {
  11691. dir = y1 < y0 ? 0.5 : -0.5;
  11692. }
  11693. var x_ = t * (x1 - x0) + x0;
  11694. return x_ > x ? dir : 0;
  11695. }
  11696. var CMD$1 = PathProxy.CMD;
  11697. var PI2$1 = Math.PI * 2;
  11698. var EPSILON$2 = 1e-4;
  11699. function isAroundEqual(a, b) {
  11700. return Math.abs(a - b) < EPSILON$2;
  11701. }
  11702. // 临时数组
  11703. var roots = [-1, -1, -1];
  11704. var extrema = [-1, -1];
  11705. function swapExtrema() {
  11706. var tmp = extrema[0];
  11707. extrema[0] = extrema[1];
  11708. extrema[1] = tmp;
  11709. }
  11710. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  11711. // Quick reject
  11712. if (
  11713. (y > y0 && y > y1 && y > y2 && y > y3)
  11714. || (y < y0 && y < y1 && y < y2 && y < y3)
  11715. ) {
  11716. return 0;
  11717. }
  11718. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  11719. if (nRoots === 0) {
  11720. return 0;
  11721. }
  11722. else {
  11723. var w = 0;
  11724. var nExtrema = -1;
  11725. var y0_, y1_;
  11726. for (var i = 0; i < nRoots; i++) {
  11727. var t = roots[i];
  11728. // Avoid winding error when intersection point is the connect point of two line of polygon
  11729. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  11730. var x_ = cubicAt(x0, x1, x2, x3, t);
  11731. if (x_ < x) { // Quick reject
  11732. continue;
  11733. }
  11734. if (nExtrema < 0) {
  11735. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  11736. if (extrema[1] < extrema[0] && nExtrema > 1) {
  11737. swapExtrema();
  11738. }
  11739. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  11740. if (nExtrema > 1) {
  11741. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  11742. }
  11743. }
  11744. if (nExtrema == 2) {
  11745. // 分成三段单调函数
  11746. if (t < extrema[0]) {
  11747. w += y0_ < y0 ? unit : -unit;
  11748. }
  11749. else if (t < extrema[1]) {
  11750. w += y1_ < y0_ ? unit : -unit;
  11751. }
  11752. else {
  11753. w += y3 < y1_ ? unit : -unit;
  11754. }
  11755. }
  11756. else {
  11757. // 分成两段单调函数
  11758. if (t < extrema[0]) {
  11759. w += y0_ < y0 ? unit : -unit;
  11760. }
  11761. else {
  11762. w += y3 < y0_ ? unit : -unit;
  11763. }
  11764. }
  11765. }
  11766. return w;
  11767. }
  11768. }
  11769. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  11770. // Quick reject
  11771. if (
  11772. (y > y0 && y > y1 && y > y2)
  11773. || (y < y0 && y < y1 && y < y2)
  11774. ) {
  11775. return 0;
  11776. }
  11777. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  11778. if (nRoots === 0) {
  11779. return 0;
  11780. }
  11781. else {
  11782. var t = quadraticExtremum(y0, y1, y2);
  11783. if (t >= 0 && t <= 1) {
  11784. var w = 0;
  11785. var y_ = quadraticAt(y0, y1, y2, t);
  11786. for (var i = 0; i < nRoots; i++) {
  11787. // Remove one endpoint.
  11788. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  11789. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  11790. if (x_ < x) { // Quick reject
  11791. continue;
  11792. }
  11793. if (roots[i] < t) {
  11794. w += y_ < y0 ? unit : -unit;
  11795. }
  11796. else {
  11797. w += y2 < y_ ? unit : -unit;
  11798. }
  11799. }
  11800. return w;
  11801. }
  11802. else {
  11803. // Remove one endpoint.
  11804. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  11805. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  11806. if (x_ < x) { // Quick reject
  11807. return 0;
  11808. }
  11809. return y2 < y0 ? unit : -unit;
  11810. }
  11811. }
  11812. }
  11813. // TODO
  11814. // Arc 旋转
  11815. function windingArc(
  11816. cx, cy, r, startAngle, endAngle, anticlockwise, x, y
  11817. ) {
  11818. y -= cy;
  11819. if (y > r || y < -r) {
  11820. return 0;
  11821. }
  11822. var tmp = Math.sqrt(r * r - y * y);
  11823. roots[0] = -tmp;
  11824. roots[1] = tmp;
  11825. var diff = Math.abs(startAngle - endAngle);
  11826. if (diff < 1e-4) {
  11827. return 0;
  11828. }
  11829. if (diff % PI2$1 < 1e-4) {
  11830. // Is a circle
  11831. startAngle = 0;
  11832. endAngle = PI2$1;
  11833. var dir = anticlockwise ? 1 : -1;
  11834. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  11835. return dir;
  11836. } else {
  11837. return 0;
  11838. }
  11839. }
  11840. if (anticlockwise) {
  11841. var tmp = startAngle;
  11842. startAngle = normalizeRadian(endAngle);
  11843. endAngle = normalizeRadian(tmp);
  11844. }
  11845. else {
  11846. startAngle = normalizeRadian(startAngle);
  11847. endAngle = normalizeRadian(endAngle);
  11848. }
  11849. if (startAngle > endAngle) {
  11850. endAngle += PI2$1;
  11851. }
  11852. var w = 0;
  11853. for (var i = 0; i < 2; i++) {
  11854. var x_ = roots[i];
  11855. if (x_ + cx > x) {
  11856. var angle = Math.atan2(y, x_);
  11857. var dir = anticlockwise ? 1 : -1;
  11858. if (angle < 0) {
  11859. angle = PI2$1 + angle;
  11860. }
  11861. if (
  11862. (angle >= startAngle && angle <= endAngle)
  11863. || (angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle)
  11864. ) {
  11865. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  11866. dir = -dir;
  11867. }
  11868. w += dir;
  11869. }
  11870. }
  11871. }
  11872. return w;
  11873. }
  11874. function containPath(data, lineWidth, isStroke, x, y) {
  11875. var w = 0;
  11876. var xi = 0;
  11877. var yi = 0;
  11878. var x0 = 0;
  11879. var y0 = 0;
  11880. for (var i = 0; i < data.length;) {
  11881. var cmd = data[i++];
  11882. // Begin a new subpath
  11883. if (cmd === CMD$1.M && i > 1) {
  11884. // Close previous subpath
  11885. if (!isStroke) {
  11886. w += windingLine(xi, yi, x0, y0, x, y);
  11887. }
  11888. // 如果被任何一个 subpath 包含
  11889. // if (w !== 0) {
  11890. // return true;
  11891. // }
  11892. }
  11893. if (i == 1) {
  11894. // 如果第一个命令是 L, C, Q
  11895. // 则 previous point 同绘制命令的第一个 point
  11896. //
  11897. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11898. xi = data[i];
  11899. yi = data[i + 1];
  11900. x0 = xi;
  11901. y0 = yi;
  11902. }
  11903. switch (cmd) {
  11904. case CMD$1.M:
  11905. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11906. // 在 closePath 的时候使用
  11907. x0 = data[i++];
  11908. y0 = data[i++];
  11909. xi = x0;
  11910. yi = y0;
  11911. break;
  11912. case CMD$1.L:
  11913. if (isStroke) {
  11914. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  11915. return true;
  11916. }
  11917. }
  11918. else {
  11919. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  11920. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  11921. }
  11922. xi = data[i++];
  11923. yi = data[i++];
  11924. break;
  11925. case CMD$1.C:
  11926. if (isStroke) {
  11927. if (containStroke$2(xi, yi,
  11928. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11929. lineWidth, x, y
  11930. )) {
  11931. return true;
  11932. }
  11933. }
  11934. else {
  11935. w += windingCubic(
  11936. xi, yi,
  11937. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11938. x, y
  11939. ) || 0;
  11940. }
  11941. xi = data[i++];
  11942. yi = data[i++];
  11943. break;
  11944. case CMD$1.Q:
  11945. if (isStroke) {
  11946. if (containStroke$3(xi, yi,
  11947. data[i++], data[i++], data[i], data[i + 1],
  11948. lineWidth, x, y
  11949. )) {
  11950. return true;
  11951. }
  11952. }
  11953. else {
  11954. w += windingQuadratic(
  11955. xi, yi,
  11956. data[i++], data[i++], data[i], data[i + 1],
  11957. x, y
  11958. ) || 0;
  11959. }
  11960. xi = data[i++];
  11961. yi = data[i++];
  11962. break;
  11963. case CMD$1.A:
  11964. // TODO Arc 判断的开销比较大
  11965. var cx = data[i++];
  11966. var cy = data[i++];
  11967. var rx = data[i++];
  11968. var ry = data[i++];
  11969. var theta = data[i++];
  11970. var dTheta = data[i++];
  11971. // TODO Arc 旋转
  11972. var psi = data[i++];
  11973. var anticlockwise = 1 - data[i++];
  11974. var x1 = Math.cos(theta) * rx + cx;
  11975. var y1 = Math.sin(theta) * ry + cy;
  11976. // 不是直接使用 arc 命令
  11977. if (i > 1) {
  11978. w += windingLine(xi, yi, x1, y1, x, y);
  11979. }
  11980. else {
  11981. // 第一个命令起点还未定义
  11982. x0 = x1;
  11983. y0 = y1;
  11984. }
  11985. // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  11986. var _x = (x - cx) * ry / rx + cx;
  11987. if (isStroke) {
  11988. if (containStroke$4(
  11989. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  11990. lineWidth, _x, y
  11991. )) {
  11992. return true;
  11993. }
  11994. }
  11995. else {
  11996. w += windingArc(
  11997. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  11998. _x, y
  11999. );
  12000. }
  12001. xi = Math.cos(theta + dTheta) * rx + cx;
  12002. yi = Math.sin(theta + dTheta) * ry + cy;
  12003. break;
  12004. case CMD$1.R:
  12005. x0 = xi = data[i++];
  12006. y0 = yi = data[i++];
  12007. var width = data[i++];
  12008. var height = data[i++];
  12009. var x1 = x0 + width;
  12010. var y1 = y0 + height;
  12011. if (isStroke) {
  12012. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y)
  12013. || containStroke$1(x1, y0, x1, y1, lineWidth, x, y)
  12014. || containStroke$1(x1, y1, x0, y1, lineWidth, x, y)
  12015. || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)
  12016. ) {
  12017. return true;
  12018. }
  12019. }
  12020. else {
  12021. // FIXME Clockwise ?
  12022. w += windingLine(x1, y0, x1, y1, x, y);
  12023. w += windingLine(x0, y1, x0, y0, x, y);
  12024. }
  12025. break;
  12026. case CMD$1.Z:
  12027. if (isStroke) {
  12028. if (containStroke$1(
  12029. xi, yi, x0, y0, lineWidth, x, y
  12030. )) {
  12031. return true;
  12032. }
  12033. }
  12034. else {
  12035. // Close a subpath
  12036. w += windingLine(xi, yi, x0, y0, x, y);
  12037. // 如果被任何一个 subpath 包含
  12038. // FIXME subpaths may overlap
  12039. // if (w !== 0) {
  12040. // return true;
  12041. // }
  12042. }
  12043. xi = x0;
  12044. yi = y0;
  12045. break;
  12046. }
  12047. }
  12048. if (!isStroke && !isAroundEqual(yi, y0)) {
  12049. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  12050. }
  12051. return w !== 0;
  12052. }
  12053. function contain(pathData, x, y) {
  12054. return containPath(pathData, 0, false, x, y);
  12055. }
  12056. function containStroke(pathData, lineWidth, x, y) {
  12057. return containPath(pathData, lineWidth, true, x, y);
  12058. }
  12059. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  12060. var abs = Math.abs;
  12061. var pathProxyForDraw = new PathProxy(true);
  12062. /**
  12063. * @alias module:zrender/graphic/Path
  12064. * @extends module:zrender/graphic/Displayable
  12065. * @constructor
  12066. * @param {Object} opts
  12067. */
  12068. function Path(opts) {
  12069. Displayable.call(this, opts);
  12070. /**
  12071. * @type {module:zrender/core/PathProxy}
  12072. * @readOnly
  12073. */
  12074. this.path = null;
  12075. }
  12076. Path.prototype = {
  12077. constructor: Path,
  12078. type: 'path',
  12079. __dirtyPath: true,
  12080. strokeContainThreshold: 5,
  12081. brush: function (ctx, prevEl) {
  12082. var style = this.style;
  12083. var path = this.path || pathProxyForDraw;
  12084. var hasStroke = style.hasStroke();
  12085. var hasFill = style.hasFill();
  12086. var fill = style.fill;
  12087. var stroke = style.stroke;
  12088. var hasFillGradient = hasFill && !!(fill.colorStops);
  12089. var hasStrokeGradient = hasStroke && !!(stroke.colorStops);
  12090. var hasFillPattern = hasFill && !!(fill.image);
  12091. var hasStrokePattern = hasStroke && !!(stroke.image);
  12092. style.bind(ctx, this, prevEl);
  12093. this.setTransform(ctx);
  12094. if (this.__dirty) {
  12095. var rect;
  12096. // Update gradient because bounding rect may changed
  12097. if (hasFillGradient) {
  12098. rect = rect || this.getBoundingRect();
  12099. this._fillGradient = style.getGradient(ctx, fill, rect);
  12100. }
  12101. if (hasStrokeGradient) {
  12102. rect = rect || this.getBoundingRect();
  12103. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  12104. }
  12105. }
  12106. // Use the gradient or pattern
  12107. if (hasFillGradient) {
  12108. // PENDING If may have affect the state
  12109. ctx.fillStyle = this._fillGradient;
  12110. }
  12111. else if (hasFillPattern) {
  12112. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  12113. }
  12114. if (hasStrokeGradient) {
  12115. ctx.strokeStyle = this._strokeGradient;
  12116. }
  12117. else if (hasStrokePattern) {
  12118. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  12119. }
  12120. var lineDash = style.lineDash;
  12121. var lineDashOffset = style.lineDashOffset;
  12122. var ctxLineDash = !!ctx.setLineDash;
  12123. // Update path sx, sy
  12124. var scale = this.getGlobalScale();
  12125. path.setScale(scale[0], scale[1]);
  12126. // Proxy context
  12127. // Rebuild path in following 2 cases
  12128. // 1. Path is dirty
  12129. // 2. Path needs javascript implemented lineDash stroking.
  12130. // In this case, lineDash information will not be saved in PathProxy
  12131. if (this.__dirtyPath
  12132. || (lineDash && !ctxLineDash && hasStroke)
  12133. ) {
  12134. path.beginPath(ctx);
  12135. // Setting line dash before build path
  12136. if (lineDash && !ctxLineDash) {
  12137. path.setLineDash(lineDash);
  12138. path.setLineDashOffset(lineDashOffset);
  12139. }
  12140. this.buildPath(path, this.shape, false);
  12141. // Clear path dirty flag
  12142. if (this.path) {
  12143. this.__dirtyPath = false;
  12144. }
  12145. }
  12146. else {
  12147. // Replay path building
  12148. ctx.beginPath();
  12149. this.path.rebuildPath(ctx);
  12150. }
  12151. hasFill && path.fill(ctx);
  12152. if (lineDash && ctxLineDash) {
  12153. ctx.setLineDash(lineDash);
  12154. ctx.lineDashOffset = lineDashOffset;
  12155. }
  12156. hasStroke && path.stroke(ctx);
  12157. if (lineDash && ctxLineDash) {
  12158. // PENDING
  12159. // Remove lineDash
  12160. ctx.setLineDash([]);
  12161. }
  12162. // Draw rect text
  12163. if (style.text != null) {
  12164. // Only restore transform when needs draw text.
  12165. this.restoreTransform(ctx);
  12166. this.drawRectText(ctx, this.getBoundingRect());
  12167. }
  12168. },
  12169. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  12170. // Like in circle
  12171. buildPath: function (ctx, shapeCfg, inBundle) {},
  12172. createPathProxy: function () {
  12173. this.path = new PathProxy();
  12174. },
  12175. getBoundingRect: function () {
  12176. var rect = this._rect;
  12177. var style = this.style;
  12178. var needsUpdateRect = !rect;
  12179. if (needsUpdateRect) {
  12180. var path = this.path;
  12181. if (!path) {
  12182. // Create path on demand.
  12183. path = this.path = new PathProxy();
  12184. }
  12185. if (this.__dirtyPath) {
  12186. path.beginPath();
  12187. this.buildPath(path, this.shape, false);
  12188. }
  12189. rect = path.getBoundingRect();
  12190. }
  12191. this._rect = rect;
  12192. if (style.hasStroke()) {
  12193. // Needs update rect with stroke lineWidth when
  12194. // 1. Element changes scale or lineWidth
  12195. // 2. Shape is changed
  12196. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  12197. if (this.__dirty || needsUpdateRect) {
  12198. rectWithStroke.copy(rect);
  12199. // FIXME Must after updateTransform
  12200. var w = style.lineWidth;
  12201. // PENDING, Min line width is needed when line is horizontal or vertical
  12202. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12203. // Only add extra hover lineWidth when there are no fill
  12204. if (!style.hasFill()) {
  12205. w = Math.max(w, this.strokeContainThreshold || 4);
  12206. }
  12207. // Consider line width
  12208. // Line scale can't be 0;
  12209. if (lineScale > 1e-10) {
  12210. rectWithStroke.width += w / lineScale;
  12211. rectWithStroke.height += w / lineScale;
  12212. rectWithStroke.x -= w / lineScale / 2;
  12213. rectWithStroke.y -= w / lineScale / 2;
  12214. }
  12215. }
  12216. // Return rect with stroke
  12217. return rectWithStroke;
  12218. }
  12219. return rect;
  12220. },
  12221. contain: function (x, y) {
  12222. var localPos = this.transformCoordToLocal(x, y);
  12223. var rect = this.getBoundingRect();
  12224. var style = this.style;
  12225. x = localPos[0];
  12226. y = localPos[1];
  12227. if (rect.contain(x, y)) {
  12228. var pathData = this.path.data;
  12229. if (style.hasStroke()) {
  12230. var lineWidth = style.lineWidth;
  12231. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12232. // Line scale can't be 0;
  12233. if (lineScale > 1e-10) {
  12234. // Only add extra hover lineWidth when there are no fill
  12235. if (!style.hasFill()) {
  12236. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  12237. }
  12238. if (containStroke(
  12239. pathData, lineWidth / lineScale, x, y
  12240. )) {
  12241. return true;
  12242. }
  12243. }
  12244. }
  12245. if (style.hasFill()) {
  12246. return contain(pathData, x, y);
  12247. }
  12248. }
  12249. return false;
  12250. },
  12251. /**
  12252. * @param {boolean} dirtyPath
  12253. */
  12254. dirty: function (dirtyPath) {
  12255. if (dirtyPath == null) {
  12256. dirtyPath = true;
  12257. }
  12258. // Only mark dirty, not mark clean
  12259. if (dirtyPath) {
  12260. this.__dirtyPath = dirtyPath;
  12261. this._rect = null;
  12262. }
  12263. this.__dirty = true;
  12264. this.__zr && this.__zr.refresh();
  12265. // Used as a clipping path
  12266. if (this.__clipTarget) {
  12267. this.__clipTarget.dirty();
  12268. }
  12269. },
  12270. /**
  12271. * Alias for animate('shape')
  12272. * @param {boolean} loop
  12273. */
  12274. animateShape: function (loop) {
  12275. return this.animate('shape', loop);
  12276. },
  12277. // Overwrite attrKV
  12278. attrKV: function (key, value) {
  12279. // FIXME
  12280. if (key === 'shape') {
  12281. this.setShape(value);
  12282. this.__dirtyPath = true;
  12283. this._rect = null;
  12284. }
  12285. else {
  12286. Displayable.prototype.attrKV.call(this, key, value);
  12287. }
  12288. },
  12289. /**
  12290. * @param {Object|string} key
  12291. * @param {*} value
  12292. */
  12293. setShape: function (key, value) {
  12294. var shape = this.shape;
  12295. // Path from string may not have shape
  12296. if (shape) {
  12297. if (isObject$1(key)) {
  12298. for (var name in key) {
  12299. if (key.hasOwnProperty(name)) {
  12300. shape[name] = key[name];
  12301. }
  12302. }
  12303. }
  12304. else {
  12305. shape[key] = value;
  12306. }
  12307. this.dirty(true);
  12308. }
  12309. return this;
  12310. },
  12311. getLineScale: function () {
  12312. var m = this.transform;
  12313. // Get the line scale.
  12314. // Determinant of `m` means how much the area is enlarged by the
  12315. // transformation. So its square root can be used as a scale factor
  12316. // for width.
  12317. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  12318. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  12319. : 1;
  12320. }
  12321. };
  12322. /**
  12323. * 扩展一个 Path element, 比如星形,圆等。
  12324. * Extend a path element
  12325. * @param {Object} props
  12326. * @param {string} props.type Path type
  12327. * @param {Function} props.init Initialize
  12328. * @param {Function} props.buildPath Overwrite buildPath method
  12329. * @param {Object} [props.style] Extended default style config
  12330. * @param {Object} [props.shape] Extended default shape config
  12331. */
  12332. Path.extend = function (defaults$$1) {
  12333. var Sub = function (opts) {
  12334. Path.call(this, opts);
  12335. if (defaults$$1.style) {
  12336. // Extend default style
  12337. this.style.extendFrom(defaults$$1.style, false);
  12338. }
  12339. // Extend default shape
  12340. var defaultShape = defaults$$1.shape;
  12341. if (defaultShape) {
  12342. this.shape = this.shape || {};
  12343. var thisShape = this.shape;
  12344. for (var name in defaultShape) {
  12345. if (
  12346. ! thisShape.hasOwnProperty(name)
  12347. && defaultShape.hasOwnProperty(name)
  12348. ) {
  12349. thisShape[name] = defaultShape[name];
  12350. }
  12351. }
  12352. }
  12353. defaults$$1.init && defaults$$1.init.call(this, opts);
  12354. };
  12355. inherits(Sub, Path);
  12356. // FIXME 不能 extend position, rotation 等引用对象
  12357. for (var name in defaults$$1) {
  12358. // Extending prototype values and methods
  12359. if (name !== 'style' && name !== 'shape') {
  12360. Sub.prototype[name] = defaults$$1[name];
  12361. }
  12362. }
  12363. return Sub;
  12364. };
  12365. inherits(Path, Displayable);
  12366. var CMD$2 = PathProxy.CMD;
  12367. var points = [[], [], []];
  12368. var mathSqrt$3 = Math.sqrt;
  12369. var mathAtan2 = Math.atan2;
  12370. var transformPath = function (path, m) {
  12371. var data = path.data;
  12372. var cmd;
  12373. var nPoint;
  12374. var i;
  12375. var j;
  12376. var k;
  12377. var p;
  12378. var M = CMD$2.M;
  12379. var C = CMD$2.C;
  12380. var L = CMD$2.L;
  12381. var R = CMD$2.R;
  12382. var A = CMD$2.A;
  12383. var Q = CMD$2.Q;
  12384. for (i = 0, j = 0; i < data.length;) {
  12385. cmd = data[i++];
  12386. j = i;
  12387. nPoint = 0;
  12388. switch (cmd) {
  12389. case M:
  12390. nPoint = 1;
  12391. break;
  12392. case L:
  12393. nPoint = 1;
  12394. break;
  12395. case C:
  12396. nPoint = 3;
  12397. break;
  12398. case Q:
  12399. nPoint = 2;
  12400. break;
  12401. case A:
  12402. var x = m[4];
  12403. var y = m[5];
  12404. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  12405. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  12406. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12407. // cx
  12408. data[i] *= sx;
  12409. data[i++] += x;
  12410. // cy
  12411. data[i] *= sy;
  12412. data[i++] += y;
  12413. // Scale rx and ry
  12414. // FIXME Assume psi is 0 here
  12415. data[i++] *= sx;
  12416. data[i++] *= sy;
  12417. // Start angle
  12418. data[i++] += angle;
  12419. // end angle
  12420. data[i++] += angle;
  12421. // FIXME psi
  12422. i += 2;
  12423. j = i;
  12424. break;
  12425. case R:
  12426. // x0, y0
  12427. p[0] = data[i++];
  12428. p[1] = data[i++];
  12429. applyTransform(p, p, m);
  12430. data[j++] = p[0];
  12431. data[j++] = p[1];
  12432. // x1, y1
  12433. p[0] += data[i++];
  12434. p[1] += data[i++];
  12435. applyTransform(p, p, m);
  12436. data[j++] = p[0];
  12437. data[j++] = p[1];
  12438. }
  12439. for (k = 0; k < nPoint; k++) {
  12440. var p = points[k];
  12441. p[0] = data[i++];
  12442. p[1] = data[i++];
  12443. applyTransform(p, p, m);
  12444. // Write back
  12445. data[j++] = p[0];
  12446. data[j++] = p[1];
  12447. }
  12448. }
  12449. };
  12450. // command chars
  12451. var cc = [
  12452. 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  12453. 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  12454. ];
  12455. var mathSqrt = Math.sqrt;
  12456. var mathSin = Math.sin;
  12457. var mathCos = Math.cos;
  12458. var PI = Math.PI;
  12459. var vMag = function(v) {
  12460. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12461. };
  12462. var vRatio = function(u, v) {
  12463. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12464. };
  12465. var vAngle = function(u, v) {
  12466. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12467. * Math.acos(vRatio(u, v));
  12468. };
  12469. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12470. var psi = psiDeg * (PI / 180.0);
  12471. var xp = mathCos(psi) * (x1 - x2) / 2.0
  12472. + mathSin(psi) * (y1 - y2) / 2.0;
  12473. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0
  12474. + mathCos(psi) * (y1 - y2) / 2.0;
  12475. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12476. if (lambda > 1) {
  12477. rx *= mathSqrt(lambda);
  12478. ry *= mathSqrt(lambda);
  12479. }
  12480. var f = (fa === fs ? -1 : 1)
  12481. * mathSqrt((((rx * rx) * (ry * ry))
  12482. - ((rx * rx) * (yp * yp))
  12483. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12484. + (ry * ry) * (xp * xp))
  12485. ) || 0;
  12486. var cxp = f * rx * yp / ry;
  12487. var cyp = f * -ry * xp / rx;
  12488. var cx = (x1 + x2) / 2.0
  12489. + mathCos(psi) * cxp
  12490. - mathSin(psi) * cyp;
  12491. var cy = (y1 + y2) / 2.0
  12492. + mathSin(psi) * cxp
  12493. + mathCos(psi) * cyp;
  12494. var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]);
  12495. var u = [ (xp - cxp) / rx, (yp - cyp) / ry ];
  12496. var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ];
  12497. var dTheta = vAngle(u, v);
  12498. if (vRatio(u, v) <= -1) {
  12499. dTheta = PI;
  12500. }
  12501. if (vRatio(u, v) >= 1) {
  12502. dTheta = 0;
  12503. }
  12504. if (fs === 0 && dTheta > 0) {
  12505. dTheta = dTheta - 2 * PI;
  12506. }
  12507. if (fs === 1 && dTheta < 0) {
  12508. dTheta = dTheta + 2 * PI;
  12509. }
  12510. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12511. }
  12512. function createPathProxyFromString(data) {
  12513. if (!data) {
  12514. return [];
  12515. }
  12516. // command string
  12517. var cs = data.replace(/-/g, ' -')
  12518. .replace(/ /g, ' ')
  12519. .replace(/ /g, ',')
  12520. .replace(/,,/g, ',');
  12521. var n;
  12522. // create pipes so that we can split the data
  12523. for (n = 0; n < cc.length; n++) {
  12524. cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  12525. }
  12526. // create array
  12527. var arr = cs.split('|');
  12528. // init context point
  12529. var cpx = 0;
  12530. var cpy = 0;
  12531. var path = new PathProxy();
  12532. var CMD = PathProxy.CMD;
  12533. var prevCmd;
  12534. for (n = 1; n < arr.length; n++) {
  12535. var str = arr[n];
  12536. var c = str.charAt(0);
  12537. var off = 0;
  12538. var p = str.slice(1).replace(/e,-/g, 'e-').split(',');
  12539. var cmd;
  12540. if (p.length > 0 && p[0] === '') {
  12541. p.shift();
  12542. }
  12543. for (var i = 0; i < p.length; i++) {
  12544. p[i] = parseFloat(p[i]);
  12545. }
  12546. while (off < p.length && !isNaN(p[off])) {
  12547. if (isNaN(p[0])) {
  12548. break;
  12549. }
  12550. var ctlPtx;
  12551. var ctlPty;
  12552. var rx;
  12553. var ry;
  12554. var psi;
  12555. var fa;
  12556. var fs;
  12557. var x1 = cpx;
  12558. var y1 = cpy;
  12559. // convert l, H, h, V, and v to L
  12560. switch (c) {
  12561. case 'l':
  12562. cpx += p[off++];
  12563. cpy += p[off++];
  12564. cmd = CMD.L;
  12565. path.addData(cmd, cpx, cpy);
  12566. break;
  12567. case 'L':
  12568. cpx = p[off++];
  12569. cpy = p[off++];
  12570. cmd = CMD.L;
  12571. path.addData(cmd, cpx, cpy);
  12572. break;
  12573. case 'm':
  12574. cpx += p[off++];
  12575. cpy += p[off++];
  12576. cmd = CMD.M;
  12577. path.addData(cmd, cpx, cpy);
  12578. c = 'l';
  12579. break;
  12580. case 'M':
  12581. cpx = p[off++];
  12582. cpy = p[off++];
  12583. cmd = CMD.M;
  12584. path.addData(cmd, cpx, cpy);
  12585. c = 'L';
  12586. break;
  12587. case 'h':
  12588. cpx += p[off++];
  12589. cmd = CMD.L;
  12590. path.addData(cmd, cpx, cpy);
  12591. break;
  12592. case 'H':
  12593. cpx = p[off++];
  12594. cmd = CMD.L;
  12595. path.addData(cmd, cpx, cpy);
  12596. break;
  12597. case 'v':
  12598. cpy += p[off++];
  12599. cmd = CMD.L;
  12600. path.addData(cmd, cpx, cpy);
  12601. break;
  12602. case 'V':
  12603. cpy = p[off++];
  12604. cmd = CMD.L;
  12605. path.addData(cmd, cpx, cpy);
  12606. break;
  12607. case 'C':
  12608. cmd = CMD.C;
  12609. path.addData(
  12610. cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]
  12611. );
  12612. cpx = p[off - 2];
  12613. cpy = p[off - 1];
  12614. break;
  12615. case 'c':
  12616. cmd = CMD.C;
  12617. path.addData(
  12618. cmd,
  12619. p[off++] + cpx, p[off++] + cpy,
  12620. p[off++] + cpx, p[off++] + cpy,
  12621. p[off++] + cpx, p[off++] + cpy
  12622. );
  12623. cpx += p[off - 2];
  12624. cpy += p[off - 1];
  12625. break;
  12626. case 'S':
  12627. ctlPtx = cpx;
  12628. ctlPty = cpy;
  12629. var len = path.len();
  12630. var pathData = path.data;
  12631. if (prevCmd === CMD.C) {
  12632. ctlPtx += cpx - pathData[len - 4];
  12633. ctlPty += cpy - pathData[len - 3];
  12634. }
  12635. cmd = CMD.C;
  12636. x1 = p[off++];
  12637. y1 = p[off++];
  12638. cpx = p[off++];
  12639. cpy = p[off++];
  12640. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12641. break;
  12642. case 's':
  12643. ctlPtx = cpx;
  12644. ctlPty = cpy;
  12645. var len = path.len();
  12646. var pathData = path.data;
  12647. if (prevCmd === CMD.C) {
  12648. ctlPtx += cpx - pathData[len - 4];
  12649. ctlPty += cpy - pathData[len - 3];
  12650. }
  12651. cmd = CMD.C;
  12652. x1 = cpx + p[off++];
  12653. y1 = cpy + p[off++];
  12654. cpx += p[off++];
  12655. cpy += p[off++];
  12656. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12657. break;
  12658. case 'Q':
  12659. x1 = p[off++];
  12660. y1 = p[off++];
  12661. cpx = p[off++];
  12662. cpy = p[off++];
  12663. cmd = CMD.Q;
  12664. path.addData(cmd, x1, y1, cpx, cpy);
  12665. break;
  12666. case 'q':
  12667. x1 = p[off++] + cpx;
  12668. y1 = p[off++] + cpy;
  12669. cpx += p[off++];
  12670. cpy += p[off++];
  12671. cmd = CMD.Q;
  12672. path.addData(cmd, x1, y1, cpx, cpy);
  12673. break;
  12674. case 'T':
  12675. ctlPtx = cpx;
  12676. ctlPty = cpy;
  12677. var len = path.len();
  12678. var pathData = path.data;
  12679. if (prevCmd === CMD.Q) {
  12680. ctlPtx += cpx - pathData[len - 4];
  12681. ctlPty += cpy - pathData[len - 3];
  12682. }
  12683. cpx = p[off++];
  12684. cpy = p[off++];
  12685. cmd = CMD.Q;
  12686. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12687. break;
  12688. case 't':
  12689. ctlPtx = cpx;
  12690. ctlPty = cpy;
  12691. var len = path.len();
  12692. var pathData = path.data;
  12693. if (prevCmd === CMD.Q) {
  12694. ctlPtx += cpx - pathData[len - 4];
  12695. ctlPty += cpy - pathData[len - 3];
  12696. }
  12697. cpx += p[off++];
  12698. cpy += p[off++];
  12699. cmd = CMD.Q;
  12700. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12701. break;
  12702. case 'A':
  12703. rx = p[off++];
  12704. ry = p[off++];
  12705. psi = p[off++];
  12706. fa = p[off++];
  12707. fs = p[off++];
  12708. x1 = cpx, y1 = cpy;
  12709. cpx = p[off++];
  12710. cpy = p[off++];
  12711. cmd = CMD.A;
  12712. processArc(
  12713. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  12714. );
  12715. break;
  12716. case 'a':
  12717. rx = p[off++];
  12718. ry = p[off++];
  12719. psi = p[off++];
  12720. fa = p[off++];
  12721. fs = p[off++];
  12722. x1 = cpx, y1 = cpy;
  12723. cpx += p[off++];
  12724. cpy += p[off++];
  12725. cmd = CMD.A;
  12726. processArc(
  12727. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  12728. );
  12729. break;
  12730. }
  12731. }
  12732. if (c === 'z' || c === 'Z') {
  12733. cmd = CMD.Z;
  12734. path.addData(cmd);
  12735. }
  12736. prevCmd = cmd;
  12737. }
  12738. path.toStatic();
  12739. return path;
  12740. }
  12741. // TODO Optimize double memory cost problem
  12742. function createPathOptions(str, opts) {
  12743. var pathProxy = createPathProxyFromString(str);
  12744. opts = opts || {};
  12745. opts.buildPath = function (path) {
  12746. if (path.setData) {
  12747. path.setData(pathProxy.data);
  12748. // Svg and vml renderer don't have context
  12749. var ctx = path.getContext();
  12750. if (ctx) {
  12751. path.rebuildPath(ctx);
  12752. }
  12753. }
  12754. else {
  12755. var ctx = path;
  12756. pathProxy.rebuildPath(ctx);
  12757. }
  12758. };
  12759. opts.applyTransform = function (m) {
  12760. transformPath(pathProxy, m);
  12761. this.dirty(true);
  12762. };
  12763. return opts;
  12764. }
  12765. /**
  12766. * Create a Path object from path string data
  12767. * http://www.w3.org/TR/SVG/paths.html#PathData
  12768. * @param {Object} opts Other options
  12769. */
  12770. function createFromString(str, opts) {
  12771. return new Path(createPathOptions(str, opts));
  12772. }
  12773. /**
  12774. * Create a Path class from path string data
  12775. * @param {string} str
  12776. * @param {Object} opts Other options
  12777. */
  12778. function extendFromString(str, opts) {
  12779. return Path.extend(createPathOptions(str, opts));
  12780. }
  12781. /**
  12782. * Merge multiple paths
  12783. */
  12784. // TODO Apply transform
  12785. // TODO stroke dash
  12786. // TODO Optimize double memory cost problem
  12787. function mergePath$1(pathEls, opts) {
  12788. var pathList = [];
  12789. var len = pathEls.length;
  12790. for (var i = 0; i < len; i++) {
  12791. var pathEl = pathEls[i];
  12792. if (!pathEl.path) {
  12793. pathEl.createPathProxy();
  12794. }
  12795. if (pathEl.__dirtyPath) {
  12796. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  12797. }
  12798. pathList.push(pathEl.path);
  12799. }
  12800. var pathBundle = new Path(opts);
  12801. // Need path proxy.
  12802. pathBundle.createPathProxy();
  12803. pathBundle.buildPath = function (path) {
  12804. path.appendPath(pathList);
  12805. // Svg and vml renderer don't have context
  12806. var ctx = path.getContext();
  12807. if (ctx) {
  12808. path.rebuildPath(ctx);
  12809. }
  12810. };
  12811. return pathBundle;
  12812. }
  12813. /**
  12814. * @alias zrender/graphic/Text
  12815. * @extends module:zrender/graphic/Displayable
  12816. * @constructor
  12817. * @param {Object} opts
  12818. */
  12819. var Text = function (opts) { // jshint ignore:line
  12820. Displayable.call(this, opts);
  12821. };
  12822. Text.prototype = {
  12823. constructor: Text,
  12824. type: 'text',
  12825. brush: function (ctx, prevEl) {
  12826. var style = this.style;
  12827. // Optimize, avoid normalize every time.
  12828. this.__dirty && normalizeTextStyle(style, true);
  12829. // Use props with prefix 'text'.
  12830. style.fill = style.stroke = style.shadowBlur = style.shadowColor =
  12831. style.shadowOffsetX = style.shadowOffsetY = null;
  12832. var text = style.text;
  12833. // Convert to string
  12834. text != null && (text += '');
  12835. // Always bind style
  12836. style.bind(ctx, this, prevEl);
  12837. if (!needDrawText(text, style)) {
  12838. return;
  12839. }
  12840. this.setTransform(ctx);
  12841. renderText(this, ctx, text, style);
  12842. this.restoreTransform(ctx);
  12843. },
  12844. getBoundingRect: function () {
  12845. var style = this.style;
  12846. // Optimize, avoid normalize every time.
  12847. this.__dirty && normalizeTextStyle(style, true);
  12848. if (!this._rect) {
  12849. var text = style.text;
  12850. text != null ? (text += '') : (text = '');
  12851. var rect = getBoundingRect(
  12852. style.text + '',
  12853. style.font,
  12854. style.textAlign,
  12855. style.textVerticalAlign,
  12856. style.textPadding,
  12857. style.rich
  12858. );
  12859. rect.x += style.x || 0;
  12860. rect.y += style.y || 0;
  12861. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  12862. var w = style.textStrokeWidth;
  12863. rect.x -= w / 2;
  12864. rect.y -= w / 2;
  12865. rect.width += w;
  12866. rect.height += w;
  12867. }
  12868. this._rect = rect;
  12869. }
  12870. return this._rect;
  12871. }
  12872. };
  12873. inherits(Text, Displayable);
  12874. /**
  12875. * 圆形
  12876. * @module zrender/shape/Circle
  12877. */
  12878. var Circle = Path.extend({
  12879. type: 'circle',
  12880. shape: {
  12881. cx: 0,
  12882. cy: 0,
  12883. r: 0
  12884. },
  12885. buildPath : function (ctx, shape, inBundle) {
  12886. // Better stroking in ShapeBundle
  12887. // Always do it may have performence issue ( fill may be 2x more cost)
  12888. if (inBundle) {
  12889. ctx.moveTo(shape.cx + shape.r, shape.cy);
  12890. }
  12891. // else {
  12892. // if (ctx.allocate && !ctx.data.length) {
  12893. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  12894. // }
  12895. // }
  12896. // Better stroking in ShapeBundle
  12897. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  12898. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  12899. }
  12900. });
  12901. // Fix weird bug in some version of IE11 (like 11.0.9600.178**),
  12902. // where exception "unexpected call to method or property access"
  12903. // might be thrown when calling ctx.fill or ctx.stroke after a path
  12904. // whose area size is zero is drawn and ctx.clip() is called and
  12905. // shadowBlur is set. See #4572, #3112, #5777.
  12906. // (e.g.,
  12907. // ctx.moveTo(10, 10);
  12908. // ctx.lineTo(20, 10);
  12909. // ctx.closePath();
  12910. // ctx.clip();
  12911. // ctx.shadowBlur = 10;
  12912. // ...
  12913. // ctx.fill();
  12914. // )
  12915. var shadowTemp = [
  12916. ['shadowBlur', 0],
  12917. ['shadowColor', '#000'],
  12918. ['shadowOffsetX', 0],
  12919. ['shadowOffsetY', 0]
  12920. ];
  12921. var fixClipWithShadow = function (orignalBrush) {
  12922. // version string can be: '11.0'
  12923. return (env$1.browser.ie && env$1.browser.version >= 11)
  12924. ? function () {
  12925. var clipPaths = this.__clipPaths;
  12926. var style = this.style;
  12927. var modified;
  12928. if (clipPaths) {
  12929. for (var i = 0; i < clipPaths.length; i++) {
  12930. var clipPath = clipPaths[i];
  12931. var shape = clipPath && clipPath.shape;
  12932. var type = clipPath && clipPath.type;
  12933. if (shape && (
  12934. (type === 'sector' && shape.startAngle === shape.endAngle)
  12935. || (type === 'rect' && (!shape.width || !shape.height))
  12936. )) {
  12937. for (var j = 0; j < shadowTemp.length; j++) {
  12938. // It is save to put shadowTemp static, because shadowTemp
  12939. // will be all modified each item brush called.
  12940. shadowTemp[j][2] = style[shadowTemp[j][0]];
  12941. style[shadowTemp[j][0]] = shadowTemp[j][1];
  12942. }
  12943. modified = true;
  12944. break;
  12945. }
  12946. }
  12947. }
  12948. orignalBrush.apply(this, arguments);
  12949. if (modified) {
  12950. for (var j = 0; j < shadowTemp.length; j++) {
  12951. style[shadowTemp[j][0]] = shadowTemp[j][2];
  12952. }
  12953. }
  12954. }
  12955. : orignalBrush;
  12956. };
  12957. /**
  12958. * 扇形
  12959. * @module zrender/graphic/shape/Sector
  12960. */
  12961. var Sector = Path.extend({
  12962. type: 'sector',
  12963. shape: {
  12964. cx: 0,
  12965. cy: 0,
  12966. r0: 0,
  12967. r: 0,
  12968. startAngle: 0,
  12969. endAngle: Math.PI * 2,
  12970. clockwise: true
  12971. },
  12972. brush: fixClipWithShadow(Path.prototype.brush),
  12973. buildPath: function (ctx, shape) {
  12974. var x = shape.cx;
  12975. var y = shape.cy;
  12976. var r0 = Math.max(shape.r0 || 0, 0);
  12977. var r = Math.max(shape.r, 0);
  12978. var startAngle = shape.startAngle;
  12979. var endAngle = shape.endAngle;
  12980. var clockwise = shape.clockwise;
  12981. var unitX = Math.cos(startAngle);
  12982. var unitY = Math.sin(startAngle);
  12983. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  12984. ctx.lineTo(unitX * r + x, unitY * r + y);
  12985. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  12986. ctx.lineTo(
  12987. Math.cos(endAngle) * r0 + x,
  12988. Math.sin(endAngle) * r0 + y
  12989. );
  12990. if (r0 !== 0) {
  12991. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  12992. }
  12993. ctx.closePath();
  12994. }
  12995. });
  12996. /**
  12997. * 圆环
  12998. * @module zrender/graphic/shape/Ring
  12999. */
  13000. var Ring = Path.extend({
  13001. type: 'ring',
  13002. shape: {
  13003. cx: 0,
  13004. cy: 0,
  13005. r: 0,
  13006. r0: 0
  13007. },
  13008. buildPath: function (ctx, shape) {
  13009. var x = shape.cx;
  13010. var y = shape.cy;
  13011. var PI2 = Math.PI * 2;
  13012. ctx.moveTo(x + shape.r, y);
  13013. ctx.arc(x, y, shape.r, 0, PI2, false);
  13014. ctx.moveTo(x + shape.r0, y);
  13015. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13016. }
  13017. });
  13018. /**
  13019. * Catmull-Rom spline 插值折线
  13020. * @module zrender/shape/util/smoothSpline
  13021. * @author pissang (https://www.github.com/pissang)
  13022. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13023. * errorrik (errorrik@gmail.com)
  13024. */
  13025. /**
  13026. * @inner
  13027. */
  13028. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  13029. var v0 = (p2 - p0) * 0.5;
  13030. var v1 = (p3 - p1) * 0.5;
  13031. return (2 * (p1 - p2) + v0 + v1) * t3
  13032. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  13033. + v0 * t + p1;
  13034. }
  13035. /**
  13036. * @alias module:zrender/shape/util/smoothSpline
  13037. * @param {Array} points 线段顶点数组
  13038. * @param {boolean} isLoop
  13039. * @return {Array}
  13040. */
  13041. var smoothSpline = function (points, isLoop) {
  13042. var len$$1 = points.length;
  13043. var ret = [];
  13044. var distance$$1 = 0;
  13045. for (var i = 1; i < len$$1; i++) {
  13046. distance$$1 += distance(points[i - 1], points[i]);
  13047. }
  13048. var segs = distance$$1 / 2;
  13049. segs = segs < len$$1 ? len$$1 : segs;
  13050. for (var i = 0; i < segs; i++) {
  13051. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  13052. var idx = Math.floor(pos);
  13053. var w = pos - idx;
  13054. var p0;
  13055. var p1 = points[idx % len$$1];
  13056. var p2;
  13057. var p3;
  13058. if (!isLoop) {
  13059. p0 = points[idx === 0 ? idx : idx - 1];
  13060. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  13061. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  13062. }
  13063. else {
  13064. p0 = points[(idx - 1 + len$$1) % len$$1];
  13065. p2 = points[(idx + 1) % len$$1];
  13066. p3 = points[(idx + 2) % len$$1];
  13067. }
  13068. var w2 = w * w;
  13069. var w3 = w * w2;
  13070. ret.push([
  13071. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  13072. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  13073. ]);
  13074. }
  13075. return ret;
  13076. };
  13077. /**
  13078. * 贝塞尔平滑曲线
  13079. * @module zrender/shape/util/smoothBezier
  13080. * @author pissang (https://www.github.com/pissang)
  13081. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13082. * errorrik (errorrik@gmail.com)
  13083. */
  13084. /**
  13085. * 贝塞尔平滑曲线
  13086. * @alias module:zrender/shape/util/smoothBezier
  13087. * @param {Array} points 线段顶点数组
  13088. * @param {number} smooth 平滑等级, 0-1
  13089. * @param {boolean} isLoop
  13090. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  13091. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  13092. * 整个折线的包围盒做一个并集用来约束控制点。
  13093. * @param {Array} 计算出来的控制点数组
  13094. */
  13095. var smoothBezier = function (points, smooth, isLoop, constraint) {
  13096. var cps = [];
  13097. var v = [];
  13098. var v1 = [];
  13099. var v2 = [];
  13100. var prevPoint;
  13101. var nextPoint;
  13102. var min$$1, max$$1;
  13103. if (constraint) {
  13104. min$$1 = [Infinity, Infinity];
  13105. max$$1 = [-Infinity, -Infinity];
  13106. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13107. min(min$$1, min$$1, points[i]);
  13108. max(max$$1, max$$1, points[i]);
  13109. }
  13110. // 与指定的包围盒做并集
  13111. min(min$$1, min$$1, constraint[0]);
  13112. max(max$$1, max$$1, constraint[1]);
  13113. }
  13114. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13115. var point = points[i];
  13116. if (isLoop) {
  13117. prevPoint = points[i ? i - 1 : len$$1 - 1];
  13118. nextPoint = points[(i + 1) % len$$1];
  13119. }
  13120. else {
  13121. if (i === 0 || i === len$$1 - 1) {
  13122. cps.push(clone$1(points[i]));
  13123. continue;
  13124. }
  13125. else {
  13126. prevPoint = points[i - 1];
  13127. nextPoint = points[i + 1];
  13128. }
  13129. }
  13130. sub(v, nextPoint, prevPoint);
  13131. // use degree to scale the handle length
  13132. scale(v, v, smooth);
  13133. var d0 = distance(point, prevPoint);
  13134. var d1 = distance(point, nextPoint);
  13135. var sum = d0 + d1;
  13136. if (sum !== 0) {
  13137. d0 /= sum;
  13138. d1 /= sum;
  13139. }
  13140. scale(v1, v, -d0);
  13141. scale(v2, v, d1);
  13142. var cp0 = add([], point, v1);
  13143. var cp1 = add([], point, v2);
  13144. if (constraint) {
  13145. max(cp0, cp0, min$$1);
  13146. min(cp0, cp0, max$$1);
  13147. max(cp1, cp1, min$$1);
  13148. min(cp1, cp1, max$$1);
  13149. }
  13150. cps.push(cp0);
  13151. cps.push(cp1);
  13152. }
  13153. if (isLoop) {
  13154. cps.push(cps.shift());
  13155. }
  13156. return cps;
  13157. };
  13158. function buildPath$1(ctx, shape, closePath) {
  13159. var points = shape.points;
  13160. var smooth = shape.smooth;
  13161. if (points && points.length >= 2) {
  13162. if (smooth && smooth !== 'spline') {
  13163. var controlPoints = smoothBezier(
  13164. points, smooth, closePath, shape.smoothConstraint
  13165. );
  13166. ctx.moveTo(points[0][0], points[0][1]);
  13167. var len = points.length;
  13168. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13169. var cp1 = controlPoints[i * 2];
  13170. var cp2 = controlPoints[i * 2 + 1];
  13171. var p = points[(i + 1) % len];
  13172. ctx.bezierCurveTo(
  13173. cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]
  13174. );
  13175. }
  13176. }
  13177. else {
  13178. if (smooth === 'spline') {
  13179. points = smoothSpline(points, closePath);
  13180. }
  13181. ctx.moveTo(points[0][0], points[0][1]);
  13182. for (var i = 1, l = points.length; i < l; i++) {
  13183. ctx.lineTo(points[i][0], points[i][1]);
  13184. }
  13185. }
  13186. closePath && ctx.closePath();
  13187. }
  13188. }
  13189. /**
  13190. * 多边形
  13191. * @module zrender/shape/Polygon
  13192. */
  13193. var Polygon = Path.extend({
  13194. type: 'polygon',
  13195. shape: {
  13196. points: null,
  13197. smooth: false,
  13198. smoothConstraint: null
  13199. },
  13200. buildPath: function (ctx, shape) {
  13201. buildPath$1(ctx, shape, true);
  13202. }
  13203. });
  13204. /**
  13205. * @module zrender/graphic/shape/Polyline
  13206. */
  13207. var Polyline = Path.extend({
  13208. type: 'polyline',
  13209. shape: {
  13210. points: null,
  13211. smooth: false,
  13212. smoothConstraint: null
  13213. },
  13214. style: {
  13215. stroke: '#000',
  13216. fill: null
  13217. },
  13218. buildPath: function (ctx, shape) {
  13219. buildPath$1(ctx, shape, false);
  13220. }
  13221. });
  13222. /**
  13223. * 矩形
  13224. * @module zrender/graphic/shape/Rect
  13225. */
  13226. var Rect = Path.extend({
  13227. type: 'rect',
  13228. shape: {
  13229. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  13230. // r缩写为1 相当于 [1, 1, 1, 1]
  13231. // r缩写为[1] 相当于 [1, 1, 1, 1]
  13232. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  13233. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  13234. r: 0,
  13235. x: 0,
  13236. y: 0,
  13237. width: 0,
  13238. height: 0
  13239. },
  13240. buildPath: function (ctx, shape) {
  13241. var x = shape.x;
  13242. var y = shape.y;
  13243. var width = shape.width;
  13244. var height = shape.height;
  13245. if (!shape.r) {
  13246. ctx.rect(x, y, width, height);
  13247. }
  13248. else {
  13249. buildPath(ctx, shape);
  13250. }
  13251. ctx.closePath();
  13252. return;
  13253. }
  13254. });
  13255. /**
  13256. * 直线
  13257. * @module zrender/graphic/shape/Line
  13258. */
  13259. var Line = Path.extend({
  13260. type: 'line',
  13261. shape: {
  13262. // Start point
  13263. x1: 0,
  13264. y1: 0,
  13265. // End point
  13266. x2: 0,
  13267. y2: 0,
  13268. percent: 1
  13269. },
  13270. style: {
  13271. stroke: '#000',
  13272. fill: null
  13273. },
  13274. buildPath: function (ctx, shape) {
  13275. var x1 = shape.x1;
  13276. var y1 = shape.y1;
  13277. var x2 = shape.x2;
  13278. var y2 = shape.y2;
  13279. var percent = shape.percent;
  13280. if (percent === 0) {
  13281. return;
  13282. }
  13283. ctx.moveTo(x1, y1);
  13284. if (percent < 1) {
  13285. x2 = x1 * (1 - percent) + x2 * percent;
  13286. y2 = y1 * (1 - percent) + y2 * percent;
  13287. }
  13288. ctx.lineTo(x2, y2);
  13289. },
  13290. /**
  13291. * Get point at percent
  13292. * @param {number} percent
  13293. * @return {Array.<number>}
  13294. */
  13295. pointAt: function (p) {
  13296. var shape = this.shape;
  13297. return [
  13298. shape.x1 * (1 - p) + shape.x2 * p,
  13299. shape.y1 * (1 - p) + shape.y2 * p
  13300. ];
  13301. }
  13302. });
  13303. /**
  13304. * 贝塞尔曲线
  13305. * @module zrender/shape/BezierCurve
  13306. */
  13307. var out = [];
  13308. function someVectorAt(shape, t, isTangent) {
  13309. var cpx2 = shape.cpx2;
  13310. var cpy2 = shape.cpy2;
  13311. if (cpx2 === null || cpy2 === null) {
  13312. return [
  13313. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13314. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13315. ];
  13316. }
  13317. else {
  13318. return [
  13319. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13320. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13321. ];
  13322. }
  13323. }
  13324. var BezierCurve = Path.extend({
  13325. type: 'bezier-curve',
  13326. shape: {
  13327. x1: 0,
  13328. y1: 0,
  13329. x2: 0,
  13330. y2: 0,
  13331. cpx1: 0,
  13332. cpy1: 0,
  13333. // cpx2: 0,
  13334. // cpy2: 0
  13335. // Curve show percent, for animating
  13336. percent: 1
  13337. },
  13338. style: {
  13339. stroke: '#000',
  13340. fill: null
  13341. },
  13342. buildPath: function (ctx, shape) {
  13343. var x1 = shape.x1;
  13344. var y1 = shape.y1;
  13345. var x2 = shape.x2;
  13346. var y2 = shape.y2;
  13347. var cpx1 = shape.cpx1;
  13348. var cpy1 = shape.cpy1;
  13349. var cpx2 = shape.cpx2;
  13350. var cpy2 = shape.cpy2;
  13351. var percent = shape.percent;
  13352. if (percent === 0) {
  13353. return;
  13354. }
  13355. ctx.moveTo(x1, y1);
  13356. if (cpx2 == null || cpy2 == null) {
  13357. if (percent < 1) {
  13358. quadraticSubdivide(
  13359. x1, cpx1, x2, percent, out
  13360. );
  13361. cpx1 = out[1];
  13362. x2 = out[2];
  13363. quadraticSubdivide(
  13364. y1, cpy1, y2, percent, out
  13365. );
  13366. cpy1 = out[1];
  13367. y2 = out[2];
  13368. }
  13369. ctx.quadraticCurveTo(
  13370. cpx1, cpy1,
  13371. x2, y2
  13372. );
  13373. }
  13374. else {
  13375. if (percent < 1) {
  13376. cubicSubdivide(
  13377. x1, cpx1, cpx2, x2, percent, out
  13378. );
  13379. cpx1 = out[1];
  13380. cpx2 = out[2];
  13381. x2 = out[3];
  13382. cubicSubdivide(
  13383. y1, cpy1, cpy2, y2, percent, out
  13384. );
  13385. cpy1 = out[1];
  13386. cpy2 = out[2];
  13387. y2 = out[3];
  13388. }
  13389. ctx.bezierCurveTo(
  13390. cpx1, cpy1,
  13391. cpx2, cpy2,
  13392. x2, y2
  13393. );
  13394. }
  13395. },
  13396. /**
  13397. * Get point at percent
  13398. * @param {number} t
  13399. * @return {Array.<number>}
  13400. */
  13401. pointAt: function (t) {
  13402. return someVectorAt(this.shape, t, false);
  13403. },
  13404. /**
  13405. * Get tangent at percent
  13406. * @param {number} t
  13407. * @return {Array.<number>}
  13408. */
  13409. tangentAt: function (t) {
  13410. var p = someVectorAt(this.shape, t, true);
  13411. return normalize(p, p);
  13412. }
  13413. });
  13414. /**
  13415. * 圆弧
  13416. * @module zrender/graphic/shape/Arc
  13417. */
  13418. var Arc = Path.extend({
  13419. type: 'arc',
  13420. shape: {
  13421. cx: 0,
  13422. cy: 0,
  13423. r: 0,
  13424. startAngle: 0,
  13425. endAngle: Math.PI * 2,
  13426. clockwise: true
  13427. },
  13428. style: {
  13429. stroke: '#000',
  13430. fill: null
  13431. },
  13432. buildPath: function (ctx, shape) {
  13433. var x = shape.cx;
  13434. var y = shape.cy;
  13435. var r = Math.max(shape.r, 0);
  13436. var startAngle = shape.startAngle;
  13437. var endAngle = shape.endAngle;
  13438. var clockwise = shape.clockwise;
  13439. var unitX = Math.cos(startAngle);
  13440. var unitY = Math.sin(startAngle);
  13441. ctx.moveTo(unitX * r + x, unitY * r + y);
  13442. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13443. }
  13444. });
  13445. // CompoundPath to improve performance
  13446. var CompoundPath = Path.extend({
  13447. type: 'compound',
  13448. shape: {
  13449. paths: null
  13450. },
  13451. _updatePathDirty: function () {
  13452. var dirtyPath = this.__dirtyPath;
  13453. var paths = this.shape.paths;
  13454. for (var i = 0; i < paths.length; i++) {
  13455. // Mark as dirty if any subpath is dirty
  13456. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  13457. }
  13458. this.__dirtyPath = dirtyPath;
  13459. this.__dirty = this.__dirty || dirtyPath;
  13460. },
  13461. beforeBrush: function () {
  13462. this._updatePathDirty();
  13463. var paths = this.shape.paths || [];
  13464. var scale = this.getGlobalScale();
  13465. // Update path scale
  13466. for (var i = 0; i < paths.length; i++) {
  13467. if (!paths[i].path) {
  13468. paths[i].createPathProxy();
  13469. }
  13470. paths[i].path.setScale(scale[0], scale[1]);
  13471. }
  13472. },
  13473. buildPath: function (ctx, shape) {
  13474. var paths = shape.paths || [];
  13475. for (var i = 0; i < paths.length; i++) {
  13476. paths[i].buildPath(ctx, paths[i].shape, true);
  13477. }
  13478. },
  13479. afterBrush: function () {
  13480. var paths = this.shape.paths || [];
  13481. for (var i = 0; i < paths.length; i++) {
  13482. paths[i].__dirtyPath = false;
  13483. }
  13484. },
  13485. getBoundingRect: function () {
  13486. this._updatePathDirty();
  13487. return Path.prototype.getBoundingRect.call(this);
  13488. }
  13489. });
  13490. /**
  13491. * @param {Array.<Object>} colorStops
  13492. */
  13493. var Gradient = function (colorStops) {
  13494. this.colorStops = colorStops || [];
  13495. };
  13496. Gradient.prototype = {
  13497. constructor: Gradient,
  13498. addColorStop: function (offset, color) {
  13499. this.colorStops.push({
  13500. offset: offset,
  13501. color: color
  13502. });
  13503. }
  13504. };
  13505. /**
  13506. * x, y, x2, y2 are all percent from 0 to 1
  13507. * @param {number} [x=0]
  13508. * @param {number} [y=0]
  13509. * @param {number} [x2=1]
  13510. * @param {number} [y2=0]
  13511. * @param {Array.<Object>} colorStops
  13512. * @param {boolean} [globalCoord=false]
  13513. */
  13514. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  13515. // Should do nothing more in this constructor. Because gradient can be
  13516. // declard by `color: {type: 'linear', colorStops: ...}`, where
  13517. // this constructor will not be called.
  13518. this.x = x == null ? 0 : x;
  13519. this.y = y == null ? 0 : y;
  13520. this.x2 = x2 == null ? 1 : x2;
  13521. this.y2 = y2 == null ? 0 : y2;
  13522. // Can be cloned
  13523. this.type = 'linear';
  13524. // If use global coord
  13525. this.global = globalCoord || false;
  13526. Gradient.call(this, colorStops);
  13527. };
  13528. LinearGradient.prototype = {
  13529. constructor: LinearGradient
  13530. };
  13531. inherits(LinearGradient, Gradient);
  13532. /**
  13533. * x, y, r are all percent from 0 to 1
  13534. * @param {number} [x=0.5]
  13535. * @param {number} [y=0.5]
  13536. * @param {number} [r=0.5]
  13537. * @param {Array.<Object>} [colorStops]
  13538. * @param {boolean} [globalCoord=false]
  13539. */
  13540. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  13541. // Should do nothing more in this constructor. Because gradient can be
  13542. // declard by `color: {type: 'radial', colorStops: ...}`, where
  13543. // this constructor will not be called.
  13544. this.x = x == null ? 0.5 : x;
  13545. this.y = y == null ? 0.5 : y;
  13546. this.r = r == null ? 0.5 : r;
  13547. // Can be cloned
  13548. this.type = 'radial';
  13549. // If use global coord
  13550. this.global = globalCoord || false;
  13551. Gradient.call(this, colorStops);
  13552. };
  13553. RadialGradient.prototype = {
  13554. constructor: RadialGradient
  13555. };
  13556. inherits(RadialGradient, Gradient);
  13557. /**
  13558. * Displayable for incremental rendering. It will be rendered in a separate layer
  13559. * IncrementalDisplay have too main methods. `clearDisplayables` and `addDisplayables`
  13560. * addDisplayables will render the added displayables incremetally.
  13561. *
  13562. * It use a not clearFlag to tell the painter don't clear the layer if it's the first element.
  13563. */
  13564. // TODO Style override ?
  13565. function IncrementalDisplayble(opts) {
  13566. Displayable.call(this, opts);
  13567. this._displayables = [];
  13568. this._temporaryDisplayables = [];
  13569. this._cursor = 0;
  13570. this.notClear = true;
  13571. }
  13572. IncrementalDisplayble.prototype.incremental = true;
  13573. IncrementalDisplayble.prototype.clearDisplaybles = function () {
  13574. this._displayables = [];
  13575. this._temporaryDisplayables = [];
  13576. this._cursor = 0;
  13577. this.dirty();
  13578. this.notClear = false;
  13579. };
  13580. IncrementalDisplayble.prototype.addDisplayable = function (displayable, notPersistent) {
  13581. if (notPersistent) {
  13582. this._temporaryDisplayables.push(displayable);
  13583. }
  13584. else {
  13585. this._displayables.push(displayable);
  13586. }
  13587. this.dirty();
  13588. };
  13589. IncrementalDisplayble.prototype.addDisplayables = function (displayables, notPersistent) {
  13590. notPersistent = notPersistent || false;
  13591. for (var i = 0; i < displayables.length; i++) {
  13592. this.addDisplayable(displayables[i], notPersistent);
  13593. }
  13594. };
  13595. IncrementalDisplayble.prototype.eachPendingDisplayable = function (cb) {
  13596. for (var i = this._cursor; i < this._displayables.length; i++) {
  13597. cb && cb(this._displayables[i]);
  13598. }
  13599. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13600. cb && cb(this._temporaryDisplayables[i]);
  13601. }
  13602. };
  13603. IncrementalDisplayble.prototype.update = function () {
  13604. this.updateTransform();
  13605. for (var i = this._cursor; i < this._displayables.length; i++) {
  13606. var displayable = this._displayables[i];
  13607. // PENDING
  13608. displayable.parent = this;
  13609. displayable.update();
  13610. displayable.parent = null;
  13611. }
  13612. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13613. var displayable = this._temporaryDisplayables[i];
  13614. // PENDING
  13615. displayable.parent = this;
  13616. displayable.update();
  13617. displayable.parent = null;
  13618. }
  13619. };
  13620. IncrementalDisplayble.prototype.brush = function (ctx, prevEl) {
  13621. // Render persistant displayables.
  13622. for (var i = this._cursor; i < this._displayables.length; i++) {
  13623. var displayable = this._temporaryDisplayables[i];
  13624. displayable.beforeBrush && displayable.beforeBrush(ctx);
  13625. displayable.brush(ctx, i === this._cursor ? null : this._displayables[i - 1]);
  13626. displayable.afterBrush && displayable.afterBrush(ctx);
  13627. }
  13628. this._cursor = i;
  13629. // Render temporary displayables.
  13630. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13631. var displayable = this._temporaryDisplayables[i];
  13632. displayable.beforeBrush && displayable.beforeBrush(ctx);
  13633. displayable.brush(ctx, i === 0 ? null : this._temporaryDisplayables[i - 1]);
  13634. displayable.afterBrush && displayable.afterBrush(ctx);
  13635. }
  13636. this._temporaryDisplayables = [];
  13637. this.notClear = true;
  13638. };
  13639. var m = [];
  13640. IncrementalDisplayble.prototype.getBoundingRect = function () {
  13641. if (!this._rect) {
  13642. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  13643. for (var i = 0; i < this._displayables.length; i++) {
  13644. var displayable = this._displayables[i];
  13645. var childRect = displayable.getBoundingRect().clone();
  13646. if (displayable.needLocalTransform()) {
  13647. childRect.applyTransform(displayable.getLocalTransform(m));
  13648. }
  13649. rect.union(childRect);
  13650. }
  13651. this._rect = rect;
  13652. }
  13653. return this._rect;
  13654. };
  13655. IncrementalDisplayble.prototype.contain = function (x, y) {
  13656. var localPos = this.transformCoordToLocal(x, y);
  13657. var rect = this.getBoundingRect();
  13658. if (rect.contain(localPos[0], localPos[1])) {
  13659. for (var i = 0; i < this._displayables.length; i++) {
  13660. var displayable = this._displayables[i];
  13661. if (displayable.contain(x, y)) {
  13662. return true;
  13663. }
  13664. }
  13665. }
  13666. return false;
  13667. };
  13668. inherits(IncrementalDisplayble, Displayable);
  13669. var round = Math.round;
  13670. var mathMax$1 = Math.max;
  13671. var mathMin$1 = Math.min;
  13672. var EMPTY_OBJ = {};
  13673. /**
  13674. * Extend shape with parameters
  13675. */
  13676. function extendShape(opts) {
  13677. return Path.extend(opts);
  13678. }
  13679. /**
  13680. * Extend path
  13681. */
  13682. function extendPath(pathData, opts) {
  13683. return extendFromString(pathData, opts);
  13684. }
  13685. /**
  13686. * Create a path element from path data string
  13687. * @param {string} pathData
  13688. * @param {Object} opts
  13689. * @param {module:zrender/core/BoundingRect} rect
  13690. * @param {string} [layout=cover] 'center' or 'cover'
  13691. */
  13692. function makePath(pathData, opts, rect, layout) {
  13693. var path = createFromString(pathData, opts);
  13694. var boundingRect = path.getBoundingRect();
  13695. if (rect) {
  13696. if (layout === 'center') {
  13697. rect = centerGraphic(rect, boundingRect);
  13698. }
  13699. resizePath(path, rect);
  13700. }
  13701. return path;
  13702. }
  13703. /**
  13704. * Create a image element from image url
  13705. * @param {string} imageUrl image url
  13706. * @param {Object} opts options
  13707. * @param {module:zrender/core/BoundingRect} rect constrain rect
  13708. * @param {string} [layout=cover] 'center' or 'cover'
  13709. */
  13710. function makeImage(imageUrl, rect, layout) {
  13711. var path = new ZImage({
  13712. style: {
  13713. image: imageUrl,
  13714. x: rect.x,
  13715. y: rect.y,
  13716. width: rect.width,
  13717. height: rect.height
  13718. },
  13719. onload: function (img) {
  13720. if (layout === 'center') {
  13721. var boundingRect = {
  13722. width: img.width,
  13723. height: img.height
  13724. };
  13725. path.setStyle(centerGraphic(rect, boundingRect));
  13726. }
  13727. }
  13728. });
  13729. return path;
  13730. }
  13731. /**
  13732. * Get position of centered element in bounding box.
  13733. *
  13734. * @param {Object} rect element local bounding box
  13735. * @param {Object} boundingRect constraint bounding box
  13736. * @return {Object} element position containing x, y, width, and height
  13737. */
  13738. function centerGraphic(rect, boundingRect) {
  13739. // Set rect to center, keep width / height ratio.
  13740. var aspect = boundingRect.width / boundingRect.height;
  13741. var width = rect.height * aspect;
  13742. var height;
  13743. if (width <= rect.width) {
  13744. height = rect.height;
  13745. }
  13746. else {
  13747. width = rect.width;
  13748. height = width / aspect;
  13749. }
  13750. var cx = rect.x + rect.width / 2;
  13751. var cy = rect.y + rect.height / 2;
  13752. return {
  13753. x: cx - width / 2,
  13754. y: cy - height / 2,
  13755. width: width,
  13756. height: height
  13757. };
  13758. }
  13759. var mergePath = mergePath$1;
  13760. /**
  13761. * Resize a path to fit the rect
  13762. * @param {module:zrender/graphic/Path} path
  13763. * @param {Object} rect
  13764. */
  13765. function resizePath(path, rect) {
  13766. if (!path.applyTransform) {
  13767. return;
  13768. }
  13769. var pathRect = path.getBoundingRect();
  13770. var m = pathRect.calculateTransform(rect);
  13771. path.applyTransform(m);
  13772. }
  13773. /**
  13774. * Sub pixel optimize line for canvas
  13775. *
  13776. * @param {Object} param
  13777. * @param {Object} [param.shape]
  13778. * @param {number} [param.shape.x1]
  13779. * @param {number} [param.shape.y1]
  13780. * @param {number} [param.shape.x2]
  13781. * @param {number} [param.shape.y2]
  13782. * @param {Object} [param.style]
  13783. * @param {number} [param.style.lineWidth]
  13784. * @return {Object} Modified param
  13785. */
  13786. function subPixelOptimizeLine(param) {
  13787. var shape = param.shape;
  13788. var lineWidth = param.style.lineWidth;
  13789. if (round(shape.x1 * 2) === round(shape.x2 * 2)) {
  13790. shape.x1 = shape.x2 = subPixelOptimize(shape.x1, lineWidth, true);
  13791. }
  13792. if (round(shape.y1 * 2) === round(shape.y2 * 2)) {
  13793. shape.y1 = shape.y2 = subPixelOptimize(shape.y1, lineWidth, true);
  13794. }
  13795. return param;
  13796. }
  13797. /**
  13798. * Sub pixel optimize rect for canvas
  13799. *
  13800. * @param {Object} param
  13801. * @param {Object} [param.shape]
  13802. * @param {number} [param.shape.x]
  13803. * @param {number} [param.shape.y]
  13804. * @param {number} [param.shape.width]
  13805. * @param {number} [param.shape.height]
  13806. * @param {Object} [param.style]
  13807. * @param {number} [param.style.lineWidth]
  13808. * @return {Object} Modified param
  13809. */
  13810. function subPixelOptimizeRect(param) {
  13811. var shape = param.shape;
  13812. var lineWidth = param.style.lineWidth;
  13813. var originX = shape.x;
  13814. var originY = shape.y;
  13815. var originWidth = shape.width;
  13816. var originHeight = shape.height;
  13817. shape.x = subPixelOptimize(shape.x, lineWidth, true);
  13818. shape.y = subPixelOptimize(shape.y, lineWidth, true);
  13819. shape.width = Math.max(
  13820. subPixelOptimize(originX + originWidth, lineWidth, false) - shape.x,
  13821. originWidth === 0 ? 0 : 1
  13822. );
  13823. shape.height = Math.max(
  13824. subPixelOptimize(originY + originHeight, lineWidth, false) - shape.y,
  13825. originHeight === 0 ? 0 : 1
  13826. );
  13827. return param;
  13828. }
  13829. /**
  13830. * Sub pixel optimize for canvas
  13831. *
  13832. * @param {number} position Coordinate, such as x, y
  13833. * @param {number} lineWidth Should be nonnegative integer.
  13834. * @param {boolean=} positiveOrNegative Default false (negative).
  13835. * @return {number} Optimized position.
  13836. */
  13837. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  13838. // Assure that (position + lineWidth / 2) is near integer edge,
  13839. // otherwise line will be fuzzy in canvas.
  13840. var doubledPosition = round(position * 2);
  13841. return (doubledPosition + round(lineWidth)) % 2 === 0
  13842. ? doubledPosition / 2
  13843. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  13844. }
  13845. function hasFillOrStroke(fillOrStroke) {
  13846. return fillOrStroke != null && fillOrStroke != 'none';
  13847. }
  13848. function liftColor(color) {
  13849. return typeof color === 'string' ? lift(color, -0.1) : color;
  13850. }
  13851. /**
  13852. * @private
  13853. */
  13854. function cacheElementStl(el) {
  13855. if (el.__hoverStlDirty) {
  13856. var stroke = el.style.stroke;
  13857. var fill = el.style.fill;
  13858. // Create hoverStyle on mouseover
  13859. var hoverStyle = el.__hoverStl;
  13860. hoverStyle.fill = hoverStyle.fill
  13861. || (hasFillOrStroke(fill) ? liftColor(fill) : null);
  13862. hoverStyle.stroke = hoverStyle.stroke
  13863. || (hasFillOrStroke(stroke) ? liftColor(stroke) : null);
  13864. var normalStyle = {};
  13865. for (var name in hoverStyle) {
  13866. // See comment in `doSingleEnterHover`.
  13867. if (hoverStyle[name] != null) {
  13868. normalStyle[name] = el.style[name];
  13869. }
  13870. }
  13871. el.__normalStl = normalStyle;
  13872. el.__hoverStlDirty = false;
  13873. }
  13874. }
  13875. /**
  13876. * @private
  13877. */
  13878. function doSingleEnterHover(el) {
  13879. if (el.__isHover) {
  13880. return;
  13881. }
  13882. cacheElementStl(el);
  13883. if (el.useHoverLayer) {
  13884. el.__zr && el.__zr.addHover(el, el.__hoverStl);
  13885. }
  13886. else {
  13887. var style = el.style;
  13888. var insideRollbackOpt = style.insideRollbackOpt;
  13889. // Consider case: only `position: 'top'` is set on emphasis, then text
  13890. // color should be returned to `autoColor`, rather than remain '#fff'.
  13891. // So we should rollback then apply again after style merging.
  13892. insideRollbackOpt && rollbackInsideStyle(style);
  13893. // styles can be:
  13894. // {
  13895. // label: {
  13896. // show: false,
  13897. // position: 'outside',
  13898. // fontSize: 18
  13899. // },
  13900. // emphasis: {
  13901. // label: {
  13902. // show: true
  13903. // }
  13904. // }
  13905. // },
  13906. // where properties of `emphasis` may not appear in `normal`. We previously use
  13907. // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
  13908. // But consider rich text and setOption in merge mode, it is impossible to cover
  13909. // all properties in merge. So we use merge mode when setting style here, where
  13910. // only properties that is not `null/undefined` can be set. The disadventage:
  13911. // null/undefined can not be used to remove style any more in `emphasis`.
  13912. style.extendFrom(el.__hoverStl);
  13913. // Do not save `insideRollback`.
  13914. if (insideRollbackOpt) {
  13915. applyInsideStyle(style, style.insideOriginalTextPosition, insideRollbackOpt);
  13916. // textFill may be rollbacked to null.
  13917. if (style.textFill == null) {
  13918. style.textFill = insideRollbackOpt.autoColor;
  13919. }
  13920. }
  13921. el.dirty(false);
  13922. el.z2 += 1;
  13923. }
  13924. el.__isHover = true;
  13925. }
  13926. /**
  13927. * @inner
  13928. */
  13929. function doSingleLeaveHover(el) {
  13930. if (!el.__isHover) {
  13931. return;
  13932. }
  13933. var normalStl = el.__normalStl;
  13934. if (el.useHoverLayer) {
  13935. el.__zr && el.__zr.removeHover(el);
  13936. }
  13937. else {
  13938. // Consider null/undefined value, should use
  13939. // `setStyle` but not `extendFrom(stl, true)`.
  13940. normalStl && el.setStyle(normalStl);
  13941. el.z2 -= 1;
  13942. }
  13943. el.__isHover = false;
  13944. }
  13945. /**
  13946. * @inner
  13947. */
  13948. function doEnterHover(el) {
  13949. el.type === 'group'
  13950. ? el.traverse(function (child) {
  13951. if (child.type !== 'group') {
  13952. doSingleEnterHover(child);
  13953. }
  13954. })
  13955. : doSingleEnterHover(el);
  13956. }
  13957. function doLeaveHover(el) {
  13958. el.type === 'group'
  13959. ? el.traverse(function (child) {
  13960. if (child.type !== 'group') {
  13961. doSingleLeaveHover(child);
  13962. }
  13963. })
  13964. : doSingleLeaveHover(el);
  13965. }
  13966. /**
  13967. * @inner
  13968. */
  13969. function setElementHoverStl(el, hoverStl) {
  13970. // If element has sepcified hoverStyle, then use it instead of given hoverStyle
  13971. // Often used when item group has a label element and it's hoverStyle is different
  13972. el.__hoverStl = el.hoverStyle || hoverStl || {};
  13973. el.__hoverStlDirty = true;
  13974. if (el.__isHover) {
  13975. cacheElementStl(el);
  13976. }
  13977. }
  13978. /**
  13979. * @inner
  13980. */
  13981. function onElementMouseOver(e) {
  13982. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  13983. return;
  13984. }
  13985. // Only if element is not in emphasis status
  13986. !this.__isEmphasis && doEnterHover(this);
  13987. }
  13988. /**
  13989. * @inner
  13990. */
  13991. function onElementMouseOut(e) {
  13992. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  13993. return;
  13994. }
  13995. // Only if element is not in emphasis status
  13996. !this.__isEmphasis && doLeaveHover(this);
  13997. }
  13998. /**
  13999. * @inner
  14000. */
  14001. function enterEmphasis() {
  14002. this.__isEmphasis = true;
  14003. doEnterHover(this);
  14004. }
  14005. /**
  14006. * @inner
  14007. */
  14008. function leaveEmphasis() {
  14009. this.__isEmphasis = false;
  14010. doLeaveHover(this);
  14011. }
  14012. /**
  14013. * Set hover style of element.
  14014. * This method can be called repeatly without side-effects.
  14015. * @param {module:zrender/Element} el
  14016. * @param {Object} [hoverStyle]
  14017. * @param {Object} [opt]
  14018. * @param {boolean} [opt.hoverSilentOnTouch=false]
  14019. * In touch device, mouseover event will be trigger on touchstart event
  14020. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  14021. * conviniently use hoverStyle when tap on touch screen without additional
  14022. * code for compatibility.
  14023. * But if the chart/component has select feature, which usually also use
  14024. * hoverStyle, there might be conflict between 'select-highlight' and
  14025. * 'hover-highlight' especially when roam is enabled (see geo for example).
  14026. * In this case, hoverSilentOnTouch should be used to disable hover-highlight
  14027. * on touch device.
  14028. */
  14029. function setHoverStyle(el, hoverStyle, opt) {
  14030. el.__hoverSilentOnTouch = opt && opt.hoverSilentOnTouch;
  14031. el.type === 'group'
  14032. ? el.traverse(function (child) {
  14033. if (child.type !== 'group') {
  14034. setElementHoverStl(child, hoverStyle);
  14035. }
  14036. })
  14037. : setElementHoverStl(el, hoverStyle);
  14038. // Duplicated function will be auto-ignored, see Eventful.js.
  14039. el.on('mouseover', onElementMouseOver)
  14040. .on('mouseout', onElementMouseOut);
  14041. // Emphasis, normal can be triggered manually
  14042. el.on('emphasis', enterEmphasis)
  14043. .on('normal', leaveEmphasis);
  14044. }
  14045. /**
  14046. * @param {Object|module:zrender/graphic/Style} normalStyle
  14047. * @param {Object} emphasisStyle
  14048. * @param {module:echarts/model/Model} normalModel
  14049. * @param {module:echarts/model/Model} emphasisModel
  14050. * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props.
  14051. * @param {string|Function} [opt.defaultText]
  14052. * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by
  14053. * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14054. * @param {module:echarts/model/Model} [opt.labelDataIndex] Fetch text by
  14055. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14056. * @param {module:echarts/model/Model} [opt.labelDimIndex] Fetch text by
  14057. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14058. * @param {Object} [normalSpecified]
  14059. * @param {Object} [emphasisSpecified]
  14060. */
  14061. function setLabelStyle(
  14062. normalStyle, emphasisStyle,
  14063. normalModel, emphasisModel,
  14064. opt,
  14065. normalSpecified, emphasisSpecified
  14066. ) {
  14067. opt = opt || EMPTY_OBJ;
  14068. var labelFetcher = opt.labelFetcher;
  14069. var labelDataIndex = opt.labelDataIndex;
  14070. var labelDimIndex = opt.labelDimIndex;
  14071. // This scenario, `label.normal.show = true; label.emphasis.show = false`,
  14072. // is not supported util someone requests.
  14073. var showNormal = normalModel.getShallow('show');
  14074. var showEmphasis = emphasisModel.getShallow('show');
  14075. // Consider performance, only fetch label when necessary.
  14076. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set,
  14077. // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`.
  14078. var baseText;
  14079. if (showNormal || showEmphasis) {
  14080. if (labelFetcher) {
  14081. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex);
  14082. }
  14083. if (baseText == null) {
  14084. baseText = isFunction$1(opt.defaultText) ? opt.defaultText(labelDataIndex, opt) : opt.defaultText;
  14085. }
  14086. }
  14087. var normalStyleText = showNormal ? baseText : null;
  14088. var emphasisStyleText = showEmphasis
  14089. ? retrieve2(
  14090. labelFetcher
  14091. ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex)
  14092. : null,
  14093. baseText
  14094. )
  14095. : null;
  14096. // Optimize: If style.text is null, text will not be drawn.
  14097. if (normalStyleText != null || emphasisStyleText != null) {
  14098. // Always set `textStyle` even if `normalStyle.text` is null, because default
  14099. // values have to be set on `normalStyle`.
  14100. // If we set default values on `emphasisStyle`, consider case:
  14101. // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);`
  14102. // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);`
  14103. // Then the 'red' will not work on emphasis.
  14104. setTextStyle(normalStyle, normalModel, normalSpecified, opt);
  14105. setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true);
  14106. }
  14107. normalStyle.text = normalStyleText;
  14108. emphasisStyle.text = emphasisStyleText;
  14109. }
  14110. /**
  14111. * Set basic textStyle properties.
  14112. * @param {Object|module:zrender/graphic/Style} textStyle
  14113. * @param {module:echarts/model/Model} model
  14114. * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
  14115. * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
  14116. * @param {boolean} [isEmphasis]
  14117. */
  14118. function setTextStyle(
  14119. textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis
  14120. ) {
  14121. setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis);
  14122. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  14123. textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14124. return textStyle;
  14125. }
  14126. /**
  14127. * Set text option in the style.
  14128. * @deprecated
  14129. * @param {Object} textStyle
  14130. * @param {module:echarts/model/Model} labelModel
  14131. * @param {string|boolean} defaultColor Default text color.
  14132. * If set as false, it will be processed as a emphasis style.
  14133. */
  14134. function setText(textStyle, labelModel, defaultColor) {
  14135. var opt = {isRectText: true};
  14136. var isEmphasis;
  14137. if (defaultColor === false) {
  14138. isEmphasis = true;
  14139. }
  14140. else {
  14141. // Support setting color as 'auto' to get visual color.
  14142. opt.autoColor = defaultColor;
  14143. }
  14144. setTextStyleCommon(textStyle, labelModel, opt, isEmphasis);
  14145. textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14146. }
  14147. /**
  14148. * {
  14149. * disableBox: boolean, Whether diable drawing box of block (outer most).
  14150. * isRectText: boolean,
  14151. * autoColor: string, specify a color when color is 'auto',
  14152. * for textFill, textStroke, textBackgroundColor, and textBorderColor.
  14153. * If autoColor specified, it is used as default textFill.
  14154. * useInsideStyle:
  14155. * `true`: Use inside style (textFill, textStroke, textStrokeWidth)
  14156. * if `textFill` is not specified.
  14157. * `false`: Do not use inside style.
  14158. * `null/undefined`: use inside style if `isRectText` is true and
  14159. * `textFill` is not specified and textPosition contains `'inside'`.
  14160. * forceRich: boolean
  14161. * }
  14162. */
  14163. function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
  14164. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14165. opt = opt || EMPTY_OBJ;
  14166. if (opt.isRectText) {
  14167. var textPosition = textStyleModel.getShallow('position')
  14168. || (isEmphasis ? null : 'inside');
  14169. // 'outside' is not a valid zr textPostion value, but used
  14170. // in bar series, and magric type should be considered.
  14171. textPosition === 'outside' && (textPosition = 'top');
  14172. textStyle.textPosition = textPosition;
  14173. textStyle.textOffset = textStyleModel.getShallow('offset');
  14174. var labelRotate = textStyleModel.getShallow('rotate');
  14175. labelRotate != null && (labelRotate *= Math.PI / 180);
  14176. textStyle.textRotation = labelRotate;
  14177. textStyle.textDistance = retrieve2(
  14178. textStyleModel.getShallow('distance'), isEmphasis ? null : 5
  14179. );
  14180. }
  14181. var ecModel = textStyleModel.ecModel;
  14182. var globalTextStyle = ecModel && ecModel.option.textStyle;
  14183. // Consider case:
  14184. // {
  14185. // data: [{
  14186. // value: 12,
  14187. // label: {
  14188. // rich: {
  14189. // // no 'a' here but using parent 'a'.
  14190. // }
  14191. // }
  14192. // }],
  14193. // rich: {
  14194. // a: { ... }
  14195. // }
  14196. // }
  14197. var richItemNames = getRichItemNames(textStyleModel);
  14198. var richResult;
  14199. if (richItemNames) {
  14200. richResult = {};
  14201. for (var name in richItemNames) {
  14202. if (richItemNames.hasOwnProperty(name)) {
  14203. // Cascade is supported in rich.
  14204. var richTextStyle = textStyleModel.getModel(['rich', name]);
  14205. // In rich, never `disableBox`.
  14206. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
  14207. }
  14208. }
  14209. }
  14210. textStyle.rich = richResult;
  14211. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
  14212. if (opt.forceRich && !opt.textStyle) {
  14213. opt.textStyle = {};
  14214. }
  14215. return textStyle;
  14216. }
  14217. // Consider case:
  14218. // {
  14219. // data: [{
  14220. // value: 12,
  14221. // label: {
  14222. // rich: {
  14223. // // no 'a' here but using parent 'a'.
  14224. // }
  14225. // }
  14226. // }],
  14227. // rich: {
  14228. // a: { ... }
  14229. // }
  14230. // }
  14231. function getRichItemNames(textStyleModel) {
  14232. // Use object to remove duplicated names.
  14233. var richItemNameMap;
  14234. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  14235. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  14236. if (rich) {
  14237. richItemNameMap = richItemNameMap || {};
  14238. for (var name in rich) {
  14239. if (rich.hasOwnProperty(name)) {
  14240. richItemNameMap[name] = 1;
  14241. }
  14242. }
  14243. }
  14244. textStyleModel = textStyleModel.parentModel;
  14245. }
  14246. return richItemNameMap;
  14247. }
  14248. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) {
  14249. // In merge mode, default value should not be given.
  14250. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ;
  14251. textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt)
  14252. || globalTextStyle.color;
  14253. textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt)
  14254. || globalTextStyle.textBorderColor;
  14255. textStyle.textStrokeWidth = retrieve2(
  14256. textStyleModel.getShallow('textBorderWidth'),
  14257. globalTextStyle.textBorderWidth
  14258. );
  14259. if (!isEmphasis) {
  14260. if (isBlock) {
  14261. // Always set `insideRollback`, for clearing previous.
  14262. var originalTextPosition = textStyle.textPosition;
  14263. textStyle.insideRollback = applyInsideStyle(textStyle, originalTextPosition, opt);
  14264. // Save original textPosition, because style.textPosition will be repalced by
  14265. // real location (like [10, 30]) in zrender.
  14266. textStyle.insideOriginalTextPosition = originalTextPosition;
  14267. textStyle.insideRollbackOpt = opt;
  14268. }
  14269. // Set default finally.
  14270. if (textStyle.textFill == null) {
  14271. textStyle.textFill = opt.autoColor;
  14272. }
  14273. }
  14274. // Do not use `getFont` here, because merge should be supported, where
  14275. // part of these properties may be changed in emphasis style, and the
  14276. // others should remain their original value got from normal style.
  14277. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle;
  14278. textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight;
  14279. textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize;
  14280. textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily;
  14281. textStyle.textAlign = textStyleModel.getShallow('align');
  14282. textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign')
  14283. || textStyleModel.getShallow('baseline');
  14284. textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
  14285. textStyle.textWidth = textStyleModel.getShallow('width');
  14286. textStyle.textHeight = textStyleModel.getShallow('height');
  14287. textStyle.textTag = textStyleModel.getShallow('tag');
  14288. if (!isBlock || !opt.disableBox) {
  14289. textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
  14290. textStyle.textPadding = textStyleModel.getShallow('padding');
  14291. textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
  14292. textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
  14293. textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');
  14294. textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
  14295. textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
  14296. textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
  14297. textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
  14298. }
  14299. textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor')
  14300. || globalTextStyle.textShadowColor;
  14301. textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur')
  14302. || globalTextStyle.textShadowBlur;
  14303. textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX')
  14304. || globalTextStyle.textShadowOffsetX;
  14305. textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY')
  14306. || globalTextStyle.textShadowOffsetY;
  14307. }
  14308. function getAutoColor(color, opt) {
  14309. return color !== 'auto' ? color : (opt && opt.autoColor) ? opt.autoColor : null;
  14310. }
  14311. function applyInsideStyle(textStyle, textPosition, opt) {
  14312. var useInsideStyle = opt.useInsideStyle;
  14313. var insideRollback;
  14314. if (textStyle.textFill == null
  14315. && useInsideStyle !== false
  14316. && (useInsideStyle === true
  14317. || (opt.isRectText
  14318. && textPosition
  14319. // textPosition can be [10, 30]
  14320. && typeof textPosition === 'string'
  14321. && textPosition.indexOf('inside') >= 0
  14322. )
  14323. )
  14324. ) {
  14325. insideRollback = {
  14326. textFill: null,
  14327. textStroke: textStyle.textStroke,
  14328. textStrokeWidth: textStyle.textStrokeWidth
  14329. };
  14330. textStyle.textFill = '#fff';
  14331. // Consider text with #fff overflow its container.
  14332. if (textStyle.textStroke == null) {
  14333. textStyle.textStroke = opt.autoColor;
  14334. textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
  14335. }
  14336. }
  14337. return insideRollback;
  14338. }
  14339. function rollbackInsideStyle(style) {
  14340. var insideRollback = style.insideRollback;
  14341. if (insideRollback) {
  14342. style.textFill = insideRollback.textFill;
  14343. style.textStroke = insideRollback.textStroke;
  14344. style.textStrokeWidth = insideRollback.textStrokeWidth;
  14345. }
  14346. }
  14347. function getFont(opt, ecModel) {
  14348. // ecModel or default text style model.
  14349. var gTextStyleModel = ecModel || ecModel.getModel('textStyle');
  14350. return trim([
  14351. // FIXME in node-canvas fontWeight is before fontStyle
  14352. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '',
  14353. opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '',
  14354. (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px',
  14355. opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'
  14356. ].join(' '));
  14357. }
  14358. function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
  14359. if (typeof dataIndex === 'function') {
  14360. cb = dataIndex;
  14361. dataIndex = null;
  14362. }
  14363. // Do not check 'animation' property directly here. Consider this case:
  14364. // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
  14365. // but its parent model (`seriesModel`) does.
  14366. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  14367. if (animationEnabled) {
  14368. var postfix = isUpdate ? 'Update' : '';
  14369. var duration = animatableModel.getShallow('animationDuration' + postfix);
  14370. var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
  14371. var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
  14372. if (typeof animationDelay === 'function') {
  14373. animationDelay = animationDelay(
  14374. dataIndex,
  14375. animatableModel.getAnimationDelayParams
  14376. ? animatableModel.getAnimationDelayParams(el, dataIndex)
  14377. : null
  14378. );
  14379. }
  14380. if (typeof duration === 'function') {
  14381. duration = duration(dataIndex);
  14382. }
  14383. duration > 0
  14384. ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb)
  14385. : (el.stopAnimation(), el.attr(props), cb && cb());
  14386. }
  14387. else {
  14388. el.stopAnimation();
  14389. el.attr(props);
  14390. cb && cb();
  14391. }
  14392. }
  14393. /**
  14394. * Update graphic element properties with or without animation according to the
  14395. * configuration in series.
  14396. *
  14397. * Caution: this method will stop previous animation.
  14398. * So if do not use this method to one element twice before
  14399. * animation starts, unless you know what you are doing.
  14400. *
  14401. * @param {module:zrender/Element} el
  14402. * @param {Object} props
  14403. * @param {module:echarts/model/Model} [animatableModel]
  14404. * @param {number} [dataIndex]
  14405. * @param {Function} [cb]
  14406. * @example
  14407. * graphic.updateProps(el, {
  14408. * position: [100, 100]
  14409. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  14410. * // Or
  14411. * graphic.updateProps(el, {
  14412. * position: [100, 100]
  14413. * }, seriesModel, function () { console.log('Animation done!'); });
  14414. */
  14415. function updateProps(el, props, animatableModel, dataIndex, cb) {
  14416. animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
  14417. }
  14418. /**
  14419. * Init graphic element properties with or without animation according to the
  14420. * configuration in series.
  14421. *
  14422. * Caution: this method will stop previous animation.
  14423. * So if do not use this method to one element twice before
  14424. * animation starts, unless you know what you are doing.
  14425. *
  14426. * @param {module:zrender/Element} el
  14427. * @param {Object} props
  14428. * @param {module:echarts/model/Model} [animatableModel]
  14429. * @param {number} [dataIndex]
  14430. * @param {Function} cb
  14431. */
  14432. function initProps(el, props, animatableModel, dataIndex, cb) {
  14433. animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
  14434. }
  14435. /**
  14436. * Get transform matrix of target (param target),
  14437. * in coordinate of its ancestor (param ancestor)
  14438. *
  14439. * @param {module:zrender/mixin/Transformable} target
  14440. * @param {module:zrender/mixin/Transformable} [ancestor]
  14441. */
  14442. function getTransform(target, ancestor) {
  14443. var mat = identity([]);
  14444. while (target && target !== ancestor) {
  14445. mul$1(mat, target.getLocalTransform(), mat);
  14446. target = target.parent;
  14447. }
  14448. return mat;
  14449. }
  14450. /**
  14451. * Apply transform to an vertex.
  14452. * @param {Array.<number>} target [x, y]
  14453. * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
  14454. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  14455. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  14456. * @param {boolean=} invert Whether use invert matrix.
  14457. * @return {Array.<number>} [x, y]
  14458. */
  14459. function applyTransform$1(target, transform, invert$$1) {
  14460. if (transform && !isArrayLike(transform)) {
  14461. transform = Transformable.getLocalTransform(transform);
  14462. }
  14463. if (invert$$1) {
  14464. transform = invert([], transform);
  14465. }
  14466. return applyTransform([], target, transform);
  14467. }
  14468. /**
  14469. * @param {string} direction 'left' 'right' 'top' 'bottom'
  14470. * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  14471. * @param {boolean=} invert Whether use invert matrix.
  14472. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
  14473. */
  14474. function transformDirection(direction, transform, invert$$1) {
  14475. // Pick a base, ensure that transform result will not be (0, 0).
  14476. var hBase = (transform[4] === 0 || transform[5] === 0 || transform[0] === 0)
  14477. ? 1 : Math.abs(2 * transform[4] / transform[0]);
  14478. var vBase = (transform[4] === 0 || transform[5] === 0 || transform[2] === 0)
  14479. ? 1 : Math.abs(2 * transform[4] / transform[2]);
  14480. var vertex = [
  14481. direction === 'left' ? -hBase : direction === 'right' ? hBase : 0,
  14482. direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0
  14483. ];
  14484. vertex = applyTransform$1(vertex, transform, invert$$1);
  14485. return Math.abs(vertex[0]) > Math.abs(vertex[1])
  14486. ? (vertex[0] > 0 ? 'right' : 'left')
  14487. : (vertex[1] > 0 ? 'bottom' : 'top');
  14488. }
  14489. /**
  14490. * Apply group transition animation from g1 to g2.
  14491. * If no animatableModel, no animation.
  14492. */
  14493. function groupTransition(g1, g2, animatableModel, cb) {
  14494. if (!g1 || !g2) {
  14495. return;
  14496. }
  14497. function getElMap(g) {
  14498. var elMap = {};
  14499. g.traverse(function (el) {
  14500. if (!el.isGroup && el.anid) {
  14501. elMap[el.anid] = el;
  14502. }
  14503. });
  14504. return elMap;
  14505. }
  14506. function getAnimatableProps(el) {
  14507. var obj = {
  14508. position: clone$1(el.position),
  14509. rotation: el.rotation
  14510. };
  14511. if (el.shape) {
  14512. obj.shape = extend({}, el.shape);
  14513. }
  14514. return obj;
  14515. }
  14516. var elMap1 = getElMap(g1);
  14517. g2.traverse(function (el) {
  14518. if (!el.isGroup && el.anid) {
  14519. var oldEl = elMap1[el.anid];
  14520. if (oldEl) {
  14521. var newProp = getAnimatableProps(el);
  14522. el.attr(getAnimatableProps(oldEl));
  14523. updateProps(el, newProp, animatableModel, el.dataIndex);
  14524. }
  14525. // else {
  14526. // if (el.previousProps) {
  14527. // graphic.updateProps
  14528. // }
  14529. // }
  14530. }
  14531. });
  14532. }
  14533. /**
  14534. * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
  14535. * @param {Object} rect {x, y, width, height}
  14536. * @return {Array.<Array.<number>>} A new clipped points.
  14537. */
  14538. function clipPointsByRect(points, rect) {
  14539. return map(points, function (point) {
  14540. var x = point[0];
  14541. x = mathMax$1(x, rect.x);
  14542. x = mathMin$1(x, rect.x + rect.width);
  14543. var y = point[1];
  14544. y = mathMax$1(y, rect.y);
  14545. y = mathMin$1(y, rect.y + rect.height);
  14546. return [x, y];
  14547. });
  14548. }
  14549. /**
  14550. * @param {Object} targetRect {x, y, width, height}
  14551. * @param {Object} rect {x, y, width, height}
  14552. * @return {Object} A new clipped rect. If rect size are negative, return undefined.
  14553. */
  14554. function clipRectByRect(targetRect, rect) {
  14555. var x = mathMax$1(targetRect.x, rect.x);
  14556. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  14557. var y = mathMax$1(targetRect.y, rect.y);
  14558. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height);
  14559. if (x2 >= x && y2 >= y) {
  14560. return {
  14561. x: x,
  14562. y: y,
  14563. width: x2 - x,
  14564. height: y2 - y
  14565. };
  14566. }
  14567. }
  14568. /**
  14569. * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
  14570. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
  14571. * @param {Object} [rect] {x, y, width, height}
  14572. * @return {module:zrender/Element} Icon path or image element.
  14573. */
  14574. function createIcon(iconStr, opt, rect) {
  14575. opt = extend({rectHover: true}, opt);
  14576. var style = opt.style = {strokeNoScale: true};
  14577. rect = rect || {x: -1, y: -1, width: 2, height: 2};
  14578. if (iconStr) {
  14579. return iconStr.indexOf('image://') === 0
  14580. ? (
  14581. style.image = iconStr.slice(8),
  14582. defaults(style, rect),
  14583. new ZImage(opt)
  14584. )
  14585. : (
  14586. makePath(
  14587. iconStr.replace('path://', ''),
  14588. opt,
  14589. rect,
  14590. 'center'
  14591. )
  14592. );
  14593. }
  14594. }
  14595. var graphic = (Object.freeze || Object)({
  14596. extendShape: extendShape,
  14597. extendPath: extendPath,
  14598. makePath: makePath,
  14599. makeImage: makeImage,
  14600. mergePath: mergePath,
  14601. resizePath: resizePath,
  14602. subPixelOptimizeLine: subPixelOptimizeLine,
  14603. subPixelOptimizeRect: subPixelOptimizeRect,
  14604. subPixelOptimize: subPixelOptimize,
  14605. setHoverStyle: setHoverStyle,
  14606. setLabelStyle: setLabelStyle,
  14607. setTextStyle: setTextStyle,
  14608. setText: setText,
  14609. getFont: getFont,
  14610. updateProps: updateProps,
  14611. initProps: initProps,
  14612. getTransform: getTransform,
  14613. applyTransform: applyTransform$1,
  14614. transformDirection: transformDirection,
  14615. groupTransition: groupTransition,
  14616. clipPointsByRect: clipPointsByRect,
  14617. clipRectByRect: clipRectByRect,
  14618. createIcon: createIcon,
  14619. Group: Group,
  14620. Image: ZImage,
  14621. Text: Text,
  14622. Circle: Circle,
  14623. Sector: Sector,
  14624. Ring: Ring,
  14625. Polygon: Polygon,
  14626. Polyline: Polyline,
  14627. Rect: Rect,
  14628. Line: Line,
  14629. BezierCurve: BezierCurve,
  14630. Arc: Arc,
  14631. IncrementalDisplayable: IncrementalDisplayble,
  14632. CompoundPath: CompoundPath,
  14633. LinearGradient: LinearGradient,
  14634. RadialGradient: RadialGradient,
  14635. BoundingRect: BoundingRect
  14636. });
  14637. var PATH_COLOR = ['textStyle', 'color'];
  14638. var textStyleMixin = {
  14639. /**
  14640. * Get color property or get color from option.textStyle.color
  14641. * @param {boolean} [isEmphasis]
  14642. * @return {string}
  14643. */
  14644. getTextColor: function (isEmphasis) {
  14645. var ecModel = this.ecModel;
  14646. return this.getShallow('color')
  14647. || (
  14648. (!isEmphasis && ecModel) ? ecModel.get(PATH_COLOR) : null
  14649. );
  14650. },
  14651. /**
  14652. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  14653. * @return {string}
  14654. */
  14655. getFont: function () {
  14656. return getFont({
  14657. fontStyle: this.getShallow('fontStyle'),
  14658. fontWeight: this.getShallow('fontWeight'),
  14659. fontSize: this.getShallow('fontSize'),
  14660. fontFamily: this.getShallow('fontFamily')
  14661. }, this.ecModel);
  14662. },
  14663. getTextRect: function (text) {
  14664. return getBoundingRect(
  14665. text,
  14666. this.getFont(),
  14667. this.getShallow('align'),
  14668. this.getShallow('verticalAlign') || this.getShallow('baseline'),
  14669. this.getShallow('padding'),
  14670. this.getShallow('rich'),
  14671. this.getShallow('truncateText')
  14672. );
  14673. }
  14674. };
  14675. var getItemStyle = makeStyleMapper(
  14676. [
  14677. ['fill', 'color'],
  14678. ['stroke', 'borderColor'],
  14679. ['lineWidth', 'borderWidth'],
  14680. ['opacity'],
  14681. ['shadowBlur'],
  14682. ['shadowOffsetX'],
  14683. ['shadowOffsetY'],
  14684. ['shadowColor'],
  14685. ['textPosition'],
  14686. ['textAlign']
  14687. ]
  14688. );
  14689. var itemStyleMixin = {
  14690. getItemStyle: function (excludes, includes) {
  14691. var style = getItemStyle(this, excludes, includes);
  14692. var lineDash = this.getBorderLineDash();
  14693. lineDash && (style.lineDash = lineDash);
  14694. return style;
  14695. },
  14696. getBorderLineDash: function () {
  14697. var lineType = this.get('borderType');
  14698. return (lineType === 'solid' || lineType == null) ? null
  14699. : (lineType === 'dashed' ? [5, 5] : [1, 1]);
  14700. }
  14701. };
  14702. /**
  14703. * @module echarts/model/Model
  14704. */
  14705. var mixin$1 = mixin;
  14706. var inner = makeInner();
  14707. /**
  14708. * @alias module:echarts/model/Model
  14709. * @constructor
  14710. * @param {Object} option
  14711. * @param {module:echarts/model/Model} [parentModel]
  14712. * @param {module:echarts/model/Global} [ecModel]
  14713. */
  14714. function Model(option, parentModel, ecModel) {
  14715. /**
  14716. * @type {module:echarts/model/Model}
  14717. * @readOnly
  14718. */
  14719. this.parentModel = parentModel;
  14720. /**
  14721. * @type {module:echarts/model/Global}
  14722. * @readOnly
  14723. */
  14724. this.ecModel = ecModel;
  14725. /**
  14726. * @type {Object}
  14727. * @protected
  14728. */
  14729. this.option = option;
  14730. // Simple optimization
  14731. // if (this.init) {
  14732. // if (arguments.length <= 4) {
  14733. // this.init(option, parentModel, ecModel, extraOpt);
  14734. // }
  14735. // else {
  14736. // this.init.apply(this, arguments);
  14737. // }
  14738. // }
  14739. }
  14740. Model.prototype = {
  14741. constructor: Model,
  14742. /**
  14743. * Model 的初始化函数
  14744. * @param {Object} option
  14745. */
  14746. init: null,
  14747. /**
  14748. * 从新的 Option merge
  14749. */
  14750. mergeOption: function (option) {
  14751. merge(this.option, option, true);
  14752. },
  14753. /**
  14754. * @param {string|Array.<string>} path
  14755. * @param {boolean} [ignoreParent=false]
  14756. * @return {*}
  14757. */
  14758. get: function (path, ignoreParent) {
  14759. if (path == null) {
  14760. return this.option;
  14761. }
  14762. return doGet(
  14763. this.option,
  14764. this.parsePath(path),
  14765. !ignoreParent && getParent(this, path)
  14766. );
  14767. },
  14768. /**
  14769. * @param {string} key
  14770. * @param {boolean} [ignoreParent=false]
  14771. * @return {*}
  14772. */
  14773. getShallow: function (key, ignoreParent) {
  14774. var option = this.option;
  14775. var val = option == null ? option : option[key];
  14776. var parentModel = !ignoreParent && getParent(this, key);
  14777. if (val == null && parentModel) {
  14778. val = parentModel.getShallow(key);
  14779. }
  14780. return val;
  14781. },
  14782. /**
  14783. * @param {string|Array.<string>} [path]
  14784. * @param {module:echarts/model/Model} [parentModel]
  14785. * @return {module:echarts/model/Model}
  14786. */
  14787. getModel: function (path, parentModel) {
  14788. var obj = path == null
  14789. ? this.option
  14790. : doGet(this.option, path = this.parsePath(path));
  14791. var thisParentModel;
  14792. parentModel = parentModel || (
  14793. (thisParentModel = getParent(this, path))
  14794. && thisParentModel.getModel(path)
  14795. );
  14796. return new Model(obj, parentModel, this.ecModel);
  14797. },
  14798. /**
  14799. * If model has option
  14800. */
  14801. isEmpty: function () {
  14802. return this.option == null;
  14803. },
  14804. restoreData: function () {},
  14805. // Pending
  14806. clone: function () {
  14807. var Ctor = this.constructor;
  14808. return new Ctor(clone(this.option));
  14809. },
  14810. setReadOnly: function (properties) {
  14811. // clazzUtil.setReadOnly(this, properties);
  14812. },
  14813. // If path is null/undefined, return null/undefined.
  14814. parsePath: function(path) {
  14815. if (typeof path === 'string') {
  14816. path = path.split('.');
  14817. }
  14818. return path;
  14819. },
  14820. /**
  14821. * @param {Function} getParentMethod
  14822. * param {Array.<string>|string} path
  14823. * return {module:echarts/model/Model}
  14824. */
  14825. customizeGetParent: function (getParentMethod) {
  14826. inner(this).getParent = getParentMethod;
  14827. },
  14828. isAnimationEnabled: function () {
  14829. if (!env$1.node) {
  14830. if (this.option.animation != null) {
  14831. return !!this.option.animation;
  14832. }
  14833. else if (this.parentModel) {
  14834. return this.parentModel.isAnimationEnabled();
  14835. }
  14836. }
  14837. }
  14838. };
  14839. function doGet(obj, pathArr, parentModel) {
  14840. for (var i = 0; i < pathArr.length; i++) {
  14841. // Ignore empty
  14842. if (!pathArr[i]) {
  14843. continue;
  14844. }
  14845. // obj could be number/string/... (like 0)
  14846. obj = (obj && typeof obj === 'object') ? obj[pathArr[i]] : null;
  14847. if (obj == null) {
  14848. break;
  14849. }
  14850. }
  14851. if (obj == null && parentModel) {
  14852. obj = parentModel.get(pathArr);
  14853. }
  14854. return obj;
  14855. }
  14856. // `path` can be null/undefined
  14857. function getParent(model, path) {
  14858. var getParentMethod = inner(model).getParent;
  14859. return getParentMethod ? getParentMethod.call(model, path) : model.parentModel;
  14860. }
  14861. // Enable Model.extend.
  14862. enableClassExtend(Model);
  14863. enableClassCheck(Model);
  14864. mixin$1(Model, lineStyleMixin);
  14865. mixin$1(Model, areaStyleMixin);
  14866. mixin$1(Model, textStyleMixin);
  14867. mixin$1(Model, itemStyleMixin);
  14868. var base = 0;
  14869. /**
  14870. * @public
  14871. * @param {string} type
  14872. * @return {string}
  14873. */
  14874. function getUID(type) {
  14875. // Considering the case of crossing js context,
  14876. // use Math.random to make id as unique as possible.
  14877. return [(type || ''), base++, Math.random().toFixed(5)].join('_');
  14878. }
  14879. /**
  14880. * @inner
  14881. */
  14882. function enableSubTypeDefaulter(entity) {
  14883. var subTypeDefaulters = {};
  14884. entity.registerSubTypeDefaulter = function (componentType, defaulter) {
  14885. componentType = parseClassType$1(componentType);
  14886. subTypeDefaulters[componentType.main] = defaulter;
  14887. };
  14888. entity.determineSubType = function (componentType, option) {
  14889. var type = option.type;
  14890. if (!type) {
  14891. var componentTypeMain = parseClassType$1(componentType).main;
  14892. if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  14893. type = subTypeDefaulters[componentTypeMain](option);
  14894. }
  14895. }
  14896. return type;
  14897. };
  14898. return entity;
  14899. }
  14900. /**
  14901. * Topological travel on Activity Network (Activity On Vertices).
  14902. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  14903. *
  14904. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  14905. *
  14906. * If there is circle dependencey, Error will be thrown.
  14907. *
  14908. */
  14909. function enableTopologicalTravel(entity, dependencyGetter) {
  14910. /**
  14911. * @public
  14912. * @param {Array.<string>} targetNameList Target Component type list.
  14913. * Can be ['aa', 'bb', 'aa.xx']
  14914. * @param {Array.<string>} fullNameList By which we can build dependency graph.
  14915. * @param {Function} callback Params: componentType, dependencies.
  14916. * @param {Object} context Scope of callback.
  14917. */
  14918. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  14919. if (!targetNameList.length) {
  14920. return;
  14921. }
  14922. var result = makeDepndencyGraph(fullNameList);
  14923. var graph = result.graph;
  14924. var stack = result.noEntryList;
  14925. var targetNameSet = {};
  14926. each$1(targetNameList, function (name) {
  14927. targetNameSet[name] = true;
  14928. });
  14929. while (stack.length) {
  14930. var currComponentType = stack.pop();
  14931. var currVertex = graph[currComponentType];
  14932. var isInTargetNameSet = !!targetNameSet[currComponentType];
  14933. if (isInTargetNameSet) {
  14934. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  14935. delete targetNameSet[currComponentType];
  14936. }
  14937. each$1(
  14938. currVertex.successor,
  14939. isInTargetNameSet ? removeEdgeAndAdd : removeEdge
  14940. );
  14941. }
  14942. each$1(targetNameSet, function () {
  14943. throw new Error('Circle dependency may exists');
  14944. });
  14945. function removeEdge(succComponentType) {
  14946. graph[succComponentType].entryCount--;
  14947. if (graph[succComponentType].entryCount === 0) {
  14948. stack.push(succComponentType);
  14949. }
  14950. }
  14951. // Consider this case: legend depends on series, and we call
  14952. // chart.setOption({series: [...]}), where only series is in option.
  14953. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  14954. // not be called, but only sereis.mergeOption is called. Thus legend
  14955. // have no chance to update its local record about series (like which
  14956. // name of series is available in legend).
  14957. function removeEdgeAndAdd(succComponentType) {
  14958. targetNameSet[succComponentType] = true;
  14959. removeEdge(succComponentType);
  14960. }
  14961. };
  14962. /**
  14963. * DepndencyGraph: {Object}
  14964. * key: conponentType,
  14965. * value: {
  14966. * successor: [conponentTypes...],
  14967. * originalDeps: [conponentTypes...],
  14968. * entryCount: {number}
  14969. * }
  14970. */
  14971. function makeDepndencyGraph(fullNameList) {
  14972. var graph = {};
  14973. var noEntryList = [];
  14974. each$1(fullNameList, function (name) {
  14975. var thisItem = createDependencyGraphItem(graph, name);
  14976. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  14977. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  14978. thisItem.entryCount = availableDeps.length;
  14979. if (thisItem.entryCount === 0) {
  14980. noEntryList.push(name);
  14981. }
  14982. each$1(availableDeps, function (dependentName) {
  14983. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  14984. thisItem.predecessor.push(dependentName);
  14985. }
  14986. var thatItem = createDependencyGraphItem(graph, dependentName);
  14987. if (indexOf(thatItem.successor, dependentName) < 0) {
  14988. thatItem.successor.push(name);
  14989. }
  14990. });
  14991. });
  14992. return {graph: graph, noEntryList: noEntryList};
  14993. }
  14994. function createDependencyGraphItem(graph, name) {
  14995. if (!graph[name]) {
  14996. graph[name] = {predecessor: [], successor: []};
  14997. }
  14998. return graph[name];
  14999. }
  15000. function getAvailableDependencies(originalDeps, fullNameList) {
  15001. var availableDeps = [];
  15002. each$1(originalDeps, function (dep) {
  15003. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  15004. });
  15005. return availableDeps;
  15006. }
  15007. }
  15008. var RADIAN_EPSILON = 1e-4;
  15009. function _trim(str) {
  15010. return str.replace(/^\s+/, '').replace(/\s+$/, '');
  15011. }
  15012. /**
  15013. * Linear mapping a value from domain to range
  15014. * @memberOf module:echarts/util/number
  15015. * @param {(number|Array.<number>)} val
  15016. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  15017. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  15018. * @param {boolean} clamp
  15019. * @return {(number|Array.<number>}
  15020. */
  15021. function linearMap(val, domain, range, clamp) {
  15022. var subDomain = domain[1] - domain[0];
  15023. var subRange = range[1] - range[0];
  15024. if (subDomain === 0) {
  15025. return subRange === 0
  15026. ? range[0]
  15027. : (range[0] + range[1]) / 2;
  15028. }
  15029. // Avoid accuracy problem in edge, such as
  15030. // 146.39 - 62.83 === 83.55999999999999.
  15031. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  15032. // It is a little verbose for efficiency considering this method
  15033. // is a hotspot.
  15034. if (clamp) {
  15035. if (subDomain > 0) {
  15036. if (val <= domain[0]) {
  15037. return range[0];
  15038. }
  15039. else if (val >= domain[1]) {
  15040. return range[1];
  15041. }
  15042. }
  15043. else {
  15044. if (val >= domain[0]) {
  15045. return range[0];
  15046. }
  15047. else if (val <= domain[1]) {
  15048. return range[1];
  15049. }
  15050. }
  15051. }
  15052. else {
  15053. if (val === domain[0]) {
  15054. return range[0];
  15055. }
  15056. if (val === domain[1]) {
  15057. return range[1];
  15058. }
  15059. }
  15060. return (val - domain[0]) / subDomain * subRange + range[0];
  15061. }
  15062. /**
  15063. * Convert a percent string to absolute number.
  15064. * Returns NaN if percent is not a valid string or number
  15065. * @memberOf module:echarts/util/number
  15066. * @param {string|number} percent
  15067. * @param {number} all
  15068. * @return {number}
  15069. */
  15070. function parsePercent$1(percent, all) {
  15071. switch (percent) {
  15072. case 'center':
  15073. case 'middle':
  15074. percent = '50%';
  15075. break;
  15076. case 'left':
  15077. case 'top':
  15078. percent = '0%';
  15079. break;
  15080. case 'right':
  15081. case 'bottom':
  15082. percent = '100%';
  15083. break;
  15084. }
  15085. if (typeof percent === 'string') {
  15086. if (_trim(percent).match(/%$/)) {
  15087. return parseFloat(percent) / 100 * all;
  15088. }
  15089. return parseFloat(percent);
  15090. }
  15091. return percent == null ? NaN : +percent;
  15092. }
  15093. /**
  15094. * (1) Fix rounding error of float numbers.
  15095. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  15096. *
  15097. * @param {number} x
  15098. * @param {number} [precision]
  15099. * @param {boolean} [returnStr]
  15100. * @return {number|string}
  15101. */
  15102. function round$1(x, precision, returnStr) {
  15103. if (precision == null) {
  15104. precision = 10;
  15105. }
  15106. // Avoid range error
  15107. precision = Math.min(Math.max(0, precision), 20);
  15108. x = (+x).toFixed(precision);
  15109. return returnStr ? x : +x;
  15110. }
  15111. function asc(arr) {
  15112. arr.sort(function (a, b) {
  15113. return a - b;
  15114. });
  15115. return arr;
  15116. }
  15117. /**
  15118. * Get precision
  15119. * @param {number} val
  15120. */
  15121. function getPrecision(val) {
  15122. val = +val;
  15123. if (isNaN(val)) {
  15124. return 0;
  15125. }
  15126. // It is much faster than methods converting number to string as follows
  15127. // var tmp = val.toString();
  15128. // return tmp.length - 1 - tmp.indexOf('.');
  15129. // especially when precision is low
  15130. var e = 1;
  15131. var count = 0;
  15132. while (Math.round(val * e) / e !== val) {
  15133. e *= 10;
  15134. count++;
  15135. }
  15136. return count;
  15137. }
  15138. /**
  15139. * @param {string|number} val
  15140. * @return {number}
  15141. */
  15142. function getPrecisionSafe(val) {
  15143. var str = val.toString();
  15144. // Consider scientific notation: '3.4e-12' '3.4e+12'
  15145. var eIndex = str.indexOf('e');
  15146. if (eIndex > 0) {
  15147. var precision = +str.slice(eIndex + 1);
  15148. return precision < 0 ? -precision : 0;
  15149. }
  15150. else {
  15151. var dotIndex = str.indexOf('.');
  15152. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  15153. }
  15154. }
  15155. /**
  15156. * Minimal dicernible data precisioin according to a single pixel.
  15157. *
  15158. * @param {Array.<number>} dataExtent
  15159. * @param {Array.<number>} pixelExtent
  15160. * @return {number} precision
  15161. */
  15162. function getPixelPrecision(dataExtent, pixelExtent) {
  15163. var log = Math.log;
  15164. var LN10 = Math.LN10;
  15165. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  15166. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  15167. // toFixed() digits argument must be between 0 and 20.
  15168. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  15169. return !isFinite(precision) ? 20 : precision;
  15170. }
  15171. /**
  15172. * Get a data of given precision, assuring the sum of percentages
  15173. * in valueList is 1.
  15174. * The largest remainer method is used.
  15175. * https://en.wikipedia.org/wiki/Largest_remainder_method
  15176. *
  15177. * @param {Array.<number>} valueList a list of all data
  15178. * @param {number} idx index of the data to be processed in valueList
  15179. * @param {number} precision integer number showing digits of precision
  15180. * @return {number} percent ranging from 0 to 100
  15181. */
  15182. function getPercentWithPrecision(valueList, idx, precision) {
  15183. if (!valueList[idx]) {
  15184. return 0;
  15185. }
  15186. var sum = reduce(valueList, function (acc, val) {
  15187. return acc + (isNaN(val) ? 0 : val);
  15188. }, 0);
  15189. if (sum === 0) {
  15190. return 0;
  15191. }
  15192. var digits = Math.pow(10, precision);
  15193. var votesPerQuota = map(valueList, function (val) {
  15194. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  15195. });
  15196. var targetSeats = digits * 100;
  15197. var seats = map(votesPerQuota, function (votes) {
  15198. // Assign automatic seats.
  15199. return Math.floor(votes);
  15200. });
  15201. var currentSum = reduce(seats, function (acc, val) {
  15202. return acc + val;
  15203. }, 0);
  15204. var remainder = map(votesPerQuota, function (votes, idx) {
  15205. return votes - seats[idx];
  15206. });
  15207. // Has remainding votes.
  15208. while (currentSum < targetSeats) {
  15209. // Find next largest remainder.
  15210. var max = Number.NEGATIVE_INFINITY;
  15211. var maxId = null;
  15212. for (var i = 0, len = remainder.length; i < len; ++i) {
  15213. if (remainder[i] > max) {
  15214. max = remainder[i];
  15215. maxId = i;
  15216. }
  15217. }
  15218. // Add a vote to max remainder.
  15219. ++seats[maxId];
  15220. remainder[maxId] = 0;
  15221. ++currentSum;
  15222. }
  15223. return seats[idx] / digits;
  15224. }
  15225. // Number.MAX_SAFE_INTEGER, ie do not support.
  15226. var MAX_SAFE_INTEGER = 9007199254740991;
  15227. /**
  15228. * To 0 - 2 * PI, considering negative radian.
  15229. * @param {number} radian
  15230. * @return {number}
  15231. */
  15232. function remRadian(radian) {
  15233. var pi2 = Math.PI * 2;
  15234. return (radian % pi2 + pi2) % pi2;
  15235. }
  15236. /**
  15237. * @param {type} radian
  15238. * @return {boolean}
  15239. */
  15240. function isRadianAroundZero(val) {
  15241. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  15242. }
  15243. var TIME_REG = /^(?:(\d{4})(?:[-\/](\d{1,2})(?:[-\/](\d{1,2})(?:[T ](\d{1,2})(?::(\d\d)(?::(\d\d)(?:[.,](\d+))?)?)?(Z|[\+\-]\d\d:?\d\d)?)?)?)?)?$/; // jshint ignore:line
  15244. /**
  15245. * @param {string|Date|number} value These values can be accepted:
  15246. * + An instance of Date, represent a time in its own time zone.
  15247. * + Or string in a subset of ISO 8601, only including:
  15248. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  15249. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  15250. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  15251. * all of which will be treated as local time if time zone is not specified
  15252. * (see <https://momentjs.com/>).
  15253. * + Or other string format, including (all of which will be treated as loacal time):
  15254. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  15255. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  15256. * + a timestamp, which represent a time in UTC.
  15257. * @return {Date} date
  15258. */
  15259. function parseDate(value) {
  15260. if (value instanceof Date) {
  15261. return value;
  15262. }
  15263. else if (typeof value === 'string') {
  15264. // Different browsers parse date in different way, so we parse it manually.
  15265. // Some other issues:
  15266. // new Date('1970-01-01') is UTC,
  15267. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  15268. // See issue #3623
  15269. var match = TIME_REG.exec(value);
  15270. if (!match) {
  15271. // return Invalid Date.
  15272. return new Date(NaN);
  15273. }
  15274. // Use local time when no timezone offset specifed.
  15275. if (!match[8]) {
  15276. // match[n] can only be string or undefined.
  15277. // But take care of '12' + 1 => '121'.
  15278. return new Date(
  15279. +match[1],
  15280. +(match[2] || 1) - 1,
  15281. +match[3] || 1,
  15282. +match[4] || 0,
  15283. +(match[5] || 0),
  15284. +match[6] || 0,
  15285. +match[7] || 0
  15286. );
  15287. }
  15288. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  15289. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  15290. // For example, system timezone is set as "Time Zone: America/Toronto",
  15291. // then these code will get different result:
  15292. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  15293. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  15294. // So we should not use `new Date`, but use `Date.UTC`.
  15295. else {
  15296. var hour = +match[4] || 0;
  15297. if (match[8].toUpperCase() !== 'Z') {
  15298. hour -= match[8].slice(0, 3);
  15299. }
  15300. return new Date(Date.UTC(
  15301. +match[1],
  15302. +(match[2] || 1) - 1,
  15303. +match[3] || 1,
  15304. hour,
  15305. +(match[5] || 0),
  15306. +match[6] || 0,
  15307. +match[7] || 0
  15308. ));
  15309. }
  15310. }
  15311. else if (value == null) {
  15312. return new Date(NaN);
  15313. }
  15314. return new Date(Math.round(value));
  15315. }
  15316. /**
  15317. * Quantity of a number. e.g. 0.1, 1, 10, 100
  15318. *
  15319. * @param {number} val
  15320. * @return {number}
  15321. */
  15322. function quantity(val) {
  15323. return Math.pow(10, quantityExponent(val));
  15324. }
  15325. function quantityExponent(val) {
  15326. return Math.floor(Math.log(val) / Math.LN10);
  15327. }
  15328. /**
  15329. * find a “nice” number approximately equal to x. Round the number if round = true,
  15330. * take ceiling if round = false. The primary observation is that the “nicest”
  15331. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  15332. *
  15333. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  15334. *
  15335. * @param {number} val Non-negative value.
  15336. * @param {boolean} round
  15337. * @return {number}
  15338. */
  15339. function nice(val, round) {
  15340. var exponent = quantityExponent(val);
  15341. var exp10 = Math.pow(10, exponent);
  15342. var f = val / exp10; // 1 <= f < 10
  15343. var nf;
  15344. if (round) {
  15345. if (f < 1.5) { nf = 1; }
  15346. else if (f < 2.5) { nf = 2; }
  15347. else if (f < 4) { nf = 3; }
  15348. else if (f < 7) { nf = 5; }
  15349. else { nf = 10; }
  15350. }
  15351. else {
  15352. if (f < 1) { nf = 1; }
  15353. else if (f < 2) { nf = 2; }
  15354. else if (f < 3) { nf = 3; }
  15355. else if (f < 5) { nf = 5; }
  15356. else { nf = 10; }
  15357. }
  15358. val = nf * exp10;
  15359. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  15360. // 20 is the uppper bound of toFixed.
  15361. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  15362. }
  15363. /**
  15364. * Order intervals asc, and split them when overlap.
  15365. * expect(numberUtil.reformIntervals([
  15366. * {interval: [18, 62], close: [1, 1]},
  15367. * {interval: [-Infinity, -70], close: [0, 0]},
  15368. * {interval: [-70, -26], close: [1, 1]},
  15369. * {interval: [-26, 18], close: [1, 1]},
  15370. * {interval: [62, 150], close: [1, 1]},
  15371. * {interval: [106, 150], close: [1, 1]},
  15372. * {interval: [150, Infinity], close: [0, 0]}
  15373. * ])).toEqual([
  15374. * {interval: [-Infinity, -70], close: [0, 0]},
  15375. * {interval: [-70, -26], close: [1, 1]},
  15376. * {interval: [-26, 18], close: [0, 1]},
  15377. * {interval: [18, 62], close: [0, 1]},
  15378. * {interval: [62, 150], close: [0, 1]},
  15379. * {interval: [150, Infinity], close: [0, 0]}
  15380. * ]);
  15381. * @param {Array.<Object>} list, where `close` mean open or close
  15382. * of the interval, and Infinity can be used.
  15383. * @return {Array.<Object>} The origin list, which has been reformed.
  15384. */
  15385. function reformIntervals(list) {
  15386. list.sort(function (a, b) {
  15387. return littleThan(a, b, 0) ? -1 : 1;
  15388. });
  15389. var curr = -Infinity;
  15390. var currClose = 1;
  15391. for (var i = 0; i < list.length;) {
  15392. var interval = list[i].interval;
  15393. var close = list[i].close;
  15394. for (var lg = 0; lg < 2; lg++) {
  15395. if (interval[lg] <= curr) {
  15396. interval[lg] = curr;
  15397. close[lg] = !lg ? 1 - currClose : 1;
  15398. }
  15399. curr = interval[lg];
  15400. currClose = close[lg];
  15401. }
  15402. if (interval[0] === interval[1] && close[0] * close[1] !== 1) {
  15403. list.splice(i, 1);
  15404. }
  15405. else {
  15406. i++;
  15407. }
  15408. }
  15409. return list;
  15410. function littleThan(a, b, lg) {
  15411. return a.interval[lg] < b.interval[lg]
  15412. || (
  15413. a.interval[lg] === b.interval[lg]
  15414. && (
  15415. (a.close[lg] - b.close[lg] === (!lg ? 1 : -1))
  15416. || (!lg && littleThan(a, b, 1))
  15417. )
  15418. );
  15419. }
  15420. }
  15421. /**
  15422. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  15423. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  15424. * subtraction forces infinities to NaN
  15425. *
  15426. * @param {*} v
  15427. * @return {boolean}
  15428. */
  15429. function isNumeric(v) {
  15430. return v - parseFloat(v) >= 0;
  15431. }
  15432. var number = (Object.freeze || Object)({
  15433. linearMap: linearMap,
  15434. parsePercent: parsePercent$1,
  15435. round: round$1,
  15436. asc: asc,
  15437. getPrecision: getPrecision,
  15438. getPrecisionSafe: getPrecisionSafe,
  15439. getPixelPrecision: getPixelPrecision,
  15440. getPercentWithPrecision: getPercentWithPrecision,
  15441. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  15442. remRadian: remRadian,
  15443. isRadianAroundZero: isRadianAroundZero,
  15444. parseDate: parseDate,
  15445. quantity: quantity,
  15446. nice: nice,
  15447. reformIntervals: reformIntervals,
  15448. isNumeric: isNumeric
  15449. });
  15450. /**
  15451. * 每三位默认加,格式化
  15452. * @param {string|number} x
  15453. * @return {string}
  15454. */
  15455. function addCommas(x) {
  15456. if (isNaN(x)) {
  15457. return '-';
  15458. }
  15459. x = (x + '').split('.');
  15460. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,'$1,')
  15461. + (x.length > 1 ? ('.' + x[1]) : '');
  15462. }
  15463. /**
  15464. * @param {string} str
  15465. * @param {boolean} [upperCaseFirst=false]
  15466. * @return {string} str
  15467. */
  15468. function toCamelCase(str, upperCaseFirst) {
  15469. str = (str || '').toLowerCase().replace(/-(.)/g, function(match, group1) {
  15470. return group1.toUpperCase();
  15471. });
  15472. if (upperCaseFirst && str) {
  15473. str = str.charAt(0).toUpperCase() + str.slice(1);
  15474. }
  15475. return str;
  15476. }
  15477. var normalizeCssArray$1 = normalizeCssArray;
  15478. function encodeHTML(source) {
  15479. return String(source)
  15480. .replace(/&/g, '&amp;')
  15481. .replace(/</g, '&lt;')
  15482. .replace(/>/g, '&gt;')
  15483. .replace(/"/g, '&quot;')
  15484. .replace(/'/g, '&#39;');
  15485. }
  15486. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  15487. var wrapVar = function (varName, seriesIdx) {
  15488. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  15489. };
  15490. /**
  15491. * Template formatter
  15492. * @param {string} tpl
  15493. * @param {Array.<Object>|Object} paramsList
  15494. * @param {boolean} [encode=false]
  15495. * @return {string}
  15496. */
  15497. function formatTpl(tpl, paramsList, encode) {
  15498. if (!isArray(paramsList)) {
  15499. paramsList = [paramsList];
  15500. }
  15501. var seriesLen = paramsList.length;
  15502. if (!seriesLen) {
  15503. return '';
  15504. }
  15505. var $vars = paramsList[0].$vars || [];
  15506. for (var i = 0; i < $vars.length; i++) {
  15507. var alias = TPL_VAR_ALIAS[i];
  15508. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  15509. }
  15510. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  15511. for (var k = 0; k < $vars.length; k++) {
  15512. var val = paramsList[seriesIdx][$vars[k]];
  15513. tpl = tpl.replace(
  15514. wrapVar(TPL_VAR_ALIAS[k], seriesIdx),
  15515. encode ? encodeHTML(val) : val
  15516. );
  15517. }
  15518. }
  15519. return tpl;
  15520. }
  15521. /**
  15522. * simple Template formatter
  15523. *
  15524. * @param {string} tpl
  15525. * @param {Object} param
  15526. * @param {boolean} [encode=false]
  15527. * @return {string}
  15528. */
  15529. function formatTplSimple(tpl, param, encode) {
  15530. each$1(param, function (value, key) {
  15531. tpl = tpl.replace(
  15532. '{' + key + '}',
  15533. encode ? encodeHTML(value) : value
  15534. );
  15535. });
  15536. return tpl;
  15537. }
  15538. /**
  15539. * @param {Object|string} [opt] If string, means color.
  15540. * @param {string} [opt.color]
  15541. * @param {string} [opt.extraCssText]
  15542. * @param {string} [opt.type='item'] 'item' or 'subItem'
  15543. * @return {string}
  15544. */
  15545. function getTooltipMarker(opt, extraCssText) {
  15546. opt = isString(opt) ? {color: opt, extraCssText: extraCssText} : (opt || {});
  15547. var color = opt.color;
  15548. var type = opt.type;
  15549. var extraCssText = opt.extraCssText;
  15550. if (!color) {
  15551. return '';
  15552. }
  15553. return type === 'subItem'
  15554. ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;'
  15555. + 'border-radius:4px;width:4px;height:4px;background-color:'
  15556. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>'
  15557. : '<span style="display:inline-block;margin-right:5px;'
  15558. + 'border-radius:10px;width:10px;height:10px;background-color:'
  15559. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  15560. }
  15561. function pad(str, len) {
  15562. str += '';
  15563. return '0000'.substr(0, len - str.length) + str;
  15564. }
  15565. /**
  15566. * ISO Date format
  15567. * @param {string} tpl
  15568. * @param {number} value
  15569. * @param {boolean} [isUTC=false] Default in local time.
  15570. * see `module:echarts/scale/Time`
  15571. * and `module:echarts/util/number#parseDate`.
  15572. * @inner
  15573. */
  15574. function formatTime(tpl, value, isUTC) {
  15575. if (tpl === 'week'
  15576. || tpl === 'month'
  15577. || tpl === 'quarter'
  15578. || tpl === 'half-year'
  15579. || tpl === 'year'
  15580. ) {
  15581. tpl = 'MM-dd\nyyyy';
  15582. }
  15583. var date = parseDate(value);
  15584. var utc = isUTC ? 'UTC' : '';
  15585. var y = date['get' + utc + 'FullYear']();
  15586. var M = date['get' + utc + 'Month']() + 1;
  15587. var d = date['get' + utc + 'Date']();
  15588. var h = date['get' + utc + 'Hours']();
  15589. var m = date['get' + utc + 'Minutes']();
  15590. var s = date['get' + utc + 'Seconds']();
  15591. var S = date['get' + utc + 'Milliseconds']();
  15592. tpl = tpl.replace('MM', pad(M, 2))
  15593. .replace('M', M)
  15594. .replace('yyyy', y)
  15595. .replace('yy', y % 100)
  15596. .replace('dd', pad(d, 2))
  15597. .replace('d', d)
  15598. .replace('hh', pad(h, 2))
  15599. .replace('h', h)
  15600. .replace('mm', pad(m, 2))
  15601. .replace('m', m)
  15602. .replace('ss', pad(s, 2))
  15603. .replace('s', s)
  15604. .replace('SSS', pad(S, 3));
  15605. return tpl;
  15606. }
  15607. /**
  15608. * Capital first
  15609. * @param {string} str
  15610. * @return {string}
  15611. */
  15612. function capitalFirst(str) {
  15613. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  15614. }
  15615. var truncateText$1 = truncateText;
  15616. var getTextRect = getBoundingRect;
  15617. var format = (Object.freeze || Object)({
  15618. addCommas: addCommas,
  15619. toCamelCase: toCamelCase,
  15620. normalizeCssArray: normalizeCssArray$1,
  15621. encodeHTML: encodeHTML,
  15622. formatTpl: formatTpl,
  15623. formatTplSimple: formatTplSimple,
  15624. getTooltipMarker: getTooltipMarker,
  15625. formatTime: formatTime,
  15626. capitalFirst: capitalFirst,
  15627. truncateText: truncateText$1,
  15628. getTextRect: getTextRect
  15629. });
  15630. // Layout helpers for each component positioning
  15631. var each$3 = each$1;
  15632. /**
  15633. * @public
  15634. */
  15635. var LOCATION_PARAMS = [
  15636. 'left', 'right', 'top', 'bottom', 'width', 'height'
  15637. ];
  15638. /**
  15639. * @public
  15640. */
  15641. var HV_NAMES = [
  15642. ['width', 'left', 'right'],
  15643. ['height', 'top', 'bottom']
  15644. ];
  15645. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  15646. var x = 0;
  15647. var y = 0;
  15648. if (maxWidth == null) {
  15649. maxWidth = Infinity;
  15650. }
  15651. if (maxHeight == null) {
  15652. maxHeight = Infinity;
  15653. }
  15654. var currentLineMaxSize = 0;
  15655. group.eachChild(function (child, idx) {
  15656. var position = child.position;
  15657. var rect = child.getBoundingRect();
  15658. var nextChild = group.childAt(idx + 1);
  15659. var nextChildRect = nextChild && nextChild.getBoundingRect();
  15660. var nextX;
  15661. var nextY;
  15662. if (orient === 'horizontal') {
  15663. var moveX = rect.width + (nextChildRect ? (-nextChildRect.x + rect.x) : 0);
  15664. nextX = x + moveX;
  15665. // Wrap when width exceeds maxWidth or meet a `newline` group
  15666. // FIXME compare before adding gap?
  15667. if (nextX > maxWidth || child.newline) {
  15668. x = 0;
  15669. nextX = moveX;
  15670. y += currentLineMaxSize + gap;
  15671. currentLineMaxSize = rect.height;
  15672. }
  15673. else {
  15674. // FIXME: consider rect.y is not `0`?
  15675. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  15676. }
  15677. }
  15678. else {
  15679. var moveY = rect.height + (nextChildRect ? (-nextChildRect.y + rect.y) : 0);
  15680. nextY = y + moveY;
  15681. // Wrap when width exceeds maxHeight or meet a `newline` group
  15682. if (nextY > maxHeight || child.newline) {
  15683. x += currentLineMaxSize + gap;
  15684. y = 0;
  15685. nextY = moveY;
  15686. currentLineMaxSize = rect.width;
  15687. }
  15688. else {
  15689. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  15690. }
  15691. }
  15692. if (child.newline) {
  15693. return;
  15694. }
  15695. position[0] = x;
  15696. position[1] = y;
  15697. orient === 'horizontal'
  15698. ? (x = nextX + gap)
  15699. : (y = nextY + gap);
  15700. });
  15701. }
  15702. /**
  15703. * VBox or HBox layouting
  15704. * @param {string} orient
  15705. * @param {module:zrender/container/Group} group
  15706. * @param {number} gap
  15707. * @param {number} [width=Infinity]
  15708. * @param {number} [height=Infinity]
  15709. */
  15710. var box = boxLayout;
  15711. /**
  15712. * VBox layouting
  15713. * @param {module:zrender/container/Group} group
  15714. * @param {number} gap
  15715. * @param {number} [width=Infinity]
  15716. * @param {number} [height=Infinity]
  15717. */
  15718. var vbox = curry(boxLayout, 'vertical');
  15719. /**
  15720. * HBox layouting
  15721. * @param {module:zrender/container/Group} group
  15722. * @param {number} gap
  15723. * @param {number} [width=Infinity]
  15724. * @param {number} [height=Infinity]
  15725. */
  15726. var hbox = curry(boxLayout, 'horizontal');
  15727. /**
  15728. * If x or x2 is not specified or 'center' 'left' 'right',
  15729. * the width would be as long as possible.
  15730. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  15731. * the height would be as long as possible.
  15732. *
  15733. * @param {Object} positionInfo
  15734. * @param {number|string} [positionInfo.x]
  15735. * @param {number|string} [positionInfo.y]
  15736. * @param {number|string} [positionInfo.x2]
  15737. * @param {number|string} [positionInfo.y2]
  15738. * @param {Object} containerRect {width, height}
  15739. * @param {string|number} margin
  15740. * @return {Object} {width, height}
  15741. */
  15742. /**
  15743. * Parse position info.
  15744. *
  15745. * @param {Object} positionInfo
  15746. * @param {number|string} [positionInfo.left]
  15747. * @param {number|string} [positionInfo.top]
  15748. * @param {number|string} [positionInfo.right]
  15749. * @param {number|string} [positionInfo.bottom]
  15750. * @param {number|string} [positionInfo.width]
  15751. * @param {number|string} [positionInfo.height]
  15752. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  15753. * @param {Object} containerRect
  15754. * @param {string|number} [margin]
  15755. *
  15756. * @return {module:zrender/core/BoundingRect}
  15757. */
  15758. function getLayoutRect(
  15759. positionInfo, containerRect, margin
  15760. ) {
  15761. margin = normalizeCssArray$1(margin || 0);
  15762. var containerWidth = containerRect.width;
  15763. var containerHeight = containerRect.height;
  15764. var left = parsePercent$1(positionInfo.left, containerWidth);
  15765. var top = parsePercent$1(positionInfo.top, containerHeight);
  15766. var right = parsePercent$1(positionInfo.right, containerWidth);
  15767. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  15768. var width = parsePercent$1(positionInfo.width, containerWidth);
  15769. var height = parsePercent$1(positionInfo.height, containerHeight);
  15770. var verticalMargin = margin[2] + margin[0];
  15771. var horizontalMargin = margin[1] + margin[3];
  15772. var aspect = positionInfo.aspect;
  15773. // If width is not specified, calculate width from left and right
  15774. if (isNaN(width)) {
  15775. width = containerWidth - right - horizontalMargin - left;
  15776. }
  15777. if (isNaN(height)) {
  15778. height = containerHeight - bottom - verticalMargin - top;
  15779. }
  15780. if (aspect != null) {
  15781. // If width and height are not given
  15782. // 1. Graph should not exceeds the container
  15783. // 2. Aspect must be keeped
  15784. // 3. Graph should take the space as more as possible
  15785. // FIXME
  15786. // Margin is not considered, because there is no case that both
  15787. // using margin and aspect so far.
  15788. if (isNaN(width) && isNaN(height)) {
  15789. if (aspect > containerWidth / containerHeight) {
  15790. width = containerWidth * 0.8;
  15791. }
  15792. else {
  15793. height = containerHeight * 0.8;
  15794. }
  15795. }
  15796. // Calculate width or height with given aspect
  15797. if (isNaN(width)) {
  15798. width = aspect * height;
  15799. }
  15800. if (isNaN(height)) {
  15801. height = width / aspect;
  15802. }
  15803. }
  15804. // If left is not specified, calculate left from right and width
  15805. if (isNaN(left)) {
  15806. left = containerWidth - right - width - horizontalMargin;
  15807. }
  15808. if (isNaN(top)) {
  15809. top = containerHeight - bottom - height - verticalMargin;
  15810. }
  15811. // Align left and top
  15812. switch (positionInfo.left || positionInfo.right) {
  15813. case 'center':
  15814. left = containerWidth / 2 - width / 2 - margin[3];
  15815. break;
  15816. case 'right':
  15817. left = containerWidth - width - horizontalMargin;
  15818. break;
  15819. }
  15820. switch (positionInfo.top || positionInfo.bottom) {
  15821. case 'middle':
  15822. case 'center':
  15823. top = containerHeight / 2 - height / 2 - margin[0];
  15824. break;
  15825. case 'bottom':
  15826. top = containerHeight - height - verticalMargin;
  15827. break;
  15828. }
  15829. // If something is wrong and left, top, width, height are calculated as NaN
  15830. left = left || 0;
  15831. top = top || 0;
  15832. if (isNaN(width)) {
  15833. // Width may be NaN if only one value is given except width
  15834. width = containerWidth - horizontalMargin - left - (right || 0);
  15835. }
  15836. if (isNaN(height)) {
  15837. // Height may be NaN if only one value is given except height
  15838. height = containerHeight - verticalMargin - top - (bottom || 0);
  15839. }
  15840. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  15841. rect.margin = margin;
  15842. return rect;
  15843. }
  15844. /**
  15845. * Position a zr element in viewport
  15846. * Group position is specified by either
  15847. * {left, top}, {right, bottom}
  15848. * If all properties exists, right and bottom will be igonred.
  15849. *
  15850. * Logic:
  15851. * 1. Scale (against origin point in parent coord)
  15852. * 2. Rotate (against origin point in parent coord)
  15853. * 3. Traslate (with el.position by this method)
  15854. * So this method only fixes the last step 'Traslate', which does not affect
  15855. * scaling and rotating.
  15856. *
  15857. * If be called repeatly with the same input el, the same result will be gotten.
  15858. *
  15859. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  15860. * @param {Object} positionInfo
  15861. * @param {number|string} [positionInfo.left]
  15862. * @param {number|string} [positionInfo.top]
  15863. * @param {number|string} [positionInfo.right]
  15864. * @param {number|string} [positionInfo.bottom]
  15865. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  15866. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  15867. * @param {Object} containerRect
  15868. * @param {string|number} margin
  15869. * @param {Object} [opt]
  15870. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  15871. * @param {Array.<number>} [opt.boundingMode='all']
  15872. * Specify how to calculate boundingRect when locating.
  15873. * 'all': Position the boundingRect that is transformed and uioned
  15874. * both itself and its descendants.
  15875. * This mode simplies confine the elements in the bounding
  15876. * of their container (e.g., using 'right: 0').
  15877. * 'raw': Position the boundingRect that is not transformed and only itself.
  15878. * This mode is useful when you want a element can overflow its
  15879. * container. (Consider a rotated circle needs to be located in a corner.)
  15880. * In this mode positionInfo.width/height can only be number.
  15881. */
  15882. function positionElement(el, positionInfo, containerRect, margin, opt) {
  15883. var h = !opt || !opt.hv || opt.hv[0];
  15884. var v = !opt || !opt.hv || opt.hv[1];
  15885. var boundingMode = opt && opt.boundingMode || 'all';
  15886. if (!h && !v) {
  15887. return;
  15888. }
  15889. var rect;
  15890. if (boundingMode === 'raw') {
  15891. rect = el.type === 'group'
  15892. ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0)
  15893. : el.getBoundingRect();
  15894. }
  15895. else {
  15896. rect = el.getBoundingRect();
  15897. if (el.needLocalTransform()) {
  15898. var transform = el.getLocalTransform();
  15899. // Notice: raw rect may be inner object of el,
  15900. // which should not be modified.
  15901. rect = rect.clone();
  15902. rect.applyTransform(transform);
  15903. }
  15904. }
  15905. // The real width and height can not be specified but calculated by the given el.
  15906. positionInfo = getLayoutRect(
  15907. defaults(
  15908. {width: rect.width, height: rect.height},
  15909. positionInfo
  15910. ),
  15911. containerRect,
  15912. margin
  15913. );
  15914. // Because 'tranlate' is the last step in transform
  15915. // (see zrender/core/Transformable#getLocalTransform),
  15916. // we can just only modify el.position to get final result.
  15917. var elPos = el.position;
  15918. var dx = h ? positionInfo.x - rect.x : 0;
  15919. var dy = v ? positionInfo.y - rect.y : 0;
  15920. el.attr('position', boundingMode === 'raw' ? [dx, dy] : [elPos[0] + dx, elPos[1] + dy]);
  15921. }
  15922. /**
  15923. * @param {Object} option Contains some of the properties in HV_NAMES.
  15924. * @param {number} hvIdx 0: horizontal; 1: vertical.
  15925. */
  15926. /**
  15927. * Consider Case:
  15928. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  15929. * through setOption or media query, using normal zrUtil.merge will cause
  15930. * {right: 0} does not take effect.
  15931. *
  15932. * @example
  15933. * ComponentModel.extend({
  15934. * init: function () {
  15935. * ...
  15936. * var inputPositionParams = layout.getLayoutParams(option);
  15937. * this.mergeOption(inputPositionParams);
  15938. * },
  15939. * mergeOption: function (newOption) {
  15940. * newOption && zrUtil.merge(thisOption, newOption, true);
  15941. * layout.mergeLayoutParam(thisOption, newOption);
  15942. * }
  15943. * });
  15944. *
  15945. * @param {Object} targetOption
  15946. * @param {Object} newOption
  15947. * @param {Object|string} [opt]
  15948. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  15949. * that width (or height) should not be calculated by left and right (or top and bottom).
  15950. */
  15951. function mergeLayoutParam(targetOption, newOption, opt) {
  15952. !isObject$1(opt) && (opt = {});
  15953. var ignoreSize = opt.ignoreSize;
  15954. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  15955. var hResult = merge$$1(HV_NAMES[0], 0);
  15956. var vResult = merge$$1(HV_NAMES[1], 1);
  15957. copy(HV_NAMES[0], targetOption, hResult);
  15958. copy(HV_NAMES[1], targetOption, vResult);
  15959. function merge$$1(names, hvIdx) {
  15960. var newParams = {};
  15961. var newValueCount = 0;
  15962. var merged = {};
  15963. var mergedValueCount = 0;
  15964. var enoughParamNumber = 2;
  15965. each$3(names, function (name) {
  15966. merged[name] = targetOption[name];
  15967. });
  15968. each$3(names, function (name) {
  15969. // Consider case: newOption.width is null, which is
  15970. // set by user for removing width setting.
  15971. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  15972. hasValue(newParams, name) && newValueCount++;
  15973. hasValue(merged, name) && mergedValueCount++;
  15974. });
  15975. if (ignoreSize[hvIdx]) {
  15976. // Only one of left/right is premitted to exist.
  15977. if (hasValue(newOption, names[1])) {
  15978. merged[names[2]] = null;
  15979. }
  15980. else if (hasValue(newOption, names[2])) {
  15981. merged[names[1]] = null;
  15982. }
  15983. return merged;
  15984. }
  15985. // Case: newOption: {width: ..., right: ...},
  15986. // or targetOption: {right: ...} and newOption: {width: ...},
  15987. // There is no conflict when merged only has params count
  15988. // little than enoughParamNumber.
  15989. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  15990. return merged;
  15991. }
  15992. // Case: newOption: {width: ..., right: ...},
  15993. // Than we can make sure user only want those two, and ignore
  15994. // all origin params in targetOption.
  15995. else if (newValueCount >= enoughParamNumber) {
  15996. return newParams;
  15997. }
  15998. else {
  15999. // Chose another param from targetOption by priority.
  16000. for (var i = 0; i < names.length; i++) {
  16001. var name = names[i];
  16002. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  16003. newParams[name] = targetOption[name];
  16004. break;
  16005. }
  16006. }
  16007. return newParams;
  16008. }
  16009. }
  16010. function hasProp(obj, name) {
  16011. return obj.hasOwnProperty(name);
  16012. }
  16013. function hasValue(obj, name) {
  16014. return obj[name] != null && obj[name] !== 'auto';
  16015. }
  16016. function copy(names, target, source) {
  16017. each$3(names, function (name) {
  16018. target[name] = source[name];
  16019. });
  16020. }
  16021. }
  16022. /**
  16023. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16024. * @param {Object} source
  16025. * @return {Object} Result contains those props.
  16026. */
  16027. function getLayoutParams(source) {
  16028. return copyLayoutParams({}, source);
  16029. }
  16030. /**
  16031. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16032. * @param {Object} source
  16033. * @return {Object} Result contains those props.
  16034. */
  16035. function copyLayoutParams(target, source) {
  16036. source && target && each$3(LOCATION_PARAMS, function (name) {
  16037. source.hasOwnProperty(name) && (target[name] = source[name]);
  16038. });
  16039. return target;
  16040. }
  16041. var boxLayoutMixin = {
  16042. getBoxLayoutParams: function () {
  16043. return {
  16044. left: this.get('left'),
  16045. top: this.get('top'),
  16046. right: this.get('right'),
  16047. bottom: this.get('bottom'),
  16048. width: this.get('width'),
  16049. height: this.get('height')
  16050. };
  16051. }
  16052. };
  16053. /**
  16054. * Component model
  16055. *
  16056. * @module echarts/model/Component
  16057. */
  16058. var inner$1 = makeInner();
  16059. /**
  16060. * @alias module:echarts/model/Component
  16061. * @constructor
  16062. * @param {Object} option
  16063. * @param {module:echarts/model/Model} parentModel
  16064. * @param {module:echarts/model/Model} ecModel
  16065. */
  16066. var ComponentModel = Model.extend({
  16067. type: 'component',
  16068. /**
  16069. * @readOnly
  16070. * @type {string}
  16071. */
  16072. id: '',
  16073. /**
  16074. * Because simplified concept is probably better, series.name (or component.name)
  16075. * has been having too many resposibilities:
  16076. * (1) Generating id (which requires name in option should not be modified).
  16077. * (2) As an index to mapping series when merging option or calling API (a name
  16078. * can refer to more then one components, which is convinient is some case).
  16079. * (3) Display.
  16080. * @readOnly
  16081. */
  16082. name: '',
  16083. /**
  16084. * @readOnly
  16085. * @type {string}
  16086. */
  16087. mainType: '',
  16088. /**
  16089. * @readOnly
  16090. * @type {string}
  16091. */
  16092. subType: '',
  16093. /**
  16094. * @readOnly
  16095. * @type {number}
  16096. */
  16097. componentIndex: 0,
  16098. /**
  16099. * @type {Object}
  16100. * @protected
  16101. */
  16102. defaultOption: null,
  16103. /**
  16104. * @type {module:echarts/model/Global}
  16105. * @readOnly
  16106. */
  16107. ecModel: null,
  16108. /**
  16109. * key: componentType
  16110. * value: Component model list, can not be null.
  16111. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  16112. * @readOnly
  16113. */
  16114. dependentModels: [],
  16115. /**
  16116. * @type {string}
  16117. * @readOnly
  16118. */
  16119. uid: null,
  16120. /**
  16121. * Support merge layout params.
  16122. * Only support 'box' now (left/right/top/bottom/width/height).
  16123. * @type {string|Object} Object can be {ignoreSize: true}
  16124. * @readOnly
  16125. */
  16126. layoutMode: null,
  16127. $constructor: function (option, parentModel, ecModel, extraOpt) {
  16128. Model.call(this, option, parentModel, ecModel, extraOpt);
  16129. this.uid = getUID('ec_cpt_model');
  16130. },
  16131. init: function (option, parentModel, ecModel, extraOpt) {
  16132. this.mergeDefaultAndTheme(option, ecModel);
  16133. },
  16134. mergeDefaultAndTheme: function (option, ecModel) {
  16135. var layoutMode = this.layoutMode;
  16136. var inputPositionParams = layoutMode
  16137. ? getLayoutParams(option) : {};
  16138. var themeModel = ecModel.getTheme();
  16139. merge(option, themeModel.get(this.mainType));
  16140. merge(option, this.getDefaultOption());
  16141. if (layoutMode) {
  16142. mergeLayoutParam(option, inputPositionParams, layoutMode);
  16143. }
  16144. },
  16145. mergeOption: function (option, extraOpt) {
  16146. merge(this.option, option, true);
  16147. var layoutMode = this.layoutMode;
  16148. if (layoutMode) {
  16149. mergeLayoutParam(this.option, option, layoutMode);
  16150. }
  16151. },
  16152. // Hooker after init or mergeOption
  16153. optionUpdated: function (newCptOption, isInit) {},
  16154. getDefaultOption: function () {
  16155. var fields = inner$1(this);
  16156. if (!fields.defaultOption) {
  16157. var optList = [];
  16158. var Class = this.constructor;
  16159. while (Class) {
  16160. var opt = Class.prototype.defaultOption;
  16161. opt && optList.push(opt);
  16162. Class = Class.superClass;
  16163. }
  16164. var defaultOption = {};
  16165. for (var i = optList.length - 1; i >= 0; i--) {
  16166. defaultOption = merge(defaultOption, optList[i], true);
  16167. }
  16168. fields.defaultOption = defaultOption;
  16169. }
  16170. return fields.defaultOption;
  16171. },
  16172. getReferringComponents: function (mainType) {
  16173. return this.ecModel.queryComponents({
  16174. mainType: mainType,
  16175. index: this.get(mainType + 'Index', true),
  16176. id: this.get(mainType + 'Id', true)
  16177. });
  16178. }
  16179. });
  16180. // Reset ComponentModel.extend, add preConstruct.
  16181. // clazzUtil.enableClassExtend(
  16182. // ComponentModel,
  16183. // function (option, parentModel, ecModel, extraOpt) {
  16184. // // Set dependentModels, componentIndex, name, id, mainType, subType.
  16185. // zrUtil.extend(this, extraOpt);
  16186. // this.uid = componentUtil.getUID('componentModel');
  16187. // // this.setReadOnly([
  16188. // // 'type', 'id', 'uid', 'name', 'mainType', 'subType',
  16189. // // 'dependentModels', 'componentIndex'
  16190. // // ]);
  16191. // }
  16192. // );
  16193. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  16194. enableClassManagement(
  16195. ComponentModel, {registerWhenExtend: true}
  16196. );
  16197. enableSubTypeDefaulter(ComponentModel);
  16198. // Add capability of ComponentModel.topologicalTravel.
  16199. enableTopologicalTravel(ComponentModel, getDependencies);
  16200. function getDependencies(componentType) {
  16201. var deps = [];
  16202. each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) {
  16203. deps = deps.concat(Clazz.prototype.dependencies || []);
  16204. });
  16205. // Ensure main type.
  16206. deps = map(deps, function (type) {
  16207. return parseClassType$1(type).main;
  16208. });
  16209. // Hack dataset for convenience.
  16210. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  16211. deps.unshift('dataset');
  16212. }
  16213. return deps;
  16214. }
  16215. mixin(ComponentModel, boxLayoutMixin);
  16216. var platform = '';
  16217. // Navigator not exists in node
  16218. if (typeof navigator !== 'undefined') {
  16219. platform = navigator.platform || '';
  16220. }
  16221. var globalDefault = {
  16222. // backgroundColor: 'rgba(0,0,0,0)',
  16223. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  16224. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  16225. // Light colors:
  16226. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  16227. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  16228. // Dark colors:
  16229. color: ['#c23531','#2f4554', '#61a0a8', '#d48265', '#91c7ae','#749f83', '#ca8622', '#bda29a','#6e7074', '#546570', '#c4ccd3'],
  16230. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  16231. // If xAxis and yAxis declared, grid is created by default.
  16232. // grid: {},
  16233. textStyle: {
  16234. // color: '#000',
  16235. // decoration: 'none',
  16236. // PENDING
  16237. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  16238. // fontFamily: 'Arial, Verdana, sans-serif',
  16239. fontSize: 12,
  16240. fontStyle: 'normal',
  16241. fontWeight: 'normal'
  16242. },
  16243. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  16244. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  16245. // Default is source-over
  16246. blendMode: null,
  16247. animation: 'auto',
  16248. animationDuration: 1000,
  16249. animationDurationUpdate: 300,
  16250. animationEasing: 'exponentialOut',
  16251. animationEasingUpdate: 'cubicOut',
  16252. animationThreshold: 2000,
  16253. // Configuration for progressive/incremental rendering
  16254. progressiveThreshold: 3000,
  16255. progressive: 400,
  16256. // Threshold of if use single hover layer to optimize.
  16257. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  16258. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  16259. // which is unexpected.
  16260. // see example <echarts/test/heatmap-large.html>.
  16261. hoverLayerThreshold: 3000,
  16262. // See: module:echarts/scale/Time
  16263. useUTC: false
  16264. };
  16265. var inner$2 = makeInner();
  16266. function getNearestColorPalette(colors, requestColorNum) {
  16267. var paletteNum = colors.length;
  16268. // TODO colors must be in order
  16269. for (var i = 0; i < paletteNum; i++) {
  16270. if (colors[i].length > requestColorNum) {
  16271. return colors[i];
  16272. }
  16273. }
  16274. return colors[paletteNum - 1];
  16275. }
  16276. var colorPaletteMixin = {
  16277. clearColorPalette: function () {
  16278. inner$2(this).colorIdx = 0;
  16279. inner$2(this).colorNameMap = {};
  16280. },
  16281. /**
  16282. * @param {string} name MUST NOT be null/undefined. Otherwise call this function
  16283. * twise with the same parameters will get different result.
  16284. * @param {Object} [scope=this]
  16285. * @param {Object} [requestColorNum]
  16286. * @return {string} color string.
  16287. */
  16288. getColorFromPalette: function (name, scope, requestColorNum) {
  16289. scope = scope || this;
  16290. var scopeFields = inner$2(scope);
  16291. var colorIdx = scopeFields.colorIdx || 0;
  16292. var colorNameMap = scopeFields.colorNameMap = scopeFields.colorNameMap || {};
  16293. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  16294. if (colorNameMap.hasOwnProperty(name)) {
  16295. return colorNameMap[name];
  16296. }
  16297. var defaultColorPalette = normalizeToArray(this.get('color', true));
  16298. var layeredColorPalette = this.get('colorLayer', true);
  16299. var colorPalette = ((requestColorNum == null || !layeredColorPalette)
  16300. ? defaultColorPalette : getNearestColorPalette(layeredColorPalette, requestColorNum));
  16301. // In case can't find in layered color palette.
  16302. colorPalette = colorPalette || defaultColorPalette;
  16303. if (!colorPalette || !colorPalette.length) {
  16304. return;
  16305. }
  16306. var color = colorPalette[colorIdx];
  16307. if (name) {
  16308. colorNameMap[name] = color;
  16309. }
  16310. scopeFields.colorIdx = (colorIdx + 1) % colorPalette.length;
  16311. return color;
  16312. }
  16313. };
  16314. /**
  16315. * Helper for model references.
  16316. * There are many manners to refer axis/coordSys.
  16317. */
  16318. // TODO
  16319. // merge relevant logic to this file?
  16320. // check: "modelHelper" of tooltip and "BrushTargetManager".
  16321. /**
  16322. * @return {Object} For example:
  16323. * {
  16324. * coordSysName: 'cartesian2d',
  16325. * coordSysDims: ['x', 'y', ...],
  16326. * axisMap: HashMap({
  16327. * x: xAxisModel,
  16328. * y: yAxisModel
  16329. * }),
  16330. * categoryAxisMap: HashMap({
  16331. * x: xAxisModel,
  16332. * y: undefined
  16333. * }),
  16334. * // It also indicate that whether there is category axis.
  16335. * firstCategoryDimIndex: 1,
  16336. * // To replace user specified encode.
  16337. * }
  16338. */
  16339. function getCoordSysDefineBySeries(seriesModel) {
  16340. var coordSysName = seriesModel.get('coordinateSystem');
  16341. var result = {
  16342. coordSysName: coordSysName,
  16343. coordSysDims: [],
  16344. axisMap: createHashMap(),
  16345. categoryAxisMap: createHashMap()
  16346. };
  16347. var fetch = fetchers[coordSysName];
  16348. if (fetch) {
  16349. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  16350. return result;
  16351. }
  16352. }
  16353. var fetchers = {
  16354. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  16355. var xAxisModel = seriesModel.getReferringComponents('xAxis')[0];
  16356. var yAxisModel = seriesModel.getReferringComponents('yAxis')[0];
  16357. if (__DEV__) {
  16358. if (!xAxisModel) {
  16359. throw new Error('xAxis "' + retrieve(
  16360. seriesModel.get('xAxisIndex'),
  16361. seriesModel.get('xAxisId'),
  16362. 0
  16363. ) + '" not found');
  16364. }
  16365. if (!yAxisModel) {
  16366. throw new Error('yAxis "' + retrieve(
  16367. seriesModel.get('xAxisIndex'),
  16368. seriesModel.get('yAxisId'),
  16369. 0
  16370. ) + '" not found');
  16371. }
  16372. }
  16373. result.coordSysDims = ['x', 'y'];
  16374. axisMap.set('x', xAxisModel);
  16375. axisMap.set('y', yAxisModel);
  16376. if (isCategory(xAxisModel)) {
  16377. categoryAxisMap.set('x', xAxisModel);
  16378. result.firstCategoryDimIndex = 0;
  16379. }
  16380. if (isCategory(yAxisModel)) {
  16381. categoryAxisMap.set('y', yAxisModel);
  16382. result.firstCategoryDimIndex = 1;
  16383. }
  16384. },
  16385. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  16386. var singleAxisModel = seriesModel.getReferringComponents('singleAxis')[0];
  16387. if (__DEV__) {
  16388. if (!singleAxisModel) {
  16389. throw new Error('singleAxis should be specified.');
  16390. }
  16391. }
  16392. result.coordSysDims = ['single'];
  16393. axisMap.set('single', singleAxisModel);
  16394. if (isCategory(singleAxisModel)) {
  16395. categoryAxisMap.set('single', singleAxisModel);
  16396. result.firstCategoryDimIndex = 0;
  16397. }
  16398. },
  16399. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  16400. var polarModel = seriesModel.getReferringComponents('polar')[0];
  16401. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  16402. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  16403. if (__DEV__) {
  16404. if (!angleAxisModel) {
  16405. throw new Error('angleAxis option not found');
  16406. }
  16407. if (!radiusAxisModel) {
  16408. throw new Error('radiusAxis option not found');
  16409. }
  16410. }
  16411. result.coordSysDims = ['radius', 'angle'];
  16412. axisMap.set('radius', radiusAxisModel);
  16413. axisMap.set('angle', angleAxisModel);
  16414. if (isCategory(radiusAxisModel)) {
  16415. categoryAxisMap.set('radius', radiusAxisModel);
  16416. result.firstCategoryDimIndex = 0;
  16417. }
  16418. if (isCategory(angleAxisModel)) {
  16419. categoryAxisMap.set('angle', angleAxisModel);
  16420. result.firstCategoryDimIndex = 1;
  16421. }
  16422. },
  16423. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  16424. result.coordSysDims = ['lng', 'lat'];
  16425. },
  16426. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  16427. var ecModel = seriesModel.ecModel;
  16428. var parallelModel = ecModel.getComponent(
  16429. 'parallel', seriesModel.get('parallelIndex')
  16430. );
  16431. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  16432. each$1(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  16433. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  16434. var axisDim = coordSysDims[index];
  16435. axisMap.set(axisDim, axisModel);
  16436. if (isCategory(axisModel) && result.firstCategoryDimIndex == null) {
  16437. categoryAxisMap.set(axisDim, axisModel);
  16438. result.firstCategoryDimIndex = index;
  16439. }
  16440. });
  16441. }
  16442. };
  16443. function isCategory(axisModel) {
  16444. return axisModel.get('type') === 'category';
  16445. }
  16446. // Avoid typo.
  16447. var SOURCE_FORMAT_ORIGINAL = 'original';
  16448. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  16449. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  16450. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  16451. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  16452. // ??? CHANGE A NAME
  16453. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  16454. var SERIES_LAYOUT_BY_COLUMN = 'column';
  16455. var SERIES_LAYOUT_BY_ROW = 'row';
  16456. /**
  16457. * [sourceFormat]
  16458. *
  16459. * + "original":
  16460. * This format is only used in series.data, where
  16461. * itemStyle can be specified in data item.
  16462. *
  16463. * + "arrayRows":
  16464. * [
  16465. * ['product', 'score', 'amount'],
  16466. * ['Matcha Latte', 89.3, 95.8],
  16467. * ['Milk Tea', 92.1, 89.4],
  16468. * ['Cheese Cocoa', 94.4, 91.2],
  16469. * ['Walnut Brownie', 85.4, 76.9]
  16470. * ]
  16471. *
  16472. * + "objectRows":
  16473. * [
  16474. * {product: 'Matcha Latte', score: 89.3, amount: 95.8},
  16475. * {product: 'Milk Tea', score: 92.1, amount: 89.4},
  16476. * {product: 'Cheese Cocoa', score: 94.4, amount: 91.2},
  16477. * {product: 'Walnut Brownie', score: 85.4, amount: 76.9}
  16478. * ]
  16479. *
  16480. * + "keyedColumns":
  16481. * {
  16482. * 'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
  16483. * 'count': [823, 235, 1042, 988],
  16484. * 'score': [95.8, 81.4, 91.2, 76.9]
  16485. * }
  16486. *
  16487. * + "typedArray"
  16488. *
  16489. * + "unknown"
  16490. */
  16491. /**
  16492. * @constructor
  16493. * @param {Object} fields
  16494. * @param {string} fields.sourceFormat
  16495. * @param {Array|Object} fields.fromDataset
  16496. * @param {Array|Object} [fields.data]
  16497. * @param {string} [seriesLayoutBy='column']
  16498. * @param {Array.<Object|string>} [dimensionsDefine]
  16499. * @param {Objet|HashMap} [encodeDefine]
  16500. * @param {number} [startIndex=0]
  16501. * @param {number} [dimensionsDetectCount]
  16502. */
  16503. function Source(fields) {
  16504. /**
  16505. * @type {boolean}
  16506. */
  16507. this.fromDataset = fields.fromDataset;
  16508. /**
  16509. * Not null/undefined.
  16510. * @type {Array|Object}
  16511. */
  16512. this.data = fields.data || (
  16513. fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []
  16514. );
  16515. /**
  16516. * See also "detectSourceFormat".
  16517. * Not null/undefined.
  16518. * @type {string}
  16519. */
  16520. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  16521. /**
  16522. * 'row' or 'column'
  16523. * Not null/undefined.
  16524. * @type {string} seriesLayoutBy
  16525. */
  16526. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  16527. /**
  16528. * dimensions definition in option.
  16529. * can be null/undefined.
  16530. * @type {Array.<Object|string>}
  16531. */
  16532. this.dimensionsDefine = fields.dimensionsDefine;
  16533. /**
  16534. * encode definition in option.
  16535. * can be null/undefined.
  16536. * @type {Objet|HashMap}
  16537. */
  16538. this.encodeDefine = fields.encodeDefine && createHashMap(fields.encodeDefine);
  16539. /**
  16540. * Not null/undefined, uint.
  16541. * @type {number}
  16542. */
  16543. this.startIndex = fields.startIndex || 0;
  16544. /**
  16545. * Can be null/undefined (when unknown), uint.
  16546. * @type {number}
  16547. */
  16548. this.dimensionsDetectCount = fields.dimensionsDetectCount;
  16549. }
  16550. /**
  16551. * Wrap original series data for some compatibility cases.
  16552. */
  16553. Source.seriesDataToSource = function (data) {
  16554. return new Source({
  16555. data: data,
  16556. sourceFormat: isTypedArray(data)
  16557. ? SOURCE_FORMAT_TYPED_ARRAY
  16558. : SOURCE_FORMAT_ORIGINAL,
  16559. fromDataset: false
  16560. });
  16561. };
  16562. enableClassCheck(Source);
  16563. var inner$3 = makeInner();
  16564. /**
  16565. * @see {module:echarts/data/Source}
  16566. * @param {module:echarts/component/dataset/DatasetModel} datasetModel
  16567. * @return {string} sourceFormat
  16568. */
  16569. function detectSourceFormat(datasetModel) {
  16570. var data = datasetModel.option.source;
  16571. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  16572. if (isTypedArray(data)) {
  16573. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  16574. }
  16575. else if (isArray(data)) {
  16576. // FIXME Whether tolerate null in top level array?
  16577. for (var i = 0, len = data.length; i < len; i++) {
  16578. var item = data[i];
  16579. if (item == null) {
  16580. continue;
  16581. }
  16582. else if (isArray(item)) {
  16583. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  16584. break;
  16585. }
  16586. else if (isObject$1(item)) {
  16587. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  16588. break;
  16589. }
  16590. }
  16591. }
  16592. else if (isObject$1(data)) {
  16593. for (var key in data) {
  16594. if (data.hasOwnProperty(key) && isArrayLike(data[key])) {
  16595. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  16596. break;
  16597. }
  16598. }
  16599. }
  16600. else if (data != null) {
  16601. throw new Error('Invalid data');
  16602. }
  16603. inner$3(datasetModel).sourceFormat = sourceFormat;
  16604. }
  16605. /**
  16606. * [Scenarios]:
  16607. * (1) Provide source data directly:
  16608. * series: {
  16609. * encode: {...},
  16610. * dimensions: [...]
  16611. * seriesLayoutBy: 'row',
  16612. * data: [[...]]
  16613. * }
  16614. * (2) Refer to datasetModel.
  16615. * series: [{
  16616. * encode: {...}
  16617. * // Ignore datasetIndex means `datasetIndex: 0`
  16618. * // and the dimensions defination in dataset is used
  16619. * }, {
  16620. * encode: {...},
  16621. * seriesLayoutBy: 'column',
  16622. * datasetIndex: 1
  16623. * }]
  16624. *
  16625. * Get data from series itself or datset.
  16626. * @return {module:echarts/data/Source} source
  16627. */
  16628. function getSource(seriesModel) {
  16629. return inner$3(seriesModel).source;
  16630. }
  16631. /**
  16632. * MUST be called before mergeOption of all series.
  16633. * @param {module:echarts/model/Global} ecModel
  16634. */
  16635. function resetSourceDefaulter(ecModel) {
  16636. // `datasetMap` is used to make default encode.
  16637. inner$3(ecModel).datasetMap = createHashMap();
  16638. }
  16639. /**
  16640. * [Caution]:
  16641. * MUST be called after series option merged and
  16642. * before "series.getInitailData()" called.
  16643. *
  16644. * [The rule of making default encode]:
  16645. * Category axis (if exists) alway map to the first dimension.
  16646. * Each other axis occupies a subsequent dimension.
  16647. *
  16648. * [Why make default encode]:
  16649. * Simplify the typing of encode in option, avoiding the case like that:
  16650. * series: [{encode: {x: 0, y: 1}}, {encode: {x: 0, y: 2}}, {encode: {x: 0, y: 3}}],
  16651. * where the "y" have to be manually typed as "1, 2, 3, ...".
  16652. *
  16653. * @param {module:echarts/model/Series} seriesModel
  16654. */
  16655. function prepareSource(seriesModel) {
  16656. var seriesOption = seriesModel.option;
  16657. var data = seriesOption.data;
  16658. var sourceFormat = isTypedArray(data)
  16659. ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  16660. var fromDataset = false;
  16661. var seriesLayoutBy = seriesOption.seriesLayoutBy;
  16662. var sourceHeader = seriesOption.sourceHeader;
  16663. var dimensionsDefine = seriesOption.dimensions;
  16664. var datasetModel = getDatasetModel(seriesModel);
  16665. if (datasetModel) {
  16666. var datasetOption = datasetModel.option;
  16667. data = datasetOption.source;
  16668. sourceFormat = inner$3(datasetModel).sourceFormat;
  16669. fromDataset = true;
  16670. // These settings from series has higher priority.
  16671. seriesLayoutBy = seriesLayoutBy || datasetOption.seriesLayoutBy;
  16672. sourceHeader == null && (sourceHeader = datasetOption.sourceHeader);
  16673. dimensionsDefine = dimensionsDefine || datasetOption.dimensions;
  16674. }
  16675. var completeResult = completeBySourceData(
  16676. data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine
  16677. );
  16678. // Note: dataset option does not have `encode`.
  16679. var encodeDefine = seriesOption.encode;
  16680. if (!encodeDefine && datasetModel) {
  16681. encodeDefine = makeDefaultEncode(
  16682. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  16683. );
  16684. }
  16685. inner$3(seriesModel).source = new Source({
  16686. data: data,
  16687. fromDataset: fromDataset,
  16688. seriesLayoutBy: seriesLayoutBy,
  16689. sourceFormat: sourceFormat,
  16690. dimensionsDefine: completeResult.dimensionsDefine,
  16691. startIndex: completeResult.startIndex,
  16692. dimensionsDetectCount: completeResult.dimensionsDetectCount,
  16693. encodeDefine: encodeDefine
  16694. });
  16695. }
  16696. // return {startIndex, dimensionsDefine, dimensionsCount}
  16697. function completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine) {
  16698. if (!data) {
  16699. return {dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine)};
  16700. }
  16701. var dimensionsDetectCount;
  16702. var startIndex;
  16703. var findPotentialName;
  16704. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  16705. // Rule: Most of the first line are string: it is header.
  16706. // Caution: consider a line with 5 string and 1 number,
  16707. // it still can not be sure it is a head, because the
  16708. // 5 string may be 5 values of category columns.
  16709. if (sourceHeader === 'auto' || sourceHeader == null) {
  16710. arrayRowsTravelFirst(function (val) {
  16711. // '-' is regarded as null/undefined.
  16712. if (val != null && val !== '-') {
  16713. if (isString(val)) {
  16714. startIndex == null && (startIndex = 1);
  16715. }
  16716. else {
  16717. startIndex = 0;
  16718. }
  16719. }
  16720. // 10 is an experience number, avoid long loop.
  16721. }, seriesLayoutBy, data, 10);
  16722. }
  16723. else {
  16724. startIndex = sourceHeader ? 1 : 0;
  16725. }
  16726. if (!dimensionsDefine && startIndex === 1) {
  16727. dimensionsDefine = [];
  16728. arrayRowsTravelFirst(function (val, index) {
  16729. dimensionsDefine[index] = val != null ? val : '';
  16730. }, seriesLayoutBy, data);
  16731. }
  16732. dimensionsDetectCount = dimensionsDefine
  16733. ? dimensionsDefine.length
  16734. : seriesLayoutBy === SERIES_LAYOUT_BY_ROW
  16735. ? data.length
  16736. : data[0]
  16737. ? data[0].length
  16738. : null;
  16739. }
  16740. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  16741. if (!dimensionsDefine) {
  16742. dimensionsDefine = objectRowsCollectDimensions(data);
  16743. findPotentialName = true;
  16744. }
  16745. }
  16746. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  16747. if (!dimensionsDefine) {
  16748. dimensionsDefine = [];
  16749. findPotentialName = true;
  16750. each$1(data, function (colArr, key) {
  16751. dimensionsDefine.push(key);
  16752. });
  16753. }
  16754. }
  16755. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  16756. var value0 = getDataItemValue(data[0]);
  16757. dimensionsDetectCount = isArray(value0) && value0.length || 1;
  16758. }
  16759. else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  16760. if (__DEV__) {
  16761. assert$1(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  16762. }
  16763. }
  16764. var potentialNameDimIndex;
  16765. if (findPotentialName) {
  16766. each$1(dimensionsDefine, function (dim, idx) {
  16767. if ((isObject$1(dim) ? dim.name : dim) === 'name') {
  16768. potentialNameDimIndex = idx;
  16769. }
  16770. });
  16771. }
  16772. return {
  16773. startIndex: startIndex,
  16774. dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine),
  16775. dimensionsDetectCount: dimensionsDetectCount,
  16776. potentialNameDimIndex: potentialNameDimIndex
  16777. // TODO: potentialIdDimIdx
  16778. };
  16779. }
  16780. // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  16781. // which is reasonable. But dimension name is duplicated.
  16782. // Returns undefined or an array contains only object without null/undefiend or string.
  16783. function normalizeDimensionsDefine(dimensionsDefine) {
  16784. if (!dimensionsDefine) {
  16785. // The meaning of null/undefined is different from empty array.
  16786. return;
  16787. }
  16788. var nameMap = createHashMap();
  16789. return map(dimensionsDefine, function (item, index) {
  16790. item = extend({}, isObject$1(item) ? item : {name: item});
  16791. // User can set null in dimensions.
  16792. // We dont auto specify name, othewise a given name may
  16793. // cause it be refered unexpectedly.
  16794. if (item.name == null) {
  16795. return item;
  16796. }
  16797. // Also consider number form like 2012.
  16798. item.name += '';
  16799. // User may also specify displayName.
  16800. // displayName will always exists except user not
  16801. // specified or dim name is not specified or detected.
  16802. // (A auto generated dim name will not be used as
  16803. // displayName).
  16804. if (item.displayName == null) {
  16805. item.displayName = item.name;
  16806. }
  16807. var exist = nameMap.get(item.name);
  16808. if (!exist) {
  16809. nameMap.set(item.name, {count: 1});
  16810. }
  16811. else {
  16812. item.name += '-' + exist.count++;
  16813. }
  16814. return item;
  16815. });
  16816. }
  16817. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  16818. maxLoop == null && (maxLoop = Infinity);
  16819. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  16820. for (var i = 0; i < data.length && i < maxLoop; i++) {
  16821. cb(data[i] ? data[i][0] : null, i);
  16822. }
  16823. }
  16824. else {
  16825. var value0 = data[0] || [];
  16826. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  16827. cb(value0[i], i);
  16828. }
  16829. }
  16830. }
  16831. function objectRowsCollectDimensions(data) {
  16832. var firstIndex = 0;
  16833. var obj;
  16834. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  16835. if (obj) {
  16836. var dimensions = [];
  16837. each$1(obj, function (value, key) {
  16838. dimensions.push(key);
  16839. });
  16840. return dimensions;
  16841. }
  16842. }
  16843. // ??? TODO merge to completedimensions, where also has
  16844. // default encode making logic. And the default rule
  16845. // should depends on series? consider 'map'.
  16846. function makeDefaultEncode(
  16847. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  16848. ) {
  16849. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  16850. var encode = {};
  16851. // var encodeTooltip = [];
  16852. // var encodeLabel = [];
  16853. var encodeItemName = [];
  16854. var encodeSeriesName = [];
  16855. var seriesType = seriesModel.subType;
  16856. // ??? TODO refactor: provide by series itself.
  16857. // Consider the case: 'map' series is based on geo coordSys,
  16858. // 'graph', 'heatmap' can be based on cartesian. But can not
  16859. // give default rule simply here.
  16860. var nSeriesMap = createHashMap(['pie', 'map', 'funnel']);
  16861. var cSeriesMap = createHashMap([
  16862. 'line', 'bar', 'pictorialBar', 'scatter', 'effectScatter', 'candlestick', 'boxplot'
  16863. ]);
  16864. // Usually in this case series will use the first data
  16865. // dimension as the "value" dimension, or other default
  16866. // processes respectively.
  16867. if (coordSysDefine && cSeriesMap.get(seriesType) != null) {
  16868. var ecModel = seriesModel.ecModel;
  16869. var datasetMap = inner$3(ecModel).datasetMap;
  16870. var key = datasetModel.uid + '_' + seriesLayoutBy;
  16871. var datasetRecord = datasetMap.get(key)
  16872. || datasetMap.set(key, {categoryWayDim: 1, valueWayDim: 0});
  16873. // TODO
  16874. // Auto detect first time axis and do arrangement.
  16875. each$1(coordSysDefine.coordSysDims, function (coordDim) {
  16876. // In value way.
  16877. if (coordSysDefine.firstCategoryDimIndex == null) {
  16878. var dataDim = datasetRecord.valueWayDim++;
  16879. encode[coordDim] = dataDim;
  16880. // ??? TODO give a better default series name rule?
  16881. // especially when encode x y specified.
  16882. // consider: when mutiple series share one dimension
  16883. // category axis, series name should better use
  16884. // the other dimsion name. On the other hand, use
  16885. // both dimensions name.
  16886. encodeSeriesName.push(dataDim);
  16887. // encodeTooltip.push(dataDim);
  16888. // encodeLabel.push(dataDim);
  16889. }
  16890. // In category way, category axis.
  16891. else if (coordSysDefine.categoryAxisMap.get(coordDim)) {
  16892. encode[coordDim] = 0;
  16893. encodeItemName.push(0);
  16894. }
  16895. // In category way, non-category axis.
  16896. else {
  16897. var dataDim = datasetRecord.categoryWayDim++;
  16898. encode[coordDim] = dataDim;
  16899. // encodeTooltip.push(dataDim);
  16900. // encodeLabel.push(dataDim);
  16901. encodeSeriesName.push(dataDim);
  16902. }
  16903. });
  16904. }
  16905. // Do not make a complex rule! Hard to code maintain and not necessary.
  16906. // ??? TODO refactor: provide by series itself.
  16907. // [{name: ..., value: ...}, ...] like:
  16908. else if (nSeriesMap.get(seriesType) != null) {
  16909. // Find the first not ordinal. (5 is an experience value)
  16910. var firstNotOrdinal;
  16911. for (var i = 0; i < 5 && firstNotOrdinal == null; i++) {
  16912. if (!doGuessOrdinal(
  16913. data, sourceFormat, seriesLayoutBy,
  16914. completeResult.dimensionsDefine, completeResult.startIndex, i
  16915. )) {
  16916. firstNotOrdinal = i;
  16917. }
  16918. }
  16919. if (firstNotOrdinal != null) {
  16920. encode.value = firstNotOrdinal;
  16921. var nameDimIndex = completeResult.potentialNameDimIndex
  16922. || Math.max(firstNotOrdinal - 1, 0);
  16923. // By default, label use itemName in charts.
  16924. // So we dont set encodeLabel here.
  16925. encodeSeriesName.push(nameDimIndex);
  16926. encodeItemName.push(nameDimIndex);
  16927. // encodeTooltip.push(firstNotOrdinal);
  16928. }
  16929. }
  16930. // encodeTooltip.length && (encode.tooltip = encodeTooltip);
  16931. // encodeLabel.length && (encode.label = encodeLabel);
  16932. encodeItemName.length && (encode.itemName = encodeItemName);
  16933. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  16934. return encode;
  16935. }
  16936. /**
  16937. * If return null/undefined, indicate that should not use datasetModel.
  16938. */
  16939. function getDatasetModel(seriesModel) {
  16940. var option = seriesModel.option;
  16941. // Caution: consider the scenario:
  16942. // A dataset is declared and a series is not expected to use the dataset,
  16943. // and at the beginning `setOption({series: { noData })` (just prepare other
  16944. // option but no data), then `setOption({series: {data: [...]}); In this case,
  16945. // the user should set an empty array to avoid that dataset is used by default.
  16946. var thisData = option.data;
  16947. if (!thisData) {
  16948. return seriesModel.ecModel.getComponent('dataset', option.datasetIndex || 0);
  16949. }
  16950. }
  16951. /**
  16952. * The rule should not be complex, otherwise user might not
  16953. * be able to known where the data is wrong.
  16954. * The code is ugly, but how to make it neat?
  16955. *
  16956. * @param {module:echars/data/Source} source
  16957. * @param {number} dimIndex
  16958. * @return {boolean} Whether ordinal.
  16959. */
  16960. function guessOrdinal(source, dimIndex) {
  16961. return doGuessOrdinal(
  16962. source.data,
  16963. source.sourceFormat,
  16964. source.seriesLayoutBy,
  16965. source.dimensionsDefine,
  16966. source.startIndex,
  16967. dimIndex
  16968. );
  16969. }
  16970. // dimIndex may be overflow source data.
  16971. function doGuessOrdinal(
  16972. data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex
  16973. ) {
  16974. var result;
  16975. // Experience value.
  16976. var maxLoop = 5;
  16977. if (isTypedArray(data)) {
  16978. return false;
  16979. }
  16980. // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  16981. // always exists in source.
  16982. var dimName;
  16983. if (dimensionsDefine) {
  16984. dimName = dimensionsDefine[dimIndex];
  16985. dimName = isObject$1(dimName) ? dimName.name : dimName;
  16986. }
  16987. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  16988. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  16989. var sample = data[dimIndex];
  16990. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  16991. if ((result = detectValue(sample[startIndex + i])) != null) {
  16992. return result;
  16993. }
  16994. }
  16995. }
  16996. else {
  16997. for (var i = 0; i < data.length && i < maxLoop; i++) {
  16998. var row = data[startIndex + i];
  16999. if (row && (result = detectValue(row[dimIndex])) != null) {
  17000. return result;
  17001. }
  17002. }
  17003. }
  17004. }
  17005. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17006. if (!dimName) {
  17007. return;
  17008. }
  17009. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17010. var item = data[i];
  17011. if (item && (result = detectValue(item[dimName])) != null) {
  17012. return result;
  17013. }
  17014. }
  17015. }
  17016. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17017. if (!dimName) {
  17018. return;
  17019. }
  17020. var sample = data[dimName];
  17021. if (!sample || isTypedArray(sample)) {
  17022. return false;
  17023. }
  17024. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  17025. if ((result = detectValue(sample[i])) != null) {
  17026. return result;
  17027. }
  17028. }
  17029. }
  17030. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17031. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17032. var item = data[i];
  17033. var val = getDataItemValue(item);
  17034. if (!isArray(val)) {
  17035. return false;
  17036. }
  17037. if ((result = detectValue(val[dimIndex])) != null) {
  17038. return result;
  17039. }
  17040. }
  17041. }
  17042. function detectValue(val) {
  17043. // Consider usage convenience, '1', '2' will be treated as "number".
  17044. // `isFinit('')` get `true`.
  17045. if (val != null && isFinite(val) && val !== '') {
  17046. return false;
  17047. }
  17048. else if (isString(val) && val !== '-') {
  17049. return true;
  17050. }
  17051. }
  17052. return false;
  17053. }
  17054. /**
  17055. * ECharts global model
  17056. *
  17057. * @module {echarts/model/Global}
  17058. */
  17059. /**
  17060. * Caution: If the mechanism should be changed some day, these cases
  17061. * should be considered:
  17062. *
  17063. * (1) In `merge option` mode, if using the same option to call `setOption`
  17064. * many times, the result should be the same (try our best to ensure that).
  17065. * (2) In `merge option` mode, if a component has no id/name specified, it
  17066. * will be merged by index, and the result sequence of the components is
  17067. * consistent to the original sequence.
  17068. * (3) `reset` feature (in toolbox). Find detailed info in comments about
  17069. * `mergeOption` in module:echarts/model/OptionManager.
  17070. */
  17071. var OPTION_INNER_KEY = '\0_ec_inner';
  17072. /**
  17073. * @alias module:echarts/model/Global
  17074. *
  17075. * @param {Object} option
  17076. * @param {module:echarts/model/Model} parentModel
  17077. * @param {Object} theme
  17078. */
  17079. var GlobalModel = Model.extend({
  17080. constructor: GlobalModel,
  17081. init: function (option, parentModel, theme, optionManager) {
  17082. theme = theme || {};
  17083. this.option = null; // Mark as not initialized.
  17084. /**
  17085. * @type {module:echarts/model/Model}
  17086. * @private
  17087. */
  17088. this._theme = new Model(theme);
  17089. /**
  17090. * @type {module:echarts/model/OptionManager}
  17091. */
  17092. this._optionManager = optionManager;
  17093. },
  17094. setOption: function (option, optionPreprocessorFuncs) {
  17095. assert$1(
  17096. !(OPTION_INNER_KEY in option),
  17097. 'please use chart.getOption()'
  17098. );
  17099. this._optionManager.setOption(option, optionPreprocessorFuncs);
  17100. this.resetOption(null);
  17101. },
  17102. /**
  17103. * @param {string} type null/undefined: reset all.
  17104. * 'recreate': force recreate all.
  17105. * 'timeline': only reset timeline option
  17106. * 'media': only reset media query option
  17107. * @return {boolean} Whether option changed.
  17108. */
  17109. resetOption: function (type) {
  17110. var optionChanged = false;
  17111. var optionManager = this._optionManager;
  17112. if (!type || type === 'recreate') {
  17113. var baseOption = optionManager.mountOption(type === 'recreate');
  17114. if (!this.option || type === 'recreate') {
  17115. initBase.call(this, baseOption);
  17116. }
  17117. else {
  17118. this.restoreData();
  17119. this.mergeOption(baseOption);
  17120. }
  17121. optionChanged = true;
  17122. }
  17123. if (type === 'timeline' || type === 'media') {
  17124. this.restoreData();
  17125. }
  17126. if (!type || type === 'recreate' || type === 'timeline') {
  17127. var timelineOption = optionManager.getTimelineOption(this);
  17128. timelineOption && (this.mergeOption(timelineOption), optionChanged = true);
  17129. }
  17130. if (!type || type === 'recreate' || type === 'media') {
  17131. var mediaOptions = optionManager.getMediaOption(this, this._api);
  17132. if (mediaOptions.length) {
  17133. each$1(mediaOptions, function (mediaOption) {
  17134. this.mergeOption(mediaOption, optionChanged = true);
  17135. }, this);
  17136. }
  17137. }
  17138. return optionChanged;
  17139. },
  17140. /**
  17141. * @protected
  17142. */
  17143. mergeOption: function (newOption) {
  17144. var option = this.option;
  17145. var componentsMap = this._componentsMap;
  17146. var newCptTypes = [];
  17147. resetSourceDefaulter(this);
  17148. // If no component class, merge directly.
  17149. // For example: color, animaiton options, etc.
  17150. each$1(newOption, function (componentOption, mainType) {
  17151. if (componentOption == null) {
  17152. return;
  17153. }
  17154. if (!ComponentModel.hasClass(mainType)) {
  17155. // globalSettingTask.dirty();
  17156. option[mainType] = option[mainType] == null
  17157. ? clone(componentOption)
  17158. : merge(option[mainType], componentOption, true);
  17159. }
  17160. else if (mainType) {
  17161. newCptTypes.push(mainType);
  17162. }
  17163. });
  17164. ComponentModel.topologicalTravel(
  17165. newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this
  17166. );
  17167. function visitComponent(mainType, dependencies) {
  17168. var newCptOptionList = normalizeToArray(newOption[mainType]);
  17169. var mapResult = mappingToExists(
  17170. componentsMap.get(mainType), newCptOptionList
  17171. );
  17172. makeIdAndName(mapResult);
  17173. // Set mainType and complete subType.
  17174. each$1(mapResult, function (item, index) {
  17175. var opt = item.option;
  17176. if (isObject$1(opt)) {
  17177. item.keyInfo.mainType = mainType;
  17178. item.keyInfo.subType = determineSubType(mainType, opt, item.exist);
  17179. }
  17180. });
  17181. var dependentModels = getComponentsByTypes(
  17182. componentsMap, dependencies
  17183. );
  17184. option[mainType] = [];
  17185. componentsMap.set(mainType, []);
  17186. each$1(mapResult, function (resultItem, index) {
  17187. var componentModel = resultItem.exist;
  17188. var newCptOption = resultItem.option;
  17189. assert$1(
  17190. isObject$1(newCptOption) || componentModel,
  17191. 'Empty component definition'
  17192. );
  17193. // Consider where is no new option and should be merged using {},
  17194. // see removeEdgeAndAdd in topologicalTravel and
  17195. // ComponentModel.getAllClassMainTypes.
  17196. if (!newCptOption) {
  17197. componentModel.mergeOption({}, this);
  17198. componentModel.optionUpdated({}, false);
  17199. }
  17200. else {
  17201. var ComponentModelClass = ComponentModel.getClass(
  17202. mainType, resultItem.keyInfo.subType, true
  17203. );
  17204. if (componentModel && componentModel instanceof ComponentModelClass) {
  17205. componentModel.name = resultItem.keyInfo.name;
  17206. // componentModel.settingTask && componentModel.settingTask.dirty();
  17207. componentModel.mergeOption(newCptOption, this);
  17208. componentModel.optionUpdated(newCptOption, false);
  17209. }
  17210. else {
  17211. // PENDING Global as parent ?
  17212. var extraOpt = extend(
  17213. {
  17214. dependentModels: dependentModels,
  17215. componentIndex: index
  17216. },
  17217. resultItem.keyInfo
  17218. );
  17219. componentModel = new ComponentModelClass(
  17220. newCptOption, this, this, extraOpt
  17221. );
  17222. extend(componentModel, extraOpt);
  17223. componentModel.init(newCptOption, this, this, extraOpt);
  17224. // Call optionUpdated after init.
  17225. // newCptOption has been used as componentModel.option
  17226. // and may be merged with theme and default, so pass null
  17227. // to avoid confusion.
  17228. componentModel.optionUpdated(null, true);
  17229. }
  17230. }
  17231. componentsMap.get(mainType)[index] = componentModel;
  17232. option[mainType][index] = componentModel.option;
  17233. }, this);
  17234. // Backup series for filtering.
  17235. if (mainType === 'series') {
  17236. createSeriesIndices(this, componentsMap.get('series'));
  17237. }
  17238. }
  17239. this._seriesIndicesMap = createHashMap(
  17240. this._seriesIndices = this._seriesIndices || []
  17241. );
  17242. },
  17243. /**
  17244. * Get option for output (cloned option and inner info removed)
  17245. * @public
  17246. * @return {Object}
  17247. */
  17248. getOption: function () {
  17249. var option = clone(this.option);
  17250. each$1(option, function (opts, mainType) {
  17251. if (ComponentModel.hasClass(mainType)) {
  17252. var opts = normalizeToArray(opts);
  17253. for (var i = opts.length - 1; i >= 0; i--) {
  17254. // Remove options with inner id.
  17255. if (isIdInner(opts[i])) {
  17256. opts.splice(i, 1);
  17257. }
  17258. }
  17259. option[mainType] = opts;
  17260. }
  17261. });
  17262. delete option[OPTION_INNER_KEY];
  17263. return option;
  17264. },
  17265. /**
  17266. * @return {module:echarts/model/Model}
  17267. */
  17268. getTheme: function () {
  17269. return this._theme;
  17270. },
  17271. /**
  17272. * @param {string} mainType
  17273. * @param {number} [idx=0]
  17274. * @return {module:echarts/model/Component}
  17275. */
  17276. getComponent: function (mainType, idx) {
  17277. var list = this._componentsMap.get(mainType);
  17278. if (list) {
  17279. return list[idx || 0];
  17280. }
  17281. },
  17282. /**
  17283. * If none of index and id and name used, return all components with mainType.
  17284. * @param {Object} condition
  17285. * @param {string} condition.mainType
  17286. * @param {string} [condition.subType] If ignore, only query by mainType
  17287. * @param {number|Array.<number>} [condition.index] Either input index or id or name.
  17288. * @param {string|Array.<string>} [condition.id] Either input index or id or name.
  17289. * @param {string|Array.<string>} [condition.name] Either input index or id or name.
  17290. * @return {Array.<module:echarts/model/Component>}
  17291. */
  17292. queryComponents: function (condition) {
  17293. var mainType = condition.mainType;
  17294. if (!mainType) {
  17295. return [];
  17296. }
  17297. var index = condition.index;
  17298. var id = condition.id;
  17299. var name = condition.name;
  17300. var cpts = this._componentsMap.get(mainType);
  17301. if (!cpts || !cpts.length) {
  17302. return [];
  17303. }
  17304. var result;
  17305. if (index != null) {
  17306. if (!isArray(index)) {
  17307. index = [index];
  17308. }
  17309. result = filter(map(index, function (idx) {
  17310. return cpts[idx];
  17311. }), function (val) {
  17312. return !!val;
  17313. });
  17314. }
  17315. else if (id != null) {
  17316. var isIdArray = isArray(id);
  17317. result = filter(cpts, function (cpt) {
  17318. return (isIdArray && indexOf(id, cpt.id) >= 0)
  17319. || (!isIdArray && cpt.id === id);
  17320. });
  17321. }
  17322. else if (name != null) {
  17323. var isNameArray = isArray(name);
  17324. result = filter(cpts, function (cpt) {
  17325. return (isNameArray && indexOf(name, cpt.name) >= 0)
  17326. || (!isNameArray && cpt.name === name);
  17327. });
  17328. }
  17329. else {
  17330. // Return all components with mainType
  17331. result = cpts.slice();
  17332. }
  17333. return filterBySubType(result, condition);
  17334. },
  17335. /**
  17336. * The interface is different from queryComponents,
  17337. * which is convenient for inner usage.
  17338. *
  17339. * @usage
  17340. * var result = findComponents(
  17341. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  17342. * );
  17343. * var result = findComponents(
  17344. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  17345. * );
  17346. * var result = findComponents(
  17347. * {mainType: 'series'},
  17348. * function (model, index) {...}
  17349. * );
  17350. * // result like [component0, componnet1, ...]
  17351. *
  17352. * @param {Object} condition
  17353. * @param {string} condition.mainType Mandatory.
  17354. * @param {string} [condition.subType] Optional.
  17355. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName},
  17356. * where xxx is mainType.
  17357. * If query attribute is null/undefined or has no index/id/name,
  17358. * do not filtering by query conditions, which is convenient for
  17359. * no-payload situations or when target of action is global.
  17360. * @param {Function} [condition.filter] parameter: component, return boolean.
  17361. * @return {Array.<module:echarts/model/Component>}
  17362. */
  17363. findComponents: function (condition) {
  17364. var query = condition.query;
  17365. var mainType = condition.mainType;
  17366. var queryCond = getQueryCond(query);
  17367. var result = queryCond
  17368. ? this.queryComponents(queryCond)
  17369. : this._componentsMap.get(mainType);
  17370. return doFilter(filterBySubType(result, condition));
  17371. function getQueryCond(q) {
  17372. var indexAttr = mainType + 'Index';
  17373. var idAttr = mainType + 'Id';
  17374. var nameAttr = mainType + 'Name';
  17375. return q && (
  17376. q[indexAttr] != null
  17377. || q[idAttr] != null
  17378. || q[nameAttr] != null
  17379. )
  17380. ? {
  17381. mainType: mainType,
  17382. // subType will be filtered finally.
  17383. index: q[indexAttr],
  17384. id: q[idAttr],
  17385. name: q[nameAttr]
  17386. }
  17387. : null;
  17388. }
  17389. function doFilter(res) {
  17390. return condition.filter
  17391. ? filter(res, condition.filter)
  17392. : res;
  17393. }
  17394. },
  17395. /**
  17396. * @usage
  17397. * eachComponent('legend', function (legendModel, index) {
  17398. * ...
  17399. * });
  17400. * eachComponent(function (componentType, model, index) {
  17401. * // componentType does not include subType
  17402. * // (componentType is 'xxx' but not 'xxx.aa')
  17403. * });
  17404. * eachComponent(
  17405. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}},
  17406. * function (model, index) {...}
  17407. * );
  17408. * eachComponent(
  17409. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}},
  17410. * function (model, index) {...}
  17411. * );
  17412. *
  17413. * @param {string|Object=} mainType When mainType is object, the definition
  17414. * is the same as the method 'findComponents'.
  17415. * @param {Function} cb
  17416. * @param {*} context
  17417. */
  17418. eachComponent: function (mainType, cb, context) {
  17419. var componentsMap = this._componentsMap;
  17420. if (typeof mainType === 'function') {
  17421. context = cb;
  17422. cb = mainType;
  17423. componentsMap.each(function (components, componentType) {
  17424. each$1(components, function (component, index) {
  17425. cb.call(context, componentType, component, index);
  17426. });
  17427. });
  17428. }
  17429. else if (isString(mainType)) {
  17430. each$1(componentsMap.get(mainType), cb, context);
  17431. }
  17432. else if (isObject$1(mainType)) {
  17433. var queryResult = this.findComponents(mainType);
  17434. each$1(queryResult, cb, context);
  17435. }
  17436. },
  17437. /**
  17438. * @param {string} name
  17439. * @return {Array.<module:echarts/model/Series>}
  17440. */
  17441. getSeriesByName: function (name) {
  17442. var series = this._componentsMap.get('series');
  17443. return filter(series, function (oneSeries) {
  17444. return oneSeries.name === name;
  17445. });
  17446. },
  17447. /**
  17448. * @param {number} seriesIndex
  17449. * @return {module:echarts/model/Series}
  17450. */
  17451. getSeriesByIndex: function (seriesIndex) {
  17452. return this._componentsMap.get('series')[seriesIndex];
  17453. },
  17454. /**
  17455. * Get series list before filtered by type.
  17456. * FIXME: rename to getRawSeriesByType?
  17457. *
  17458. * @param {string} subType
  17459. * @return {Array.<module:echarts/model/Series>}
  17460. */
  17461. getSeriesByType: function (subType) {
  17462. var series = this._componentsMap.get('series');
  17463. return filter(series, function (oneSeries) {
  17464. return oneSeries.subType === subType;
  17465. });
  17466. },
  17467. /**
  17468. * @return {Array.<module:echarts/model/Series>}
  17469. */
  17470. getSeries: function () {
  17471. return this._componentsMap.get('series').slice();
  17472. },
  17473. /**
  17474. * @return {number}
  17475. */
  17476. getSeriesCount: function () {
  17477. return this._componentsMap.get('series').length;
  17478. },
  17479. /**
  17480. * After filtering, series may be different
  17481. * frome raw series.
  17482. *
  17483. * @param {Function} cb
  17484. * @param {*} context
  17485. */
  17486. eachSeries: function (cb, context) {
  17487. assertSeriesInitialized(this);
  17488. each$1(this._seriesIndices, function (rawSeriesIndex) {
  17489. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17490. cb.call(context, series, rawSeriesIndex);
  17491. }, this);
  17492. },
  17493. /**
  17494. * Iterate raw series before filtered.
  17495. *
  17496. * @param {Function} cb
  17497. * @param {*} context
  17498. */
  17499. eachRawSeries: function (cb, context) {
  17500. each$1(this._componentsMap.get('series'), cb, context);
  17501. },
  17502. /**
  17503. * After filtering, series may be different.
  17504. * frome raw series.
  17505. *
  17506. * @parma {string} subType
  17507. * @param {Function} cb
  17508. * @param {*} context
  17509. */
  17510. eachSeriesByType: function (subType, cb, context) {
  17511. assertSeriesInitialized(this);
  17512. each$1(this._seriesIndices, function (rawSeriesIndex) {
  17513. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17514. if (series.subType === subType) {
  17515. cb.call(context, series, rawSeriesIndex);
  17516. }
  17517. }, this);
  17518. },
  17519. /**
  17520. * Iterate raw series before filtered of given type.
  17521. *
  17522. * @parma {string} subType
  17523. * @param {Function} cb
  17524. * @param {*} context
  17525. */
  17526. eachRawSeriesByType: function (subType, cb, context) {
  17527. return each$1(this.getSeriesByType(subType), cb, context);
  17528. },
  17529. /**
  17530. * @param {module:echarts/model/Series} seriesModel
  17531. */
  17532. isSeriesFiltered: function (seriesModel) {
  17533. assertSeriesInitialized(this);
  17534. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  17535. },
  17536. /**
  17537. * @return {Array.<number>}
  17538. */
  17539. getCurrentSeriesIndices: function () {
  17540. return (this._seriesIndices || []).slice();
  17541. },
  17542. /**
  17543. * @param {Function} cb
  17544. * @param {*} context
  17545. */
  17546. filterSeries: function (cb, context) {
  17547. assertSeriesInitialized(this);
  17548. var filteredSeries = filter(
  17549. this._componentsMap.get('series'), cb, context
  17550. );
  17551. createSeriesIndices(this, filteredSeries);
  17552. },
  17553. restoreData: function (payload) {
  17554. var componentsMap = this._componentsMap;
  17555. createSeriesIndices(this, componentsMap.get('series'));
  17556. var componentTypes = [];
  17557. componentsMap.each(function (components, componentType) {
  17558. componentTypes.push(componentType);
  17559. });
  17560. ComponentModel.topologicalTravel(
  17561. componentTypes,
  17562. ComponentModel.getAllClassMainTypes(),
  17563. function (componentType, dependencies) {
  17564. each$1(componentsMap.get(componentType), function (component) {
  17565. (componentType !== 'series' || !isNotTargetSeries(component, payload))
  17566. && component.restoreData();
  17567. });
  17568. }
  17569. );
  17570. }
  17571. });
  17572. function isNotTargetSeries(seriesModel, payload) {
  17573. if (payload) {
  17574. var index = payload.seiresIndex;
  17575. var id = payload.seriesId;
  17576. var name = payload.seriesName;
  17577. return (index != null && seriesModel.componentIndex !== index)
  17578. || (id != null && seriesModel.id !== id)
  17579. || (name != null && seriesModel.name !== name);
  17580. }
  17581. }
  17582. /**
  17583. * @inner
  17584. */
  17585. function mergeTheme(option, theme) {
  17586. // PENDING
  17587. // NOT use `colorLayer` in theme if option has `color`
  17588. var notMergeColorLayer = option.color && !option.colorLayer;
  17589. each$1(theme, function (themeItem, name) {
  17590. if (name === 'colorLayer' && notMergeColorLayer) {
  17591. return;
  17592. }
  17593. // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理
  17594. if (!ComponentModel.hasClass(name)) {
  17595. if (typeof themeItem === 'object') {
  17596. option[name] = !option[name]
  17597. ? clone(themeItem)
  17598. : merge(option[name], themeItem, false);
  17599. }
  17600. else {
  17601. if (option[name] == null) {
  17602. option[name] = themeItem;
  17603. }
  17604. }
  17605. }
  17606. });
  17607. }
  17608. function initBase(baseOption) {
  17609. baseOption = baseOption;
  17610. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  17611. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  17612. this.option = {};
  17613. this.option[OPTION_INNER_KEY] = 1;
  17614. /**
  17615. * Init with series: [], in case of calling findSeries method
  17616. * before series initialized.
  17617. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  17618. * @private
  17619. */
  17620. this._componentsMap = createHashMap({series: []});
  17621. /**
  17622. * Mapping between filtered series list and raw series list.
  17623. * key: filtered series indices, value: raw series indices.
  17624. * @type {Array.<nubmer>}
  17625. * @private
  17626. */
  17627. this._seriesIndices;
  17628. this._seriesIndicesMap;
  17629. mergeTheme(baseOption, this._theme.option);
  17630. // TODO Needs clone when merging to the unexisted property
  17631. merge(baseOption, globalDefault, false);
  17632. this.mergeOption(baseOption);
  17633. }
  17634. /**
  17635. * @inner
  17636. * @param {Array.<string>|string} types model types
  17637. * @return {Object} key: {string} type, value: {Array.<Object>} models
  17638. */
  17639. function getComponentsByTypes(componentsMap, types) {
  17640. if (!isArray(types)) {
  17641. types = types ? [types] : [];
  17642. }
  17643. var ret = {};
  17644. each$1(types, function (type) {
  17645. ret[type] = (componentsMap.get(type) || []).slice();
  17646. });
  17647. return ret;
  17648. }
  17649. /**
  17650. * @inner
  17651. */
  17652. function determineSubType(mainType, newCptOption, existComponent) {
  17653. var subType = newCptOption.type
  17654. ? newCptOption.type
  17655. : existComponent
  17656. ? existComponent.subType
  17657. // Use determineSubType only when there is no existComponent.
  17658. : ComponentModel.determineSubType(mainType, newCptOption);
  17659. // tooltip, markline, markpoint may always has no subType
  17660. return subType;
  17661. }
  17662. /**
  17663. * @inner
  17664. */
  17665. function createSeriesIndices(ecModel, seriesModels) {
  17666. ecModel._seriesIndicesMap = createHashMap(
  17667. ecModel._seriesIndices = map(seriesModels, function (series) {
  17668. return series.componentIndex;
  17669. }) || []
  17670. );
  17671. }
  17672. /**
  17673. * @inner
  17674. */
  17675. function filterBySubType(components, condition) {
  17676. // Using hasOwnProperty for restrict. Consider
  17677. // subType is undefined in user payload.
  17678. return condition.hasOwnProperty('subType')
  17679. ? filter(components, function (cpt) {
  17680. return cpt.subType === condition.subType;
  17681. })
  17682. : components;
  17683. }
  17684. /**
  17685. * @inner
  17686. */
  17687. function assertSeriesInitialized(ecModel) {
  17688. // Components that use _seriesIndices should depends on series component,
  17689. // which make sure that their initialization is after series.
  17690. if (__DEV__) {
  17691. if (!ecModel._seriesIndices) {
  17692. throw new Error('Option should contains series.');
  17693. }
  17694. }
  17695. }
  17696. mixin(GlobalModel, colorPaletteMixin);
  17697. var echartsAPIList = [
  17698. 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed',
  17699. 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption',
  17700. 'getViewOfComponentModel', 'getViewOfSeriesModel'
  17701. ];
  17702. // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js
  17703. function ExtensionAPI(chartInstance) {
  17704. each$1(echartsAPIList, function (name) {
  17705. this[name] = bind(chartInstance[name], chartInstance);
  17706. }, this);
  17707. }
  17708. var coordinateSystemCreators = {};
  17709. function CoordinateSystemManager() {
  17710. this._coordinateSystems = [];
  17711. }
  17712. CoordinateSystemManager.prototype = {
  17713. constructor: CoordinateSystemManager,
  17714. create: function (ecModel, api) {
  17715. var coordinateSystems = [];
  17716. each$1(coordinateSystemCreators, function (creater, type) {
  17717. var list = creater.create(ecModel, api);
  17718. coordinateSystems = coordinateSystems.concat(list || []);
  17719. });
  17720. this._coordinateSystems = coordinateSystems;
  17721. },
  17722. update: function (ecModel, api) {
  17723. each$1(this._coordinateSystems, function (coordSys) {
  17724. coordSys.update && coordSys.update(ecModel, api);
  17725. });
  17726. },
  17727. getCoordinateSystems: function () {
  17728. return this._coordinateSystems.slice();
  17729. }
  17730. };
  17731. CoordinateSystemManager.register = function (type, coordinateSystemCreator) {
  17732. coordinateSystemCreators[type] = coordinateSystemCreator;
  17733. };
  17734. CoordinateSystemManager.get = function (type) {
  17735. return coordinateSystemCreators[type];
  17736. };
  17737. /**
  17738. * ECharts option manager
  17739. *
  17740. * @module {echarts/model/OptionManager}
  17741. */
  17742. var each$4 = each$1;
  17743. var clone$3 = clone;
  17744. var map$1 = map;
  17745. var merge$1 = merge;
  17746. var QUERY_REG = /^(min|max)?(.+)$/;
  17747. /**
  17748. * TERM EXPLANATIONS:
  17749. *
  17750. * [option]:
  17751. *
  17752. * An object that contains definitions of components. For example:
  17753. * var option = {
  17754. * title: {...},
  17755. * legend: {...},
  17756. * visualMap: {...},
  17757. * series: [
  17758. * {data: [...]},
  17759. * {data: [...]},
  17760. * ...
  17761. * ]
  17762. * };
  17763. *
  17764. * [rawOption]:
  17765. *
  17766. * An object input to echarts.setOption. 'rawOption' may be an
  17767. * 'option', or may be an object contains multi-options. For example:
  17768. * var option = {
  17769. * baseOption: {
  17770. * title: {...},
  17771. * legend: {...},
  17772. * series: [
  17773. * {data: [...]},
  17774. * {data: [...]},
  17775. * ...
  17776. * ]
  17777. * },
  17778. * timeline: {...},
  17779. * options: [
  17780. * {title: {...}, series: {data: [...]}},
  17781. * {title: {...}, series: {data: [...]}},
  17782. * ...
  17783. * ],
  17784. * media: [
  17785. * {
  17786. * query: {maxWidth: 320},
  17787. * option: {series: {x: 20}, visualMap: {show: false}}
  17788. * },
  17789. * {
  17790. * query: {minWidth: 320, maxWidth: 720},
  17791. * option: {series: {x: 500}, visualMap: {show: true}}
  17792. * },
  17793. * {
  17794. * option: {series: {x: 1200}, visualMap: {show: true}}
  17795. * }
  17796. * ]
  17797. * };
  17798. *
  17799. * @alias module:echarts/model/OptionManager
  17800. * @param {module:echarts/ExtensionAPI} api
  17801. */
  17802. function OptionManager(api) {
  17803. /**
  17804. * @private
  17805. * @type {module:echarts/ExtensionAPI}
  17806. */
  17807. this._api = api;
  17808. /**
  17809. * @private
  17810. * @type {Array.<number>}
  17811. */
  17812. this._timelineOptions = [];
  17813. /**
  17814. * @private
  17815. * @type {Array.<Object>}
  17816. */
  17817. this._mediaList = [];
  17818. /**
  17819. * @private
  17820. * @type {Object}
  17821. */
  17822. this._mediaDefault;
  17823. /**
  17824. * -1, means default.
  17825. * empty means no media.
  17826. * @private
  17827. * @type {Array.<number>}
  17828. */
  17829. this._currentMediaIndices = [];
  17830. /**
  17831. * @private
  17832. * @type {Object}
  17833. */
  17834. this._optionBackup;
  17835. /**
  17836. * @private
  17837. * @type {Object}
  17838. */
  17839. this._newBaseOption;
  17840. }
  17841. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  17842. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  17843. // rawOption cloned and backuped when timeline changed, which does no
  17844. // good to performance. What's more, that both timeline and setOption
  17845. // method supply 'notMerge' brings complex and some problems.
  17846. // Consider this case:
  17847. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  17848. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  17849. OptionManager.prototype = {
  17850. constructor: OptionManager,
  17851. /**
  17852. * @public
  17853. * @param {Object} rawOption Raw option.
  17854. * @param {module:echarts/model/Global} ecModel
  17855. * @param {Array.<Function>} optionPreprocessorFuncs
  17856. * @return {Object} Init option
  17857. */
  17858. setOption: function (rawOption, optionPreprocessorFuncs) {
  17859. if (rawOption) {
  17860. // That set dat primitive is dangerous if user reuse the data when setOption again.
  17861. each$1(normalizeToArray(rawOption.series), function (series) {
  17862. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  17863. });
  17864. }
  17865. // Caution: some series modify option data, if do not clone,
  17866. // it should ensure that the repeat modify correctly
  17867. // (create a new object when modify itself).
  17868. rawOption = clone$3(rawOption, true);
  17869. // FIXME
  17870. // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。
  17871. var oldOptionBackup = this._optionBackup;
  17872. var newParsedOption = parseRawOption.call(
  17873. this, rawOption, optionPreprocessorFuncs, !oldOptionBackup
  17874. );
  17875. this._newBaseOption = newParsedOption.baseOption;
  17876. // For setOption at second time (using merge mode);
  17877. if (oldOptionBackup) {
  17878. // Only baseOption can be merged.
  17879. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption);
  17880. // For simplicity, timeline options and media options do not support merge,
  17881. // that is, if you `setOption` twice and both has timeline options, the latter
  17882. // timeline opitons will not be merged to the formers, but just substitude them.
  17883. if (newParsedOption.timelineOptions.length) {
  17884. oldOptionBackup.timelineOptions = newParsedOption.timelineOptions;
  17885. }
  17886. if (newParsedOption.mediaList.length) {
  17887. oldOptionBackup.mediaList = newParsedOption.mediaList;
  17888. }
  17889. if (newParsedOption.mediaDefault) {
  17890. oldOptionBackup.mediaDefault = newParsedOption.mediaDefault;
  17891. }
  17892. }
  17893. else {
  17894. this._optionBackup = newParsedOption;
  17895. }
  17896. },
  17897. /**
  17898. * @param {boolean} isRecreate
  17899. * @return {Object}
  17900. */
  17901. mountOption: function (isRecreate) {
  17902. var optionBackup = this._optionBackup;
  17903. // TODO
  17904. // 如果没有reset功能则不clone。
  17905. this._timelineOptions = map$1(optionBackup.timelineOptions, clone$3);
  17906. this._mediaList = map$1(optionBackup.mediaList, clone$3);
  17907. this._mediaDefault = clone$3(optionBackup.mediaDefault);
  17908. this._currentMediaIndices = [];
  17909. return clone$3(isRecreate
  17910. // this._optionBackup.baseOption, which is created at the first `setOption`
  17911. // called, and is merged into every new option by inner method `mergeOption`
  17912. // each time `setOption` called, can be only used in `isRecreate`, because
  17913. // its reliability is under suspicion. In other cases option merge is
  17914. // performed by `model.mergeOption`.
  17915. ? optionBackup.baseOption : this._newBaseOption
  17916. );
  17917. },
  17918. /**
  17919. * @param {module:echarts/model/Global} ecModel
  17920. * @return {Object}
  17921. */
  17922. getTimelineOption: function (ecModel) {
  17923. var option;
  17924. var timelineOptions = this._timelineOptions;
  17925. if (timelineOptions.length) {
  17926. // getTimelineOption can only be called after ecModel inited,
  17927. // so we can get currentIndex from timelineModel.
  17928. var timelineModel = ecModel.getComponent('timeline');
  17929. if (timelineModel) {
  17930. option = clone$3(
  17931. timelineOptions[timelineModel.getCurrentIndex()],
  17932. true
  17933. );
  17934. }
  17935. }
  17936. return option;
  17937. },
  17938. /**
  17939. * @param {module:echarts/model/Global} ecModel
  17940. * @return {Array.<Object>}
  17941. */
  17942. getMediaOption: function (ecModel) {
  17943. var ecWidth = this._api.getWidth();
  17944. var ecHeight = this._api.getHeight();
  17945. var mediaList = this._mediaList;
  17946. var mediaDefault = this._mediaDefault;
  17947. var indices = [];
  17948. var result = [];
  17949. // No media defined.
  17950. if (!mediaList.length && !mediaDefault) {
  17951. return result;
  17952. }
  17953. // Multi media may be applied, the latter defined media has higher priority.
  17954. for (var i = 0, len = mediaList.length; i < len; i++) {
  17955. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  17956. indices.push(i);
  17957. }
  17958. }
  17959. // FIXME
  17960. // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。
  17961. if (!indices.length && mediaDefault) {
  17962. indices = [-1];
  17963. }
  17964. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  17965. result = map$1(indices, function (index) {
  17966. return clone$3(
  17967. index === -1 ? mediaDefault.option : mediaList[index].option
  17968. );
  17969. });
  17970. }
  17971. // Otherwise return nothing.
  17972. this._currentMediaIndices = indices;
  17973. return result;
  17974. }
  17975. };
  17976. function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) {
  17977. var timelineOptions = [];
  17978. var mediaList = [];
  17979. var mediaDefault;
  17980. var baseOption;
  17981. // Compatible with ec2.
  17982. var timelineOpt = rawOption.timeline;
  17983. if (rawOption.baseOption) {
  17984. baseOption = rawOption.baseOption;
  17985. }
  17986. // For timeline
  17987. if (timelineOpt || rawOption.options) {
  17988. baseOption = baseOption || {};
  17989. timelineOptions = (rawOption.options || []).slice();
  17990. }
  17991. // For media query
  17992. if (rawOption.media) {
  17993. baseOption = baseOption || {};
  17994. var media = rawOption.media;
  17995. each$4(media, function (singleMedia) {
  17996. if (singleMedia && singleMedia.option) {
  17997. if (singleMedia.query) {
  17998. mediaList.push(singleMedia);
  17999. }
  18000. else if (!mediaDefault) {
  18001. // Use the first media default.
  18002. mediaDefault = singleMedia;
  18003. }
  18004. }
  18005. });
  18006. }
  18007. // For normal option
  18008. if (!baseOption) {
  18009. baseOption = rawOption;
  18010. }
  18011. // Set timelineOpt to baseOption in ec3,
  18012. // which is convenient for merge option.
  18013. if (!baseOption.timeline) {
  18014. baseOption.timeline = timelineOpt;
  18015. }
  18016. // Preprocess.
  18017. each$4([baseOption].concat(timelineOptions)
  18018. .concat(map(mediaList, function (media) {
  18019. return media.option;
  18020. })),
  18021. function (option) {
  18022. each$4(optionPreprocessorFuncs, function (preProcess) {
  18023. preProcess(option, isNew);
  18024. });
  18025. }
  18026. );
  18027. return {
  18028. baseOption: baseOption,
  18029. timelineOptions: timelineOptions,
  18030. mediaDefault: mediaDefault,
  18031. mediaList: mediaList
  18032. };
  18033. }
  18034. /**
  18035. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  18036. * Support: width, height, aspectRatio
  18037. * Can use max or min as prefix.
  18038. */
  18039. function applyMediaQuery(query, ecWidth, ecHeight) {
  18040. var realMap = {
  18041. width: ecWidth,
  18042. height: ecHeight,
  18043. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  18044. };
  18045. var applicatable = true;
  18046. each$1(query, function (value, attr) {
  18047. var matched = attr.match(QUERY_REG);
  18048. if (!matched || !matched[1] || !matched[2]) {
  18049. return;
  18050. }
  18051. var operator = matched[1];
  18052. var realAttr = matched[2].toLowerCase();
  18053. if (!compare(realMap[realAttr], value, operator)) {
  18054. applicatable = false;
  18055. }
  18056. });
  18057. return applicatable;
  18058. }
  18059. function compare(real, expect, operator) {
  18060. if (operator === 'min') {
  18061. return real >= expect;
  18062. }
  18063. else if (operator === 'max') {
  18064. return real <= expect;
  18065. }
  18066. else { // Equals
  18067. return real === expect;
  18068. }
  18069. }
  18070. function indicesEquals(indices1, indices2) {
  18071. // indices is always order by asc and has only finite number.
  18072. return indices1.join(',') === indices2.join(',');
  18073. }
  18074. /**
  18075. * Consider case:
  18076. * `chart.setOption(opt1);`
  18077. * Then user do some interaction like dataZoom, dataView changing.
  18078. * `chart.setOption(opt2);`
  18079. * Then user press 'reset button' in toolbox.
  18080. *
  18081. * After doing that all of the interaction effects should be reset, the
  18082. * chart should be the same as the result of invoke
  18083. * `chart.setOption(opt1); chart.setOption(opt2);`.
  18084. *
  18085. * Although it is not able ensure that
  18086. * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to
  18087. * `chart.setOption(merge(opt1, opt2));` exactly,
  18088. * this might be the only simple way to implement that feature.
  18089. *
  18090. * MEMO: We've considered some other approaches:
  18091. * 1. Each model handle its self restoration but not uniform treatment.
  18092. * (Too complex in logic and error-prone)
  18093. * 2. Use a shadow ecModel. (Performace expensive)
  18094. */
  18095. function mergeOption(oldOption, newOption) {
  18096. newOption = newOption || {};
  18097. each$4(newOption, function (newCptOpt, mainType) {
  18098. if (newCptOpt == null) {
  18099. return;
  18100. }
  18101. var oldCptOpt = oldOption[mainType];
  18102. if (!ComponentModel.hasClass(mainType)) {
  18103. oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true);
  18104. }
  18105. else {
  18106. newCptOpt = normalizeToArray(newCptOpt);
  18107. oldCptOpt = normalizeToArray(oldCptOpt);
  18108. var mapResult = mappingToExists(oldCptOpt, newCptOpt);
  18109. oldOption[mainType] = map$1(mapResult, function (item) {
  18110. return (item.option && item.exist)
  18111. ? merge$1(item.exist, item.option, true)
  18112. : (item.exist || item.option);
  18113. });
  18114. }
  18115. });
  18116. }
  18117. var each$5 = each$1;
  18118. var isObject$3 = isObject$1;
  18119. var POSSIBLE_STYLES = [
  18120. 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle',
  18121. 'chordStyle', 'label', 'labelLine'
  18122. ];
  18123. function compatEC2ItemStyle(opt) {
  18124. var itemStyleOpt = opt && opt.itemStyle;
  18125. if (!itemStyleOpt) {
  18126. return;
  18127. }
  18128. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  18129. var styleName = POSSIBLE_STYLES[i];
  18130. var normalItemStyleOpt = itemStyleOpt.normal;
  18131. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  18132. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  18133. opt[styleName] = opt[styleName] || {};
  18134. if (!opt[styleName].normal) {
  18135. opt[styleName].normal = normalItemStyleOpt[styleName];
  18136. }
  18137. else {
  18138. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  18139. }
  18140. normalItemStyleOpt[styleName] = null;
  18141. }
  18142. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  18143. opt[styleName] = opt[styleName] || {};
  18144. if (!opt[styleName].emphasis) {
  18145. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  18146. }
  18147. else {
  18148. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  18149. }
  18150. emphasisItemStyleOpt[styleName] = null;
  18151. }
  18152. }
  18153. }
  18154. function convertNormalEmphasis(opt, optType, useExtend) {
  18155. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  18156. var normalOpt = opt[optType].normal;
  18157. var emphasisOpt = opt[optType].emphasis;
  18158. if (normalOpt) {
  18159. // Timeline controlStyle has other properties besides normal and emphasis
  18160. if (useExtend) {
  18161. opt[optType].normal = opt[optType].emphasis = null;
  18162. defaults(opt[optType], normalOpt);
  18163. }
  18164. else {
  18165. opt[optType] = normalOpt;
  18166. }
  18167. }
  18168. if (emphasisOpt) {
  18169. opt.emphasis = opt.emphasis || {};
  18170. opt.emphasis[optType] = emphasisOpt;
  18171. }
  18172. }
  18173. }
  18174. function removeEC3NormalStatus(opt) {
  18175. convertNormalEmphasis(opt, 'itemStyle');
  18176. convertNormalEmphasis(opt, 'lineStyle');
  18177. convertNormalEmphasis(opt, 'areaStyle');
  18178. convertNormalEmphasis(opt, 'label');
  18179. convertNormalEmphasis(opt, 'labelLine');
  18180. // treemap
  18181. convertNormalEmphasis(opt, 'upperLabel');
  18182. // graph
  18183. convertNormalEmphasis(opt, 'edgeLabel');
  18184. }
  18185. function compatTextStyle(opt, propName) {
  18186. // Check whether is not object (string\null\undefined ...)
  18187. var labelOptSingle = isObject$3(opt) && opt[propName];
  18188. var textStyle = isObject$3(labelOptSingle) && labelOptSingle.textStyle;
  18189. if (textStyle) {
  18190. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  18191. var propName = TEXT_STYLE_OPTIONS[i];
  18192. if (textStyle.hasOwnProperty(propName)) {
  18193. labelOptSingle[propName] = textStyle[propName];
  18194. }
  18195. }
  18196. }
  18197. }
  18198. function compatEC3CommonStyles(opt) {
  18199. if (opt) {
  18200. removeEC3NormalStatus(opt);
  18201. compatTextStyle(opt, 'label');
  18202. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  18203. }
  18204. }
  18205. function processSeries(seriesOpt) {
  18206. if (!isObject$3(seriesOpt)) {
  18207. return;
  18208. }
  18209. compatEC2ItemStyle(seriesOpt);
  18210. removeEC3NormalStatus(seriesOpt);
  18211. compatTextStyle(seriesOpt, 'label');
  18212. // treemap
  18213. compatTextStyle(seriesOpt, 'upperLabel');
  18214. // graph
  18215. compatTextStyle(seriesOpt, 'edgeLabel');
  18216. if (seriesOpt.emphasis) {
  18217. compatTextStyle(seriesOpt.emphasis, 'label');
  18218. // treemap
  18219. compatTextStyle(seriesOpt.emphasis, 'upperLabel');
  18220. // graph
  18221. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  18222. }
  18223. var markPoint = seriesOpt.markPoint;
  18224. if (markPoint) {
  18225. compatEC2ItemStyle(markPoint);
  18226. compatEC3CommonStyles(markPoint);
  18227. }
  18228. var markLine = seriesOpt.markLine;
  18229. if (markLine) {
  18230. compatEC2ItemStyle(markLine);
  18231. compatEC3CommonStyles(markLine);
  18232. }
  18233. var markArea = seriesOpt.markArea;
  18234. if (markArea) {
  18235. compatEC3CommonStyles(markArea);
  18236. }
  18237. var data = seriesOpt.data;
  18238. // Break with ec3: if `setOption` again, there may be no `type` in option,
  18239. // then the backward compat based on option type will not be performed.
  18240. if (seriesOpt.type === 'graph') {
  18241. data = data || seriesOpt.nodes;
  18242. var edgeData = seriesOpt.links || seriesOpt.edges;
  18243. if (edgeData && !isTypedArray(edgeData)) {
  18244. for (var i = 0; i < edgeData.length; i++) {
  18245. compatEC3CommonStyles(edgeData[i]);
  18246. }
  18247. }
  18248. each$1(seriesOpt.categories, function (opt) {
  18249. removeEC3NormalStatus(opt);
  18250. });
  18251. }
  18252. if (data && !isTypedArray(data)) {
  18253. for (var i = 0; i < data.length; i++) {
  18254. compatEC3CommonStyles(data[i]);
  18255. }
  18256. }
  18257. // mark point data
  18258. var markPoint = seriesOpt.markPoint;
  18259. if (markPoint && markPoint.data) {
  18260. var mpData = markPoint.data;
  18261. for (var i = 0; i < mpData.length; i++) {
  18262. compatEC3CommonStyles(mpData[i]);
  18263. }
  18264. }
  18265. // mark line data
  18266. var markLine = seriesOpt.markLine;
  18267. if (markLine && markLine.data) {
  18268. var mlData = markLine.data;
  18269. for (var i = 0; i < mlData.length; i++) {
  18270. if (isArray(mlData[i])) {
  18271. compatEC3CommonStyles(mlData[i][0]);
  18272. compatEC3CommonStyles(mlData[i][1]);
  18273. }
  18274. else {
  18275. compatEC3CommonStyles(mlData[i]);
  18276. }
  18277. }
  18278. }
  18279. // Series
  18280. if (seriesOpt.type === 'gauge') {
  18281. compatTextStyle(seriesOpt, 'axisLabel');
  18282. compatTextStyle(seriesOpt, 'title');
  18283. compatTextStyle(seriesOpt, 'detail');
  18284. }
  18285. else if (seriesOpt.type === 'treemap') {
  18286. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  18287. each$1(seriesOpt.levels, function (opt) {
  18288. removeEC3NormalStatus(opt);
  18289. });
  18290. }
  18291. // sunburst starts from ec4, so it does not need to compat levels.
  18292. }
  18293. function toArr(o) {
  18294. return isArray(o) ? o : o ? [o] : [];
  18295. }
  18296. function toObj(o) {
  18297. return (isArray(o) ? o[0] : o) || {};
  18298. }
  18299. var compatStyle = function (option, isTheme) {
  18300. each$5(toArr(option.series), function (seriesOpt) {
  18301. isObject$3(seriesOpt) && processSeries(seriesOpt);
  18302. });
  18303. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  18304. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  18305. each$5(
  18306. axes,
  18307. function (axisName) {
  18308. each$5(toArr(option[axisName]), function (axisOpt) {
  18309. if (axisOpt) {
  18310. compatTextStyle(axisOpt, 'axisLabel');
  18311. compatTextStyle(axisOpt.axisPointer, 'label');
  18312. }
  18313. });
  18314. }
  18315. );
  18316. each$5(toArr(option.parallel), function (parallelOpt) {
  18317. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  18318. compatTextStyle(parallelAxisDefault, 'axisLabel');
  18319. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  18320. });
  18321. each$5(toArr(option.calendar), function (calendarOpt) {
  18322. convertNormalEmphasis(calendarOpt, 'itemStyle');
  18323. compatTextStyle(calendarOpt, 'dayLabel');
  18324. compatTextStyle(calendarOpt, 'monthLabel');
  18325. compatTextStyle(calendarOpt, 'yearLabel');
  18326. });
  18327. // radar.name.textStyle
  18328. each$5(toArr(option.radar), function (radarOpt) {
  18329. compatTextStyle(radarOpt, 'name');
  18330. });
  18331. each$5(toArr(option.geo), function (geoOpt) {
  18332. if (isObject$3(geoOpt)) {
  18333. compatEC3CommonStyles(geoOpt);
  18334. each$5(toArr(geoOpt.regions), function (regionObj) {
  18335. compatEC3CommonStyles(regionObj);
  18336. });
  18337. }
  18338. });
  18339. each$5(toArr(option.timeline), function (timelineOpt) {
  18340. compatEC3CommonStyles(timelineOpt);
  18341. convertNormalEmphasis(timelineOpt, 'label');
  18342. convertNormalEmphasis(timelineOpt, 'itemStyle');
  18343. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  18344. var data = timelineOpt.data;
  18345. isArray(data) && each$1(data, function (item) {
  18346. if (isObject$1(item)) {
  18347. convertNormalEmphasis(item, 'label');
  18348. convertNormalEmphasis(item, 'itemStyle');
  18349. }
  18350. });
  18351. });
  18352. each$5(toArr(option.toolbox), function (toolboxOpt) {
  18353. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  18354. each$5(toolboxOpt.feature, function (featureOpt) {
  18355. convertNormalEmphasis(featureOpt, 'iconStyle');
  18356. });
  18357. });
  18358. compatTextStyle(toObj(option.axisPointer), 'label');
  18359. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  18360. };
  18361. // Compatitable with 2.0
  18362. function get(opt, path) {
  18363. path = path.split(',');
  18364. var obj = opt;
  18365. for (var i = 0; i < path.length; i++) {
  18366. obj = obj && obj[path[i]];
  18367. if (obj == null) {
  18368. break;
  18369. }
  18370. }
  18371. return obj;
  18372. }
  18373. function set$1(opt, path, val, overwrite) {
  18374. path = path.split(',');
  18375. var obj = opt;
  18376. var key;
  18377. for (var i = 0; i < path.length - 1; i++) {
  18378. key = path[i];
  18379. if (obj[key] == null) {
  18380. obj[key] = {};
  18381. }
  18382. obj = obj[key];
  18383. }
  18384. if (overwrite || obj[path[i]] == null) {
  18385. obj[path[i]] = val;
  18386. }
  18387. }
  18388. function compatLayoutProperties(option) {
  18389. each$1(LAYOUT_PROPERTIES, function (prop) {
  18390. if (prop[0] in option && !(prop[1] in option)) {
  18391. option[prop[1]] = option[prop[0]];
  18392. }
  18393. });
  18394. }
  18395. var LAYOUT_PROPERTIES = [
  18396. ['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']
  18397. ];
  18398. var COMPATITABLE_COMPONENTS = [
  18399. 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'
  18400. ];
  18401. var backwardCompat = function (option, isTheme) {
  18402. compatStyle(option, isTheme);
  18403. // Make sure series array for model initialization.
  18404. option.series = normalizeToArray(option.series);
  18405. each$1(option.series, function (seriesOpt) {
  18406. if (!isObject$1(seriesOpt)) {
  18407. return;
  18408. }
  18409. var seriesType = seriesOpt.type;
  18410. if (seriesType === 'pie' || seriesType === 'gauge') {
  18411. if (seriesOpt.clockWise != null) {
  18412. seriesOpt.clockwise = seriesOpt.clockWise;
  18413. }
  18414. }
  18415. if (seriesType === 'gauge') {
  18416. var pointerColor = get(seriesOpt, 'pointer.color');
  18417. pointerColor != null
  18418. && set$1(seriesOpt, 'itemStyle.normal.color', pointerColor);
  18419. }
  18420. compatLayoutProperties(seriesOpt);
  18421. });
  18422. // dataRange has changed to visualMap
  18423. if (option.dataRange) {
  18424. option.visualMap = option.dataRange;
  18425. }
  18426. each$1(COMPATITABLE_COMPONENTS, function (componentName) {
  18427. var options = option[componentName];
  18428. if (options) {
  18429. if (!isArray(options)) {
  18430. options = [options];
  18431. }
  18432. each$1(options, function (option) {
  18433. compatLayoutProperties(option);
  18434. });
  18435. }
  18436. });
  18437. };
  18438. // (1) [Caution]: the logic is correct based on the premises:
  18439. // data processing stage is blocked in stream.
  18440. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  18441. // (2) Only register once when import repeatly.
  18442. // Should be executed before after series filtered and before stack calculation.
  18443. var dataStack = function (ecModel) {
  18444. var stackInfoMap = createHashMap();
  18445. ecModel.eachSeries(function (seriesModel) {
  18446. var stack = seriesModel.get('stack');
  18447. // Compatibal: when `stack` is set as '', do not stack.
  18448. if (stack) {
  18449. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  18450. var data = seriesModel.getData();
  18451. var stackInfo = {
  18452. // Used for calculate axis extent automatically.
  18453. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  18454. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  18455. stackedDimension: data.getCalculationInfo('stackedDimension'),
  18456. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  18457. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  18458. data: data,
  18459. seriesModel: seriesModel
  18460. };
  18461. // If stacked on axis that do not support data stack.
  18462. if (!stackInfo.stackedDimension
  18463. || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)
  18464. ) {
  18465. return;
  18466. }
  18467. stackInfoList.length && data.setCalculationInfo(
  18468. 'stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel
  18469. );
  18470. stackInfoList.push(stackInfo);
  18471. }
  18472. });
  18473. stackInfoMap.each(calculateStack);
  18474. };
  18475. function calculateStack(stackInfoList) {
  18476. each$1(stackInfoList, function (targetStackInfo, idxInStack) {
  18477. var resultVal = [];
  18478. var resultNaN = [NaN, NaN];
  18479. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  18480. var targetData = targetStackInfo.data;
  18481. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  18482. // Should not write on raw data, because stack series model list changes
  18483. // depending on legend selection.
  18484. var newData = targetData.map(dims, function (v0, v1, dataIndex) {
  18485. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex);
  18486. // Consider `connectNulls` of line area, if value is NaN, stackedOver
  18487. // should also be NaN, to draw a appropriate belt area.
  18488. if (isNaN(sum)) {
  18489. return resultNaN;
  18490. }
  18491. var byValue;
  18492. var stackedDataRawIndex;
  18493. if (isStackedByIndex) {
  18494. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  18495. }
  18496. else {
  18497. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  18498. }
  18499. // If stackOver is NaN, chart view will render point on value start.
  18500. var stackedOver = NaN;
  18501. for (var j = idxInStack - 1; j >= 0; j--) {
  18502. var stackInfo = stackInfoList[j];
  18503. // Has been optimized by inverted indices on `stackedByDimension`.
  18504. if (!isStackedByIndex) {
  18505. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  18506. }
  18507. if (stackedDataRawIndex >= 0) {
  18508. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex);
  18509. // Considering positive stack, negative stack and empty data
  18510. if ((sum >= 0 && val > 0) // Positive stack
  18511. || (sum <= 0 && val < 0) // Negative stack
  18512. ) {
  18513. sum += val;
  18514. stackedOver = val;
  18515. break;
  18516. }
  18517. }
  18518. }
  18519. resultVal[0] = sum;
  18520. resultVal[1] = stackedOver;
  18521. return resultVal;
  18522. });
  18523. targetData.hostModel.setData(newData);
  18524. // Update for consequent calculation
  18525. targetStackInfo.data = newData;
  18526. });
  18527. }
  18528. // TODO
  18529. // ??? refactor? check the outer usage of data provider.
  18530. // merge with defaultDimValueGetter?
  18531. /**
  18532. * If normal array used, mutable chunk size is supported.
  18533. * If typed array used, chunk size must be fixed.
  18534. */
  18535. function DefaultDataProvider(source, dimSize) {
  18536. if (!Source.isInstance(source)) {
  18537. source = Source.seriesDataToSource(source);
  18538. }
  18539. this._source = source;
  18540. var data = this._data = source.data;
  18541. var sourceFormat = source.sourceFormat;
  18542. // Typed array. TODO IE10+?
  18543. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18544. if (__DEV__) {
  18545. if (dimSize == null) {
  18546. throw new Error('Typed array data must specify dimension size');
  18547. }
  18548. }
  18549. this._offset = 0;
  18550. this._dimSize = dimSize;
  18551. this._data = data;
  18552. }
  18553. var methods = providerMethods[
  18554. sourceFormat === SOURCE_FORMAT_ARRAY_ROWS
  18555. ? sourceFormat + '_' + source.seriesLayoutBy
  18556. : sourceFormat
  18557. ];
  18558. if (__DEV__) {
  18559. assert$1(methods, 'Invalide sourceFormat: ' + sourceFormat);
  18560. }
  18561. extend(this, methods);
  18562. }
  18563. var providerProto = DefaultDataProvider.prototype;
  18564. // If data is pure without style configuration
  18565. providerProto.pure = false;
  18566. // If data is persistent and will not be released after use.
  18567. providerProto.persistent = true;
  18568. // ???! FIXME legacy data provider do not has method getSource
  18569. providerProto.getSource = function () {
  18570. return this._source;
  18571. };
  18572. var providerMethods = {
  18573. 'arrayRows_column': {
  18574. pure: true,
  18575. count: function () {
  18576. return Math.max(0, this._data.length - this._source.startIndex);
  18577. },
  18578. getItem: function (idx) {
  18579. return this._data[idx + this._source.startIndex];
  18580. },
  18581. appendData: appendDataSimply
  18582. },
  18583. 'arrayRows_row': {
  18584. pure: true,
  18585. count: function () {
  18586. var row = this._data[0];
  18587. return row ? Math.max(0, row.length - this._source.startIndex) : 0;
  18588. },
  18589. getItem: function (idx) {
  18590. idx += this._source.startIndex;
  18591. var item = [];
  18592. var data = this._data;
  18593. for (var i = 0; i < data.length; i++) {
  18594. var row = data[i];
  18595. item.push(row ? row[idx] : null);
  18596. }
  18597. return item;
  18598. },
  18599. appendData: function () {
  18600. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  18601. }
  18602. },
  18603. 'objectRows': {
  18604. pure: true,
  18605. count: countSimply,
  18606. getItem: getItemSimply,
  18607. appendData: appendDataSimply
  18608. },
  18609. 'keyedColumns': {
  18610. pure: true,
  18611. count: function () {
  18612. var dimName = this._source.dimensionsDefine[0].name;
  18613. var col = this._data[dimName];
  18614. return col ? col.length : 0;
  18615. },
  18616. getItem: function (idx) {
  18617. var item = [];
  18618. var dims = this._source.dimensionsDefine;
  18619. for (var i = 0; i < dims.length; i++) {
  18620. var col = this._data[dims[i].name];
  18621. item.push(col ? col[idx] : null);
  18622. }
  18623. return item;
  18624. },
  18625. appendData: function (newData) {
  18626. var data = this._data;
  18627. each$1(newData, function (newCol, key) {
  18628. var oldCol = data[key] || (data[key] = []);
  18629. for (var i = 0; i < (newCol || []).length; i++) {
  18630. oldCol.push(newCol[i]);
  18631. }
  18632. });
  18633. }
  18634. },
  18635. 'original': {
  18636. count: countSimply,
  18637. getItem: getItemSimply,
  18638. appendData: appendDataSimply
  18639. },
  18640. 'typedArray': {
  18641. persistent: false,
  18642. pure: true,
  18643. count: function () {
  18644. return this._data ? (this._data.length / this._dimSize) : 0;
  18645. },
  18646. getItem: function (idx) {
  18647. idx = idx - this._offset;
  18648. var item = [];
  18649. var offset = this._dimSize * idx;
  18650. for (var i = 0; i < this._dimSize; i++) {
  18651. item[i] = this._data[offset + i];
  18652. }
  18653. return item;
  18654. },
  18655. appendData: function (newData) {
  18656. if (__DEV__) {
  18657. assert$1(
  18658. isTypedArray(newData),
  18659. 'Added data must be TypedArray if data in initialization is TypedArray'
  18660. );
  18661. }
  18662. this._data = newData;
  18663. },
  18664. // Clean self if data is already used.
  18665. clean: function () {
  18666. // PENDING
  18667. this._offset += this.count();
  18668. this._data = null;
  18669. }
  18670. }
  18671. };
  18672. function countSimply() {
  18673. return this._data.length;
  18674. }
  18675. function getItemSimply(idx) {
  18676. return this._data[idx];
  18677. }
  18678. function appendDataSimply(newData) {
  18679. for (var i = 0; i < newData.length; i++) {
  18680. this._data.push(newData[i]);
  18681. }
  18682. }
  18683. var rawValueGetters = {
  18684. arrayRows: getRawValueSimply,
  18685. objectRows: function (dataItem, dataIndex, dimIndex, dimName) {
  18686. return dimIndex != null ? dataItem[dimName] : dataItem;
  18687. },
  18688. keyedColumns: getRawValueSimply,
  18689. original: function (dataItem, dataIndex, dimIndex, dimName) {
  18690. // FIXME
  18691. // In some case (markpoint in geo (geo-map.html)), dataItem
  18692. // is {coord: [...]}
  18693. var value = getDataItemValue(dataItem);
  18694. return (dimIndex == null || !(value instanceof Array))
  18695. ? value
  18696. : value[dimIndex];
  18697. },
  18698. typedArray: getRawValueSimply
  18699. };
  18700. function getRawValueSimply(dataItem, dataIndex, dimIndex, dimName) {
  18701. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  18702. }
  18703. var defaultDimValueGetters = {
  18704. arrayRows: getDimValueSimply,
  18705. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  18706. return converDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  18707. },
  18708. keyedColumns: getDimValueSimply,
  18709. original: function (dataItem, dimName, dataIndex, dimIndex) {
  18710. // Performance sensitive, do not use modelUtil.getDataItemValue.
  18711. // If dataItem is an plain object with no value field, the var `value`
  18712. // will be assigned with the object, but it will be tread correctly
  18713. // in the `convertDataValue`.
  18714. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  18715. // If any dataItem is like { value: 10 }
  18716. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  18717. this.hasItemOption = true;
  18718. }
  18719. return converDataValue(
  18720. (value instanceof Array)
  18721. ? value[dimIndex]
  18722. // If value is a single number or something else not array.
  18723. : value,
  18724. this._dimensionInfos[dimName]
  18725. );
  18726. },
  18727. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  18728. return dataItem[dimIndex];
  18729. }
  18730. };
  18731. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  18732. return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  18733. }
  18734. /**
  18735. * This helper method convert value in data.
  18736. * @param {string|number|Date} value
  18737. * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
  18738. * If "dimInfo.ordinalParseAndSave", ordinal value can be parsed.
  18739. */
  18740. function converDataValue(value, dimInfo) {
  18741. // Performance sensitive.
  18742. var dimType = dimInfo && dimInfo.type;
  18743. if (dimType === 'ordinal') {
  18744. // If given value is a category string
  18745. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  18746. return ordinalMeta
  18747. ? ordinalMeta.parseAndCollect(value)
  18748. : value;
  18749. }
  18750. if (dimType === 'time'
  18751. // spead up when using timestamp
  18752. && typeof value !== 'number'
  18753. && value != null
  18754. && value !== '-'
  18755. ) {
  18756. value = +parseDate(value);
  18757. }
  18758. // dimType defaults 'number'.
  18759. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  18760. // parse to NaN.
  18761. return (value == null || value === '')
  18762. ? NaN
  18763. // If string (like '-'), using '+' parse to NaN
  18764. // If object, also parse to NaN
  18765. : +value;
  18766. }
  18767. // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  18768. // Consider persistent.
  18769. // Caution: why use raw value to display on label or tooltip?
  18770. // A reason is to avoid format. For example time value we do not know
  18771. // how to format is expected. More over, if stack is used, calculated
  18772. // value may be 0.91000000001, which have brings trouble to display.
  18773. // TODO: consider how to treat null/undefined/NaN when display?
  18774. /**
  18775. * @param {module:echarts/data/List} data
  18776. * @param {number} dataIndex
  18777. * @param {string|number} [dim] dimName or dimIndex
  18778. * @return {Array.<number>|string|number} can be null/undefined.
  18779. */
  18780. function retrieveRawValue(data, dataIndex, dim) {
  18781. if (!data) {
  18782. return;
  18783. }
  18784. // Consider data may be not persistent.
  18785. var dataItem = data.getRawDataItem(dataIndex);
  18786. if (dataItem == null) {
  18787. return;
  18788. }
  18789. var sourceFormat = data.getProvider().getSource().sourceFormat;
  18790. var dimName;
  18791. var dimIndex;
  18792. var dimInfo = data.getDimensionInfo(dim);
  18793. if (dimInfo) {
  18794. dimName = dimInfo.name;
  18795. dimIndex = dimInfo.index;
  18796. }
  18797. return rawValueGetters[sourceFormat](dataItem, dataIndex, dimIndex, dimName);
  18798. }
  18799. /**
  18800. * Compatible with some cases (in pie, map) like:
  18801. * data: [{name: 'xx', value: 5, selected: true}, ...]
  18802. * where only sourceFormat is 'original' and 'objectRows' supported.
  18803. *
  18804. * ??? TODO
  18805. * Supported detail options in data item when using 'arrayRows'.
  18806. *
  18807. * @param {module:echarts/data/List} data
  18808. * @param {number} dataIndex
  18809. * @param {string} attr like 'selected'
  18810. */
  18811. function retrieveRawAttr(data, dataIndex, attr) {
  18812. if (!data) {
  18813. return;
  18814. }
  18815. var sourceFormat = data.getProvider().getSource().sourceFormat;
  18816. if (sourceFormat !== SOURCE_FORMAT_ORIGINAL
  18817. && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS
  18818. ) {
  18819. return;
  18820. }
  18821. var dataItem = data.getRawDataItem(dataIndex);
  18822. if (sourceFormat === SOURCE_FORMAT_ORIGINAL && !isObject$1(dataItem)) {
  18823. dataItem = null;
  18824. }
  18825. if (dataItem) {
  18826. return dataItem[attr];
  18827. }
  18828. }
  18829. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  18830. // PENDING A little ugly
  18831. var dataFormatMixin = {
  18832. /**
  18833. * Get params for formatter
  18834. * @param {number} dataIndex
  18835. * @param {string} [dataType]
  18836. * @return {Object}
  18837. */
  18838. getDataParams: function (dataIndex, dataType) {
  18839. var data = this.getData(dataType);
  18840. var rawValue = this.getRawValue(dataIndex, dataType);
  18841. var rawDataIndex = data.getRawIndex(dataIndex);
  18842. var name = data.getName(dataIndex, true);
  18843. var itemOpt = data.getRawDataItem(dataIndex);
  18844. var color = data.getItemVisual(dataIndex, 'color');
  18845. return {
  18846. componentType: this.mainType,
  18847. componentSubType: this.subType,
  18848. seriesType: this.mainType === 'series' ? this.subType : null,
  18849. seriesIndex: this.seriesIndex,
  18850. seriesId: this.id,
  18851. seriesName: this.name,
  18852. name: name,
  18853. dataIndex: rawDataIndex,
  18854. data: itemOpt,
  18855. dataType: dataType,
  18856. value: rawValue,
  18857. color: color,
  18858. marker: getTooltipMarker(color),
  18859. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  18860. $vars: ['seriesName', 'name', 'value']
  18861. };
  18862. },
  18863. /**
  18864. * Format label
  18865. * @param {number} dataIndex
  18866. * @param {string} [status='normal'] 'normal' or 'emphasis'
  18867. * @param {string} [dataType]
  18868. * @param {number} [dimIndex]
  18869. * @param {string} [labelProp='label']
  18870. * @return {string} If not formatter, return null/undefined
  18871. */
  18872. getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) {
  18873. status = status || 'normal';
  18874. var data = this.getData(dataType);
  18875. var itemModel = data.getItemModel(dataIndex);
  18876. var params = this.getDataParams(dataIndex, dataType);
  18877. if (dimIndex != null && (params.value instanceof Array)) {
  18878. params.value = params.value[dimIndex];
  18879. }
  18880. var formatter = itemModel.get(
  18881. status === 'normal'
  18882. ? [labelProp || 'label', 'formatter']
  18883. : [status, labelProp || 'label', 'formatter']
  18884. );
  18885. if (typeof formatter === 'function') {
  18886. params.status = status;
  18887. return formatter(params);
  18888. }
  18889. else if (typeof formatter === 'string') {
  18890. var str = formatTpl(formatter, params);
  18891. // Support 'aaa{@[3]}bbb{@product}ccc'.
  18892. // Do not support '}' in dim name util have to.
  18893. return str.replace(DIMENSION_LABEL_REG, function (origin, dim) {
  18894. var len = dim.length;
  18895. if (dim.charAt(0) === '[' && dim.charAt(len - 1) === ']') {
  18896. dim = +dim.slice(1, len - 1); // Also: '[]' => 0
  18897. }
  18898. return retrieveRawValue(data, dataIndex, dim);
  18899. });
  18900. }
  18901. },
  18902. /**
  18903. * Get raw value in option
  18904. * @param {number} idx
  18905. * @param {string} [dataType]
  18906. * @return {Array|number|string}
  18907. */
  18908. getRawValue: function (idx, dataType) {
  18909. return retrieveRawValue(this.getData(dataType), idx);
  18910. },
  18911. /**
  18912. * Should be implemented.
  18913. * @param {number} dataIndex
  18914. * @param {boolean} [multipleSeries=false]
  18915. * @param {number} [dataType]
  18916. * @return {string} tooltip string
  18917. */
  18918. formatTooltip: function () {
  18919. // Empty function
  18920. }
  18921. };
  18922. /**
  18923. * @param {Object} define
  18924. * @return See the return of `createTask`.
  18925. */
  18926. function createTask(define) {
  18927. return new Task(define);
  18928. }
  18929. /**
  18930. * @constructor
  18931. * @param {Object} define
  18932. * @param {Function} define.reset Custom reset
  18933. * @param {Function} [define.plan] Returns 'reset' indicate reset immediately.
  18934. * @param {Function} [define.count] count is used to determin data task.
  18935. * @param {Function} [define.onDirty] count is used to determin data task.
  18936. */
  18937. function Task(define) {
  18938. define = define || {};
  18939. this._reset = define.reset;
  18940. this._plan = define.plan;
  18941. this._count = define.count;
  18942. this._onDirty = define.onDirty;
  18943. this._dirty = true;
  18944. // Context must be specified implicitly, to
  18945. // avoid miss update context when model changed.
  18946. this.context;
  18947. }
  18948. var taskProto = Task.prototype;
  18949. /**
  18950. * @param {Object} performArgs
  18951. * @param {number} [performArgs.step] Specified step.
  18952. * @param {number} [performArgs.skip] Skip customer perform call.
  18953. */
  18954. taskProto.perform = function (performArgs) {
  18955. var upTask = this._upstream;
  18956. var skip = performArgs && performArgs.skip;
  18957. // TODO some refactor.
  18958. // Pull data. Must pull data each time, because context.data
  18959. // may be updated by Series.setData.
  18960. if (this._dirty && upTask) {
  18961. var context = this.context;
  18962. context.data = context.outputData = upTask.context.outputData;
  18963. }
  18964. if (this.__pipeline) {
  18965. this.__pipeline.currentTask = this;
  18966. }
  18967. var planResult;
  18968. if (this._plan && !skip) {
  18969. planResult = this._plan(this.context);
  18970. }
  18971. var forceFirstProgress;
  18972. if (this._dirty || planResult === 'reset') {
  18973. this._dirty = false;
  18974. forceFirstProgress = reset(this, skip);
  18975. }
  18976. var step = performArgs && performArgs.step;
  18977. if (upTask) {
  18978. if (__DEV__) {
  18979. assert$1(upTask._outputDueEnd != null);
  18980. }
  18981. // ??? FIXME move to schedueler?
  18982. // this._dueEnd = Math.max(upTask._outputDueEnd, this._dueEnd);
  18983. this._dueEnd = upTask._outputDueEnd;
  18984. }
  18985. // DataTask or overallTask
  18986. else {
  18987. if (__DEV__) {
  18988. assert$1(!this._progress || this._count);
  18989. }
  18990. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  18991. }
  18992. // Note: Stubs, that its host overall task let it has progress, has progress.
  18993. // If no progress, pass index from upstream to downstream each time plan called.
  18994. if (this._progress) {
  18995. var start = this._dueIndex;
  18996. var end = Math.min(
  18997. step != null ? this._dueIndex + step : Infinity,
  18998. this._dueEnd
  18999. );
  19000. !skip && (forceFirstProgress || start < end) && (
  19001. this._progress({start: start, end: end}, this.context)
  19002. );
  19003. this._dueIndex = end;
  19004. // If no `outputDueEnd`, assume that output data and
  19005. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  19006. var outputDueEnd = this._settedOutputEnd != null
  19007. ? this._settedOutputEnd : end;
  19008. if (__DEV__) {
  19009. // ??? Can not rollback.
  19010. assert$1(outputDueEnd >= this._outputDueEnd);
  19011. }
  19012. this._outputDueEnd = outputDueEnd;
  19013. }
  19014. else {
  19015. // (1) Some overall task has no progress.
  19016. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  19017. // This should always be performed so it can be passed to downstream.
  19018. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null
  19019. ? this._settedOutputEnd : this._dueEnd;
  19020. }
  19021. return this.unfinished();
  19022. };
  19023. taskProto.dirty = function () {
  19024. this._dirty = true;
  19025. this._onDirty && this._onDirty(this.context);
  19026. };
  19027. /**
  19028. * @param {Object} [params]
  19029. */
  19030. function reset(taskIns, skip) {
  19031. taskIns._dueIndex = taskIns._outputDueEnd = taskIns._dueEnd = 0;
  19032. taskIns._settedOutputEnd = null;
  19033. var progress;
  19034. var forceFirstProgress;
  19035. if (!skip && taskIns._reset) {
  19036. progress = taskIns._reset(taskIns.context);
  19037. if (progress && progress.progress) {
  19038. forceFirstProgress = progress.forceFirstProgress;
  19039. progress = progress.progress;
  19040. }
  19041. }
  19042. taskIns._progress = progress;
  19043. var downstream = taskIns._downstream;
  19044. downstream && downstream.dirty();
  19045. return forceFirstProgress;
  19046. }
  19047. /**
  19048. * @return {boolean}
  19049. */
  19050. taskProto.unfinished = function () {
  19051. return this._progress && this._dueIndex < this._dueEnd;
  19052. };
  19053. /**
  19054. * @param {Object} downTask The downstream task.
  19055. * @return {Object} The downstream task.
  19056. */
  19057. taskProto.pipe = function (downTask) {
  19058. if (__DEV__) {
  19059. assert$1(downTask && !downTask._disposed && downTask !== this);
  19060. }
  19061. // If already downstream, do not dirty downTask.
  19062. if (this._downstream !== downTask || this._dirty) {
  19063. this._downstream = downTask;
  19064. downTask._upstream = this;
  19065. downTask.dirty();
  19066. }
  19067. };
  19068. taskProto.dispose = function () {
  19069. if (this._disposed) {
  19070. return;
  19071. }
  19072. this._upstream && (this._upstream._downstream = null);
  19073. this._downstream && (this._downstream._upstream = null);
  19074. this._dirty = false;
  19075. this._disposed = true;
  19076. };
  19077. taskProto.getUpstream = function () {
  19078. return this._upstream;
  19079. };
  19080. taskProto.getDownstream = function () {
  19081. return this._downstream;
  19082. };
  19083. taskProto.setOutputEnd = function (end) {
  19084. // ??? FIXME: check
  19085. // This only happend in dataTask, dataZoom, map, currently.
  19086. // where dataZoom do not set end each time, but only set
  19087. // when reset. So we should record the setted end, in case
  19088. // that the stub of dataZoom perform again and earse the
  19089. // setted end by upstream.
  19090. this._outputDueEnd = this._settedOutputEnd = end;
  19091. // this._outputDueEnd = end;
  19092. };
  19093. ///////////////////////////////////////////////////////////
  19094. // For stream debug (Should be commented out after used!)
  19095. // Usage: printTask(this, 'begin');
  19096. // Usage: printTask(this, null, {someExtraProp});
  19097. // function printTask(task, prefix, extra) {
  19098. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  19099. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  19100. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  19101. // var props = [];
  19102. // if (task.__pipeline) {
  19103. // var val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  19104. // props.push({text: 'idx', value: val});
  19105. // } else {
  19106. // var stubCount = 0;
  19107. // task.agentStubMap.each(() => stubCount++);
  19108. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  19109. // }
  19110. // props.push({text: 'uid', value: task.uidDebug});
  19111. // if (task.__pipeline) {
  19112. // props.push({text: 'pid', value: task.__pipeline.id});
  19113. // task.agent && props.push(
  19114. // {text: 'stubFor', value: task.agent.uidDebug}
  19115. // );
  19116. // }
  19117. // props.push(
  19118. // {text: 'dirty', value: task._dirty},
  19119. // {text: 'dueIndex', value: task._dueIndex},
  19120. // {text: 'dueEnd', value: task._dueEnd},
  19121. // {text: 'outputDueEnd', value: task._outputDueEnd}
  19122. // );
  19123. // if (extra) {
  19124. // Object.keys(extra).forEach(key => {
  19125. // props.push({text: key, value: extra[key]});
  19126. // });
  19127. // }
  19128. // var args = ['color: blue'];
  19129. // var msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  19130. // args.push('color: black', 'color: red'),
  19131. // `${item.text}: %c${item.value}`
  19132. // )).join('%c, ');
  19133. // console.log.apply(console, [msg].concat(args));
  19134. // // console.log(this);
  19135. // }
  19136. var inner$4 = makeInner();
  19137. var SeriesModel = ComponentModel.extend({
  19138. type: 'series.__base__',
  19139. /**
  19140. * @readOnly
  19141. */
  19142. seriesIndex: 0,
  19143. // coodinateSystem will be injected in the echarts/CoordinateSystem
  19144. coordinateSystem: null,
  19145. /**
  19146. * @type {Object}
  19147. * @protected
  19148. */
  19149. defaultOption: null,
  19150. /**
  19151. * Data provided for legend
  19152. * @type {Function}
  19153. */
  19154. // PENDING
  19155. legendDataProvider: null,
  19156. /**
  19157. * Access path of color for visual
  19158. */
  19159. visualColorAccessPath: 'itemStyle.color',
  19160. /**
  19161. * Support merge layout params.
  19162. * Only support 'box' now (left/right/top/bottom/width/height).
  19163. * @type {string|Object} Object can be {ignoreSize: true}
  19164. * @readOnly
  19165. */
  19166. layoutMode: null,
  19167. init: function (option, parentModel, ecModel, extraOpt) {
  19168. /**
  19169. * @type {number}
  19170. * @readOnly
  19171. */
  19172. this.seriesIndex = this.componentIndex;
  19173. this.dataTask = createTask({
  19174. count: dataTaskCount,
  19175. reset: dataTaskReset
  19176. });
  19177. this.dataTask.context = {model: this};
  19178. this.mergeDefaultAndTheme(option, ecModel);
  19179. prepareSource(this);
  19180. var data = this.getInitialData(option, ecModel);
  19181. wrapData(data, this);
  19182. this.dataTask.context.data = data;
  19183. if (__DEV__) {
  19184. assert$1(data, 'getInitialData returned invalid data.');
  19185. }
  19186. /**
  19187. * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
  19188. * @private
  19189. */
  19190. inner$4(this).dataBeforeProcessed = data;
  19191. // If we reverse the order (make data firstly, and then make
  19192. // dataBeforeProcessed by cloneShallow), cloneShallow will
  19193. // cause data.graph.data !== data when using
  19194. // module:echarts/data/Graph or module:echarts/data/Tree.
  19195. // See module:echarts/data/helper/linkList
  19196. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  19197. // init or merge stage, because the data can be restored. So we do not `restoreData`
  19198. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  19199. // Call `seriesModel.getRawData()` instead.
  19200. // this.restoreData();
  19201. autoSeriesName(this);
  19202. },
  19203. /**
  19204. * Util for merge default and theme to option
  19205. * @param {Object} option
  19206. * @param {module:echarts/model/Global} ecModel
  19207. */
  19208. mergeDefaultAndTheme: function (option, ecModel) {
  19209. var layoutMode = this.layoutMode;
  19210. var inputPositionParams = layoutMode
  19211. ? getLayoutParams(option) : {};
  19212. // Backward compat: using subType on theme.
  19213. // But if name duplicate between series subType
  19214. // (for example: parallel) add component mainType,
  19215. // add suffix 'Series'.
  19216. var themeSubType = this.subType;
  19217. if (ComponentModel.hasClass(themeSubType)) {
  19218. themeSubType += 'Series';
  19219. }
  19220. merge(
  19221. option,
  19222. ecModel.getTheme().get(this.subType)
  19223. );
  19224. merge(option, this.getDefaultOption());
  19225. // Default label emphasis `show`
  19226. defaultEmphasis(option, 'label', ['show']);
  19227. this.fillDataTextStyle(option.data);
  19228. if (layoutMode) {
  19229. mergeLayoutParam(option, inputPositionParams, layoutMode);
  19230. }
  19231. },
  19232. mergeOption: function (newSeriesOption, ecModel) {
  19233. // this.settingTask.dirty();
  19234. newSeriesOption = merge(this.option, newSeriesOption, true);
  19235. this.fillDataTextStyle(newSeriesOption.data);
  19236. var layoutMode = this.layoutMode;
  19237. if (layoutMode) {
  19238. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  19239. }
  19240. prepareSource(this);
  19241. var data = this.getInitialData(newSeriesOption, ecModel);
  19242. wrapData(data, this);
  19243. this.dataTask.dirty();
  19244. this.dataTask.context.data = data;
  19245. inner$4(this).dataBeforeProcessed = data;
  19246. autoSeriesName(this);
  19247. },
  19248. fillDataTextStyle: function (data) {
  19249. // Default data label emphasis `show`
  19250. // FIXME Tree structure data ?
  19251. // FIXME Performance ?
  19252. if (data) {
  19253. var props = ['show'];
  19254. for (var i = 0; i < data.length; i++) {
  19255. if (data[i] && data[i].label) {
  19256. defaultEmphasis(data[i], 'label', props);
  19257. }
  19258. }
  19259. }
  19260. },
  19261. /**
  19262. * Init a data structure from data related option in series
  19263. * Must be overwritten
  19264. */
  19265. getInitialData: function () {},
  19266. /**
  19267. * Append data to list
  19268. * @param {Object} params
  19269. * @param {Array|TypedArray} params.data
  19270. */
  19271. appendData: function (params) {
  19272. // FIXME ???
  19273. // (1) If data from dataset, forbidden append.
  19274. // (2) support append data of dataset.
  19275. var data = this.getRawData();
  19276. data.appendData(params.data);
  19277. },
  19278. /**
  19279. * Consider some method like `filter`, `map` need make new data,
  19280. * We should make sure that `seriesModel.getData()` get correct
  19281. * data in the stream procedure. So we fetch data from upstream
  19282. * each time `task.perform` called.
  19283. * @param {string} [dataType]
  19284. * @return {module:echarts/data/List}
  19285. */
  19286. getData: function (dataType) {
  19287. var task = getCurrentTask(this);
  19288. if (task) {
  19289. var data = task.context.data;
  19290. return dataType == null ? data : data.getLinkedData(dataType);
  19291. }
  19292. else {
  19293. // When series is not alive (that may happen when click toolbox
  19294. // restore or setOption with not merge mode), series data may
  19295. // be still need to judge animation or something when graphic
  19296. // elements want to know whether fade out.
  19297. return inner$4(this).data;
  19298. }
  19299. },
  19300. /**
  19301. * @param {module:echarts/data/List} data
  19302. */
  19303. setData: function (data) {
  19304. var task = getCurrentTask(this);
  19305. if (task) {
  19306. var context = task.context;
  19307. // Consider case: filter, data sample.
  19308. if (context.data !== data && task.isOverallFilter) {
  19309. task.setOutputEnd(data.count());
  19310. }
  19311. context.outputData = data;
  19312. // Caution: setData should update context.data,
  19313. // Because getData may be called multiply in a
  19314. // single stage and expect to get the data just
  19315. // set. (For example, AxisProxy, x y both call
  19316. // getData and setDate sequentially).
  19317. // So the context.data should be fetched from
  19318. // upstream each time when a stage starts to be
  19319. // performed.
  19320. if (task !== this.dataTask) {
  19321. context.data = data;
  19322. }
  19323. }
  19324. inner$4(this).data = data;
  19325. },
  19326. /**
  19327. * @see {module:echarts/data/helper/sourceHelper#getSource}
  19328. * @return {module:echarts/data/Source} source
  19329. */
  19330. getSource: function () {
  19331. return getSource(this);
  19332. },
  19333. /**
  19334. * Get data before processed
  19335. * @return {module:echarts/data/List}
  19336. */
  19337. getRawData: function () {
  19338. return inner$4(this).dataBeforeProcessed;
  19339. },
  19340. /**
  19341. * Get base axis if has coordinate system and has axis.
  19342. * By default use coordSys.getBaseAxis();
  19343. * Can be overrided for some chart.
  19344. * @return {type} description
  19345. */
  19346. getBaseAxis: function () {
  19347. var coordSys = this.coordinateSystem;
  19348. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  19349. },
  19350. // FIXME
  19351. /**
  19352. * Default tooltip formatter
  19353. *
  19354. * @param {number} dataIndex
  19355. * @param {boolean} [multipleSeries=false]
  19356. * @param {number} [dataType]
  19357. */
  19358. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  19359. function formatArrayValue(value) {
  19360. // ??? TODO refactor these logic.
  19361. // check: category-no-encode-has-axis-data in dataset.html
  19362. var vertially = reduce(value, function (vertially, val, idx) {
  19363. var dimItem = data.getDimensionInfo(idx);
  19364. return vertially |= dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  19365. }, 0);
  19366. var result = [];
  19367. tooltipDims.length
  19368. ? each$1(tooltipDims, function (dim) {
  19369. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  19370. })
  19371. // By default, all dims is used on tooltip.
  19372. : each$1(value, setEachItem);
  19373. function setEachItem(val, dim) {
  19374. var dimInfo = data.getDimensionInfo(dim);
  19375. // If `dimInfo.tooltip` is not set, show tooltip.
  19376. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  19377. return;
  19378. }
  19379. var dimType = dimInfo.type;
  19380. var dimHead = getTooltipMarker({color: color, type: 'subItem'});
  19381. var valStr = (vertially
  19382. ? dimHead + encodeHTML(dimInfo.displayName || '-') + ': '
  19383. : ''
  19384. )
  19385. // FIXME should not format time for raw data?
  19386. + encodeHTML(dimType === 'ordinal'
  19387. ? val + ''
  19388. : dimType === 'time'
  19389. ? (multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val))
  19390. : addCommas(val)
  19391. );
  19392. valStr && result.push(valStr);
  19393. }
  19394. return (vertially ? '<br/>' : '') + result.join(vertially ? '<br/>' : ', ');
  19395. }
  19396. function formatSingleValue(val) {
  19397. return encodeHTML(addCommas(val));
  19398. }
  19399. var data = this.getData();
  19400. var tooltipDims = data.mapDimension('defaultedTooltip', true);
  19401. var tooltipDimLen = tooltipDims.length;
  19402. var value = this.getRawValue(dataIndex);
  19403. var isValueArr = isArray(value);
  19404. var color = data.getItemVisual(dataIndex, 'color');
  19405. if (isObject$1(color) && color.colorStops) {
  19406. color = (color.colorStops[0] || {}).color;
  19407. }
  19408. color = color || 'transparent';
  19409. // Complicated rule for pretty tooltip.
  19410. var formattedValue = (tooltipDimLen > 1 || (isValueArr && !tooltipDimLen))
  19411. ? formatArrayValue(value)
  19412. : tooltipDimLen
  19413. ? formatSingleValue(retrieveRawValue(data, dataIndex, tooltipDims[0]))
  19414. : formatSingleValue(isValueArr ? value[0] : value);
  19415. var colorEl = getTooltipMarker(color);
  19416. var name = data.getName(dataIndex);
  19417. var seriesName = this.name;
  19418. if (!isNameSpecified(this)) {
  19419. seriesName = '';
  19420. }
  19421. seriesName = seriesName
  19422. ? encodeHTML(seriesName) + (!multipleSeries ? '<br/>' : ': ')
  19423. : '';
  19424. return !multipleSeries
  19425. ? seriesName + colorEl
  19426. + (name
  19427. ? encodeHTML(name) + ': ' + formattedValue
  19428. : formattedValue
  19429. )
  19430. : colorEl + seriesName + formattedValue;
  19431. },
  19432. /**
  19433. * @return {boolean}
  19434. */
  19435. isAnimationEnabled: function () {
  19436. if (env$1.node) {
  19437. return false;
  19438. }
  19439. var animationEnabled = this.getShallow('animation');
  19440. if (animationEnabled) {
  19441. if (this.getData().count() > this.getShallow('animationThreshold')) {
  19442. animationEnabled = false;
  19443. }
  19444. }
  19445. return animationEnabled;
  19446. },
  19447. restoreData: function () {
  19448. this.dataTask.dirty();
  19449. },
  19450. getColorFromPalette: function (name, scope, requestColorNum) {
  19451. var ecModel = this.ecModel;
  19452. // PENDING
  19453. var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope, requestColorNum);
  19454. if (!color) {
  19455. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  19456. }
  19457. return color;
  19458. },
  19459. /**
  19460. * Use `data.mapDimension(coordDim, true)` instead.
  19461. * @deprecated
  19462. */
  19463. coordDimToDataDim: function (coordDim) {
  19464. return this.getRawData().mapDimension(coordDim, true);
  19465. },
  19466. /**
  19467. * Get progressive rendering count each step
  19468. * @return {number}
  19469. */
  19470. getProgressive: function () {
  19471. return this.get('progressive');
  19472. },
  19473. /**
  19474. * Get progressive rendering count each step
  19475. * @return {number}
  19476. */
  19477. getProgressiveThreshold: function () {
  19478. return this.get('progressiveThreshold');
  19479. },
  19480. /**
  19481. * Get data indices for show tooltip content. See tooltip.
  19482. * @abstract
  19483. * @param {Array.<string>|string} dim
  19484. * @param {Array.<number>} value
  19485. * @param {module:echarts/coord/single/SingleAxis} baseAxis
  19486. * @return {Object} {dataIndices, nestestValue}.
  19487. */
  19488. getAxisTooltipData: null,
  19489. /**
  19490. * See tooltip.
  19491. * @abstract
  19492. * @param {number} dataIndex
  19493. * @return {Array.<number>} Point of tooltip. null/undefined can be returned.
  19494. */
  19495. getTooltipPosition: null,
  19496. /**
  19497. * @see {module:echarts/stream/Scheduler}
  19498. */
  19499. pipeTask: null,
  19500. /**
  19501. * Convinient for override in extended class.
  19502. * @protected
  19503. * @type {Function}
  19504. */
  19505. preventIncremental: null,
  19506. /**
  19507. * @public
  19508. * @readOnly
  19509. * @type {Object}
  19510. */
  19511. pipelineContext: null
  19512. });
  19513. mixin(SeriesModel, dataFormatMixin);
  19514. mixin(SeriesModel, colorPaletteMixin);
  19515. /**
  19516. * MUST be called after `prepareSource` called
  19517. * Here we need to make auto series, especially for auto legend. But we
  19518. * do not modify series.name in option to avoid side effects.
  19519. */
  19520. function autoSeriesName(seriesModel) {
  19521. // User specified name has higher priority, otherwise it may cause
  19522. // series can not be queried unexpectedly.
  19523. var name = seriesModel.name;
  19524. if (!isNameSpecified(seriesModel)) {
  19525. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  19526. }
  19527. }
  19528. function getSeriesAutoName(seriesModel) {
  19529. var data = seriesModel.getRawData();
  19530. var dataDims = data.mapDimension('seriesName', true);
  19531. var nameArr = [];
  19532. each$1(dataDims, function (dataDim) {
  19533. var dimInfo = data.getDimensionInfo(dataDim);
  19534. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  19535. });
  19536. return nameArr.join(' ');
  19537. }
  19538. function dataTaskCount(context) {
  19539. return context.model.getRawData().count();
  19540. }
  19541. function dataTaskReset(context) {
  19542. var seriesModel = context.model;
  19543. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  19544. return dataTaskProgress;
  19545. }
  19546. function dataTaskProgress(param, context) {
  19547. // Avoid repead cloneShallow when data just created in reset.
  19548. if (param.end > context.outputData.count()) {
  19549. context.model.getRawData().cloneShallow(context.outputData);
  19550. }
  19551. }
  19552. // TODO refactor
  19553. function wrapData(data, seriesModel) {
  19554. each$1(data.CHANGABLE_METHODS, function (methodName) {
  19555. data.wrapMethod(methodName, curry(onDataSelfChange, seriesModel));
  19556. });
  19557. }
  19558. function onDataSelfChange(seriesModel) {
  19559. var task = getCurrentTask(seriesModel);
  19560. if (task) {
  19561. // Consider case: filter, selectRange
  19562. task.setOutputEnd(this.count());
  19563. }
  19564. }
  19565. function getCurrentTask(seriesModel) {
  19566. var scheduler = (seriesModel.ecModel || {}).scheduler;
  19567. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  19568. if (pipeline) {
  19569. // When pipline finished, the currrentTask keep the last
  19570. // task (renderTask).
  19571. var task = pipeline.currentTask;
  19572. if (task) {
  19573. var agentStubMap = task.agentStubMap;
  19574. if (agentStubMap) {
  19575. task = agentStubMap.get(seriesModel.uid);
  19576. }
  19577. }
  19578. return task;
  19579. }
  19580. }
  19581. var Component$1 = function () {
  19582. /**
  19583. * @type {module:zrender/container/Group}
  19584. * @readOnly
  19585. */
  19586. this.group = new Group();
  19587. /**
  19588. * @type {string}
  19589. * @readOnly
  19590. */
  19591. this.uid = getUID('viewComponent');
  19592. };
  19593. Component$1.prototype = {
  19594. constructor: Component$1,
  19595. init: function (ecModel, api) {},
  19596. render: function (componentModel, ecModel, api, payload) {},
  19597. dispose: function () {}
  19598. };
  19599. var componentProto = Component$1.prototype;
  19600. componentProto.updateView
  19601. = componentProto.updateLayout
  19602. = componentProto.updateVisual
  19603. = function (seriesModel, ecModel, api, payload) {
  19604. // Do nothing;
  19605. };
  19606. // Enable Component.extend.
  19607. enableClassExtend(Component$1);
  19608. // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  19609. enableClassManagement(Component$1, {registerWhenExtend: true});
  19610. /**
  19611. * @return {string} If large mode changed, return string 'reset';
  19612. */
  19613. var createRenderPlanner = function () {
  19614. var inner = makeInner();
  19615. return function (seriesModel) {
  19616. var fields = inner(seriesModel);
  19617. var pipelineContext = seriesModel.pipelineContext;
  19618. var originalLarge = fields.large;
  19619. var originalProgressive = fields.canProgressiveRender;
  19620. var large = fields.large = pipelineContext.large;
  19621. var progressive = fields.canProgressiveRender = pipelineContext.canProgressiveRender;
  19622. return !!((originalLarge ^ large) || (originalProgressive ^ progressive)) && 'reset';
  19623. };
  19624. };
  19625. var inner$5 = makeInner();
  19626. var renderPlanner = createRenderPlanner();
  19627. function Chart() {
  19628. /**
  19629. * @type {module:zrender/container/Group}
  19630. * @readOnly
  19631. */
  19632. this.group = new Group();
  19633. /**
  19634. * @type {string}
  19635. * @readOnly
  19636. */
  19637. this.uid = getUID('viewChart');
  19638. this.renderTask = createTask({
  19639. plan: renderTaskPlan,
  19640. reset: renderTaskReset
  19641. });
  19642. this.renderTask.context = {view: this};
  19643. }
  19644. Chart.prototype = {
  19645. type: 'chart',
  19646. /**
  19647. * Init the chart.
  19648. * @param {module:echarts/model/Global} ecModel
  19649. * @param {module:echarts/ExtensionAPI} api
  19650. */
  19651. init: function (ecModel, api) {},
  19652. /**
  19653. * Render the chart.
  19654. * @param {module:echarts/model/Series} seriesModel
  19655. * @param {module:echarts/model/Global} ecModel
  19656. * @param {module:echarts/ExtensionAPI} api
  19657. * @param {Object} payload
  19658. */
  19659. render: function (seriesModel, ecModel, api, payload) {},
  19660. /**
  19661. * Highlight series or specified data item.
  19662. * @param {module:echarts/model/Series} seriesModel
  19663. * @param {module:echarts/model/Global} ecModel
  19664. * @param {module:echarts/ExtensionAPI} api
  19665. * @param {Object} payload
  19666. */
  19667. highlight: function (seriesModel, ecModel, api, payload) {
  19668. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  19669. },
  19670. /**
  19671. * Downplay series or specified data item.
  19672. * @param {module:echarts/model/Series} seriesModel
  19673. * @param {module:echarts/model/Global} ecModel
  19674. * @param {module:echarts/ExtensionAPI} api
  19675. * @param {Object} payload
  19676. */
  19677. downplay: function (seriesModel, ecModel, api, payload) {
  19678. toggleHighlight(seriesModel.getData(), payload, 'normal');
  19679. },
  19680. /**
  19681. * Remove self.
  19682. * @param {module:echarts/model/Global} ecModel
  19683. * @param {module:echarts/ExtensionAPI} api
  19684. */
  19685. remove: function (ecModel, api) {
  19686. this.group.removeAll();
  19687. },
  19688. /**
  19689. * Dispose self.
  19690. * @param {module:echarts/model/Global} ecModel
  19691. * @param {module:echarts/ExtensionAPI} api
  19692. */
  19693. dispose: function () {},
  19694. /**
  19695. * Rendering preparation in progressive mode.
  19696. * @param {module:echarts/model/Series} seriesModel
  19697. * @param {module:echarts/model/Global} ecModel
  19698. * @param {module:echarts/ExtensionAPI} api
  19699. * @param {Object} payload
  19700. */
  19701. incrementalPrepareRender: null,
  19702. /**
  19703. * Render in progressive mode.
  19704. * @param {module:echarts/model/Series} seriesModel
  19705. * @param {module:echarts/model/Global} ecModel
  19706. * @param {module:echarts/ExtensionAPI} api
  19707. * @param {Object} payload
  19708. */
  19709. incrementalRender: null,
  19710. /**
  19711. * Update transform directly.
  19712. * @param {module:echarts/model/Series} seriesModel
  19713. * @param {module:echarts/model/Global} ecModel
  19714. * @param {module:echarts/ExtensionAPI} api
  19715. * @param {Object} payload
  19716. * @return {Object} {update: true}
  19717. */
  19718. updateTransform: null
  19719. /**
  19720. * The view contains the given point.
  19721. * @interface
  19722. * @param {Array.<number>} point
  19723. * @return {boolean}
  19724. */
  19725. // containPoint: function () {}
  19726. };
  19727. var chartProto = Chart.prototype;
  19728. chartProto.updateView
  19729. = chartProto.updateLayout
  19730. = chartProto.updateVisual
  19731. = function (seriesModel, ecModel, api, payload) {
  19732. this.render(seriesModel, ecModel, api, payload);
  19733. };
  19734. /**
  19735. * Set state of single element
  19736. * @param {module:zrender/Element} el
  19737. * @param {string} state
  19738. */
  19739. function elSetState(el, state) {
  19740. if (el) {
  19741. el.trigger(state);
  19742. if (el.type === 'group') {
  19743. for (var i = 0; i < el.childCount(); i++) {
  19744. elSetState(el.childAt(i), state);
  19745. }
  19746. }
  19747. }
  19748. }
  19749. /**
  19750. * @param {module:echarts/data/List} data
  19751. * @param {Object} payload
  19752. * @param {string} state 'normal'|'emphasis'
  19753. */
  19754. function toggleHighlight(data, payload, state) {
  19755. var dataIndex = queryDataIndex(data, payload);
  19756. if (dataIndex != null) {
  19757. each$1(normalizeToArray(dataIndex), function (dataIdx) {
  19758. elSetState(data.getItemGraphicEl(dataIdx), state);
  19759. });
  19760. }
  19761. else {
  19762. data.eachItemGraphicEl(function (el) {
  19763. elSetState(el, state);
  19764. });
  19765. }
  19766. }
  19767. // Enable Chart.extend.
  19768. enableClassExtend(Chart, ['dispose']);
  19769. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  19770. enableClassManagement(Chart, {registerWhenExtend: true});
  19771. Chart.markUpdateMethod = function (payload, methodName) {
  19772. inner$5(payload).updateMethod = methodName;
  19773. };
  19774. function renderTaskPlan(context) {
  19775. return renderPlanner(context.model);
  19776. }
  19777. function renderTaskReset(context) {
  19778. var seriesModel = context.model;
  19779. var ecModel = context.ecModel;
  19780. var api = context.api;
  19781. var payload = context.payload;
  19782. // ???! remove updateView updateVisual
  19783. var canProgressiveRender = seriesModel.pipelineContext.canProgressiveRender;
  19784. var view = context.view;
  19785. var updateMethod = payload && inner$5(payload).updateMethod;
  19786. var methodName = canProgressiveRender
  19787. ? 'incrementalPrepareRender'
  19788. : (updateMethod && view[updateMethod])
  19789. ? updateMethod
  19790. // `appendData` is also supported when data amount
  19791. // is less than progressive threshold.
  19792. : 'render';
  19793. if (methodName !== 'render') {
  19794. view[methodName](seriesModel, ecModel, api, payload);
  19795. }
  19796. return progressMethodMap[methodName];
  19797. }
  19798. var progressMethodMap = {
  19799. incrementalPrepareRender: {
  19800. progress: function (params, context) {
  19801. context.view.incrementalRender(
  19802. params, context.model, context.ecModel, context.api, context.payload
  19803. );
  19804. }
  19805. },
  19806. render: {
  19807. // Put view.render in `progress` to support appendData. But in this case
  19808. // view.render should not be called in reset, otherwise it will be called
  19809. // twise. Use `forceFirstProgress` to make sure that view.render is called
  19810. // in any cases.
  19811. forceFirstProgress: true,
  19812. progress: function (params, context) {
  19813. context.view.render(
  19814. context.model, context.ecModel, context.api, context.payload
  19815. );
  19816. }
  19817. }
  19818. };
  19819. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  19820. var RATE = '\0__throttleRate';
  19821. var THROTTLE_TYPE = '\0__throttleType';
  19822. /**
  19823. * @public
  19824. * @param {(Function)} fn
  19825. * @param {number} [delay=0] Unit: ms.
  19826. * @param {boolean} [debounce=false]
  19827. * true: If call interval less than `delay`, only the last call works.
  19828. * false: If call interval less than `delay, call works on fixed rate.
  19829. * @return {(Function)} throttled fn.
  19830. */
  19831. function throttle(fn, delay, debounce) {
  19832. var currCall;
  19833. var lastCall = 0;
  19834. var lastExec = 0;
  19835. var timer = null;
  19836. var diff;
  19837. var scope;
  19838. var args;
  19839. var debounceNextCall;
  19840. delay = delay || 0;
  19841. function exec() {
  19842. lastExec = (new Date()).getTime();
  19843. timer = null;
  19844. fn.apply(scope, args || []);
  19845. }
  19846. var cb = function () {
  19847. currCall = (new Date()).getTime();
  19848. scope = this;
  19849. args = arguments;
  19850. var thisDelay = debounceNextCall || delay;
  19851. var thisDebounce = debounceNextCall || debounce;
  19852. debounceNextCall = null;
  19853. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  19854. clearTimeout(timer);
  19855. if (thisDebounce) {
  19856. timer = setTimeout(exec, thisDelay);
  19857. }
  19858. else {
  19859. if (diff >= 0) {
  19860. exec();
  19861. }
  19862. else {
  19863. timer = setTimeout(exec, -diff);
  19864. }
  19865. }
  19866. lastCall = currCall;
  19867. };
  19868. /**
  19869. * Clear throttle.
  19870. * @public
  19871. */
  19872. cb.clear = function () {
  19873. if (timer) {
  19874. clearTimeout(timer);
  19875. timer = null;
  19876. }
  19877. };
  19878. /**
  19879. * Enable debounce once.
  19880. */
  19881. cb.debounceNextCall = function (debounceDelay) {
  19882. debounceNextCall = debounceDelay;
  19883. };
  19884. return cb;
  19885. }
  19886. /**
  19887. * Create throttle method or update throttle rate.
  19888. *
  19889. * @example
  19890. * ComponentView.prototype.render = function () {
  19891. * ...
  19892. * throttle.createOrUpdate(
  19893. * this,
  19894. * '_dispatchAction',
  19895. * this.model.get('throttle'),
  19896. * 'fixRate'
  19897. * );
  19898. * };
  19899. * ComponentView.prototype.remove = function () {
  19900. * throttle.clear(this, '_dispatchAction');
  19901. * };
  19902. * ComponentView.prototype.dispose = function () {
  19903. * throttle.clear(this, '_dispatchAction');
  19904. * };
  19905. *
  19906. * @public
  19907. * @param {Object} obj
  19908. * @param {string} fnAttr
  19909. * @param {number} [rate]
  19910. * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce'
  19911. * @return {Function} throttled function.
  19912. */
  19913. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  19914. var fn = obj[fnAttr];
  19915. if (!fn) {
  19916. return;
  19917. }
  19918. var originFn = fn[ORIGIN_METHOD] || fn;
  19919. var lastThrottleType = fn[THROTTLE_TYPE];
  19920. var lastRate = fn[RATE];
  19921. if (lastRate !== rate || lastThrottleType !== throttleType) {
  19922. if (rate == null || !throttleType) {
  19923. return (obj[fnAttr] = originFn);
  19924. }
  19925. fn = obj[fnAttr] = throttle(
  19926. originFn, rate, throttleType === 'debounce'
  19927. );
  19928. fn[ORIGIN_METHOD] = originFn;
  19929. fn[THROTTLE_TYPE] = throttleType;
  19930. fn[RATE] = rate;
  19931. }
  19932. return fn;
  19933. }
  19934. /**
  19935. * Clear throttle. Example see throttle.createOrUpdate.
  19936. *
  19937. * @public
  19938. * @param {Object} obj
  19939. * @param {string} fnAttr
  19940. */
  19941. function clear(obj, fnAttr) {
  19942. var fn = obj[fnAttr];
  19943. if (fn && fn[ORIGIN_METHOD]) {
  19944. obj[fnAttr] = fn[ORIGIN_METHOD];
  19945. }
  19946. }
  19947. var seriesColor = {
  19948. createOnAllSeries: true,
  19949. performRawSeries: true,
  19950. reset: function (seriesModel, ecModel) {
  19951. var data = seriesModel.getData();
  19952. var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.color').split('.');
  19953. var color = seriesModel.get(colorAccessPath) // Set in itemStyle
  19954. || seriesModel.getColorFromPalette(
  19955. // TODO series count changed.
  19956. seriesModel.name, null, ecModel.getSeriesCount()
  19957. ); // Default color
  19958. // FIXME Set color function or use the platte color
  19959. data.setVisual('color', color);
  19960. // Only visible series has each data be visual encoded
  19961. if (!ecModel.isSeriesFiltered(seriesModel)) {
  19962. if (typeof color === 'function' && !(color instanceof Gradient)) {
  19963. data.each(function (idx) {
  19964. data.setItemVisual(
  19965. idx, 'color', color(seriesModel.getDataParams(idx))
  19966. );
  19967. });
  19968. }
  19969. // itemStyle in each data item
  19970. var dataEach = function (data, idx) {
  19971. var itemModel = data.getItemModel(idx);
  19972. var color = itemModel.get(colorAccessPath, true);
  19973. if (color != null) {
  19974. data.setItemVisual(idx, 'color', color);
  19975. }
  19976. };
  19977. return { dataEach: data.hasItemOption ? dataEach : null };
  19978. }
  19979. }
  19980. };
  19981. var lang = {
  19982. toolbox: {
  19983. brush: {
  19984. title: {
  19985. rect: '矩形选择',
  19986. polygon: '圈选',
  19987. lineX: '横向选择',
  19988. lineY: '纵向选择',
  19989. keep: '保持选择',
  19990. clear: '清除选择'
  19991. }
  19992. },
  19993. dataView: {
  19994. title: '数据视图',
  19995. lang: ['数据视图', '关闭', '刷新']
  19996. },
  19997. dataZoom: {
  19998. title: {
  19999. zoom: '区域缩放',
  20000. back: '区域缩放还原'
  20001. }
  20002. },
  20003. magicType: {
  20004. title: {
  20005. line: '切换为折线图',
  20006. bar: '切换为柱状图',
  20007. stack: '切换为堆叠',
  20008. tiled: '切换为平铺'
  20009. }
  20010. },
  20011. restore: {
  20012. title: '还原'
  20013. },
  20014. saveAsImage: {
  20015. title: '保存为图片',
  20016. lang: ['右键另存为图片']
  20017. }
  20018. },
  20019. series: {
  20020. typeNames: {
  20021. pie: '饼图',
  20022. bar: '柱状图',
  20023. line: '折线图',
  20024. scatter: '散点图',
  20025. effectScatter: '涟漪散点图',
  20026. radar: '雷达图',
  20027. tree: '树图',
  20028. treemap: '矩形树图',
  20029. boxplot: '箱型图',
  20030. candlestick: 'K线图',
  20031. k: 'K线图',
  20032. heatmap: '热力图',
  20033. map: '地图',
  20034. parallel: '平行坐标图',
  20035. lines: '线图',
  20036. graph: '关系图',
  20037. sankey: '桑基图',
  20038. funnel: '漏斗图',
  20039. gauge: '仪表盘图',
  20040. pictorialBar: '象形柱图',
  20041. themeRiver: '主题河流图',
  20042. sunburst: '旭日图'
  20043. }
  20044. },
  20045. aria: {
  20046. general: {
  20047. withTitle: '这是一个关于“{title}”的图表。',
  20048. withoutTitle: '这是一个图表,'
  20049. },
  20050. series: {
  20051. single: {
  20052. prefix: '',
  20053. withName: '图表类型是{seriesType},表示{seriesName}。',
  20054. withoutName: '图表类型是{seriesType}。'
  20055. },
  20056. multiple: {
  20057. prefix: '它由{seriesCount}个图表系列组成。',
  20058. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  20059. withoutName: '第{seriesId}个系列是一个{seriesType},',
  20060. separator: {
  20061. middle: ';',
  20062. end: '。'
  20063. }
  20064. }
  20065. },
  20066. data: {
  20067. allData: '其数据是——',
  20068. partialData: '其中,前{displayCnt}项是——',
  20069. withName: '{name}的数据是{value}',
  20070. withoutName: '{value}',
  20071. separator: {
  20072. middle: ',',
  20073. end: ''
  20074. }
  20075. }
  20076. }
  20077. };
  20078. var aria = function (dom, ecModel) {
  20079. var ariaModel = ecModel.getModel('aria');
  20080. if (!ariaModel.get('show')) {
  20081. return;
  20082. }
  20083. else if (ariaModel.get('description')) {
  20084. dom.setAttribute('aria-label', ariaModel.get('description'));
  20085. return;
  20086. }
  20087. var seriesCnt = 0;
  20088. ecModel.eachSeries(function (seriesModel, idx) {
  20089. ++seriesCnt;
  20090. }, this);
  20091. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  20092. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  20093. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  20094. var ariaLabel;
  20095. if (seriesCnt < 1) {
  20096. // No series, no aria label
  20097. return;
  20098. }
  20099. else {
  20100. var title = getTitle();
  20101. if (title) {
  20102. ariaLabel = replace(getConfig('general.withTitle'), {
  20103. title: title
  20104. });
  20105. }
  20106. else {
  20107. ariaLabel = getConfig('general.withoutTitle');
  20108. }
  20109. var seriesLabels = [];
  20110. var prefix = seriesCnt > 1
  20111. ? 'series.multiple.prefix'
  20112. : 'series.single.prefix';
  20113. ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });
  20114. ecModel.eachSeries(function (seriesModel, idx) {
  20115. if (idx < displaySeriesCnt) {
  20116. var seriesLabel;
  20117. var seriesName = seriesModel.get('name');
  20118. var seriesTpl = 'series.'
  20119. + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  20120. seriesLabel = getConfig(seriesName
  20121. ? seriesTpl + 'withName'
  20122. : seriesTpl + 'withoutName');
  20123. seriesLabel = replace(seriesLabel, {
  20124. seriesId: seriesModel.seriesIndex,
  20125. seriesName: seriesModel.get('name'),
  20126. seriesType: getSeriesTypeName(seriesModel.subType)
  20127. });
  20128. var data = seriesModel.getData();
  20129. window.data = data;
  20130. if (data.count() > maxDataCnt) {
  20131. // Show part of data
  20132. seriesLabel += replace(getConfig('data.partialData'), {
  20133. displayCnt: maxDataCnt
  20134. });
  20135. }
  20136. else {
  20137. seriesLabel += getConfig('data.allData');
  20138. }
  20139. var dataLabels = [];
  20140. for (var i = 0; i < data.count(); i++) {
  20141. if (i < maxDataCnt) {
  20142. var name = data.getName(i);
  20143. var value = retrieveRawValue(data, i);
  20144. dataLabels.push(
  20145. replace(
  20146. name
  20147. ? getConfig('data.withName')
  20148. : getConfig('data.withoutName'),
  20149. {
  20150. name: name,
  20151. value: value
  20152. }
  20153. )
  20154. );
  20155. }
  20156. }
  20157. seriesLabel += dataLabels
  20158. .join(getConfig('data.separator.middle'))
  20159. + getConfig('data.separator.end');
  20160. seriesLabels.push(seriesLabel);
  20161. }
  20162. });
  20163. ariaLabel += seriesLabels
  20164. .join(getConfig('series.multiple.separator.middle'))
  20165. + getConfig('series.multiple.separator.end');
  20166. dom.setAttribute('aria-label', ariaLabel);
  20167. }
  20168. function replace(str, keyValues) {
  20169. if (typeof str !== 'string') {
  20170. return str;
  20171. }
  20172. var result = str;
  20173. each$1(keyValues, function (value, key) {
  20174. result = result.replace(
  20175. new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
  20176. value
  20177. );
  20178. });
  20179. return result;
  20180. }
  20181. function getConfig(path) {
  20182. var userConfig = ariaModel.get(path);
  20183. if (userConfig == null) {
  20184. var pathArr = path.split('.');
  20185. var result = lang.aria;
  20186. for (var i = 0; i < pathArr.length; ++i) {
  20187. result = result[pathArr[i]];
  20188. }
  20189. return result;
  20190. }
  20191. else {
  20192. return userConfig;
  20193. }
  20194. }
  20195. function getTitle() {
  20196. var title = ecModel.getModel('title').option;
  20197. if (title && title.length) {
  20198. title = title[0];
  20199. }
  20200. return title && title.text;
  20201. }
  20202. function getSeriesTypeName(type) {
  20203. return lang.series.typeNames[type] || '自定义图';
  20204. }
  20205. };
  20206. var PI$1 = Math.PI;
  20207. /**
  20208. * @param {module:echarts/ExtensionAPI} api
  20209. * @param {Object} [opts]
  20210. * @param {string} [opts.text]
  20211. * @param {string} [opts.color]
  20212. * @param {string} [opts.textColor]
  20213. * @return {module:zrender/Element}
  20214. */
  20215. var loadingDefault = function (api, opts) {
  20216. opts = opts || {};
  20217. defaults(opts, {
  20218. text: 'loading',
  20219. color: '#c23531',
  20220. textColor: '#000',
  20221. maskColor: 'rgba(255, 255, 255, 0.8)',
  20222. zlevel: 0
  20223. });
  20224. var mask = new Rect({
  20225. style: {
  20226. fill: opts.maskColor
  20227. },
  20228. zlevel: opts.zlevel,
  20229. z: 10000
  20230. });
  20231. var arc = new Arc({
  20232. shape: {
  20233. startAngle: -PI$1 / 2,
  20234. endAngle: -PI$1 / 2 + 0.1,
  20235. r: 10
  20236. },
  20237. style: {
  20238. stroke: opts.color,
  20239. lineCap: 'round',
  20240. lineWidth: 5
  20241. },
  20242. zlevel: opts.zlevel,
  20243. z: 10001
  20244. });
  20245. var labelRect = new Rect({
  20246. style: {
  20247. fill: 'none',
  20248. text: opts.text,
  20249. textPosition: 'right',
  20250. textDistance: 10,
  20251. textFill: opts.textColor
  20252. },
  20253. zlevel: opts.zlevel,
  20254. z: 10001
  20255. });
  20256. arc.animateShape(true)
  20257. .when(1000, {
  20258. endAngle: PI$1 * 3 / 2
  20259. })
  20260. .start('circularInOut');
  20261. arc.animateShape(true)
  20262. .when(1000, {
  20263. startAngle: PI$1 * 3 / 2
  20264. })
  20265. .delay(300)
  20266. .start('circularInOut');
  20267. var group = new Group();
  20268. group.add(arc);
  20269. group.add(labelRect);
  20270. group.add(mask);
  20271. // Inject resize
  20272. group.resize = function () {
  20273. var cx = api.getWidth() / 2;
  20274. var cy = api.getHeight() / 2;
  20275. arc.setShape({
  20276. cx: cx,
  20277. cy: cy
  20278. });
  20279. var r = arc.shape.r;
  20280. labelRect.setShape({
  20281. x: cx - r,
  20282. y: cy - r,
  20283. width: r * 2,
  20284. height: r * 2
  20285. });
  20286. mask.setShape({
  20287. x: 0,
  20288. y: 0,
  20289. width: api.getWidth(),
  20290. height: api.getHeight()
  20291. });
  20292. };
  20293. group.resize();
  20294. return group;
  20295. };
  20296. /**
  20297. * @module echarts/stream/Scheduler
  20298. */
  20299. /**
  20300. * @constructor
  20301. */
  20302. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  20303. // this._pipelineMap = createHashMap();
  20304. this.ecInstance = ecInstance;
  20305. this.api = api;
  20306. this.unfinished;
  20307. // Fix current processors in case that in some rear cases that
  20308. // processors might be registered after echarts instance created.
  20309. // Register processors incrementally for a echarts instance is
  20310. // not supported by this stream architecture.
  20311. this._dataProcessorHandlers = dataProcessorHandlers.slice();
  20312. this._visualHandlers = visualHandlers.slice();
  20313. /**
  20314. * @private
  20315. * @type {
  20316. * [handlerUID: string]: {
  20317. * seriesTaskMap?: {
  20318. * [seriesUID: string]: Task
  20319. * },
  20320. * overallTask?: Task
  20321. * }
  20322. * }
  20323. */
  20324. this._stageTaskMap = createHashMap();
  20325. }
  20326. var proto = Scheduler.prototype;
  20327. // If seriesModel provided, incremental threshold is check by series data.
  20328. proto.getPerformArgs = function (task, isBlock) {
  20329. // For overall task
  20330. if (!task.__pipeline) {
  20331. return;
  20332. }
  20333. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  20334. var pCtx = pipeline.context;
  20335. var incremental = !isBlock
  20336. && pipeline.progressiveEnabled
  20337. && (!pCtx || pCtx.canProgressiveRender)
  20338. && task.__idxInPipeline > pipeline.bockIndex;
  20339. return {step: incremental ? pipeline.step : null};
  20340. };
  20341. proto.getPipeline = function (pipelineId) {
  20342. return this._pipelineMap.get(pipelineId);
  20343. };
  20344. /**
  20345. * Current, progressive rendering starts from visual and layout.
  20346. * Always detect render mode in the same stage, avoiding that incorrect
  20347. * detection caused by data filtering.
  20348. * Caution:
  20349. * `updateStreamModes` use `seriesModel.getData()`.
  20350. */
  20351. proto.updateStreamModes = function (seriesModel, view) {
  20352. var pipeline = this._pipelineMap.get(seriesModel.uid);
  20353. var data = seriesModel.getData();
  20354. var dataLen = data.count();
  20355. // `canProgressiveRender` means that can render progressively in each
  20356. // animation frame. Note that some types of series do not provide
  20357. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  20358. // use the term `incremental` but not `progressive` to describe the
  20359. // case that `chart.appendData`.
  20360. var canProgressiveRender = pipeline.progressiveEnabled
  20361. && view.incrementalPrepareRender
  20362. && dataLen >= pipeline.threshold;
  20363. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  20364. seriesModel.pipelineContext = pipeline.context = {
  20365. canProgressiveRender: canProgressiveRender,
  20366. large: large
  20367. };
  20368. };
  20369. proto.restorePipelines = function (ecModel) {
  20370. var scheduler = this;
  20371. var pipelineMap = scheduler._pipelineMap = createHashMap();
  20372. ecModel.eachSeries(function (seriesModel) {
  20373. var progressive = seriesModel.getProgressive();
  20374. var pipelineId = seriesModel.uid;
  20375. pipelineMap.set(pipelineId, {
  20376. id: pipelineId,
  20377. head: null,
  20378. tail: null,
  20379. threshold: seriesModel.getProgressiveThreshold(),
  20380. progressiveEnabled: progressive
  20381. && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  20382. bockIndex: -1,
  20383. step: progressive || 700, // ??? Temporarily number
  20384. count: 0
  20385. });
  20386. pipe(scheduler, seriesModel, seriesModel.dataTask);
  20387. });
  20388. };
  20389. proto.prepareStageTasks = function () {
  20390. var stageTaskMap = this._stageTaskMap;
  20391. var ecModel = this.ecInstance.getModel();
  20392. var api = this.api;
  20393. each$1([this._dataProcessorHandlers, this._visualHandlers], function (stageHandlers) {
  20394. each$1(stageHandlers, function (handler) {
  20395. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  20396. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  20397. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  20398. }, this);
  20399. }, this);
  20400. };
  20401. proto.prepareView = function (view, model, ecModel, api) {
  20402. var renderTask = view.renderTask;
  20403. var context = renderTask.context;
  20404. context.model = model;
  20405. context.ecModel = ecModel;
  20406. context.api = api;
  20407. renderTask.__block = !view.incrementalPrepareRender;
  20408. pipe(this, model, renderTask);
  20409. };
  20410. proto.performDataProcessorTasks = function (ecModel, payload) {
  20411. // If we do not use `block` here, it should be considered when to update modes.
  20412. performStageTasks(this, this._dataProcessorHandlers, ecModel, payload, {block: true});
  20413. };
  20414. // opt
  20415. // opt.visualType: 'visual' or 'layout'
  20416. // opt.setDirty
  20417. proto.performVisualTasks = function (ecModel, payload, opt) {
  20418. performStageTasks(this, this._visualHandlers, ecModel, payload, opt);
  20419. };
  20420. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  20421. opt = opt || {};
  20422. var unfinished;
  20423. each$1(stageHandlers, function (stageHandler, idx) {
  20424. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  20425. return;
  20426. }
  20427. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  20428. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  20429. var overallTask = stageHandlerRecord.overallTask;
  20430. if (overallTask) {
  20431. var overallNeedDirty;
  20432. var agentStubMap = overallTask.agentStubMap;
  20433. agentStubMap.each(function (stub) {
  20434. if (needSetDirty(opt, stub)) {
  20435. stub.dirty();
  20436. overallNeedDirty = true;
  20437. }
  20438. });
  20439. overallNeedDirty && overallTask.dirty();
  20440. updatePayload(overallTask, payload);
  20441. var performArgs = scheduler.getPerformArgs(overallTask, opt.block);
  20442. // Execute stubs firstly, which may set the overall task dirty,
  20443. // then execute the overall task. And stub will call seriesModel.setData,
  20444. // which ensures that in the overallTask seriesModel.getData() will not
  20445. // return incorrect data.
  20446. agentStubMap.each(function (stub) {
  20447. stub.perform(performArgs);
  20448. });
  20449. unfinished |= overallTask.perform(performArgs);
  20450. }
  20451. else if (seriesTaskMap) {
  20452. seriesTaskMap.each(function (task, pipelineId) {
  20453. if (needSetDirty(opt, task)) {
  20454. task.dirty();
  20455. }
  20456. var performArgs = scheduler.getPerformArgs(task, opt.block);
  20457. performArgs.skip = !stageHandler.performRawSeries
  20458. && ecModel.isSeriesFiltered(task.context.model);
  20459. updatePayload(task, payload);
  20460. unfinished |= task.perform(performArgs);
  20461. });
  20462. }
  20463. });
  20464. function needSetDirty(opt, task) {
  20465. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  20466. }
  20467. scheduler.unfinished |= unfinished;
  20468. }
  20469. proto.performSeriesTasks = function (ecModel) {
  20470. var unfinished;
  20471. ecModel.eachSeries(function (seriesModel) {
  20472. // Progress to the end for dataInit and dataRestore.
  20473. unfinished |= seriesModel.dataTask.perform();
  20474. });
  20475. this.unfinished |= unfinished;
  20476. };
  20477. proto.plan = function () {
  20478. // Travel pipelines, check block.
  20479. this._pipelineMap.each(function (pipeline) {
  20480. var task = pipeline.tail;
  20481. do {
  20482. if (task.__block) {
  20483. pipeline.bockIndex = task.__idxInPipeline;
  20484. break;
  20485. }
  20486. task = task.getUpstream();
  20487. }
  20488. while (task);
  20489. });
  20490. };
  20491. var updatePayload = proto.updatePayload = function (task, payload) {
  20492. payload !== 'remain' && (task.context.payload = payload);
  20493. };
  20494. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  20495. var seriesTaskMap = stageHandlerRecord.seriesTaskMap
  20496. || (stageHandlerRecord.seriesTaskMap = createHashMap());
  20497. var seriesType = stageHandler.seriesType;
  20498. var getTargetSeries = stageHandler.getTargetSeries;
  20499. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  20500. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  20501. // it works but it may cause other irrelevant charts blocked.
  20502. if (stageHandler.createOnAllSeries) {
  20503. ecModel.eachRawSeries(create);
  20504. }
  20505. else if (seriesType) {
  20506. ecModel.eachRawSeriesByType(seriesType, create);
  20507. }
  20508. else if (getTargetSeries) {
  20509. getTargetSeries(ecModel, api).each(create);
  20510. }
  20511. function create(seriesModel) {
  20512. var pipelineId = seriesModel.uid;
  20513. // Init tasks for each seriesModel only once.
  20514. // Reuse original task instance.
  20515. var task = seriesTaskMap.get(pipelineId)
  20516. || seriesTaskMap.set(pipelineId, createTask({
  20517. plan: seriesTaskPlan,
  20518. reset: seriesTaskReset,
  20519. count: seriesTaskCount
  20520. }));
  20521. task.context = {
  20522. model: seriesModel,
  20523. ecModel: ecModel,
  20524. api: api,
  20525. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  20526. plan: stageHandler.plan,
  20527. reset: stageHandler.reset,
  20528. scheduler: scheduler
  20529. };
  20530. pipe(scheduler, seriesModel, task);
  20531. }
  20532. // Clear unused series tasks.
  20533. var pipelineMap = scheduler._pipelineMap;
  20534. seriesTaskMap.each(function (task, pipelineId) {
  20535. if (!pipelineMap.get(pipelineId)) {
  20536. task.dispose();
  20537. seriesTaskMap.removeKey(pipelineId);
  20538. }
  20539. });
  20540. }
  20541. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  20542. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  20543. // For overall task, the function only be called on reset stage.
  20544. || createTask({reset: overallTaskReset});
  20545. overallTask.context = {
  20546. ecModel: ecModel,
  20547. api: api,
  20548. overallReset: stageHandler.overallReset,
  20549. scheduler: scheduler
  20550. };
  20551. // Reuse orignal stubs.
  20552. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  20553. var seriesType = stageHandler.seriesType;
  20554. var getTargetSeries = stageHandler.getTargetSeries;
  20555. var overallProgress = true;
  20556. var isOverallFilter = stageHandler.isOverallFilter;
  20557. // An overall task with seriesType detected or has `getTargetSeries`, we add
  20558. // stub in each pipelines, it will set the overall task dirty when the pipeline
  20559. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  20560. // we set the pipeline block.
  20561. if (seriesType) {
  20562. ecModel.eachRawSeriesByType(seriesType, createStub);
  20563. }
  20564. else if (getTargetSeries) {
  20565. getTargetSeries(ecModel, api).each(createStub);
  20566. }
  20567. // Otherwise, (usually it is legancy case), the overall task will only be
  20568. // executed when upstream dirty. Otherwise the progressive rendering of all
  20569. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  20570. // dirty info from upsteam.
  20571. else {
  20572. overallProgress = false;
  20573. each$1(ecModel.getSeries(), createStub);
  20574. }
  20575. function createStub(seriesModel) {
  20576. var pipelineId = seriesModel.uid;
  20577. var stub = agentStubMap.get(pipelineId) || agentStubMap.set(pipelineId, createTask(
  20578. {reset: stubReset, onDirty: stubOnDirty}
  20579. ));
  20580. stub.context = {
  20581. model: seriesModel,
  20582. overallProgress: overallProgress,
  20583. isOverallFilter: isOverallFilter
  20584. };
  20585. stub.agent = overallTask;
  20586. stub.__block = overallProgress;
  20587. pipe(scheduler, seriesModel, stub);
  20588. }
  20589. // Clear unused stubs.
  20590. var pipelineMap = scheduler._pipelineMap;
  20591. agentStubMap.each(function (stub, pipelineId) {
  20592. if (!pipelineMap.get(pipelineId)) {
  20593. stub.dispose();
  20594. agentStubMap.removeKey(pipelineId);
  20595. }
  20596. });
  20597. }
  20598. function overallTaskReset(context) {
  20599. context.overallReset(
  20600. context.ecModel, context.api, context.payload
  20601. );
  20602. }
  20603. function stubReset(context, upstreamContext) {
  20604. return context.overallProgress && stubProgress;
  20605. }
  20606. function stubProgress() {
  20607. this.agent.dirty();
  20608. this.getDownstream().dirty();
  20609. }
  20610. function stubOnDirty() {
  20611. this.agent && this.agent.dirty();
  20612. }
  20613. function seriesTaskPlan(context) {
  20614. return context.plan && context.plan(
  20615. context.model, context.ecModel, context.api, context.payload
  20616. );
  20617. }
  20618. function seriesTaskReset(context) {
  20619. if (context.useClearVisual) {
  20620. context.data.clearAllVisual();
  20621. }
  20622. var resetDefines = context.resetDefines = normalizeToArray(context.reset(
  20623. context.model, context.ecModel, context.api, context.payload
  20624. ));
  20625. if (resetDefines.length) {
  20626. return seriesTaskProgress;
  20627. }
  20628. }
  20629. function seriesTaskProgress(params, context) {
  20630. var data = context.data;
  20631. var resetDefines = context.resetDefines;
  20632. for (var k = 0; k < resetDefines.length; k++) {
  20633. var resetDefine = resetDefines[k];
  20634. if (resetDefine && resetDefine.dataEach) {
  20635. for (var i = params.start; i < params.end; i++) {
  20636. resetDefine.dataEach(data, i);
  20637. }
  20638. }
  20639. else if (resetDefine && resetDefine.progress) {
  20640. resetDefine.progress(params, data);
  20641. }
  20642. }
  20643. }
  20644. function seriesTaskCount(context) {
  20645. return context.data.count();
  20646. }
  20647. function pipe(scheduler, seriesModel, task) {
  20648. var pipelineId = seriesModel.uid;
  20649. var pipeline = scheduler._pipelineMap.get(pipelineId);
  20650. !pipeline.head && (pipeline.head = task);
  20651. pipeline.tail && pipeline.tail.pipe(task);
  20652. pipeline.tail = task;
  20653. task.__idxInPipeline = pipeline.count++;
  20654. task.__pipeline = pipeline;
  20655. }
  20656. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  20657. if (isFunction$1(stageHandler)) {
  20658. stageHandler = {
  20659. overallReset: stageHandler,
  20660. seriesType: detectSeriseType(stageHandler)
  20661. };
  20662. }
  20663. stageHandler.uid = getUID('stageHandler');
  20664. visualType && (stageHandler.visualType = visualType);
  20665. return stageHandler;
  20666. };
  20667. /**
  20668. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  20669. * To ensure that they can work normally, they should work in block mode, that is,
  20670. * they should not be started util the previous tasks finished. So they cause the
  20671. * progressive rendering disabled. We try to detect the series type, to narrow down
  20672. * the block range to only the series type they concern, but not all series.
  20673. */
  20674. function detectSeriseType(legacyFunc) {
  20675. seriesType = null;
  20676. try {
  20677. // Assume there is no async when calling `eachSeriesByType`.
  20678. legacyFunc(ecModelMock, apiMock);
  20679. }
  20680. catch (e) {
  20681. }
  20682. return seriesType;
  20683. }
  20684. var ecModelMock = {};
  20685. var apiMock = {};
  20686. var seriesType;
  20687. mockMethods(ecModelMock, GlobalModel);
  20688. mockMethods(apiMock, ExtensionAPI);
  20689. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  20690. seriesType = type;
  20691. };
  20692. ecModelMock.eachComponent = function (cond) {
  20693. if (cond.mainType === 'series' && cond.subType) {
  20694. seriesType = cond.subType;
  20695. }
  20696. };
  20697. function mockMethods(target, Clz) {
  20698. for (var name in Clz.prototype) {
  20699. // Do not use hasOwnProperty
  20700. target[name] = noop;
  20701. }
  20702. }
  20703. var colorAll = ['#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C','#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'];
  20704. var lightTheme = {
  20705. color: colorAll,
  20706. colorLayer: [
  20707. ['#37A2DA', '#ffd85c', '#fd7b5f'],
  20708. ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'],
  20709. ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'],
  20710. colorAll
  20711. ]
  20712. };
  20713. var contrastColor = '#eee';
  20714. var axisCommon = function () {
  20715. return {
  20716. axisLine: {
  20717. lineStyle: {
  20718. color: contrastColor
  20719. }
  20720. },
  20721. axisTick: {
  20722. lineStyle: {
  20723. color: contrastColor
  20724. }
  20725. },
  20726. axisLabel: {
  20727. textStyle: {
  20728. color: contrastColor
  20729. }
  20730. },
  20731. splitLine: {
  20732. lineStyle: {
  20733. type: 'dashed',
  20734. color: '#aaa'
  20735. }
  20736. },
  20737. splitArea: {
  20738. areaStyle: {
  20739. color: contrastColor
  20740. }
  20741. }
  20742. };
  20743. };
  20744. var colorPalette = ['#dd6b66','#759aa0','#e69d87','#8dc1a9','#ea7e53','#eedd78','#73a373','#73b9bc','#7289ab', '#91ca8c','#f49f42'];
  20745. var theme = {
  20746. color: colorPalette,
  20747. backgroundColor: '#333',
  20748. tooltip: {
  20749. axisPointer: {
  20750. lineStyle: {
  20751. color: contrastColor
  20752. },
  20753. crossStyle: {
  20754. color: contrastColor
  20755. }
  20756. }
  20757. },
  20758. legend: {
  20759. textStyle: {
  20760. color: contrastColor
  20761. }
  20762. },
  20763. textStyle: {
  20764. color: contrastColor
  20765. },
  20766. title: {
  20767. textStyle: {
  20768. color: contrastColor
  20769. }
  20770. },
  20771. toolbox: {
  20772. iconStyle: {
  20773. normal: {
  20774. borderColor: contrastColor
  20775. }
  20776. }
  20777. },
  20778. dataZoom: {
  20779. textStyle: {
  20780. color: contrastColor
  20781. }
  20782. },
  20783. visualMap: {
  20784. textStyle: {
  20785. color: contrastColor
  20786. }
  20787. },
  20788. timeline: {
  20789. lineStyle: {
  20790. color: contrastColor
  20791. },
  20792. itemStyle: {
  20793. normal: {
  20794. color: colorPalette[1]
  20795. }
  20796. },
  20797. label: {
  20798. normal: {
  20799. textStyle: {
  20800. color: contrastColor
  20801. }
  20802. }
  20803. },
  20804. controlStyle: {
  20805. normal: {
  20806. color: contrastColor,
  20807. borderColor: contrastColor
  20808. }
  20809. }
  20810. },
  20811. timeAxis: axisCommon(),
  20812. logAxis: axisCommon(),
  20813. valueAxis: axisCommon(),
  20814. categoryAxis: axisCommon(),
  20815. line: {
  20816. symbol: 'circle'
  20817. },
  20818. graph: {
  20819. color: colorPalette
  20820. },
  20821. gauge: {
  20822. title: {
  20823. textStyle: {
  20824. color: contrastColor
  20825. }
  20826. }
  20827. },
  20828. candlestick: {
  20829. itemStyle: {
  20830. normal: {
  20831. color: '#FD1050',
  20832. color0: '#0CF49B',
  20833. borderColor: '#FD1050',
  20834. borderColor0: '#0CF49B'
  20835. }
  20836. }
  20837. }
  20838. };
  20839. theme.categoryAxis.splitLine.show = false;
  20840. /*!
  20841. * ECharts, a free, powerful charting and visualization library.
  20842. *
  20843. * Copyright (c) 2017, Baidu Inc.
  20844. * All rights reserved.
  20845. *
  20846. * LICENSE
  20847. * https://github.com/ecomfe/echarts/blob/master/LICENSE.txt
  20848. */
  20849. var assert = assert$1;
  20850. var each = each$1;
  20851. var isFunction = isFunction$1;
  20852. var isObject = isObject$1;
  20853. var parseClassType = ComponentModel.parseClassType;
  20854. var version = '4.0.4';
  20855. var dependencies = {
  20856. zrender: '4.0.3'
  20857. };
  20858. var TEST_FRAME_REMAIN_TIME = 1;
  20859. var PRIORITY_PROCESSOR_FILTER = 1000;
  20860. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  20861. var PRIORITY_VISUAL_LAYOUT = 1000;
  20862. var PRIORITY_VISUAL_GLOBAL = 2000;
  20863. var PRIORITY_VISUAL_CHART = 3000;
  20864. var PRIORITY_VISUAL_COMPONENT = 4000;
  20865. // FIXME
  20866. // necessary?
  20867. var PRIORITY_VISUAL_BRUSH = 5000;
  20868. var PRIORITY = {
  20869. PROCESSOR: {
  20870. FILTER: PRIORITY_PROCESSOR_FILTER,
  20871. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  20872. },
  20873. VISUAL: {
  20874. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  20875. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  20876. CHART: PRIORITY_VISUAL_CHART,
  20877. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  20878. BRUSH: PRIORITY_VISUAL_BRUSH
  20879. }
  20880. };
  20881. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  20882. // where they must not be invoked nestedly, except the only case: invoke
  20883. // dispatchAction with updateMethod "none" in main process.
  20884. // This flag is used to carry out this rule.
  20885. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  20886. var IN_MAIN_PROCESS = '__flagInMainProcess';
  20887. var OPTION_UPDATED = '__optionUpdated';
  20888. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  20889. function createRegisterEventWithLowercaseName(method) {
  20890. return function (eventName, handler, context) {
  20891. // Event name is all lowercase
  20892. eventName = eventName && eventName.toLowerCase();
  20893. Eventful.prototype[method].call(this, eventName, handler, context);
  20894. };
  20895. }
  20896. /**
  20897. * @module echarts~MessageCenter
  20898. */
  20899. function MessageCenter() {
  20900. Eventful.call(this);
  20901. }
  20902. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on');
  20903. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off');
  20904. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one');
  20905. mixin(MessageCenter, Eventful);
  20906. /**
  20907. * @module echarts~ECharts
  20908. */
  20909. function ECharts(dom, theme$$1, opts) {
  20910. opts = opts || {};
  20911. // Get theme by name
  20912. if (typeof theme$$1 === 'string') {
  20913. theme$$1 = themeStorage[theme$$1];
  20914. }
  20915. /**
  20916. * @type {string}
  20917. */
  20918. this.id;
  20919. /**
  20920. * Group id
  20921. * @type {string}
  20922. */
  20923. this.group;
  20924. /**
  20925. * @type {HTMLElement}
  20926. * @private
  20927. */
  20928. this._dom = dom;
  20929. var defaultRenderer = 'canvas';
  20930. if (__DEV__) {
  20931. defaultRenderer = (
  20932. typeof window === 'undefined' ? global : window
  20933. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  20934. }
  20935. /**
  20936. * @type {module:zrender/ZRender}
  20937. * @private
  20938. */
  20939. var zr = this._zr = init$1(dom, {
  20940. renderer: opts.renderer || defaultRenderer,
  20941. devicePixelRatio: opts.devicePixelRatio,
  20942. width: opts.width,
  20943. height: opts.height
  20944. });
  20945. /**
  20946. * Expect 60 pfs.
  20947. * @type {Function}
  20948. * @private
  20949. */
  20950. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  20951. var theme$$1 = clone(theme$$1);
  20952. theme$$1 && backwardCompat(theme$$1, true);
  20953. /**
  20954. * @type {Object}
  20955. * @private
  20956. */
  20957. this._theme = theme$$1;
  20958. /**
  20959. * @type {Array.<module:echarts/view/Chart>}
  20960. * @private
  20961. */
  20962. this._chartsViews = [];
  20963. /**
  20964. * @type {Object.<string, module:echarts/view/Chart>}
  20965. * @private
  20966. */
  20967. this._chartsMap = {};
  20968. /**
  20969. * @type {Array.<module:echarts/view/Component>}
  20970. * @private
  20971. */
  20972. this._componentsViews = [];
  20973. /**
  20974. * @type {Object.<string, module:echarts/view/Component>}
  20975. * @private
  20976. */
  20977. this._componentsMap = {};
  20978. /**
  20979. * @type {module:echarts/CoordinateSystem}
  20980. * @private
  20981. */
  20982. this._coordSysMgr = new CoordinateSystemManager();
  20983. /**
  20984. * @type {module:echarts/ExtensionAPI}
  20985. * @private
  20986. */
  20987. var api = this._api = createExtensionAPI(this);
  20988. // Sort on demand
  20989. function prioritySortFunc(a, b) {
  20990. return a.__prio - b.__prio;
  20991. }
  20992. sort(visualFuncs, prioritySortFunc);
  20993. sort(dataProcessorFuncs, prioritySortFunc);
  20994. /**
  20995. * @type {module:echarts/stream/Scheduler}
  20996. */
  20997. this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs);
  20998. Eventful.call(this);
  20999. /**
  21000. * @type {module:echarts~MessageCenter}
  21001. * @private
  21002. */
  21003. this._messageCenter = new MessageCenter();
  21004. // Init mouse events
  21005. this._initEvents();
  21006. // In case some people write `window.onresize = chart.resize`
  21007. this.resize = bind(this.resize, this);
  21008. // Can't dispatch action during rendering procedure
  21009. this._pendingActions = [];
  21010. zr.animation.on('frame', this._onframe, this);
  21011. bindRenderedEvent(zr, this);
  21012. // ECharts instance can be used as value.
  21013. setAsPrimitive(this);
  21014. }
  21015. var echartsProto = ECharts.prototype;
  21016. echartsProto._onframe = function () {
  21017. if (this._disposed) {
  21018. return;
  21019. }
  21020. var scheduler = this._scheduler;
  21021. // Lazy update
  21022. if (this[OPTION_UPDATED]) {
  21023. var silent = this[OPTION_UPDATED].silent;
  21024. this[IN_MAIN_PROCESS] = true;
  21025. prepare(this);
  21026. updateMethods.update.call(this);
  21027. this[IN_MAIN_PROCESS] = false;
  21028. this[OPTION_UPDATED] = false;
  21029. flushPendingActions.call(this, silent);
  21030. triggerUpdatedEvent.call(this, silent);
  21031. }
  21032. // Avoid do both lazy update and progress in one frame.
  21033. else if (scheduler.unfinished) {
  21034. // Stream progress.
  21035. var remainTime = TEST_FRAME_REMAIN_TIME;
  21036. var ecModel = this._model;
  21037. var api = this._api;
  21038. scheduler.unfinished = false;
  21039. do {
  21040. var startTime = +new Date();
  21041. scheduler.performSeriesTasks(ecModel);
  21042. // Currently dataProcessorFuncs do not check threshold.
  21043. scheduler.performDataProcessorTasks(ecModel);
  21044. updateStreamModes(this, ecModel);
  21045. // Do not update coordinate system here. Because that coord system update in
  21046. // each frame is not a good user experience. So we follow the rule that
  21047. // the extent of the coordinate system is determin in the first frame (the
  21048. // frame is executed immedietely after task reset.
  21049. // this._coordSysMgr.update(ecModel, api);
  21050. // console.log('--- ec frame visual ---', remainTime);
  21051. scheduler.performVisualTasks(ecModel);
  21052. renderSeries(this, this._model, api, 'remain');
  21053. remainTime -= (+new Date() - startTime);
  21054. }
  21055. while (remainTime > 0 && scheduler.unfinished);
  21056. // Call flush explicitly for trigger finished event.
  21057. if (!scheduler.unfinished) {
  21058. this._zr.flush();
  21059. }
  21060. // Else, zr flushing be ensue within the same frame,
  21061. // because zr flushing is after onframe event.
  21062. }
  21063. };
  21064. /**
  21065. * @return {HTMLElement}
  21066. */
  21067. echartsProto.getDom = function () {
  21068. return this._dom;
  21069. };
  21070. /**
  21071. * @return {module:zrender~ZRender}
  21072. */
  21073. echartsProto.getZr = function () {
  21074. return this._zr;
  21075. };
  21076. /**
  21077. * Usage:
  21078. * chart.setOption(option, notMerge, lazyUpdate);
  21079. * chart.setOption(option, {
  21080. * notMerge: ...,
  21081. * lazyUpdate: ...,
  21082. * silent: ...
  21083. * });
  21084. *
  21085. * @param {Object} option
  21086. * @param {Object|boolean} [opts] opts or notMerge.
  21087. * @param {boolean} [opts.notMerge=false]
  21088. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  21089. */
  21090. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  21091. if (__DEV__) {
  21092. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  21093. }
  21094. var silent;
  21095. if (isObject(notMerge)) {
  21096. lazyUpdate = notMerge.lazyUpdate;
  21097. silent = notMerge.silent;
  21098. notMerge = notMerge.notMerge;
  21099. }
  21100. this[IN_MAIN_PROCESS] = true;
  21101. if (!this._model || notMerge) {
  21102. var optionManager = new OptionManager(this._api);
  21103. var theme$$1 = this._theme;
  21104. var ecModel = this._model = new GlobalModel(null, null, theme$$1, optionManager);
  21105. ecModel.scheduler = this._scheduler;
  21106. ecModel.init(null, null, theme$$1, optionManager);
  21107. }
  21108. this._model.setOption(option, optionPreprocessorFuncs);
  21109. if (lazyUpdate) {
  21110. this[OPTION_UPDATED] = {silent: silent};
  21111. this[IN_MAIN_PROCESS] = false;
  21112. }
  21113. else {
  21114. prepare(this);
  21115. updateMethods.update.call(this);
  21116. // Ensure zr refresh sychronously, and then pixel in canvas can be
  21117. // fetched after `setOption`.
  21118. this._zr.flush();
  21119. this[OPTION_UPDATED] = false;
  21120. this[IN_MAIN_PROCESS] = false;
  21121. flushPendingActions.call(this, silent);
  21122. triggerUpdatedEvent.call(this, silent);
  21123. }
  21124. };
  21125. /**
  21126. * @DEPRECATED
  21127. */
  21128. echartsProto.setTheme = function () {
  21129. console.log('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  21130. };
  21131. /**
  21132. * @return {module:echarts/model/Global}
  21133. */
  21134. echartsProto.getModel = function () {
  21135. return this._model;
  21136. };
  21137. /**
  21138. * @return {Object}
  21139. */
  21140. echartsProto.getOption = function () {
  21141. return this._model && this._model.getOption();
  21142. };
  21143. /**
  21144. * @return {number}
  21145. */
  21146. echartsProto.getWidth = function () {
  21147. return this._zr.getWidth();
  21148. };
  21149. /**
  21150. * @return {number}
  21151. */
  21152. echartsProto.getHeight = function () {
  21153. return this._zr.getHeight();
  21154. };
  21155. /**
  21156. * @return {number}
  21157. */
  21158. echartsProto.getDevicePixelRatio = function () {
  21159. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  21160. };
  21161. /**
  21162. * Get canvas which has all thing rendered
  21163. * @param {Object} opts
  21164. * @param {string} [opts.backgroundColor]
  21165. * @return {string}
  21166. */
  21167. echartsProto.getRenderedCanvas = function (opts) {
  21168. if (!env$1.canvasSupported) {
  21169. return;
  21170. }
  21171. opts = opts || {};
  21172. opts.pixelRatio = opts.pixelRatio || 1;
  21173. opts.backgroundColor = opts.backgroundColor
  21174. || this._model.get('backgroundColor');
  21175. var zr = this._zr;
  21176. // var list = zr.storage.getDisplayList();
  21177. // Stop animations
  21178. // Never works before in init animation, so remove it.
  21179. // zrUtil.each(list, function (el) {
  21180. // el.stopAnimation(true);
  21181. // });
  21182. return zr.painter.getRenderedCanvas(opts);
  21183. };
  21184. /**
  21185. * Get svg data url
  21186. * @return {string}
  21187. */
  21188. echartsProto.getSvgDataUrl = function () {
  21189. if (!env$1.svgSupported) {
  21190. return;
  21191. }
  21192. var zr = this._zr;
  21193. var list = zr.storage.getDisplayList();
  21194. // Stop animations
  21195. each$1(list, function (el) {
  21196. el.stopAnimation(true);
  21197. });
  21198. return zr.painter.pathToDataUrl();
  21199. };
  21200. /**
  21201. * @return {string}
  21202. * @param {Object} opts
  21203. * @param {string} [opts.type='png']
  21204. * @param {string} [opts.pixelRatio=1]
  21205. * @param {string} [opts.backgroundColor]
  21206. * @param {string} [opts.excludeComponents]
  21207. */
  21208. echartsProto.getDataURL = function (opts) {
  21209. opts = opts || {};
  21210. var excludeComponents = opts.excludeComponents;
  21211. var ecModel = this._model;
  21212. var excludesComponentViews = [];
  21213. var self = this;
  21214. each(excludeComponents, function (componentType) {
  21215. ecModel.eachComponent({
  21216. mainType: componentType
  21217. }, function (component) {
  21218. var view = self._componentsMap[component.__viewId];
  21219. if (!view.group.ignore) {
  21220. excludesComponentViews.push(view);
  21221. view.group.ignore = true;
  21222. }
  21223. });
  21224. });
  21225. var url = this._zr.painter.getType() === 'svg'
  21226. ? this.getSvgDataUrl()
  21227. : this.getRenderedCanvas(opts).toDataURL(
  21228. 'image/' + (opts && opts.type || 'png')
  21229. );
  21230. each(excludesComponentViews, function (view) {
  21231. view.group.ignore = false;
  21232. });
  21233. return url;
  21234. };
  21235. /**
  21236. * @return {string}
  21237. * @param {Object} opts
  21238. * @param {string} [opts.type='png']
  21239. * @param {string} [opts.pixelRatio=1]
  21240. * @param {string} [opts.backgroundColor]
  21241. */
  21242. echartsProto.getConnectedDataURL = function (opts) {
  21243. if (!env$1.canvasSupported) {
  21244. return;
  21245. }
  21246. var groupId = this.group;
  21247. var mathMin = Math.min;
  21248. var mathMax = Math.max;
  21249. var MAX_NUMBER = Infinity;
  21250. if (connectedGroups[groupId]) {
  21251. var left = MAX_NUMBER;
  21252. var top = MAX_NUMBER;
  21253. var right = -MAX_NUMBER;
  21254. var bottom = -MAX_NUMBER;
  21255. var canvasList = [];
  21256. var dpr = (opts && opts.pixelRatio) || 1;
  21257. each$1(instances, function (chart, id) {
  21258. if (chart.group === groupId) {
  21259. var canvas = chart.getRenderedCanvas(
  21260. clone(opts)
  21261. );
  21262. var boundingRect = chart.getDom().getBoundingClientRect();
  21263. left = mathMin(boundingRect.left, left);
  21264. top = mathMin(boundingRect.top, top);
  21265. right = mathMax(boundingRect.right, right);
  21266. bottom = mathMax(boundingRect.bottom, bottom);
  21267. canvasList.push({
  21268. dom: canvas,
  21269. left: boundingRect.left,
  21270. top: boundingRect.top
  21271. });
  21272. }
  21273. });
  21274. left *= dpr;
  21275. top *= dpr;
  21276. right *= dpr;
  21277. bottom *= dpr;
  21278. var width = right - left;
  21279. var height = bottom - top;
  21280. var targetCanvas = createCanvas();
  21281. targetCanvas.width = width;
  21282. targetCanvas.height = height;
  21283. var zr = init$1(targetCanvas);
  21284. each(canvasList, function (item) {
  21285. var img = new ZImage({
  21286. style: {
  21287. x: item.left * dpr - left,
  21288. y: item.top * dpr - top,
  21289. image: item.dom
  21290. }
  21291. });
  21292. zr.add(img);
  21293. });
  21294. zr.refreshImmediately();
  21295. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  21296. }
  21297. else {
  21298. return this.getDataURL(opts);
  21299. }
  21300. };
  21301. /**
  21302. * Convert from logical coordinate system to pixel coordinate system.
  21303. * See CoordinateSystem#convertToPixel.
  21304. * @param {string|Object} finder
  21305. * If string, e.g., 'geo', means {geoIndex: 0}.
  21306. * If Object, could contain some of these properties below:
  21307. * {
  21308. * seriesIndex / seriesId / seriesName,
  21309. * geoIndex / geoId, geoName,
  21310. * bmapIndex / bmapId / bmapName,
  21311. * xAxisIndex / xAxisId / xAxisName,
  21312. * yAxisIndex / yAxisId / yAxisName,
  21313. * gridIndex / gridId / gridName,
  21314. * ... (can be extended)
  21315. * }
  21316. * @param {Array|number} value
  21317. * @return {Array|number} result
  21318. */
  21319. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  21320. /**
  21321. * Convert from pixel coordinate system to logical coordinate system.
  21322. * See CoordinateSystem#convertFromPixel.
  21323. * @param {string|Object} finder
  21324. * If string, e.g., 'geo', means {geoIndex: 0}.
  21325. * If Object, could contain some of these properties below:
  21326. * {
  21327. * seriesIndex / seriesId / seriesName,
  21328. * geoIndex / geoId / geoName,
  21329. * bmapIndex / bmapId / bmapName,
  21330. * xAxisIndex / xAxisId / xAxisName,
  21331. * yAxisIndex / yAxisId / yAxisName
  21332. * gridIndex / gridId / gridName,
  21333. * ... (can be extended)
  21334. * }
  21335. * @param {Array|number} value
  21336. * @return {Array|number} result
  21337. */
  21338. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  21339. function doConvertPixel(methodName, finder, value) {
  21340. var ecModel = this._model;
  21341. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  21342. var result;
  21343. finder = parseFinder(ecModel, finder);
  21344. for (var i = 0; i < coordSysList.length; i++) {
  21345. var coordSys = coordSysList[i];
  21346. if (coordSys[methodName]
  21347. && (result = coordSys[methodName](ecModel, finder, value)) != null
  21348. ) {
  21349. return result;
  21350. }
  21351. }
  21352. if (__DEV__) {
  21353. console.warn(
  21354. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  21355. );
  21356. }
  21357. }
  21358. /**
  21359. * Is the specified coordinate systems or components contain the given pixel point.
  21360. * @param {string|Object} finder
  21361. * If string, e.g., 'geo', means {geoIndex: 0}.
  21362. * If Object, could contain some of these properties below:
  21363. * {
  21364. * seriesIndex / seriesId / seriesName,
  21365. * geoIndex / geoId / geoName,
  21366. * bmapIndex / bmapId / bmapName,
  21367. * xAxisIndex / xAxisId / xAxisName,
  21368. * yAxisIndex / yAxisId / yAxisName,
  21369. * gridIndex / gridId / gridName,
  21370. * ... (can be extended)
  21371. * }
  21372. * @param {Array|number} value
  21373. * @return {boolean} result
  21374. */
  21375. echartsProto.containPixel = function (finder, value) {
  21376. var ecModel = this._model;
  21377. var result;
  21378. finder = parseFinder(ecModel, finder);
  21379. each$1(finder, function (models, key) {
  21380. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  21381. var coordSys = model.coordinateSystem;
  21382. if (coordSys && coordSys.containPoint) {
  21383. result |= !!coordSys.containPoint(value);
  21384. }
  21385. else if (key === 'seriesModels') {
  21386. var view = this._chartsMap[model.__viewId];
  21387. if (view && view.containPoint) {
  21388. result |= view.containPoint(value, model);
  21389. }
  21390. else {
  21391. if (__DEV__) {
  21392. console.warn(key + ': ' + (view
  21393. ? 'The found component do not support containPoint.'
  21394. : 'No view mapping to the found component.'
  21395. ));
  21396. }
  21397. }
  21398. }
  21399. else {
  21400. if (__DEV__) {
  21401. console.warn(key + ': containPoint is not supported');
  21402. }
  21403. }
  21404. }, this);
  21405. }, this);
  21406. return !!result;
  21407. };
  21408. /**
  21409. * Get visual from series or data.
  21410. * @param {string|Object} finder
  21411. * If string, e.g., 'series', means {seriesIndex: 0}.
  21412. * If Object, could contain some of these properties below:
  21413. * {
  21414. * seriesIndex / seriesId / seriesName,
  21415. * dataIndex / dataIndexInside
  21416. * }
  21417. * If dataIndex is not specified, series visual will be fetched,
  21418. * but not data item visual.
  21419. * If all of seriesIndex, seriesId, seriesName are not specified,
  21420. * visual will be fetched from first series.
  21421. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  21422. */
  21423. echartsProto.getVisual = function (finder, visualType) {
  21424. var ecModel = this._model;
  21425. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  21426. var seriesModel = finder.seriesModel;
  21427. if (__DEV__) {
  21428. if (!seriesModel) {
  21429. console.warn('There is no specified seires model');
  21430. }
  21431. }
  21432. var data = seriesModel.getData();
  21433. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  21434. ? finder.dataIndexInside
  21435. : finder.hasOwnProperty('dataIndex')
  21436. ? data.indexOfRawIndex(finder.dataIndex)
  21437. : null;
  21438. return dataIndexInside != null
  21439. ? data.getItemVisual(dataIndexInside, visualType)
  21440. : data.getVisual(visualType);
  21441. };
  21442. /**
  21443. * Get view of corresponding component model
  21444. * @param {module:echarts/model/Component} componentModel
  21445. * @return {module:echarts/view/Component}
  21446. */
  21447. echartsProto.getViewOfComponentModel = function (componentModel) {
  21448. return this._componentsMap[componentModel.__viewId];
  21449. };
  21450. /**
  21451. * Get view of corresponding series model
  21452. * @param {module:echarts/model/Series} seriesModel
  21453. * @return {module:echarts/view/Chart}
  21454. */
  21455. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  21456. return this._chartsMap[seriesModel.__viewId];
  21457. };
  21458. var updateMethods = {
  21459. prepareAndUpdate: function (payload) {
  21460. prepare(this);
  21461. updateMethods.update.call(this, payload);
  21462. },
  21463. /**
  21464. * @param {Object} payload
  21465. * @private
  21466. */
  21467. update: function (payload) {
  21468. // console.profile && console.profile('update');
  21469. var ecModel = this._model;
  21470. var api = this._api;
  21471. var zr = this._zr;
  21472. var coordSysMgr = this._coordSysMgr;
  21473. var scheduler = this._scheduler;
  21474. // update before setOption
  21475. if (!ecModel) {
  21476. return;
  21477. }
  21478. ecModel.restoreData(payload);
  21479. scheduler.performSeriesTasks(ecModel);
  21480. // TODO
  21481. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  21482. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  21483. // Create new coordinate system each update
  21484. // In LineView may save the old coordinate system and use it to get the orignal point
  21485. coordSysMgr.create(ecModel, api);
  21486. scheduler.performDataProcessorTasks(ecModel, payload);
  21487. // Current stream render is not supported in data process. So we can update
  21488. // stream modes after data processing, where the filtered data is used to
  21489. // deteming whether use progressive rendering.
  21490. updateStreamModes(this, ecModel);
  21491. // stackSeriesData(ecModel);
  21492. coordSysMgr.update(ecModel, api);
  21493. clearColorPalette(ecModel);
  21494. scheduler.performVisualTasks(ecModel, payload);
  21495. render(this, ecModel, api, payload);
  21496. // Set background
  21497. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  21498. // In IE8
  21499. if (!env$1.canvasSupported) {
  21500. var colorArr = parse(backgroundColor);
  21501. backgroundColor = stringify(colorArr, 'rgb');
  21502. if (colorArr[3] === 0) {
  21503. backgroundColor = 'transparent';
  21504. }
  21505. }
  21506. else {
  21507. zr.setBackgroundColor(backgroundColor);
  21508. }
  21509. performPostUpdateFuncs(ecModel, api);
  21510. // console.profile && console.profileEnd('update');
  21511. },
  21512. /**
  21513. * @param {Object} payload
  21514. * @private
  21515. */
  21516. updateTransform: function (payload) {
  21517. var ecModel = this._model;
  21518. var ecIns = this;
  21519. var api = this._api;
  21520. // update before setOption
  21521. if (!ecModel) {
  21522. return;
  21523. }
  21524. // ChartView.markUpdateMethod(payload, 'updateTransform');
  21525. var componentDirtyList = [];
  21526. ecModel.eachComponent(function (componentType, componentModel) {
  21527. var componentView = ecIns.getViewOfComponentModel(componentModel);
  21528. if (componentView && componentView.__alive) {
  21529. if (componentView.updateTransform) {
  21530. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  21531. result && result.update && componentDirtyList.push(componentView);
  21532. }
  21533. else {
  21534. componentDirtyList.push(componentView);
  21535. }
  21536. }
  21537. });
  21538. var seriesDirtyMap = createHashMap();
  21539. ecModel.eachSeries(function (seriesModel) {
  21540. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  21541. if (chartView.updateTransform) {
  21542. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  21543. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  21544. }
  21545. else {
  21546. seriesDirtyMap.set(seriesModel.uid, 1);
  21547. }
  21548. });
  21549. clearColorPalette(ecModel);
  21550. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21551. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  21552. this._scheduler.performVisualTasks(
  21553. ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
  21554. );
  21555. // Currently, not call render of components. Geo render cost a lot.
  21556. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  21557. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  21558. performPostUpdateFuncs(ecModel, this._api);
  21559. },
  21560. /**
  21561. * @param {Object} payload
  21562. * @private
  21563. */
  21564. updateView: function (payload) {
  21565. var ecModel = this._model;
  21566. // update before setOption
  21567. if (!ecModel) {
  21568. return;
  21569. }
  21570. Chart.markUpdateMethod(payload, 'updateView');
  21571. clearColorPalette(ecModel);
  21572. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21573. this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  21574. render(this, this._model, this._api, payload);
  21575. performPostUpdateFuncs(ecModel, this._api);
  21576. },
  21577. /**
  21578. * @param {Object} payload
  21579. * @private
  21580. */
  21581. updateVisual: function (payload) {
  21582. updateMethods.update.call(this, payload);
  21583. // var ecModel = this._model;
  21584. // // update before setOption
  21585. // if (!ecModel) {
  21586. // return;
  21587. // }
  21588. // ChartView.markUpdateMethod(payload, 'updateVisual');
  21589. // clearColorPalette(ecModel);
  21590. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21591. // this._scheduler.performVisualTasks(ecModel, payload, {visualType: 'visual', setDirty: true});
  21592. // render(this, this._model, this._api, payload);
  21593. // performPostUpdateFuncs(ecModel, this._api);
  21594. },
  21595. /**
  21596. * @param {Object} payload
  21597. * @private
  21598. */
  21599. updateLayout: function (payload) {
  21600. updateMethods.update.call(this, payload);
  21601. // var ecModel = this._model;
  21602. // // update before setOption
  21603. // if (!ecModel) {
  21604. // return;
  21605. // }
  21606. // ChartView.markUpdateMethod(payload, 'updateLayout');
  21607. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21608. // // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  21609. // this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  21610. // render(this, this._model, this._api, payload);
  21611. // performPostUpdateFuncs(ecModel, this._api);
  21612. }
  21613. };
  21614. function prepare(ecIns) {
  21615. var ecModel = ecIns._model;
  21616. var scheduler = ecIns._scheduler;
  21617. scheduler.restorePipelines(ecModel);
  21618. scheduler.prepareStageTasks();
  21619. prepareView(ecIns, 'component', ecModel, scheduler);
  21620. prepareView(ecIns, 'chart', ecModel, scheduler);
  21621. scheduler.plan();
  21622. }
  21623. /**
  21624. * @private
  21625. */
  21626. function updateDirectly(ecIns, method, payload, mainType, subType) {
  21627. var ecModel = ecIns._model;
  21628. // broadcast
  21629. if (!mainType) {
  21630. // FIXME
  21631. // Chart will not be update directly here, except set dirty.
  21632. // But there is no such scenario now.
  21633. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  21634. return;
  21635. }
  21636. var query = {};
  21637. query[mainType + 'Id'] = payload[mainType + 'Id'];
  21638. query[mainType + 'Index'] = payload[mainType + 'Index'];
  21639. query[mainType + 'Name'] = payload[mainType + 'Name'];
  21640. var condition = {mainType: mainType, query: query};
  21641. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  21642. // If dispatchAction before setOption, do nothing.
  21643. ecModel && ecModel.eachComponent(condition, function (model, index) {
  21644. callView(ecIns[
  21645. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  21646. ][model.__viewId]);
  21647. }, ecIns);
  21648. function callView(view) {
  21649. view && view.__alive && view[method] && view[method](
  21650. view.__model, ecModel, ecIns._api, payload
  21651. );
  21652. }
  21653. }
  21654. /**
  21655. * Resize the chart
  21656. * @param {Object} opts
  21657. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  21658. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  21659. * @param {boolean} [opts.silent=false]
  21660. */
  21661. echartsProto.resize = function (opts) {
  21662. if (__DEV__) {
  21663. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  21664. }
  21665. this._zr.resize(opts);
  21666. var ecModel = this._model;
  21667. // Resize loading effect
  21668. this._loadingFX && this._loadingFX.resize();
  21669. if (!ecModel) {
  21670. return;
  21671. }
  21672. var optionChanged = ecModel.resetOption('media');
  21673. var silent = opts && opts.silent;
  21674. this[IN_MAIN_PROCESS] = true;
  21675. optionChanged && prepare(this);
  21676. updateMethods.update.call(this);
  21677. this[IN_MAIN_PROCESS] = false;
  21678. flushPendingActions.call(this, silent);
  21679. triggerUpdatedEvent.call(this, silent);
  21680. };
  21681. function updateStreamModes(ecIns, ecModel) {
  21682. var chartsMap = ecIns._chartsMap;
  21683. var scheduler = ecIns._scheduler;
  21684. ecModel.eachSeries(function (seriesModel) {
  21685. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  21686. });
  21687. }
  21688. /**
  21689. * Show loading effect
  21690. * @param {string} [name='default']
  21691. * @param {Object} [cfg]
  21692. */
  21693. echartsProto.showLoading = function (name, cfg) {
  21694. if (isObject(name)) {
  21695. cfg = name;
  21696. name = '';
  21697. }
  21698. name = name || 'default';
  21699. this.hideLoading();
  21700. if (!loadingEffects[name]) {
  21701. if (__DEV__) {
  21702. console.warn('Loading effects ' + name + ' not exists.');
  21703. }
  21704. return;
  21705. }
  21706. var el = loadingEffects[name](this._api, cfg);
  21707. var zr = this._zr;
  21708. this._loadingFX = el;
  21709. zr.add(el);
  21710. };
  21711. /**
  21712. * Hide loading effect
  21713. */
  21714. echartsProto.hideLoading = function () {
  21715. this._loadingFX && this._zr.remove(this._loadingFX);
  21716. this._loadingFX = null;
  21717. };
  21718. /**
  21719. * @param {Object} eventObj
  21720. * @return {Object}
  21721. */
  21722. echartsProto.makeActionFromEvent = function (eventObj) {
  21723. var payload = extend({}, eventObj);
  21724. payload.type = eventActionMap[eventObj.type];
  21725. return payload;
  21726. };
  21727. /**
  21728. * @pubilc
  21729. * @param {Object} payload
  21730. * @param {string} [payload.type] Action type
  21731. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  21732. * @param {boolean} [opt.silent=false] Whether trigger events.
  21733. * @param {boolean} [opt.flush=undefined]
  21734. * true: Flush immediately, and then pixel in canvas can be fetched
  21735. * immediately. Caution: it might affect performance.
  21736. * false: Not not flush.
  21737. * undefined: Auto decide whether perform flush.
  21738. */
  21739. echartsProto.dispatchAction = function (payload, opt) {
  21740. if (!isObject(opt)) {
  21741. opt = {silent: !!opt};
  21742. }
  21743. if (!actions[payload.type]) {
  21744. return;
  21745. }
  21746. // Avoid dispatch action before setOption. Especially in `connect`.
  21747. if (!this._model) {
  21748. return;
  21749. }
  21750. // May dispatchAction in rendering procedure
  21751. if (this[IN_MAIN_PROCESS]) {
  21752. this._pendingActions.push(payload);
  21753. return;
  21754. }
  21755. doDispatchAction.call(this, payload, opt.silent);
  21756. if (opt.flush) {
  21757. this._zr.flush(true);
  21758. }
  21759. else if (opt.flush !== false && env$1.browser.weChat) {
  21760. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  21761. // hang when sliding page (on touch event), which cause that zr does not
  21762. // refresh util user interaction finished, which is not expected.
  21763. // But `dispatchAction` may be called too frequently when pan on touch
  21764. // screen, which impacts performance if do not throttle them.
  21765. this._throttledZrFlush();
  21766. }
  21767. flushPendingActions.call(this, opt.silent);
  21768. triggerUpdatedEvent.call(this, opt.silent);
  21769. };
  21770. function doDispatchAction(payload, silent) {
  21771. var payloadType = payload.type;
  21772. var escapeConnect = payload.escapeConnect;
  21773. var actionWrap = actions[payloadType];
  21774. var actionInfo = actionWrap.actionInfo;
  21775. var cptType = (actionInfo.update || 'update').split(':');
  21776. var updateMethod = cptType.pop();
  21777. cptType = cptType[0] != null && parseClassType(cptType[0]);
  21778. this[IN_MAIN_PROCESS] = true;
  21779. var payloads = [payload];
  21780. var batched = false;
  21781. // Batch action
  21782. if (payload.batch) {
  21783. batched = true;
  21784. payloads = map(payload.batch, function (item) {
  21785. item = defaults(extend({}, item), payload);
  21786. item.batch = null;
  21787. return item;
  21788. });
  21789. }
  21790. var eventObjBatch = [];
  21791. var eventObj;
  21792. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  21793. each(payloads, function (batchItem) {
  21794. // Action can specify the event by return it.
  21795. eventObj = actionWrap.action(batchItem, this._model, this._api);
  21796. // Emit event outside
  21797. eventObj = eventObj || extend({}, batchItem);
  21798. // Convert type to eventType
  21799. eventObj.type = actionInfo.event || eventObj.type;
  21800. eventObjBatch.push(eventObj);
  21801. // light update does not perform data process, layout and visual.
  21802. if (isHighDown) {
  21803. // method, payload, mainType, subType
  21804. updateDirectly(this, updateMethod, batchItem, 'series');
  21805. }
  21806. else if (cptType) {
  21807. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  21808. }
  21809. }, this);
  21810. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  21811. // Still dirty
  21812. if (this[OPTION_UPDATED]) {
  21813. // FIXME Pass payload ?
  21814. prepare(this);
  21815. updateMethods.update.call(this, payload);
  21816. this[OPTION_UPDATED] = false;
  21817. }
  21818. else {
  21819. updateMethods[updateMethod].call(this, payload);
  21820. }
  21821. }
  21822. // Follow the rule of action batch
  21823. if (batched) {
  21824. eventObj = {
  21825. type: actionInfo.event || payloadType,
  21826. escapeConnect: escapeConnect,
  21827. batch: eventObjBatch
  21828. };
  21829. }
  21830. else {
  21831. eventObj = eventObjBatch[0];
  21832. }
  21833. this[IN_MAIN_PROCESS] = false;
  21834. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  21835. }
  21836. function flushPendingActions(silent) {
  21837. var pendingActions = this._pendingActions;
  21838. while (pendingActions.length) {
  21839. var payload = pendingActions.shift();
  21840. doDispatchAction.call(this, payload, silent);
  21841. }
  21842. }
  21843. function triggerUpdatedEvent(silent) {
  21844. !silent && this.trigger('updated');
  21845. }
  21846. /**
  21847. * Event `rendered` is triggered when zr
  21848. * rendered. It is useful for realtime
  21849. * snapshot (reflect animation).
  21850. *
  21851. * Event `finished` is triggered when:
  21852. * (1) zrender rendering finished.
  21853. * (2) initial animation finished.
  21854. * (3) progressive rendering finished.
  21855. * (4) no pending action.
  21856. * (5) no delayed setOption needs to be processed.
  21857. */
  21858. function bindRenderedEvent(zr, ecIns) {
  21859. zr.on('rendered', function () {
  21860. ecIns.trigger('rendered');
  21861. // The `finished` event should not be triggered repeatly,
  21862. // so it should only be triggered when rendering indeed happend
  21863. // in zrender. (Consider the case that dipatchAction is keep
  21864. // triggering when mouse move).
  21865. if (
  21866. // Although zr is dirty if initial animation is not finished
  21867. // and this checking is called on frame, we also check
  21868. // animation finished for robustness.
  21869. zr.animation.isFinished()
  21870. && !ecIns[OPTION_UPDATED]
  21871. && !ecIns._scheduler.unfinished
  21872. && !ecIns._pendingActions.length
  21873. ) {
  21874. ecIns.trigger('finished');
  21875. }
  21876. });
  21877. }
  21878. /**
  21879. * @param {Object} params
  21880. * @param {number} params.seriesIndex
  21881. * @param {Array|TypedArray} params.data
  21882. */
  21883. echartsProto.appendData = function (params) {
  21884. var seriesIndex = params.seriesIndex;
  21885. var ecModel = this.getModel();
  21886. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  21887. if (__DEV__) {
  21888. assert(params.data && seriesModel);
  21889. }
  21890. seriesModel.appendData(params);
  21891. // Note: `appendData` does not support that update extent of coordinate
  21892. // system, util some scenario require that. In the expected usage of
  21893. // `appendData`, the initial extent of coordinate system should better
  21894. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  21895. // the extent changed while `appendData`, the location of the painted
  21896. // graphic elements have to be changed, which make the usage of
  21897. // `appendData` meaningless.
  21898. this._scheduler.unfinished = true;
  21899. };
  21900. /**
  21901. * Register event
  21902. * @method
  21903. */
  21904. echartsProto.on = createRegisterEventWithLowercaseName('on');
  21905. echartsProto.off = createRegisterEventWithLowercaseName('off');
  21906. echartsProto.one = createRegisterEventWithLowercaseName('one');
  21907. /**
  21908. * Prepare view instances of charts and components
  21909. * @param {module:echarts/model/Global} ecModel
  21910. * @private
  21911. */
  21912. function prepareView(ecIns, type, ecModel, scheduler) {
  21913. var isComponent = type === 'component';
  21914. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  21915. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  21916. var zr = ecIns._zr;
  21917. var api = ecIns._api;
  21918. for (var i = 0; i < viewList.length; i++) {
  21919. viewList[i].__alive = false;
  21920. }
  21921. isComponent
  21922. ? ecModel.eachComponent(function (componentType, model) {
  21923. componentType !== 'series' && doPrepare(model);
  21924. })
  21925. : ecModel.eachSeries(doPrepare);
  21926. function doPrepare(model) {
  21927. // Consider: id same and type changed.
  21928. var viewId = '_ec_' + model.id + '_' + model.type;
  21929. var view = viewMap[viewId];
  21930. if (!view) {
  21931. var classType = parseClassType(model.type);
  21932. var Clazz = isComponent
  21933. ? Component$1.getClass(classType.main, classType.sub)
  21934. : Chart.getClass(classType.sub);
  21935. if (__DEV__) {
  21936. assert(Clazz, classType.sub + ' does not exist.');
  21937. }
  21938. view = new Clazz();
  21939. view.init(ecModel, api);
  21940. viewMap[viewId] = view;
  21941. viewList.push(view);
  21942. zr.add(view.group);
  21943. }
  21944. model.__viewId = view.__id = viewId;
  21945. view.__alive = true;
  21946. view.__model = model;
  21947. view.group.__ecComponentInfo = {
  21948. mainType: model.mainType,
  21949. index: model.componentIndex
  21950. };
  21951. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  21952. }
  21953. for (var i = 0; i < viewList.length;) {
  21954. var view = viewList[i];
  21955. if (!view.__alive) {
  21956. !isComponent && view.renderTask.dispose();
  21957. zr.remove(view.group);
  21958. view.dispose(ecModel, api);
  21959. viewList.splice(i, 1);
  21960. delete viewMap[view.__id];
  21961. view.__id = view.group.__ecComponentInfo = null;
  21962. }
  21963. else {
  21964. i++;
  21965. }
  21966. }
  21967. }
  21968. // /**
  21969. // * Encode visual infomation from data after data processing
  21970. // *
  21971. // * @param {module:echarts/model/Global} ecModel
  21972. // * @param {object} layout
  21973. // * @param {boolean} [layoutFilter] `true`: only layout,
  21974. // * `false`: only not layout,
  21975. // * `null`/`undefined`: all.
  21976. // * @param {string} taskBaseTag
  21977. // * @private
  21978. // */
  21979. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  21980. // each(visualFuncs, function (visual, index) {
  21981. // var isLayout = visual.isLayout;
  21982. // if (layoutFilter == null
  21983. // || (layoutFilter === false && !isLayout)
  21984. // || (layoutFilter === true && isLayout)
  21985. // ) {
  21986. // visual.func(ecModel, api, payload);
  21987. // }
  21988. // });
  21989. // }
  21990. function clearColorPalette(ecModel) {
  21991. ecModel.clearColorPalette();
  21992. ecModel.eachSeries(function (seriesModel) {
  21993. seriesModel.clearColorPalette();
  21994. });
  21995. }
  21996. function render(ecIns, ecModel, api, payload) {
  21997. renderComponents(ecIns, ecModel, api, payload);
  21998. each(ecIns._chartsViews, function (chart) {
  21999. chart.__alive = false;
  22000. });
  22001. renderSeries(ecIns, ecModel, api, payload);
  22002. // Remove groups of unrendered charts
  22003. each(ecIns._chartsViews, function (chart) {
  22004. if (!chart.__alive) {
  22005. chart.remove(ecModel, api);
  22006. }
  22007. });
  22008. }
  22009. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  22010. each(dirtyList || ecIns._componentsViews, function (componentView) {
  22011. var componentModel = componentView.__model;
  22012. componentView.render(componentModel, ecModel, api, payload);
  22013. updateZ(componentModel, componentView);
  22014. });
  22015. }
  22016. /**
  22017. * Render each chart and component
  22018. * @private
  22019. */
  22020. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  22021. // Render all charts
  22022. var scheduler = ecIns._scheduler;
  22023. var unfinished;
  22024. ecModel.eachSeries(function (seriesModel) {
  22025. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  22026. chartView.__alive = true;
  22027. var renderTask = chartView.renderTask;
  22028. scheduler.updatePayload(renderTask, payload);
  22029. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  22030. renderTask.dirty();
  22031. }
  22032. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  22033. chartView.group.silent = !!seriesModel.get('silent');
  22034. updateZ(seriesModel, chartView);
  22035. updateBlend(seriesModel, chartView);
  22036. });
  22037. scheduler.unfinished |= unfinished;
  22038. // If use hover layer
  22039. updateHoverLayerStatus(ecIns._zr, ecModel);
  22040. // Add aria
  22041. aria(ecIns._zr.dom, ecModel);
  22042. }
  22043. function performPostUpdateFuncs(ecModel, api) {
  22044. each(postUpdateFuncs, function (func) {
  22045. func(ecModel, api);
  22046. });
  22047. }
  22048. var MOUSE_EVENT_NAMES = [
  22049. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  22050. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  22051. ];
  22052. /**
  22053. * @private
  22054. */
  22055. echartsProto._initEvents = function () {
  22056. each(MOUSE_EVENT_NAMES, function (eveName) {
  22057. this._zr.on(eveName, function (e) {
  22058. var ecModel = this.getModel();
  22059. var el = e.target;
  22060. var params;
  22061. // no e.target when 'globalout'.
  22062. if (eveName === 'globalout') {
  22063. params = {};
  22064. }
  22065. else if (el && el.dataIndex != null) {
  22066. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  22067. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType) || {};
  22068. }
  22069. // If element has custom eventData of components
  22070. else if (el && el.eventData) {
  22071. params = extend({}, el.eventData);
  22072. }
  22073. if (params) {
  22074. params.event = e;
  22075. params.type = eveName;
  22076. this.trigger(eveName, params);
  22077. }
  22078. }, this);
  22079. }, this);
  22080. each(eventActionMap, function (actionType, eventType) {
  22081. this._messageCenter.on(eventType, function (event) {
  22082. this.trigger(eventType, event);
  22083. }, this);
  22084. }, this);
  22085. };
  22086. /**
  22087. * @return {boolean}
  22088. */
  22089. echartsProto.isDisposed = function () {
  22090. return this._disposed;
  22091. };
  22092. /**
  22093. * Clear
  22094. */
  22095. echartsProto.clear = function () {
  22096. this.setOption({ series: [] }, true);
  22097. };
  22098. /**
  22099. * Dispose instance
  22100. */
  22101. echartsProto.dispose = function () {
  22102. if (this._disposed) {
  22103. if (__DEV__) {
  22104. console.warn('Instance ' + this.id + ' has been disposed');
  22105. }
  22106. return;
  22107. }
  22108. this._disposed = true;
  22109. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  22110. var api = this._api;
  22111. var ecModel = this._model;
  22112. each(this._componentsViews, function (component) {
  22113. component.dispose(ecModel, api);
  22114. });
  22115. each(this._chartsViews, function (chart) {
  22116. chart.dispose(ecModel, api);
  22117. });
  22118. // Dispose after all views disposed
  22119. this._zr.dispose();
  22120. delete instances[this.id];
  22121. };
  22122. mixin(ECharts, Eventful);
  22123. function updateHoverLayerStatus(zr, ecModel) {
  22124. var storage = zr.storage;
  22125. var elCount = 0;
  22126. storage.traverse(function (el) {
  22127. if (!el.isGroup) {
  22128. elCount++;
  22129. }
  22130. });
  22131. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  22132. storage.traverse(function (el) {
  22133. if (!el.isGroup) {
  22134. // Don't switch back.
  22135. el.useHoverLayer = true;
  22136. }
  22137. });
  22138. }
  22139. }
  22140. /**
  22141. * Update chart progressive and blend.
  22142. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  22143. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  22144. */
  22145. function updateBlend(seriesModel, chartView) {
  22146. var blendMode = seriesModel.get('blendMode') || null;
  22147. if (__DEV__) {
  22148. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  22149. console.warn('Only canvas support blendMode');
  22150. }
  22151. }
  22152. chartView.group.traverse(function (el) {
  22153. // FIXME marker and other components
  22154. if (!el.isGroup) {
  22155. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  22156. if (el.style.blend !== blendMode) {
  22157. el.setStyle('blend', blendMode);
  22158. }
  22159. }
  22160. if (el.eachPendingDisplayable) {
  22161. el.eachPendingDisplayable(function (displayable) {
  22162. displayable.setStyle('blend', blendMode);
  22163. });
  22164. }
  22165. });
  22166. }
  22167. /**
  22168. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  22169. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  22170. */
  22171. function updateZ(model, view) {
  22172. var z = model.get('z');
  22173. var zlevel = model.get('zlevel');
  22174. // Set z and zlevel
  22175. view.group.traverse(function (el) {
  22176. if (el.type !== 'group') {
  22177. z != null && (el.z = z);
  22178. zlevel != null && (el.zlevel = zlevel);
  22179. }
  22180. });
  22181. }
  22182. function createExtensionAPI(ecInstance) {
  22183. var coordSysMgr = ecInstance._coordSysMgr;
  22184. return extend(new ExtensionAPI(ecInstance), {
  22185. // Inject methods
  22186. getCoordinateSystems: bind(
  22187. coordSysMgr.getCoordinateSystems, coordSysMgr
  22188. ),
  22189. getComponentByElement: function (el) {
  22190. while (el) {
  22191. var modelInfo = el.__ecComponentInfo;
  22192. if (modelInfo != null) {
  22193. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  22194. }
  22195. el = el.parent;
  22196. }
  22197. }
  22198. });
  22199. }
  22200. /**
  22201. * @type {Object} key: actionType.
  22202. * @inner
  22203. */
  22204. var actions = {};
  22205. /**
  22206. * Map eventType to actionType
  22207. * @type {Object}
  22208. */
  22209. var eventActionMap = {};
  22210. /**
  22211. * Data processor functions of each stage
  22212. * @type {Array.<Object.<string, Function>>}
  22213. * @inner
  22214. */
  22215. var dataProcessorFuncs = [];
  22216. /**
  22217. * @type {Array.<Function>}
  22218. * @inner
  22219. */
  22220. var optionPreprocessorFuncs = [];
  22221. /**
  22222. * @type {Array.<Function>}
  22223. * @inner
  22224. */
  22225. var postUpdateFuncs = [];
  22226. /**
  22227. * Visual encoding functions of each stage
  22228. * @type {Array.<Object.<string, Function>>}
  22229. */
  22230. var visualFuncs = [];
  22231. /**
  22232. * Theme storage
  22233. * @type {Object.<key, Object>}
  22234. */
  22235. var themeStorage = {};
  22236. /**
  22237. * Loading effects
  22238. */
  22239. var loadingEffects = {};
  22240. var instances = {};
  22241. var connectedGroups = {};
  22242. var idBase = new Date() - 0;
  22243. var groupIdBase = new Date() - 0;
  22244. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  22245. var mapDataStores = {};
  22246. function enableConnect(chart) {
  22247. var STATUS_PENDING = 0;
  22248. var STATUS_UPDATING = 1;
  22249. var STATUS_UPDATED = 2;
  22250. var STATUS_KEY = '__connectUpdateStatus';
  22251. function updateConnectedChartsStatus(charts, status) {
  22252. for (var i = 0; i < charts.length; i++) {
  22253. var otherChart = charts[i];
  22254. otherChart[STATUS_KEY] = status;
  22255. }
  22256. }
  22257. each(eventActionMap, function (actionType, eventType) {
  22258. chart._messageCenter.on(eventType, function (event) {
  22259. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  22260. if (event && event.escapeConnect) {
  22261. return;
  22262. }
  22263. var action = chart.makeActionFromEvent(event);
  22264. var otherCharts = [];
  22265. each(instances, function (otherChart) {
  22266. if (otherChart !== chart && otherChart.group === chart.group) {
  22267. otherCharts.push(otherChart);
  22268. }
  22269. });
  22270. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  22271. each(otherCharts, function (otherChart) {
  22272. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  22273. otherChart.dispatchAction(action);
  22274. }
  22275. });
  22276. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  22277. }
  22278. });
  22279. });
  22280. }
  22281. /**
  22282. * @param {HTMLElement} dom
  22283. * @param {Object} [theme]
  22284. * @param {Object} opts
  22285. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  22286. * @param {string} [opts.renderer] Currently only 'canvas' is supported.
  22287. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  22288. * Can be 'auto' (the same as null/undefined)
  22289. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  22290. * Can be 'auto' (the same as null/undefined)
  22291. */
  22292. function init(dom, theme$$1, opts) {
  22293. if (__DEV__) {
  22294. // Check version
  22295. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  22296. throw new Error(
  22297. 'zrender/src ' + version$1
  22298. + ' is too old for ECharts ' + version
  22299. + '. Current version need ZRender '
  22300. + dependencies.zrender + '+'
  22301. );
  22302. }
  22303. if (!dom) {
  22304. throw new Error('Initialize failed: invalid dom.');
  22305. }
  22306. }
  22307. var existInstance = getInstanceByDom(dom);
  22308. if (existInstance) {
  22309. if (__DEV__) {
  22310. console.warn('There is a chart instance already initialized on the dom.');
  22311. }
  22312. return existInstance;
  22313. }
  22314. if (__DEV__) {
  22315. if (isDom(dom)
  22316. && dom.nodeName.toUpperCase() !== 'CANVAS'
  22317. && (
  22318. (!dom.clientWidth && (!opts || opts.width == null))
  22319. || (!dom.clientHeight && (!opts || opts.height == null))
  22320. )
  22321. ) {
  22322. console.warn('Can\'t get dom width or height');
  22323. }
  22324. }
  22325. var chart = new ECharts(dom, theme$$1, opts);
  22326. chart.id = 'ec_' + idBase++;
  22327. instances[chart.id] = chart;
  22328. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  22329. enableConnect(chart);
  22330. return chart;
  22331. }
  22332. /**
  22333. * @return {string|Array.<module:echarts~ECharts>} groupId
  22334. */
  22335. function connect(groupId) {
  22336. // Is array of charts
  22337. if (isArray(groupId)) {
  22338. var charts = groupId;
  22339. groupId = null;
  22340. // If any chart has group
  22341. each(charts, function (chart) {
  22342. if (chart.group != null) {
  22343. groupId = chart.group;
  22344. }
  22345. });
  22346. groupId = groupId || ('g_' + groupIdBase++);
  22347. each(charts, function (chart) {
  22348. chart.group = groupId;
  22349. });
  22350. }
  22351. connectedGroups[groupId] = true;
  22352. return groupId;
  22353. }
  22354. /**
  22355. * @DEPRECATED
  22356. * @return {string} groupId
  22357. */
  22358. function disConnect(groupId) {
  22359. connectedGroups[groupId] = false;
  22360. }
  22361. /**
  22362. * @return {string} groupId
  22363. */
  22364. var disconnect = disConnect;
  22365. /**
  22366. * Dispose a chart instance
  22367. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  22368. */
  22369. function dispose(chart) {
  22370. if (typeof chart === 'string') {
  22371. chart = instances[chart];
  22372. }
  22373. else if (!(chart instanceof ECharts)){
  22374. // Try to treat as dom
  22375. chart = getInstanceByDom(chart);
  22376. }
  22377. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  22378. chart.dispose();
  22379. }
  22380. }
  22381. /**
  22382. * @param {HTMLElement} dom
  22383. * @return {echarts~ECharts}
  22384. */
  22385. function getInstanceByDom(dom) {
  22386. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  22387. }
  22388. /**
  22389. * @param {string} key
  22390. * @return {echarts~ECharts}
  22391. */
  22392. function getInstanceById(key) {
  22393. return instances[key];
  22394. }
  22395. /**
  22396. * Register theme
  22397. */
  22398. function registerTheme(name, theme$$1) {
  22399. themeStorage[name] = theme$$1;
  22400. }
  22401. /**
  22402. * Register option preprocessor
  22403. * @param {Function} preprocessorFunc
  22404. */
  22405. function registerPreprocessor(preprocessorFunc) {
  22406. optionPreprocessorFuncs.push(preprocessorFunc);
  22407. }
  22408. /**
  22409. * @param {number} [priority=1000]
  22410. * @param {Object|Function} processor
  22411. */
  22412. function registerProcessor(priority, processor) {
  22413. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  22414. }
  22415. /**
  22416. * Register postUpdater
  22417. * @param {Function} postUpdateFunc
  22418. */
  22419. function registerPostUpdate(postUpdateFunc) {
  22420. postUpdateFuncs.push(postUpdateFunc);
  22421. }
  22422. /**
  22423. * Usage:
  22424. * registerAction('someAction', 'someEvent', function () { ... });
  22425. * registerAction('someAction', function () { ... });
  22426. * registerAction(
  22427. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  22428. * function () { ... }
  22429. * );
  22430. *
  22431. * @param {(string|Object)} actionInfo
  22432. * @param {string} actionInfo.type
  22433. * @param {string} [actionInfo.event]
  22434. * @param {string} [actionInfo.update]
  22435. * @param {string} [eventName]
  22436. * @param {Function} action
  22437. */
  22438. function registerAction(actionInfo, eventName, action) {
  22439. if (typeof eventName === 'function') {
  22440. action = eventName;
  22441. eventName = '';
  22442. }
  22443. var actionType = isObject(actionInfo)
  22444. ? actionInfo.type
  22445. : ([actionInfo, actionInfo = {
  22446. event: eventName
  22447. }][0]);
  22448. // Event name is all lowercase
  22449. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  22450. eventName = actionInfo.event;
  22451. // Validate action type and event name.
  22452. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  22453. if (!actions[actionType]) {
  22454. actions[actionType] = {action: action, actionInfo: actionInfo};
  22455. }
  22456. eventActionMap[eventName] = actionType;
  22457. }
  22458. /**
  22459. * @param {string} type
  22460. * @param {*} CoordinateSystem
  22461. */
  22462. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  22463. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  22464. }
  22465. /**
  22466. * Get dimensions of specified coordinate system.
  22467. * @param {string} type
  22468. * @return {Array.<string|Object>}
  22469. */
  22470. function getCoordinateSystemDimensions(type) {
  22471. var coordSysCreator = CoordinateSystemManager.get(type);
  22472. if (coordSysCreator) {
  22473. return coordSysCreator.getDimensionsInfo
  22474. ? coordSysCreator.getDimensionsInfo()
  22475. : coordSysCreator.dimensions.slice();
  22476. }
  22477. }
  22478. /**
  22479. * Layout is a special stage of visual encoding
  22480. * Most visual encoding like color are common for different chart
  22481. * But each chart has it's own layout algorithm
  22482. *
  22483. * @param {number} [priority=1000]
  22484. * @param {Function} layoutTask
  22485. */
  22486. function registerLayout(priority, layoutTask) {
  22487. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  22488. }
  22489. /**
  22490. * @param {number} [priority=3000]
  22491. * @param {module:echarts/stream/Task} visualTask
  22492. */
  22493. function registerVisual(priority, visualTask) {
  22494. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  22495. }
  22496. /**
  22497. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  22498. */
  22499. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  22500. if (isFunction(priority) || isObject(priority)) {
  22501. fn = priority;
  22502. priority = defaultPriority;
  22503. }
  22504. if (__DEV__) {
  22505. if (isNaN(priority) || priority == null) {
  22506. throw new Error('Illegal priority');
  22507. }
  22508. // Check duplicate
  22509. each(targetList, function (wrap) {
  22510. assert(wrap.__raw !== fn);
  22511. });
  22512. }
  22513. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  22514. stageHandler.__prio = priority;
  22515. stageHandler.__raw = fn;
  22516. targetList.push(stageHandler);
  22517. return stageHandler;
  22518. }
  22519. /**
  22520. * @param {string} name
  22521. */
  22522. function registerLoading(name, loadingFx) {
  22523. loadingEffects[name] = loadingFx;
  22524. }
  22525. /**
  22526. * @param {Object} opts
  22527. * @param {string} [superClass]
  22528. */
  22529. function extendComponentModel(opts/*, superClass*/) {
  22530. // var Clazz = ComponentModel;
  22531. // if (superClass) {
  22532. // var classType = parseClassType(superClass);
  22533. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  22534. // }
  22535. return ComponentModel.extend(opts);
  22536. }
  22537. /**
  22538. * @param {Object} opts
  22539. * @param {string} [superClass]
  22540. */
  22541. function extendComponentView(opts/*, superClass*/) {
  22542. // var Clazz = ComponentView;
  22543. // if (superClass) {
  22544. // var classType = parseClassType(superClass);
  22545. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  22546. // }
  22547. return Component$1.extend(opts);
  22548. }
  22549. /**
  22550. * @param {Object} opts
  22551. * @param {string} [superClass]
  22552. */
  22553. function extendSeriesModel(opts/*, superClass*/) {
  22554. // var Clazz = SeriesModel;
  22555. // if (superClass) {
  22556. // superClass = 'series.' + superClass.replace('series.', '');
  22557. // var classType = parseClassType(superClass);
  22558. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  22559. // }
  22560. return SeriesModel.extend(opts);
  22561. }
  22562. /**
  22563. * @param {Object} opts
  22564. * @param {string} [superClass]
  22565. */
  22566. function extendChartView(opts/*, superClass*/) {
  22567. // var Clazz = ChartView;
  22568. // if (superClass) {
  22569. // superClass = superClass.replace('series.', '');
  22570. // var classType = parseClassType(superClass);
  22571. // Clazz = ChartView.getClass(classType.main, true);
  22572. // }
  22573. return Chart.extend(opts);
  22574. }
  22575. /**
  22576. * ZRender need a canvas context to do measureText.
  22577. * But in node environment canvas may be created by node-canvas.
  22578. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  22579. *
  22580. * Be careful of using it in the browser.
  22581. *
  22582. * @param {Function} creator
  22583. * @example
  22584. * var Canvas = require('canvas');
  22585. * var echarts = require('echarts');
  22586. * echarts.setCanvasCreator(function () {
  22587. * // Small size is enough.
  22588. * return new Canvas(32, 32);
  22589. * });
  22590. */
  22591. function setCanvasCreator(creator) {
  22592. $override('createCanvas', creator);
  22593. }
  22594. /**
  22595. * @param {string} mapName
  22596. * @param {Object|string} geoJson
  22597. * @param {Object} [specialAreas]
  22598. *
  22599. * @example
  22600. * $.get('USA.json', function (geoJson) {
  22601. * echarts.registerMap('USA', geoJson);
  22602. * // Or
  22603. * echarts.registerMap('USA', {
  22604. * geoJson: geoJson,
  22605. * specialAreas: {}
  22606. * })
  22607. * });
  22608. */
  22609. function registerMap(mapName, geoJson, specialAreas) {
  22610. if (geoJson.geoJson && !geoJson.features) {
  22611. specialAreas = geoJson.specialAreas;
  22612. geoJson = geoJson.geoJson;
  22613. }
  22614. if (typeof geoJson === 'string') {
  22615. geoJson = (typeof JSON !== 'undefined' && JSON.parse)
  22616. ? JSON.parse(geoJson) : (new Function('return (' + geoJson + ');'))();
  22617. }
  22618. mapDataStores[mapName] = {
  22619. geoJson: geoJson,
  22620. specialAreas: specialAreas
  22621. };
  22622. }
  22623. /**
  22624. * @param {string} mapName
  22625. * @return {Object}
  22626. */
  22627. function getMap(mapName) {
  22628. return mapDataStores[mapName];
  22629. }
  22630. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  22631. registerPreprocessor(backwardCompat);
  22632. registerProcessor(PRIORITY_PROCESSOR_STATISTIC, dataStack);
  22633. registerLoading('default', loadingDefault);
  22634. // Default actions
  22635. registerAction({
  22636. type: 'highlight',
  22637. event: 'highlight',
  22638. update: 'highlight'
  22639. }, noop);
  22640. registerAction({
  22641. type: 'downplay',
  22642. event: 'downplay',
  22643. update: 'downplay'
  22644. }, noop);
  22645. // Default theme
  22646. registerTheme('light', lightTheme);
  22647. registerTheme('dark', theme);
  22648. // For backward compatibility, where the namespace `dataTool` will
  22649. // be mounted on `echarts` is the extension `dataTool` is imported.
  22650. var dataTool = {};
  22651. function defaultKeyGetter(item) {
  22652. return item;
  22653. }
  22654. /**
  22655. * @param {Array} oldArr
  22656. * @param {Array} newArr
  22657. * @param {Function} oldKeyGetter
  22658. * @param {Function} newKeyGetter
  22659. * @param {Object} [context] Can be visited by this.context in callback.
  22660. */
  22661. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  22662. this._old = oldArr;
  22663. this._new = newArr;
  22664. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  22665. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  22666. this.context = context;
  22667. }
  22668. DataDiffer.prototype = {
  22669. constructor: DataDiffer,
  22670. /**
  22671. * Callback function when add a data
  22672. */
  22673. add: function (func) {
  22674. this._add = func;
  22675. return this;
  22676. },
  22677. /**
  22678. * Callback function when update a data
  22679. */
  22680. update: function (func) {
  22681. this._update = func;
  22682. return this;
  22683. },
  22684. /**
  22685. * Callback function when remove a data
  22686. */
  22687. remove: function (func) {
  22688. this._remove = func;
  22689. return this;
  22690. },
  22691. execute: function () {
  22692. var oldArr = this._old;
  22693. var newArr = this._new;
  22694. var oldDataIndexMap = {};
  22695. var newDataIndexMap = {};
  22696. var oldDataKeyArr = [];
  22697. var newDataKeyArr = [];
  22698. var i;
  22699. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  22700. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  22701. // Travel by inverted order to make sure order consistency
  22702. // when duplicate keys exists (consider newDataIndex.pop() below).
  22703. // For performance consideration, these code below do not look neat.
  22704. for (i = 0; i < oldArr.length; i++) {
  22705. var key = oldDataKeyArr[i];
  22706. var idx = newDataIndexMap[key];
  22707. // idx can never be empty array here. see 'set null' logic below.
  22708. if (idx != null) {
  22709. // Consider there is duplicate key (for example, use dataItem.name as key).
  22710. // We should make sure every item in newArr and oldArr can be visited.
  22711. var len = idx.length;
  22712. if (len) {
  22713. len === 1 && (newDataIndexMap[key] = null);
  22714. idx = idx.unshift();
  22715. }
  22716. else {
  22717. newDataIndexMap[key] = null;
  22718. }
  22719. this._update && this._update(idx, i);
  22720. }
  22721. else {
  22722. this._remove && this._remove(i);
  22723. }
  22724. }
  22725. for (var i = 0; i < newDataKeyArr.length; i++) {
  22726. var key = newDataKeyArr[i];
  22727. if (newDataIndexMap.hasOwnProperty(key)) {
  22728. var idx = newDataIndexMap[key];
  22729. if (idx == null) {
  22730. continue;
  22731. }
  22732. // idx can never be empty array here. see 'set null' logic above.
  22733. if (!idx.length) {
  22734. this._add && this._add(idx);
  22735. }
  22736. else {
  22737. for (var j = 0, len = idx.length; j < len; j++) {
  22738. this._add && this._add(idx[j]);
  22739. }
  22740. }
  22741. }
  22742. }
  22743. }
  22744. };
  22745. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  22746. for (var i = 0; i < arr.length; i++) {
  22747. // Add prefix to avoid conflict with Object.prototype.
  22748. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  22749. var existence = map[key];
  22750. if (existence == null) {
  22751. keyArr.push(key);
  22752. map[key] = i;
  22753. }
  22754. else {
  22755. if (!existence.length) {
  22756. map[key] = existence = [existence];
  22757. }
  22758. existence.push(i);
  22759. }
  22760. }
  22761. }
  22762. var OTHER_DIMENSIONS = createHashMap([
  22763. 'tooltip', 'label', 'itemName', 'itemId', 'seriesName'
  22764. ]);
  22765. function summarizeDimensions(data) {
  22766. var summary = {};
  22767. var encode = summary.encode = {};
  22768. var notExtraCoordDimMap = createHashMap();
  22769. var defaultedLabel = [];
  22770. each$1(data.dimensions, function (dimName) {
  22771. var dimItem = data.getDimensionInfo(dimName);
  22772. var coordDim = dimItem.coordDim;
  22773. if (coordDim) {
  22774. if (__DEV__) {
  22775. assert$1(OTHER_DIMENSIONS.get(coordDim) == null);
  22776. }
  22777. var coordDimArr = encode[coordDim];
  22778. if (!encode.hasOwnProperty(coordDim)) {
  22779. coordDimArr = encode[coordDim] = [];
  22780. }
  22781. coordDimArr[dimItem.coordDimIndex] = dimName;
  22782. if (!dimItem.isExtraCoord) {
  22783. notExtraCoordDimMap.set(coordDim, 1);
  22784. // Use the last coord dim (and label friendly) as default label,
  22785. // because when dataset is used, it is hard to guess which dimension
  22786. // can be value dimension. If both show x, y on label is not look good,
  22787. // and conventionally y axis is focused more.
  22788. if (mayLabelDimType(dimItem.type)) {
  22789. defaultedLabel[0] = dimName;
  22790. }
  22791. }
  22792. }
  22793. OTHER_DIMENSIONS.each(function (v, otherDim) {
  22794. var otherDimArr = encode[otherDim];
  22795. if (!encode.hasOwnProperty(otherDim)) {
  22796. otherDimArr = encode[otherDim] = [];
  22797. }
  22798. var dimIndex = dimItem.otherDims[otherDim];
  22799. if (dimIndex != null && dimIndex !== false) {
  22800. otherDimArr[dimIndex] = dimItem.name;
  22801. }
  22802. });
  22803. });
  22804. var dataDimsOnCoord = [];
  22805. var encodeFirstDimNotExtra = {};
  22806. notExtraCoordDimMap.each(function (v, coordDim) {
  22807. var dimArr = encode[coordDim];
  22808. // ??? FIXME extra coord should not be set in dataDimsOnCoord.
  22809. // But should fix the case that radar axes: simplify the logic
  22810. // of `completeDimension`, remove `extraPrefix`.
  22811. encodeFirstDimNotExtra[coordDim] = dimArr[0];
  22812. // Not necessary to remove duplicate, because a data
  22813. // dim canot on more than one coordDim.
  22814. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  22815. });
  22816. summary.dataDimsOnCoord = dataDimsOnCoord;
  22817. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  22818. var encodeLabel = encode.label;
  22819. // FIXME `encode.label` is not recommanded, because formatter can not be set
  22820. // in this way. Use label.formatter instead. May be remove this approach someday.
  22821. if (encodeLabel && encodeLabel.length) {
  22822. defaultedLabel = encodeLabel.slice();
  22823. }
  22824. var defaultedTooltip = defaultedLabel.slice();
  22825. var encodeTooltip = encode.tooltip;
  22826. if (encodeTooltip && encodeTooltip.length) {
  22827. defaultedTooltip = encodeTooltip.slice();
  22828. }
  22829. encode.defaultedLabel = defaultedLabel;
  22830. encode.defaultedTooltip = defaultedTooltip;
  22831. return summary;
  22832. }
  22833. function getDimensionTypeByAxis(axisType) {
  22834. return axisType === 'category'
  22835. ? 'ordinal'
  22836. : axisType === 'time'
  22837. ? 'time'
  22838. : 'float';
  22839. }
  22840. function mayLabelDimType(dimType) {
  22841. // In most cases, ordinal and time do not suitable for label.
  22842. // Ordinal info can be displayed on axis. Time is too long.
  22843. return !(dimType === 'ordinal' || dimType === 'time');
  22844. }
  22845. // function findTheLastDimMayLabel(data) {
  22846. // // Get last value dim
  22847. // var dimensions = data.dimensions.slice();
  22848. // var valueType;
  22849. // var valueDim;
  22850. // while (dimensions.length && (
  22851. // valueDim = dimensions.pop(),
  22852. // valueType = data.getDimensionInfo(valueDim).type,
  22853. // valueType === 'ordinal' || valueType === 'time'
  22854. // )) {} // jshint ignore:line
  22855. // return valueDim;
  22856. // }
  22857. /**
  22858. * List for data storage
  22859. * @module echarts/data/List
  22860. */
  22861. var isObject$4 = isObject$1;
  22862. var UNDEFINED = 'undefined';
  22863. var globalObj = typeof window === UNDEFINED ? global : window;
  22864. // Use prefix to avoid index to be the same as otherIdList[idx],
  22865. // which will cause weird udpate animation.
  22866. var ID_PREFIX = 'e\0\0';
  22867. var dataCtors = {
  22868. 'float': typeof globalObj.Float64Array === UNDEFINED
  22869. ? Array : globalObj.Float64Array,
  22870. 'int': typeof globalObj.Int32Array === UNDEFINED
  22871. ? Array : globalObj.Int32Array,
  22872. // Ordinal data type can be string or int
  22873. 'ordinal': Array,
  22874. 'number': Array,
  22875. 'time': Array
  22876. };
  22877. var CtorUint32Array = typeof globalObj.Uint32Array === UNDEFINED ? Array : globalObj.Uint32Array;
  22878. var CtorUint16Array = typeof globalObj.Uint16Array === UNDEFINED ? Array : globalObj.Uint16Array;
  22879. function getIndicesCtor(list) {
  22880. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  22881. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  22882. }
  22883. function cloneChunk(originalChunk) {
  22884. var Ctor = originalChunk.constructor;
  22885. // Only shallow clone is enough when Array.
  22886. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  22887. }
  22888. var TRANSFERABLE_PROPERTIES = [
  22889. 'hasItemOption', '_nameList', '_idList', '_calculationInfo', '_invertedIndicesMap',
  22890. '_rawData', '_rawExtent', '_chunkSize', '_chunkCount',
  22891. '_dimValueGetter', '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
  22892. ];
  22893. function transferProperties(a, b) {
  22894. each$1(TRANSFERABLE_PROPERTIES.concat(b.__wrappedMethods || []), function (propName) {
  22895. if (b.hasOwnProperty(propName)) {
  22896. a[propName] = b[propName];
  22897. }
  22898. });
  22899. a.__wrappedMethods = b.__wrappedMethods;
  22900. }
  22901. /**
  22902. * @constructor
  22903. * @alias module:echarts/data/List
  22904. *
  22905. * @param {Array.<string|Object>} dimensions
  22906. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  22907. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  22908. * Spetial fields: {
  22909. * ordinalMeta: <module:echarts/data/OrdinalMeta>
  22910. * createInvertedIndices: <boolean>
  22911. * }
  22912. * @param {module:echarts/model/Model} hostModel
  22913. */
  22914. var List = function (dimensions, hostModel) {
  22915. dimensions = dimensions || ['x', 'y'];
  22916. var dimensionInfos = {};
  22917. var dimensionNames = [];
  22918. var invertedIndicesMap = {};
  22919. for (var i = 0; i < dimensions.length; i++) {
  22920. // Use the original dimensions[i], where other flag props may exists.
  22921. var dimensionInfo = dimensions[i];
  22922. if (isString(dimensionInfo)) {
  22923. dimensionInfo = {name: dimensionInfo};
  22924. }
  22925. var dimensionName = dimensionInfo.name;
  22926. dimensionInfo.type = dimensionInfo.type || 'float';
  22927. if (!dimensionInfo.coordDim) {
  22928. dimensionInfo.coordDim = dimensionName;
  22929. dimensionInfo.coordDimIndex = 0;
  22930. }
  22931. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  22932. dimensionNames.push(dimensionName);
  22933. dimensionInfos[dimensionName] = dimensionInfo;
  22934. dimensionInfo.index = i;
  22935. if (dimensionInfo.createInvertedIndices) {
  22936. invertedIndicesMap[dimensionName] = [];
  22937. }
  22938. }
  22939. /**
  22940. * @readOnly
  22941. * @type {Array.<string>}
  22942. */
  22943. this.dimensions = dimensionNames;
  22944. /**
  22945. * Infomation of each data dimension, like data type.
  22946. * @type {Object}
  22947. */
  22948. this._dimensionInfos = dimensionInfos;
  22949. /**
  22950. * @type {module:echarts/model/Model}
  22951. */
  22952. this.hostModel = hostModel;
  22953. /**
  22954. * @type {module:echarts/model/Model}
  22955. */
  22956. this.dataType;
  22957. /**
  22958. * Indices stores the indices of data subset after filtered.
  22959. * This data subset will be used in chart.
  22960. * @type {Array.<number>}
  22961. * @readOnly
  22962. */
  22963. this._indices = null;
  22964. this._count = 0;
  22965. this._rawCount = 0;
  22966. /**
  22967. * Data storage
  22968. * @type {Object.<key, Array.<TypedArray|Array>>}
  22969. * @private
  22970. */
  22971. this._storage = {};
  22972. /**
  22973. * @type {Array.<string>}
  22974. */
  22975. this._nameList = [];
  22976. /**
  22977. * @type {Array.<string>}
  22978. */
  22979. this._idList = [];
  22980. /**
  22981. * Models of data option is stored sparse for optimizing memory cost
  22982. * @type {Array.<module:echarts/model/Model>}
  22983. * @private
  22984. */
  22985. this._optionModels = [];
  22986. /**
  22987. * Global visual properties after visual coding
  22988. * @type {Object}
  22989. * @private
  22990. */
  22991. this._visual = {};
  22992. /**
  22993. * Globel layout properties.
  22994. * @type {Object}
  22995. * @private
  22996. */
  22997. this._layout = {};
  22998. /**
  22999. * Item visual properties after visual coding
  23000. * @type {Array.<Object>}
  23001. * @private
  23002. */
  23003. this._itemVisuals = [];
  23004. /**
  23005. * Key: visual type, Value: boolean
  23006. * @type {Object}
  23007. * @readOnly
  23008. */
  23009. this.hasItemVisual = {};
  23010. /**
  23011. * Item layout properties after layout
  23012. * @type {Array.<Object>}
  23013. * @private
  23014. */
  23015. this._itemLayouts = [];
  23016. /**
  23017. * Graphic elemnents
  23018. * @type {Array.<module:zrender/Element>}
  23019. * @private
  23020. */
  23021. this._graphicEls = [];
  23022. /**
  23023. * Max size of each chunk.
  23024. * @type {number}
  23025. * @private
  23026. */
  23027. this._chunkSize = 1e5;
  23028. /**
  23029. * @type {number}
  23030. * @private
  23031. */
  23032. this._chunkCount = 0;
  23033. /**
  23034. * @type {Array.<Array|Object>}
  23035. * @private
  23036. */
  23037. this._rawData;
  23038. /**
  23039. * Raw extent will not be cloned, but only transfered.
  23040. * It will not be calculated util needed.
  23041. * key: dim,
  23042. * value: {end: number, extent: Array.<number>}
  23043. * @type {Object}
  23044. * @private
  23045. */
  23046. this._rawExtent = {};
  23047. /**
  23048. * @type {Object}
  23049. * @private
  23050. */
  23051. this._extent = {};
  23052. /**
  23053. * key: dim
  23054. * value: extent
  23055. * @type {Object}
  23056. * @private
  23057. */
  23058. this._approximateExtent = {};
  23059. /**
  23060. * Cache summary info for fast visit. See "dimensionHelper".
  23061. * @type {Object}
  23062. * @private
  23063. */
  23064. this._dimensionsSummary = summarizeDimensions(this);
  23065. /**
  23066. * @type {Object.<Array|TypedArray>}
  23067. * @private
  23068. */
  23069. this._invertedIndicesMap = invertedIndicesMap;
  23070. /**
  23071. * @type {Object}
  23072. * @private
  23073. */
  23074. this._calculationInfo = {};
  23075. };
  23076. var listProto = List.prototype;
  23077. listProto.type = 'list';
  23078. /**
  23079. * If each data item has it's own option
  23080. * @type {boolean}
  23081. */
  23082. listProto.hasItemOption = true;
  23083. /**
  23084. * Get dimension name
  23085. * @param {string|number} dim
  23086. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  23087. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  23088. * @return {string} Concrete dim name.
  23089. */
  23090. listProto.getDimension = function (dim) {
  23091. if (!isNaN(dim)) {
  23092. dim = this.dimensions[dim] || dim;
  23093. }
  23094. return dim;
  23095. };
  23096. /**
  23097. * Get type and calculation info of particular dimension
  23098. * @param {string|number} dim
  23099. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  23100. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  23101. */
  23102. listProto.getDimensionInfo = function (dim) {
  23103. // Do not clone, because there may be categories in dimInfo.
  23104. return this._dimensionInfos[this.getDimension(dim)];
  23105. };
  23106. /**
  23107. * @return {Array.<string>} concrete dimension name list on coord.
  23108. */
  23109. listProto.getDimensionsOnCoord = function () {
  23110. return this._dimensionsSummary.dataDimsOnCoord.slice();
  23111. };
  23112. /**
  23113. * @param {string} coordDim
  23114. * @param {number} [idx] A coordDim may map to more than one data dim.
  23115. * If idx is `true`, return a array of all mapped dims.
  23116. * If idx is not specified, return the first dim not extra.
  23117. * @return {string|Array.<string>} concrete data dim.
  23118. * If idx is number, and not found, return null/undefined.
  23119. * If idx is `true`, and not found, return empty array (always return array).
  23120. */
  23121. listProto.mapDimension = function (coordDim, idx) {
  23122. var dimensionsSummary = this._dimensionsSummary;
  23123. if (idx == null) {
  23124. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  23125. }
  23126. var dims = dimensionsSummary.encode[coordDim];
  23127. return idx === true
  23128. // always return array if idx is `true`
  23129. ? (dims || []).slice()
  23130. : (dims && dims[idx]);
  23131. };
  23132. /**
  23133. * Initialize from data
  23134. * @param {Array.<Object|number|Array>} data source or data or data provider.
  23135. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  23136. * defualt label/tooltip.
  23137. * A name can be specified in encode.itemName,
  23138. * or dataItem.name (only for series option data),
  23139. * or provided in nameList from outside.
  23140. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  23141. */
  23142. listProto.initData = function (data, nameList, dimValueGetter) {
  23143. var notProvider = Source.isInstance(data) || isArrayLike(data);
  23144. if (notProvider) {
  23145. data = new DefaultDataProvider(data, this.dimensions.length);
  23146. }
  23147. if (__DEV__) {
  23148. if (!notProvider && (typeof data.getItem != 'function' || typeof data.count != 'function')) {
  23149. throw new Error('Inavlid data provider.');
  23150. }
  23151. }
  23152. this._rawData = data;
  23153. // Clear
  23154. this._storage = {};
  23155. this._indices = null;
  23156. this._nameList = nameList || [];
  23157. this._idList = [];
  23158. this._nameRepeatCount = {};
  23159. if (!dimValueGetter) {
  23160. this.hasItemOption = false;
  23161. }
  23162. /**
  23163. * @readOnly
  23164. */
  23165. this.defaultDimValueGetter = defaultDimValueGetters[
  23166. this._rawData.getSource().sourceFormat
  23167. ];
  23168. // Default dim value getter
  23169. this._dimValueGetter = dimValueGetter = dimValueGetter
  23170. || this.defaultDimValueGetter;
  23171. // Reset raw extent.
  23172. this._rawExtent = {};
  23173. this._initDataFromProvider(0, data.count());
  23174. // If data has no item option.
  23175. if (data.pure) {
  23176. this.hasItemOption = false;
  23177. }
  23178. };
  23179. listProto.getProvider = function () {
  23180. return this._rawData;
  23181. };
  23182. listProto.appendData = function (data) {
  23183. if (__DEV__) {
  23184. assert$1(!this._indices, 'appendData can only be called on raw data.');
  23185. }
  23186. var rawData = this._rawData;
  23187. var start = this.count();
  23188. rawData.appendData(data);
  23189. var end = rawData.count();
  23190. if (!rawData.persistent) {
  23191. end += start;
  23192. }
  23193. this._initDataFromProvider(start, end);
  23194. };
  23195. listProto._initDataFromProvider = function (start, end) {
  23196. // Optimize.
  23197. if (start >= end) {
  23198. return;
  23199. }
  23200. var chunkSize = this._chunkSize;
  23201. var rawData = this._rawData;
  23202. var storage = this._storage;
  23203. var dimensions = this.dimensions;
  23204. var dimensionInfoMap = this._dimensionInfos;
  23205. var nameList = this._nameList;
  23206. var idList = this._idList;
  23207. var rawExtent = this._rawExtent;
  23208. var nameRepeatCount = this._nameRepeatCount = {};
  23209. var nameDimIdx;
  23210. var chunkCount = this._chunkCount;
  23211. var lastChunkIndex = chunkCount - 1;
  23212. for (var i = 0; i < dimensions.length; i++) {
  23213. var dim = dimensions[i];
  23214. if (!rawExtent[dim]) {
  23215. rawExtent[dim] = getInitialExtent();
  23216. }
  23217. var dimInfo = dimensionInfoMap[dim];
  23218. if (dimInfo.otherDims.itemName === 0) {
  23219. nameDimIdx = this._nameDimIdx = i;
  23220. }
  23221. if (dimInfo.otherDims.itemId === 0) {
  23222. this._idDimIdx = i;
  23223. }
  23224. var DataCtor = dataCtors[dimInfo.type];
  23225. if (!storage[dim]) {
  23226. storage[dim] = [];
  23227. }
  23228. var resizeChunkArray = storage[dim][lastChunkIndex];
  23229. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  23230. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
  23231. // The cost of the copy is probably inconsiderable
  23232. // within the initial chunkSize.
  23233. for (var j = 0; j < resizeChunkArray.length; j++) {
  23234. newStore[j] = resizeChunkArray[j];
  23235. }
  23236. storage[dim][lastChunkIndex] = newStore;
  23237. }
  23238. // Create new chunks.
  23239. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  23240. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  23241. }
  23242. this._chunkCount = storage[dim].length;
  23243. }
  23244. for (var idx = start; idx < end; idx++) {
  23245. // NOTICE: Try not to write things into dataItem
  23246. var dataItem = rawData.getItem(idx);
  23247. // Each data item is value
  23248. // [1, 2]
  23249. // 2
  23250. // Bar chart, line chart which uses category axis
  23251. // only gives the 'y' value. 'x' value is the indices of category
  23252. // Use a tempValue to normalize the value to be a (x, y) value
  23253. var chunkIndex = Math.floor(idx / chunkSize);
  23254. var chunkOffset = idx % chunkSize;
  23255. // Store the data by dimensions
  23256. for (var k = 0; k < dimensions.length; k++) {
  23257. var dim = dimensions[k];
  23258. var dimStorage = storage[dim][chunkIndex];
  23259. // PENDING NULL is empty or zero
  23260. var val = this._dimValueGetter(dataItem, dim, idx, k);
  23261. dimStorage[chunkOffset] = val;
  23262. if (val < rawExtent[dim][0]) {
  23263. rawExtent[dim][0] = val;
  23264. }
  23265. if (val > rawExtent[dim][1]) {
  23266. rawExtent[dim][1] = val;
  23267. }
  23268. }
  23269. // ??? FIXME not check by pure but sourceFormat?
  23270. // TODO refactor these logic.
  23271. if (!rawData.pure) {
  23272. var name = nameList[idx];
  23273. if (dataItem && !name) {
  23274. if (nameDimIdx != null) {
  23275. name = this._getNameFromStore(idx);
  23276. }
  23277. else if (dataItem.name != null) {
  23278. // There is no other place to persistent dataItem.name,
  23279. // so save it to nameList.
  23280. nameList[idx] = name = dataItem.name;
  23281. }
  23282. }
  23283. // Try using the id in option
  23284. // id or name is used on dynamical data, mapping old and new items.
  23285. var id = dataItem == null ? null : dataItem.id;
  23286. if (id == null && name != null) {
  23287. // Use name as id and add counter to avoid same name
  23288. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  23289. id = name;
  23290. if (nameRepeatCount[name] > 0) {
  23291. id += '__ec__' + nameRepeatCount[name];
  23292. }
  23293. nameRepeatCount[name]++;
  23294. }
  23295. id != null && (idList[idx] = id);
  23296. }
  23297. }
  23298. if (!rawData.persistent && rawData.clean) {
  23299. // Clean unused data if data source is typed array.
  23300. rawData.clean();
  23301. }
  23302. this._rawCount = this._count = end;
  23303. // Reset data extent
  23304. this._extent = {};
  23305. prepareInvertedIndex(this);
  23306. };
  23307. function prepareInvertedIndex(list) {
  23308. var invertedIndicesMap = list._invertedIndicesMap;
  23309. each$1(invertedIndicesMap, function (invertedIndices, dim) {
  23310. var dimInfo = list._dimensionInfos[dim];
  23311. // Currently, only dimensions that has ordinalMeta can create inverted indices.
  23312. var ordinalMeta = dimInfo.ordinalMeta;
  23313. if (ordinalMeta) {
  23314. invertedIndices = invertedIndicesMap[dim] = new CtorUint32Array(
  23315. ordinalMeta.categories.length
  23316. );
  23317. // The default value of TypedArray is 0. To avoid miss
  23318. // mapping to 0, we should set it as NaN.
  23319. for (var i = 0; i < invertedIndices.length; i++) {
  23320. invertedIndices[i] = NaN;
  23321. }
  23322. for (var i = 0; i < list._count; i++) {
  23323. // Only support the case that all values are distinct.
  23324. invertedIndices[list.get(dim, i)] = i;
  23325. }
  23326. }
  23327. });
  23328. }
  23329. // TODO refactor
  23330. listProto._getNameFromStore = function (rawIndex) {
  23331. var nameDimIdx = this._nameDimIdx;
  23332. if (nameDimIdx != null) {
  23333. var chunkSize = this._chunkSize;
  23334. var chunkIndex = Math.floor(rawIndex / chunkSize);
  23335. var chunkOffset = rawIndex % chunkSize;
  23336. var dim = this.dimensions[nameDimIdx];
  23337. var ordinalMeta = this._dimensionInfos[dim].ordinalMeta;
  23338. if (ordinalMeta) {
  23339. return ordinalMeta.categories[rawIndex];
  23340. }
  23341. else {
  23342. var chunk = this._storage[dim][chunkIndex];
  23343. return chunk && chunk[chunkOffset];
  23344. }
  23345. }
  23346. };
  23347. // TODO refactor
  23348. listProto._getIdFromStore = function (rawIndex) {
  23349. var idDimIdx = this._idDimIdx;
  23350. if (idDimIdx != null) {
  23351. var chunkSize = this._chunkSize;
  23352. var chunkIndex = Math.floor(rawIndex / chunkSize);
  23353. var chunkOffset = rawIndex % chunkSize;
  23354. var dim = this.dimensions[idDimIdx];
  23355. var ordinalMeta = this._dimensionInfos[dim].ordinalMeta;
  23356. if (ordinalMeta) {
  23357. return ordinalMeta.categories[rawIndex];
  23358. }
  23359. else {
  23360. var chunk = this._storage[dim][chunkIndex];
  23361. return chunk && chunk[chunkOffset];
  23362. }
  23363. }
  23364. };
  23365. /**
  23366. * @return {number}
  23367. */
  23368. listProto.count = function () {
  23369. return this._count;
  23370. };
  23371. listProto.getIndices = function () {
  23372. if (this._indices) {
  23373. var Ctor = this._indices.constructor;
  23374. return new Ctor(this._indices.buffer, 0, this._count);
  23375. }
  23376. var Ctor = getIndicesCtor(this);
  23377. var arr = new Ctor(this.count());
  23378. for (var i = 0; i < arr.length; i++) {
  23379. arr[i] = i;
  23380. }
  23381. return arr;
  23382. };
  23383. /**
  23384. * Get value. Return NaN if idx is out of range.
  23385. * @param {string} dim Dim must be concrete name.
  23386. * @param {number} idx
  23387. * @param {boolean} stack
  23388. * @return {number}
  23389. */
  23390. listProto.get = function (dim, idx /*, stack */) {
  23391. if (!(idx >= 0 && idx < this._count)) {
  23392. return NaN;
  23393. }
  23394. var storage = this._storage;
  23395. if (!storage[dim]) {
  23396. // TODO Warn ?
  23397. return NaN;
  23398. }
  23399. idx = this.getRawIndex(idx);
  23400. var chunkIndex = Math.floor(idx / this._chunkSize);
  23401. var chunkOffset = idx % this._chunkSize;
  23402. var chunkStore = storage[dim][chunkIndex];
  23403. var value = chunkStore[chunkOffset];
  23404. // FIXME ordinal data type is not stackable
  23405. // if (stack) {
  23406. // var dimensionInfo = this._dimensionInfos[dim];
  23407. // if (dimensionInfo && dimensionInfo.stackable) {
  23408. // var stackedOn = this.stackedOn;
  23409. // while (stackedOn) {
  23410. // // Get no stacked data of stacked on
  23411. // var stackedValue = stackedOn.get(dim, idx);
  23412. // // Considering positive stack, negative stack and empty data
  23413. // if ((value >= 0 && stackedValue > 0) // Positive stack
  23414. // || (value <= 0 && stackedValue < 0) // Negative stack
  23415. // ) {
  23416. // value += stackedValue;
  23417. // }
  23418. // stackedOn = stackedOn.stackedOn;
  23419. // }
  23420. // }
  23421. // }
  23422. return value;
  23423. };
  23424. /**
  23425. * @param {string} dim concrete dim
  23426. * @param {number} rawIndex
  23427. * @return {number|string}
  23428. */
  23429. listProto.getByRawIndex = function (dim, rawIdx) {
  23430. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  23431. return NaN;
  23432. }
  23433. var dimStore = this._storage[dim];
  23434. if (!dimStore) {
  23435. // TODO Warn ?
  23436. return NaN;
  23437. }
  23438. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  23439. var chunkOffset = rawIdx % this._chunkSize;
  23440. var chunkStore = dimStore[chunkIndex];
  23441. return chunkStore[chunkOffset];
  23442. };
  23443. /**
  23444. * FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  23445. * Hack a much simpler _getFast
  23446. * @private
  23447. */
  23448. listProto._getFast = function (dim, rawIdx) {
  23449. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  23450. var chunkOffset = rawIdx % this._chunkSize;
  23451. var chunkStore = this._storage[dim][chunkIndex];
  23452. return chunkStore[chunkOffset];
  23453. };
  23454. /**
  23455. * Get value for multi dimensions.
  23456. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  23457. * @param {number} idx
  23458. * @return {number}
  23459. */
  23460. listProto.getValues = function (dimensions, idx /*, stack */) {
  23461. var values = [];
  23462. if (!isArray(dimensions)) {
  23463. // stack = idx;
  23464. idx = dimensions;
  23465. dimensions = this.dimensions;
  23466. }
  23467. for (var i = 0, len = dimensions.length; i < len; i++) {
  23468. values.push(this.get(dimensions[i], idx /*, stack */));
  23469. }
  23470. return values;
  23471. };
  23472. /**
  23473. * If value is NaN. Inlcuding '-'
  23474. * Only check the coord dimensions.
  23475. * @param {string} dim
  23476. * @param {number} idx
  23477. * @return {number}
  23478. */
  23479. listProto.hasValue = function (idx) {
  23480. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  23481. var dimensionInfos = this._dimensionInfos;
  23482. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  23483. if (
  23484. // Ordinal type can be string or number
  23485. dimensionInfos[dataDimsOnCoord[i]].type !== 'ordinal'
  23486. // FIXME check ordinal when using index?
  23487. && isNaN(this.get(dataDimsOnCoord[i], idx))
  23488. ) {
  23489. return false;
  23490. }
  23491. }
  23492. return true;
  23493. };
  23494. /**
  23495. * Get extent of data in one dimension
  23496. * @param {string} dim
  23497. * @param {boolean} stack
  23498. */
  23499. listProto.getDataExtent = function (dim /*, stack */) {
  23500. // Make sure use concrete dim as cache name.
  23501. dim = this.getDimension(dim);
  23502. var dimData = this._storage[dim];
  23503. var initialExtent = getInitialExtent();
  23504. // stack = !!((stack || false) && this.getCalculationInfo(dim));
  23505. if (!dimData) {
  23506. return initialExtent;
  23507. }
  23508. // Make more strict checkings to ensure hitting cache.
  23509. var currEnd = this.count();
  23510. // var cacheName = [dim, !!stack].join('_');
  23511. // var cacheName = dim;
  23512. // Consider the most cases when using data zoom, `getDataExtent`
  23513. // happened before filtering. We cache raw extent, which is not
  23514. // necessary to be cleared and recalculated when restore data.
  23515. var useRaw = !this._indices; // && !stack;
  23516. var dimExtent;
  23517. if (useRaw) {
  23518. return this._rawExtent[dim].slice();
  23519. }
  23520. dimExtent = this._extent[dim];
  23521. if (dimExtent) {
  23522. return dimExtent.slice();
  23523. }
  23524. dimExtent = initialExtent;
  23525. var min = dimExtent[0];
  23526. var max = dimExtent[1];
  23527. for (var i = 0; i < currEnd; i++) {
  23528. // var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  23529. var value = this._getFast(dim, this.getRawIndex(i));
  23530. value < min && (min = value);
  23531. value > max && (max = value);
  23532. }
  23533. dimExtent = [min, max];
  23534. this._extent[dim] = dimExtent;
  23535. return dimExtent;
  23536. };
  23537. /**
  23538. * Optimize for the scenario that data is filtered by a given extent.
  23539. * Consider that if data amount is more than hundreds of thousand,
  23540. * extent calculation will cost more than 10ms and the cache will
  23541. * be erased because of the filtering.
  23542. */
  23543. listProto.getApproximateExtent = function (dim /*, stack */) {
  23544. dim = this.getDimension(dim);
  23545. return this._approximateExtent[dim] || this.getDataExtent(dim /*, stack */);
  23546. };
  23547. listProto.setApproximateExtent = function (extent, dim /*, stack */) {
  23548. dim = this.getDimension(dim);
  23549. this._approximateExtent[dim] = extent.slice();
  23550. };
  23551. /**
  23552. * @param {string} key
  23553. * @return {*}
  23554. */
  23555. listProto.getCalculationInfo = function (key) {
  23556. return this._calculationInfo[key];
  23557. };
  23558. /**
  23559. * @param {string|Object} key or k-v object
  23560. * @param {*} [value]
  23561. */
  23562. listProto.setCalculationInfo = function (key, value) {
  23563. isObject$4(key)
  23564. ? extend(this._calculationInfo, key)
  23565. : (this._calculationInfo[key] = value);
  23566. };
  23567. /**
  23568. * Get sum of data in one dimension
  23569. * @param {string} dim
  23570. */
  23571. listProto.getSum = function (dim /*, stack */) {
  23572. var dimData = this._storage[dim];
  23573. var sum = 0;
  23574. if (dimData) {
  23575. for (var i = 0, len = this.count(); i < len; i++) {
  23576. var value = this.get(dim, i /*, stack */);
  23577. if (!isNaN(value)) {
  23578. sum += value;
  23579. }
  23580. }
  23581. }
  23582. return sum;
  23583. };
  23584. // /**
  23585. // * Retreive the index with given value
  23586. // * @param {string} dim Concrete dimension.
  23587. // * @param {number} value
  23588. // * @return {number}
  23589. // */
  23590. // Currently incorrect: should return dataIndex but not rawIndex.
  23591. // Do not fix it until this method is to be used somewhere.
  23592. // FIXME Precision of float value
  23593. // listProto.indexOf = function (dim, value) {
  23594. // var storage = this._storage;
  23595. // var dimData = storage[dim];
  23596. // var chunkSize = this._chunkSize;
  23597. // if (dimData) {
  23598. // for (var i = 0, len = this.count(); i < len; i++) {
  23599. // var chunkIndex = Math.floor(i / chunkSize);
  23600. // var chunkOffset = i % chunkSize;
  23601. // if (dimData[chunkIndex][chunkOffset] === value) {
  23602. // return i;
  23603. // }
  23604. // }
  23605. // }
  23606. // return -1;
  23607. // };
  23608. /**
  23609. * Only support the dimension which inverted index created.
  23610. * Do not support other cases until required.
  23611. * @param {string} concrete dim
  23612. * @param {number|string} value
  23613. * @return {number} rawIndex
  23614. */
  23615. listProto.rawIndexOf = function (dim, value) {
  23616. var invertedIndices = dim && this._invertedIndicesMap[dim];
  23617. if (__DEV__) {
  23618. if (!invertedIndices) {
  23619. throw new Error('Do not supported yet');
  23620. }
  23621. }
  23622. var rawIndex = invertedIndices[value];
  23623. if (rawIndex == null || isNaN(rawIndex)) {
  23624. return -1;
  23625. }
  23626. return rawIndex;
  23627. };
  23628. /**
  23629. * Retreive the index with given name
  23630. * @param {number} idx
  23631. * @param {number} name
  23632. * @return {number}
  23633. */
  23634. listProto.indexOfName = function (name) {
  23635. for (var i = 0, len = this.count(); i < len; i++) {
  23636. if (this.getName(i) === name) {
  23637. return i;
  23638. }
  23639. }
  23640. return -1;
  23641. };
  23642. /**
  23643. * Retreive the index with given raw data index
  23644. * @param {number} idx
  23645. * @param {number} name
  23646. * @return {number}
  23647. */
  23648. listProto.indexOfRawIndex = function (rawIndex) {
  23649. if (!this._indices) {
  23650. return rawIndex;
  23651. }
  23652. if (rawIndex >= this._rawCount || rawIndex < 0) {
  23653. return -1;
  23654. }
  23655. // Indices are ascending
  23656. var indices = this._indices;
  23657. // If rawIndex === dataIndex
  23658. var rawDataIndex = indices[rawIndex];
  23659. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  23660. return rawIndex;
  23661. }
  23662. var left = 0;
  23663. var right = this._count - 1;
  23664. while (left <= right) {
  23665. var mid = (left + right) / 2 | 0;
  23666. if (indices[mid] < rawIndex) {
  23667. left = mid + 1;
  23668. }
  23669. else if (indices[mid] > rawIndex) {
  23670. right = mid - 1;
  23671. }
  23672. else {
  23673. return mid;
  23674. }
  23675. }
  23676. return -1;
  23677. };
  23678. /**
  23679. * Retreive the index of nearest value
  23680. * @param {string} dim
  23681. * @param {number} value
  23682. * @param {number} [maxDistance=Infinity]
  23683. * @return {Array.<number>} Considere multiple points has the same value.
  23684. */
  23685. listProto.indicesOfNearest = function (dim, value, maxDistance) {
  23686. var storage = this._storage;
  23687. var dimData = storage[dim];
  23688. var nearestIndices = [];
  23689. if (!dimData) {
  23690. return nearestIndices;
  23691. }
  23692. if (maxDistance == null) {
  23693. maxDistance = Infinity;
  23694. }
  23695. var minDist = Number.MAX_VALUE;
  23696. var minDiff = -1;
  23697. for (var i = 0, len = this.count(); i < len; i++) {
  23698. var diff = value - this.get(dim, i /*, stack */);
  23699. var dist = Math.abs(diff);
  23700. if (diff <= maxDistance && dist <= minDist) {
  23701. // For the case of two data are same on xAxis, which has sequence data.
  23702. // Show the nearest index
  23703. // https://github.com/ecomfe/echarts/issues/2869
  23704. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  23705. minDist = dist;
  23706. minDiff = diff;
  23707. nearestIndices.length = 0;
  23708. }
  23709. nearestIndices.push(i);
  23710. }
  23711. }
  23712. return nearestIndices;
  23713. };
  23714. /**
  23715. * Get raw data index
  23716. * @param {number} idx
  23717. * @return {number}
  23718. */
  23719. listProto.getRawIndex = getRawIndexWithoutIndices;
  23720. function getRawIndexWithoutIndices(idx) {
  23721. return idx;
  23722. }
  23723. function getRawIndexWithIndices(idx) {
  23724. if (idx < this._count && idx >= 0) {
  23725. return this._indices[idx];
  23726. }
  23727. return -1;
  23728. }
  23729. /**
  23730. * Get raw data item
  23731. * @param {number} idx
  23732. * @return {number}
  23733. */
  23734. listProto.getRawDataItem = function (idx) {
  23735. if (!this._rawData.persistent) {
  23736. var val = [];
  23737. for (var i = 0; i < this.dimensions.length; i++) {
  23738. var dim = this.dimensions[i];
  23739. val.push(this.get(dim, idx));
  23740. }
  23741. return val;
  23742. }
  23743. else {
  23744. return this._rawData.getItem(this.getRawIndex(idx));
  23745. }
  23746. };
  23747. /**
  23748. * @param {number} idx
  23749. * @param {boolean} [notDefaultIdx=false]
  23750. * @return {string}
  23751. */
  23752. listProto.getName = function (idx) {
  23753. var rawIndex = this.getRawIndex(idx);
  23754. return this._nameList[rawIndex]
  23755. || this._getNameFromStore(rawIndex)
  23756. || '';
  23757. };
  23758. /**
  23759. * @param {number} idx
  23760. * @param {boolean} [notDefaultIdx=false]
  23761. * @return {string}
  23762. */
  23763. listProto.getId = function (idx) {
  23764. return getId(this, this.getRawIndex(idx));
  23765. };
  23766. function getId(list, rawIndex) {
  23767. var id = list._idList[rawIndex];
  23768. if (id == null) {
  23769. id = list._getIdFromStore(rawIndex);
  23770. }
  23771. if (id == null) {
  23772. // FIXME Check the usage in graph, should not use prefix.
  23773. id = ID_PREFIX + rawIndex;
  23774. }
  23775. return id;
  23776. }
  23777. function normalizeDimensions(dimensions) {
  23778. if (!isArray(dimensions)) {
  23779. dimensions = [dimensions];
  23780. }
  23781. return dimensions;
  23782. }
  23783. function validateDimensions(list, dims) {
  23784. for (var i = 0; i < dims.length; i++) {
  23785. // stroage may be empty when no data, so use
  23786. // dimensionInfos to check.
  23787. if (!list._dimensionInfos[dims[i]]) {
  23788. console.error('Unkown dimension ' + dims[i]);
  23789. }
  23790. }
  23791. }
  23792. /**
  23793. * Data iteration
  23794. * @param {string|Array.<string>}
  23795. * @param {Function} cb
  23796. * @param {*} [context=this]
  23797. *
  23798. * @example
  23799. * list.each('x', function (x, idx) {});
  23800. * list.each(['x', 'y'], function (x, y, idx) {});
  23801. * list.each(function (idx) {})
  23802. */
  23803. listProto.each = function (dims, cb, context, contextCompat) {
  23804. 'use strict';
  23805. if (!this._count) {
  23806. return;
  23807. }
  23808. if (typeof dims === 'function') {
  23809. contextCompat = context;
  23810. context = cb;
  23811. cb = dims;
  23812. dims = [];
  23813. }
  23814. // contextCompat just for compat echarts3
  23815. context = context || contextCompat || this;
  23816. dims = map(normalizeDimensions(dims), this.getDimension, this);
  23817. if (__DEV__) {
  23818. validateDimensions(this, dims);
  23819. }
  23820. var dimSize = dims.length;
  23821. for (var i = 0; i < this.count(); i++) {
  23822. // Simple optimization
  23823. switch (dimSize) {
  23824. case 0:
  23825. cb.call(context, i);
  23826. break;
  23827. case 1:
  23828. cb.call(context, this.get(dims[0], i), i);
  23829. break;
  23830. case 2:
  23831. cb.call(context, this.get(dims[0], i), this.get(dims[1], i), i);
  23832. break;
  23833. default:
  23834. var k = 0;
  23835. var value = [];
  23836. for (; k < dimSize; k++) {
  23837. value[k] = this.get(dims[k], i);
  23838. }
  23839. // Index
  23840. value[k] = i;
  23841. cb.apply(context, value);
  23842. }
  23843. }
  23844. };
  23845. /**
  23846. * Data filter
  23847. * @param {string|Array.<string>}
  23848. * @param {Function} cb
  23849. * @param {*} [context=this]
  23850. */
  23851. listProto.filterSelf = function (dimensions, cb, context, contextCompat) {
  23852. 'use strict';
  23853. if (!this._count) {
  23854. return;
  23855. }
  23856. if (typeof dimensions === 'function') {
  23857. contextCompat = context;
  23858. context = cb;
  23859. cb = dimensions;
  23860. dimensions = [];
  23861. }
  23862. // contextCompat just for compat echarts3
  23863. context = context || contextCompat || this;
  23864. dimensions = map(
  23865. normalizeDimensions(dimensions), this.getDimension, this
  23866. );
  23867. if (__DEV__) {
  23868. validateDimensions(this, dimensions);
  23869. }
  23870. var count = this.count();
  23871. var Ctor = getIndicesCtor(this);
  23872. var newIndices = new Ctor(count);
  23873. var value = [];
  23874. var dimSize = dimensions.length;
  23875. var offset = 0;
  23876. var dim0 = dimensions[0];
  23877. for (var i = 0; i < count; i++) {
  23878. var keep;
  23879. var rawIdx = this.getRawIndex(i);
  23880. // Simple optimization
  23881. if (dimSize === 0) {
  23882. keep = cb.call(context, i);
  23883. }
  23884. else if (dimSize === 1) {
  23885. var val = this._getFast(dim0, rawIdx);
  23886. keep = cb.call(context, val, i);
  23887. }
  23888. else {
  23889. for (var k = 0; k < dimSize; k++) {
  23890. value[k] = this._getFast(dim0, rawIdx);
  23891. }
  23892. value[k] = i;
  23893. keep = cb.apply(context, value);
  23894. }
  23895. if (keep) {
  23896. newIndices[offset++] = rawIdx;
  23897. }
  23898. }
  23899. // Set indices after filtered.
  23900. if (offset < count) {
  23901. this._indices = newIndices;
  23902. }
  23903. this._count = offset;
  23904. // Reset data extent
  23905. this._extent = {};
  23906. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  23907. return this;
  23908. };
  23909. /**
  23910. * Select data in range. (For optimization of filter)
  23911. * (Manually inline code, support 5 million data filtering in data zoom.)
  23912. */
  23913. listProto.selectRange = function (range /*, stack */) {
  23914. 'use strict';
  23915. if (!this._count) {
  23916. return;
  23917. }
  23918. // stack = stack || false;
  23919. var dimensions = [];
  23920. for (var dim in range) {
  23921. if (range.hasOwnProperty(dim)) {
  23922. dimensions.push(dim);
  23923. }
  23924. }
  23925. if (__DEV__) {
  23926. validateDimensions(this, dimensions);
  23927. }
  23928. var dimSize = dimensions.length;
  23929. if (!dimSize) {
  23930. return;
  23931. }
  23932. var originalCount = this.count();
  23933. var Ctor = getIndicesCtor(this);
  23934. var newIndices = new Ctor(originalCount);
  23935. var offset = 0;
  23936. var dim0 = dimensions[0];
  23937. var min = range[dim0][0];
  23938. var max = range[dim0][1];
  23939. var quickFinished = false;
  23940. if (!this._indices /* && !stack */) {
  23941. // Extreme optimization for common case. About 2x faster in chrome.
  23942. var idx = 0;
  23943. if (dimSize === 1) {
  23944. var dimStorage = this._storage[dimensions[0]];
  23945. for (var k = 0; k < this._chunkCount; k++) {
  23946. var chunkStorage = dimStorage[k];
  23947. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  23948. for (var i = 0; i < len; i++) {
  23949. var val = chunkStorage[i];
  23950. if (val >= min && val <= max) {
  23951. newIndices[offset++] = idx;
  23952. }
  23953. idx++;
  23954. }
  23955. }
  23956. quickFinished = true;
  23957. }
  23958. else if (dimSize === 2) {
  23959. var dimStorage = this._storage[dim0];
  23960. var dimStorage2 = this._storage[dimensions[1]];
  23961. var min2 = range[dimensions[1]][0];
  23962. var max2 = range[dimensions[1]][1];
  23963. for (var k = 0; k < this._chunkCount; k++) {
  23964. var chunkStorage = dimStorage[k];
  23965. var chunkStorage2= dimStorage2[k];
  23966. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  23967. for (var i = 0; i < len; i++) {
  23968. var val = chunkStorage[i];
  23969. var val2 = chunkStorage2[i];
  23970. if (val >= min && val <= max && val2 >= min2 && val2 <= max2) {
  23971. newIndices[offset++] = idx;
  23972. }
  23973. idx++;
  23974. }
  23975. }
  23976. quickFinished = true;
  23977. }
  23978. }
  23979. if (!quickFinished) {
  23980. if (dimSize === 1) {
  23981. // stack = stack || !!this.getCalculationInfo(dim0);
  23982. for (var i = 0; i < originalCount; i++) {
  23983. var rawIndex = this.getRawIndex(i);
  23984. // var val = stack ? this.get(dim0, i, true) : this._getFast(dim0, rawIndex);
  23985. var val = this._getFast(dim0, rawIndex);
  23986. if (val >= min && val <= max) {
  23987. newIndices[offset++] = rawIndex;
  23988. }
  23989. }
  23990. }
  23991. else {
  23992. for (var i = 0; i < originalCount; i++) {
  23993. var keep = true;
  23994. var rawIndex = this.getRawIndex(i);
  23995. for (var k = 0; k < dimSize; k++) {
  23996. var dimk = dimensions[k];
  23997. // var val = stack ? this.get(dimk, i, true) : this._getFast(dim, rawIndex);
  23998. var val = this._getFast(dim, rawIndex);
  23999. if (val < range[dimk][0] || val > range[dimk][1]) {
  24000. keep = false;
  24001. }
  24002. }
  24003. if (keep) {
  24004. newIndices[offset++] = this.getRawIndex(i);
  24005. }
  24006. }
  24007. }
  24008. }
  24009. // Set indices after filtered.
  24010. if (offset < originalCount) {
  24011. this._indices = newIndices;
  24012. }
  24013. this._count = offset;
  24014. // Reset data extent
  24015. this._extent = {};
  24016. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  24017. return this;
  24018. };
  24019. /**
  24020. * Data mapping to a plain array
  24021. * @param {string|Array.<string>} [dimensions]
  24022. * @param {Function} cb
  24023. * @param {*} [context=this]
  24024. * @return {Array}
  24025. */
  24026. listProto.mapArray = function (dimensions, cb, context, contextCompat) {
  24027. 'use strict';
  24028. if (typeof dimensions === 'function') {
  24029. contextCompat = context;
  24030. context = cb;
  24031. cb = dimensions;
  24032. dimensions = [];
  24033. }
  24034. // contextCompat just for compat echarts3
  24035. context = context || contextCompat || this;
  24036. var result = [];
  24037. this.each(dimensions, function () {
  24038. result.push(cb && cb.apply(this, arguments));
  24039. }, context);
  24040. return result;
  24041. };
  24042. // Data in excludeDimensions is copied, otherwise transfered.
  24043. function cloneListForMapAndSample(original, excludeDimensions) {
  24044. var allDimensions = original.dimensions;
  24045. var list = new List(
  24046. map(allDimensions, original.getDimensionInfo, original),
  24047. original.hostModel
  24048. );
  24049. // FIXME If needs stackedOn, value may already been stacked
  24050. transferProperties(list, original);
  24051. var storage = list._storage = {};
  24052. var originalStorage = original._storage;
  24053. var rawExtent = extend({}, original._rawExtent);
  24054. // Init storage
  24055. for (var i = 0; i < allDimensions.length; i++) {
  24056. var dim = allDimensions[i];
  24057. if (originalStorage[dim]) {
  24058. if (indexOf(excludeDimensions, dim) >= 0) {
  24059. storage[dim] = cloneDimStore(originalStorage[dim]);
  24060. rawExtent[dim] = getInitialExtent();
  24061. }
  24062. else {
  24063. // Direct reference for other dimensions
  24064. storage[dim] = originalStorage[dim];
  24065. }
  24066. }
  24067. }
  24068. return list;
  24069. }
  24070. function cloneDimStore(originalDimStore) {
  24071. var newDimStore = new Array(originalDimStore.length);
  24072. for (var j = 0; j < originalDimStore.length; j++) {
  24073. newDimStore[j] = cloneChunk(originalDimStore[j]);
  24074. }
  24075. return newDimStore;
  24076. }
  24077. function getInitialExtent() {
  24078. return [Infinity, -Infinity];
  24079. }
  24080. /**
  24081. * Data mapping to a new List with given dimensions
  24082. * @param {string|Array.<string>} dimensions
  24083. * @param {Function} cb
  24084. * @param {*} [context=this]
  24085. * @return {Array}
  24086. */
  24087. listProto.map = function (dimensions, cb, context, contextCompat) {
  24088. 'use strict';
  24089. // contextCompat just for compat echarts3
  24090. context = context || contextCompat || this;
  24091. dimensions = map(
  24092. normalizeDimensions(dimensions), this.getDimension, this
  24093. );
  24094. if (__DEV__) {
  24095. validateDimensions(this, dimensions);
  24096. }
  24097. var list = cloneListForMapAndSample(this, dimensions);
  24098. // Following properties are all immutable.
  24099. // So we can reference to the same value
  24100. list._indices = this._indices;
  24101. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  24102. var storage = list._storage;
  24103. var tmpRetValue = [];
  24104. var chunkSize = this._chunkSize;
  24105. var dimSize = dimensions.length;
  24106. var dataCount = this.count();
  24107. var values = [];
  24108. var rawExtent = list._rawExtent;
  24109. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  24110. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  24111. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex /*, stack */);
  24112. }
  24113. values[dimSize] = dataIndex;
  24114. var retValue = cb && cb.apply(context, values);
  24115. if (retValue != null) {
  24116. // a number or string (in oridinal dimension)?
  24117. if (typeof retValue !== 'object') {
  24118. tmpRetValue[0] = retValue;
  24119. retValue = tmpRetValue;
  24120. }
  24121. var rawIndex = this.getRawIndex(dataIndex);
  24122. var chunkIndex = Math.floor(rawIndex / chunkSize);
  24123. var chunkOffset = rawIndex % chunkSize;
  24124. for (var i = 0; i < retValue.length; i++) {
  24125. var dim = dimensions[i];
  24126. var val = retValue[i];
  24127. var rawExtentOnDim = rawExtent[dim];
  24128. var dimStore = storage[dim];
  24129. if (dimStore) {
  24130. dimStore[chunkIndex][chunkOffset] = val;
  24131. }
  24132. if (val < rawExtentOnDim[0]) {
  24133. rawExtentOnDim[0] = val;
  24134. }
  24135. if (val > rawExtentOnDim[1]) {
  24136. rawExtentOnDim[1] = val;
  24137. }
  24138. }
  24139. }
  24140. }
  24141. return list;
  24142. };
  24143. /**
  24144. * Large data down sampling on given dimension
  24145. * @param {string} dimension
  24146. * @param {number} rate
  24147. * @param {Function} sampleValue
  24148. * @param {Function} sampleIndex Sample index for name and id
  24149. */
  24150. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  24151. var list = cloneListForMapAndSample(this, [dimension]);
  24152. var targetStorage = list._storage;
  24153. var frameValues = [];
  24154. var frameSize = Math.floor(1 / rate);
  24155. var dimStore = targetStorage[dimension];
  24156. var len = this.count();
  24157. var chunkSize = this._chunkSize;
  24158. var rawExtentOnDim = list._rawExtent[dimension];
  24159. var newIndices = new (getIndicesCtor(this))(len);
  24160. var offset = 0;
  24161. for (var i = 0; i < len; i += frameSize) {
  24162. // Last frame
  24163. if (frameSize > len - i) {
  24164. frameSize = len - i;
  24165. frameValues.length = frameSize;
  24166. }
  24167. for (var k = 0; k < frameSize; k++) {
  24168. var dataIdx = this.getRawIndex(i + k);
  24169. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  24170. var originalChunkOffset = dataIdx % chunkSize;
  24171. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  24172. }
  24173. var value = sampleValue(frameValues);
  24174. var sampleFrameIdx = this.getRawIndex(
  24175. Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
  24176. );
  24177. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  24178. var sampleChunkOffset = sampleFrameIdx % chunkSize;
  24179. // Only write value on the filtered data
  24180. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  24181. if (value < rawExtentOnDim[0]) {
  24182. rawExtentOnDim[0] = value;
  24183. }
  24184. if (value > rawExtentOnDim[1]) {
  24185. rawExtentOnDim[1] = value;
  24186. }
  24187. newIndices[offset++] = sampleFrameIdx;
  24188. }
  24189. list._count = offset;
  24190. list._indices = newIndices;
  24191. list.getRawIndex = getRawIndexWithIndices;
  24192. return list;
  24193. };
  24194. /**
  24195. * Get model of one data item.
  24196. *
  24197. * @param {number} idx
  24198. */
  24199. // FIXME Model proxy ?
  24200. listProto.getItemModel = function (idx) {
  24201. var hostModel = this.hostModel;
  24202. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  24203. };
  24204. /**
  24205. * Create a data differ
  24206. * @param {module:echarts/data/List} otherList
  24207. * @return {module:echarts/data/DataDiffer}
  24208. */
  24209. listProto.diff = function (otherList) {
  24210. var thisList = this;
  24211. return new DataDiffer(
  24212. otherList ? otherList.getIndices() : [],
  24213. this.getIndices(),
  24214. function (idx) {
  24215. return getId(otherList, idx);
  24216. },
  24217. function (idx) {
  24218. return getId(thisList, idx);
  24219. }
  24220. );
  24221. };
  24222. /**
  24223. * Get visual property.
  24224. * @param {string} key
  24225. */
  24226. listProto.getVisual = function (key) {
  24227. var visual = this._visual;
  24228. return visual && visual[key];
  24229. };
  24230. /**
  24231. * Set visual property
  24232. * @param {string|Object} key
  24233. * @param {*} [value]
  24234. *
  24235. * @example
  24236. * setVisual('color', color);
  24237. * setVisual({
  24238. * 'color': color
  24239. * });
  24240. */
  24241. listProto.setVisual = function (key, val) {
  24242. if (isObject$4(key)) {
  24243. for (var name in key) {
  24244. if (key.hasOwnProperty(name)) {
  24245. this.setVisual(name, key[name]);
  24246. }
  24247. }
  24248. return;
  24249. }
  24250. this._visual = this._visual || {};
  24251. this._visual[key] = val;
  24252. };
  24253. /**
  24254. * Set layout property.
  24255. * @param {string|Object} key
  24256. * @param {*} [val]
  24257. */
  24258. listProto.setLayout = function (key, val) {
  24259. if (isObject$4(key)) {
  24260. for (var name in key) {
  24261. if (key.hasOwnProperty(name)) {
  24262. this.setLayout(name, key[name]);
  24263. }
  24264. }
  24265. return;
  24266. }
  24267. this._layout[key] = val;
  24268. };
  24269. /**
  24270. * Get layout property.
  24271. * @param {string} key.
  24272. * @return {*}
  24273. */
  24274. listProto.getLayout = function (key) {
  24275. return this._layout[key];
  24276. };
  24277. /**
  24278. * Get layout of single data item
  24279. * @param {number} idx
  24280. */
  24281. listProto.getItemLayout = function (idx) {
  24282. return this._itemLayouts[idx];
  24283. };
  24284. /**
  24285. * Set layout of single data item
  24286. * @param {number} idx
  24287. * @param {Object} layout
  24288. * @param {boolean=} [merge=false]
  24289. */
  24290. listProto.setItemLayout = function (idx, layout, merge$$1) {
  24291. this._itemLayouts[idx] = merge$$1
  24292. ? extend(this._itemLayouts[idx] || {}, layout)
  24293. : layout;
  24294. };
  24295. /**
  24296. * Clear all layout of single data item
  24297. */
  24298. listProto.clearItemLayouts = function () {
  24299. this._itemLayouts.length = 0;
  24300. };
  24301. /**
  24302. * Get visual property of single data item
  24303. * @param {number} idx
  24304. * @param {string} key
  24305. * @param {boolean} [ignoreParent=false]
  24306. */
  24307. listProto.getItemVisual = function (idx, key, ignoreParent) {
  24308. var itemVisual = this._itemVisuals[idx];
  24309. var val = itemVisual && itemVisual[key];
  24310. if (val == null && !ignoreParent) {
  24311. // Use global visual property
  24312. return this.getVisual(key);
  24313. }
  24314. return val;
  24315. };
  24316. /**
  24317. * Set visual property of single data item
  24318. *
  24319. * @param {number} idx
  24320. * @param {string|Object} key
  24321. * @param {*} [value]
  24322. *
  24323. * @example
  24324. * setItemVisual(0, 'color', color);
  24325. * setItemVisual(0, {
  24326. * 'color': color
  24327. * });
  24328. */
  24329. listProto.setItemVisual = function (idx, key, value) {
  24330. var itemVisual = this._itemVisuals[idx] || {};
  24331. var hasItemVisual = this.hasItemVisual;
  24332. this._itemVisuals[idx] = itemVisual;
  24333. if (isObject$4(key)) {
  24334. for (var name in key) {
  24335. if (key.hasOwnProperty(name)) {
  24336. itemVisual[name] = key[name];
  24337. hasItemVisual[name] = true;
  24338. }
  24339. }
  24340. return;
  24341. }
  24342. itemVisual[key] = value;
  24343. hasItemVisual[key] = true;
  24344. };
  24345. /**
  24346. * Clear itemVisuals and list visual.
  24347. */
  24348. listProto.clearAllVisual = function () {
  24349. this._visual = {};
  24350. this._itemVisuals = [];
  24351. this.hasItemVisual = {};
  24352. };
  24353. var setItemDataAndSeriesIndex = function (child) {
  24354. child.seriesIndex = this.seriesIndex;
  24355. child.dataIndex = this.dataIndex;
  24356. child.dataType = this.dataType;
  24357. };
  24358. /**
  24359. * Set graphic element relative to data. It can be set as null
  24360. * @param {number} idx
  24361. * @param {module:zrender/Element} [el]
  24362. */
  24363. listProto.setItemGraphicEl = function (idx, el) {
  24364. var hostModel = this.hostModel;
  24365. if (el) {
  24366. // Add data index and series index for indexing the data by element
  24367. // Useful in tooltip
  24368. el.dataIndex = idx;
  24369. el.dataType = this.dataType;
  24370. el.seriesIndex = hostModel && hostModel.seriesIndex;
  24371. if (el.type === 'group') {
  24372. el.traverse(setItemDataAndSeriesIndex, el);
  24373. }
  24374. }
  24375. this._graphicEls[idx] = el;
  24376. };
  24377. /**
  24378. * @param {number} idx
  24379. * @return {module:zrender/Element}
  24380. */
  24381. listProto.getItemGraphicEl = function (idx) {
  24382. return this._graphicEls[idx];
  24383. };
  24384. /**
  24385. * @param {Function} cb
  24386. * @param {*} context
  24387. */
  24388. listProto.eachItemGraphicEl = function (cb, context) {
  24389. each$1(this._graphicEls, function (el, idx) {
  24390. if (el) {
  24391. cb && cb.call(context, el, idx);
  24392. }
  24393. });
  24394. };
  24395. /**
  24396. * Shallow clone a new list except visual and layout properties, and graph elements.
  24397. * New list only change the indices.
  24398. */
  24399. listProto.cloneShallow = function (list) {
  24400. if (!list) {
  24401. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  24402. list = new List(dimensionInfoList, this.hostModel);
  24403. }
  24404. // FIXME
  24405. list._storage = this._storage;
  24406. transferProperties(list, this);
  24407. // Clone will not change the data extent and indices
  24408. if (this._indices) {
  24409. var Ctor = this._indices.constructor;
  24410. list._indices = new Ctor(this._indices);
  24411. }
  24412. else {
  24413. list._indices = null;
  24414. }
  24415. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  24416. list._extent = clone(this._extent);
  24417. list._approximateExtent = clone(this._approximateExtent);
  24418. return list;
  24419. };
  24420. /**
  24421. * Wrap some method to add more feature
  24422. * @param {string} methodName
  24423. * @param {Function} injectFunction
  24424. */
  24425. listProto.wrapMethod = function (methodName, injectFunction) {
  24426. var originalMethod = this[methodName];
  24427. if (typeof originalMethod !== 'function') {
  24428. return;
  24429. }
  24430. this.__wrappedMethods = this.__wrappedMethods || [];
  24431. this.__wrappedMethods.push(methodName);
  24432. this[methodName] = function () {
  24433. var res = originalMethod.apply(this, arguments);
  24434. return injectFunction.apply(this, [res].concat(slice(arguments)));
  24435. };
  24436. };
  24437. // Methods that create a new list based on this list should be listed here.
  24438. // Notice that those method should `RETURN` the new list.
  24439. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  24440. // Methods that change indices of this list should be listed here.
  24441. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  24442. /**
  24443. * @deprecated
  24444. * Use `echarts/data/helper/createDimensions` instead.
  24445. */
  24446. /**
  24447. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  24448. *
  24449. * Complete the dimensions array, by user defined `dimension` and `encode`,
  24450. * and guessing from the data structure.
  24451. * If no 'value' dimension specified, the first no-named dimension will be
  24452. * named as 'value'.
  24453. *
  24454. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  24455. * provides not only dim template, but also default order.
  24456. * properties: 'name', 'type', 'displayName'.
  24457. * `name` of each item provides default coord name.
  24458. * [{dimsDef: [string...]}, ...] dimsDef of sysDim item provides default dim name, and
  24459. * provide dims count that the sysDim required.
  24460. * [{ordinalMeta}] can be specified.
  24461. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  24462. * @param {Object} [opt]
  24463. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  24464. * For example: ['asdf', {name, type}, ...].
  24465. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  24466. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  24467. * If not specified, extra dim names will be:
  24468. * 'value', 'value0', 'value1', ...
  24469. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  24470. * If `generateCoordCount` specified, the generated dim names will be:
  24471. * `generateCoord` + 0, `generateCoord` + 1, ...
  24472. * can be Infinity, indicate that use all of the remain columns.
  24473. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  24474. * @param {number} [opt.encodeDefaulter] If not specified, auto find the next available data dim.
  24475. * @return {Array.<Object>} [{
  24476. * name: string mandatory,
  24477. * displayName: string, the origin name in dimsDef, see source helper.
  24478. * If displayName given, the tooltip will displayed vertically.
  24479. * coordDim: string mandatory,
  24480. * coordDimIndex: number mandatory,
  24481. * type: string optional,
  24482. * otherDims: { never null/undefined
  24483. * tooltip: number optional,
  24484. * label: number optional,
  24485. * itemName: number optional,
  24486. * seriesName: number optional,
  24487. * },
  24488. * isExtraCoord: boolean true if coord is generated
  24489. * (not specified in encode and not series specified)
  24490. * other props ...
  24491. * }]
  24492. */
  24493. function completeDimensions(sysDims, source, opt) {
  24494. if (!Source.isInstance(source)) {
  24495. source = Source.seriesDataToSource(source);
  24496. }
  24497. opt = opt || {};
  24498. sysDims = (sysDims || []).slice();
  24499. var dimsDef = (opt.dimsDef || []).slice();
  24500. var encodeDef = createHashMap(opt.encodeDef);
  24501. var dataDimNameMap = createHashMap();
  24502. var coordDimNameMap = createHashMap();
  24503. // var valueCandidate;
  24504. var result = [];
  24505. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount);
  24506. // Apply user defined dims (`name` and `type`) and init result.
  24507. for (var i = 0; i < dimCount; i++) {
  24508. var dimDefItem = dimsDef[i] = extend(
  24509. {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]}
  24510. );
  24511. var userDimName = dimDefItem.name;
  24512. var resultItem = result[i] = {otherDims: {}};
  24513. // Name will be applied later for avoiding duplication.
  24514. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  24515. // Only if `series.dimensions` is defined in option
  24516. // displayName, will be set, and dimension will be diplayed vertically in
  24517. // tooltip by default.
  24518. resultItem.name = resultItem.displayName = userDimName;
  24519. dataDimNameMap.set(userDimName, i);
  24520. }
  24521. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  24522. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  24523. }
  24524. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  24525. encodeDef.each(function (dataDims, coordDim) {
  24526. dataDims = normalizeToArray(dataDims).slice();
  24527. var validDataDims = encodeDef.set(coordDim, []);
  24528. each$1(dataDims, function (resultDimIdx, idx) {
  24529. // The input resultDimIdx can be dim name or index.
  24530. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  24531. if (resultDimIdx != null && resultDimIdx < dimCount) {
  24532. validDataDims[idx] = resultDimIdx;
  24533. applyDim(result[resultDimIdx], coordDim, idx);
  24534. }
  24535. });
  24536. });
  24537. // Apply templetes and default order from `sysDims`.
  24538. var availDimIdx = 0;
  24539. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  24540. var coordDim;
  24541. var sysDimItem;
  24542. var sysDimItemDimsDef;
  24543. var sysDimItemOtherDims;
  24544. if (isString(sysDimItem)) {
  24545. coordDim = sysDimItem;
  24546. sysDimItem = {};
  24547. }
  24548. else {
  24549. coordDim = sysDimItem.name;
  24550. var ordinalMeta = sysDimItem.ordinalMeta;
  24551. sysDimItem.ordinalMeta = null;
  24552. sysDimItem = clone(sysDimItem);
  24553. sysDimItem.ordinalMeta = ordinalMeta;
  24554. // `coordDimIndex` should not be set directly.
  24555. sysDimItemDimsDef = sysDimItem.dimsDef;
  24556. sysDimItemOtherDims = sysDimItem.otherDims;
  24557. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex
  24558. = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  24559. }
  24560. var dataDims = normalizeToArray(encodeDef.get(coordDim));
  24561. // dimensions provides default dim sequences.
  24562. if (!dataDims.length) {
  24563. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  24564. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  24565. availDimIdx++;
  24566. }
  24567. availDimIdx < result.length && dataDims.push(availDimIdx++);
  24568. }
  24569. }
  24570. // Apply templates.
  24571. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  24572. var resultItem = result[resultDimIdx];
  24573. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  24574. if (resultItem.name == null && sysDimItemDimsDef) {
  24575. resultItem.name = resultItem.displayName = sysDimItemDimsDef[coordDimIndex];
  24576. }
  24577. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  24578. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  24579. });
  24580. });
  24581. function applyDim(resultItem, coordDim, coordDimIndex) {
  24582. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  24583. resultItem.otherDims[coordDim] = coordDimIndex;
  24584. }
  24585. else {
  24586. resultItem.coordDim = coordDim;
  24587. resultItem.coordDimIndex = coordDimIndex;
  24588. coordDimNameMap.set(coordDim, true);
  24589. }
  24590. }
  24591. // Make sure the first extra dim is 'value'.
  24592. var generateCoord = opt.generateCoord;
  24593. var generateCoordCount = opt.generateCoordCount;
  24594. var fromZero = generateCoordCount != null;
  24595. generateCoordCount = generateCoord ? (generateCoordCount || 1) : 0;
  24596. var extra = generateCoord || 'value';
  24597. // Set dim `name` and other `coordDim` and other props.
  24598. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  24599. var resultItem = result[resultDimIdx] = result[resultDimIdx] || {};
  24600. var coordDim = resultItem.coordDim;
  24601. if (coordDim == null) {
  24602. resultItem.coordDim = genName(
  24603. extra, coordDimNameMap, fromZero
  24604. );
  24605. resultItem.coordDimIndex = 0;
  24606. if (!generateCoord || generateCoordCount <= 0) {
  24607. resultItem.isExtraCoord = true;
  24608. }
  24609. generateCoordCount--;
  24610. }
  24611. resultItem.name == null && (resultItem.name = genName(
  24612. resultItem.coordDim,
  24613. dataDimNameMap
  24614. ));
  24615. if (resultItem.type == null && guessOrdinal(source, resultDimIdx, resultItem.name)) {
  24616. resultItem.type = 'ordinal';
  24617. }
  24618. }
  24619. return result;
  24620. }
  24621. // ??? TODO
  24622. // Originally detect dimCount by data[0]. Should we
  24623. // optimize it to only by sysDims and dimensions and encode.
  24624. // So only necessary dims will be initialized.
  24625. // But
  24626. // (1) custom series should be considered. where other dims
  24627. // may be visited.
  24628. // (2) sometimes user need to calcualte bubble size or use visualMap
  24629. // on other dimensions besides coordSys needed.
  24630. // So, dims that is not used by system, should be shared in storage?
  24631. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  24632. // Note that the result dimCount should not small than columns count
  24633. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  24634. var dimCount = Math.max(
  24635. source.dimensionsDetectCount || 1,
  24636. sysDims.length,
  24637. dimsDef.length,
  24638. optDimCount || 0
  24639. );
  24640. each$1(sysDims, function (sysDimItem) {
  24641. var sysDimItemDimsDef = sysDimItem.dimsDef;
  24642. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  24643. });
  24644. return dimCount;
  24645. }
  24646. function genName(name, map$$1, fromZero) {
  24647. if (fromZero || map$$1.get(name) != null) {
  24648. var i = 0;
  24649. while (map$$1.get(name + i) != null) {
  24650. i++;
  24651. }
  24652. name += i;
  24653. }
  24654. map$$1.set(name, true);
  24655. return name;
  24656. }
  24657. /**
  24658. * Substitute `completeDimensions`.
  24659. * `completeDimensions` is to be deprecated.
  24660. */
  24661. /**
  24662. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  24663. * @param {Object|Array} [opt]
  24664. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  24665. * @param {number} [opt.dimensionsCount]
  24666. * @param {string} [opt.generateCoord]
  24667. * @param {string} [opt.generateCoordCount]
  24668. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  24669. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  24670. * @return {Array.<Object>} dimensionsInfo
  24671. */
  24672. var createDimensions = function (source, opt) {
  24673. opt = opt || {};
  24674. return completeDimensions(opt.coordDimensions || [], source, {
  24675. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  24676. encodeDef: opt.encodeDefine || source.encodeDefine,
  24677. dimCount: opt.dimensionsCount,
  24678. generateCoord: opt.generateCoord,
  24679. generateCoordCount: opt.generateCoordCount
  24680. });
  24681. };
  24682. /**
  24683. * Note that it is too complicated to support 3d stack by value
  24684. * (have to create two-dimension inverted index), so in 3d case
  24685. * we just support that stacked by index.
  24686. *
  24687. * @param {module:echarts/model/Series} seriesModel
  24688. * @param {Array.<string|Object>} dimensionInfoList The same as the input of <module:echarts/data/List>.
  24689. * The input dimensionInfoList will be modified.
  24690. * @param {Object} [opt]
  24691. * @param {boolean} [opt.stackedCoordDimension=''] Specify a coord dimension if needed.
  24692. * @param {boolean} [opt.byIndex=false]
  24693. * @return {Object} calculationInfo
  24694. * {
  24695. * stackedDimension: string
  24696. * stackedByDimension: string
  24697. * isStackedByIndex: boolean
  24698. * stackedOverDimension: string
  24699. * stackResultDimension: string
  24700. * }
  24701. */
  24702. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  24703. opt = opt || {};
  24704. var byIndex = opt.byIndex;
  24705. var stackedCoordDimension = opt.stackedCoordDimension;
  24706. // Compatibal: when `stack` is set as '', do not stack.
  24707. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  24708. var stackedByDimInfo;
  24709. var stackedDimInfo;
  24710. var stackResultDimension;
  24711. var stackedOverDimension;
  24712. each$1(dimensionInfoList, function (dimensionInfo, index) {
  24713. if (isString(dimensionInfo)) {
  24714. dimensionInfoList[index] = dimensionInfo = {name: dimensionInfo};
  24715. }
  24716. if (mayStack && !dimensionInfo.isExtraCoord) {
  24717. // Find the first ordinal dimension as the stackedByDimInfo.
  24718. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  24719. stackedByDimInfo = dimensionInfo;
  24720. }
  24721. // Find the first stackable dimension as the stackedDimInfo.
  24722. if (!stackedDimInfo
  24723. && dimensionInfo.type !== 'ordinal'
  24724. && dimensionInfo.type !== 'time'
  24725. && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)
  24726. ) {
  24727. stackedDimInfo = dimensionInfo;
  24728. }
  24729. }
  24730. });
  24731. // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  24732. // That put stack logic in List is for using conveniently in echarts extensions, but it
  24733. // might not be a good way.
  24734. if (stackedDimInfo && (byIndex || stackedByDimInfo)) {
  24735. // Use a weird name that not duplicated with other names.
  24736. stackResultDimension = '__\0ecstackresult';
  24737. stackedOverDimension = '__\0ecstackedover';
  24738. // Create inverted index to fast query index by value.
  24739. if (stackedByDimInfo) {
  24740. stackedByDimInfo.createInvertedIndices = true;
  24741. }
  24742. var stackedDimCoordDim = stackedDimInfo.coordDim;
  24743. var stackedDimType = stackedDimInfo.type;
  24744. var stackedDimCoordIndex = 0;
  24745. each$1(dimensionInfoList, function (dimensionInfo) {
  24746. if (dimensionInfo.coordDim === stackedDimCoordDim) {
  24747. stackedDimCoordIndex++;
  24748. }
  24749. });
  24750. dimensionInfoList.push({
  24751. name: stackResultDimension,
  24752. coordDim: stackedDimCoordDim,
  24753. coordDimIndex: stackedDimCoordIndex,
  24754. type: stackedDimType,
  24755. isExtraCoord: true,
  24756. isCalculationCoord: true
  24757. });
  24758. stackedDimCoordIndex++;
  24759. dimensionInfoList.push({
  24760. name: stackedOverDimension,
  24761. // This dimension contains stack base (generally, 0), so do not set it as
  24762. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  24763. coordDim: stackedOverDimension,
  24764. coordDimIndex: stackedDimCoordIndex,
  24765. type: stackedDimType,
  24766. isExtraCoord: true,
  24767. isCalculationCoord: true
  24768. });
  24769. }
  24770. return {
  24771. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  24772. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  24773. isStackedByIndex: byIndex,
  24774. stackedOverDimension: stackedOverDimension,
  24775. stackResultDimension: stackResultDimension
  24776. };
  24777. }
  24778. /**
  24779. * @param {module:echarts/data/List} data
  24780. * @param {string} stackedDim
  24781. * @param {string} [stackedByDim] If not input this parameter, check whether
  24782. * stacked by index.
  24783. */
  24784. function isDimensionStacked(data, stackedDim, stackedByDim) {
  24785. return stackedDim
  24786. && stackedDim === data.getCalculationInfo('stackedDimension')
  24787. && (
  24788. stackedByDim != null
  24789. ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  24790. : data.getCalculationInfo('isStackedByIndex')
  24791. );
  24792. }
  24793. /**
  24794. * @param {module:echarts/data/Source|Array} source Or raw data.
  24795. * @param {module:echarts/model/Series} seriesModel
  24796. * @param {Object} [opt]
  24797. * @param {string} [opt.generateCoord]
  24798. */
  24799. function createListFromArray(source, seriesModel, opt) {
  24800. opt = opt || {};
  24801. if (!Source.isInstance(source)) {
  24802. source = Source.seriesDataToSource(source);
  24803. }
  24804. var coordSysName = seriesModel.get('coordinateSystem');
  24805. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  24806. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  24807. var coordSysDimDefs;
  24808. if (coordSysDefine) {
  24809. coordSysDimDefs = map(coordSysDefine.coordSysDims, function (dim) {
  24810. var dimInfo = {name: dim};
  24811. var axisModel = coordSysDefine.axisMap.get(dim);
  24812. if (axisModel) {
  24813. var axisType = axisModel.get('type');
  24814. dimInfo.type = getDimensionTypeByAxis(axisType);
  24815. // dimInfo.stackable = isStackable(axisType);
  24816. }
  24817. return dimInfo;
  24818. });
  24819. }
  24820. if (!coordSysDimDefs) {
  24821. // Get dimensions from registered coordinate system
  24822. coordSysDimDefs = (registeredCoordSys && (
  24823. registeredCoordSys.getDimensionsInfo
  24824. ? registeredCoordSys.getDimensionsInfo()
  24825. : registeredCoordSys.dimensions.slice()
  24826. )) || ['x', 'y'];
  24827. }
  24828. var dimInfoList = createDimensions(source, {
  24829. coordDimensions: coordSysDimDefs,
  24830. generateCoord: opt.generateCoord
  24831. });
  24832. var firstCategoryDimIndex;
  24833. var hasNameEncode;
  24834. coordSysDefine && each$1(dimInfoList, function (dimInfo, dimIndex) {
  24835. var coordDim = dimInfo.coordDim;
  24836. var categoryAxisModel = coordSysDefine.categoryAxisMap.get(coordDim);
  24837. if (categoryAxisModel) {
  24838. if (firstCategoryDimIndex == null) {
  24839. firstCategoryDimIndex = dimIndex;
  24840. }
  24841. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  24842. }
  24843. if (dimInfo.otherDims.itemName != null) {
  24844. hasNameEncode = true;
  24845. }
  24846. });
  24847. if (!hasNameEncode && firstCategoryDimIndex != null) {
  24848. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  24849. }
  24850. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  24851. var list = new List(dimInfoList, seriesModel);
  24852. list.setCalculationInfo(stackCalculationInfo);
  24853. var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source))
  24854. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  24855. // Use dataIndex as ordinal value in categoryAxis
  24856. return dimIndex === firstCategoryDimIndex
  24857. ? dataIndex
  24858. : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  24859. }
  24860. : null;
  24861. list.hasItemOption = false;
  24862. list.initData(source, null, dimValueGetter);
  24863. return list;
  24864. }
  24865. function isNeedCompleteOrdinalData(source) {
  24866. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  24867. var sampleItem = firstDataNotNull(source.data || []);
  24868. return sampleItem != null
  24869. && !isArray(getDataItemValue(sampleItem));
  24870. }
  24871. }
  24872. function firstDataNotNull(data) {
  24873. var i = 0;
  24874. while (i < data.length && data[i] == null) {
  24875. i++;
  24876. }
  24877. return data[i];
  24878. }
  24879. /**
  24880. * // Scale class management
  24881. * @module echarts/scale/Scale
  24882. */
  24883. /**
  24884. * @param {Object} [setting]
  24885. */
  24886. function Scale(setting) {
  24887. this._setting = setting || {};
  24888. /**
  24889. * Extent
  24890. * @type {Array.<number>}
  24891. * @protected
  24892. */
  24893. this._extent = [Infinity, -Infinity];
  24894. /**
  24895. * Step is calculated in adjustExtent
  24896. * @type {Array.<number>}
  24897. * @protected
  24898. */
  24899. this._interval = 0;
  24900. this.init && this.init.apply(this, arguments);
  24901. }
  24902. /**
  24903. * Parse input val to valid inner number.
  24904. * @param {*} val
  24905. * @return {number}
  24906. */
  24907. Scale.prototype.parse = function (val) {
  24908. // Notice: This would be a trap here, If the implementation
  24909. // of this method depends on extent, and this method is used
  24910. // before extent set (like in dataZoom), it would be wrong.
  24911. // Nevertheless, parse does not depend on extent generally.
  24912. return val;
  24913. };
  24914. Scale.prototype.getSetting = function (name) {
  24915. return this._setting[name];
  24916. };
  24917. Scale.prototype.contain = function (val) {
  24918. var extent = this._extent;
  24919. return val >= extent[0] && val <= extent[1];
  24920. };
  24921. /**
  24922. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  24923. * @param {number} val
  24924. * @return {number}
  24925. */
  24926. Scale.prototype.normalize = function (val) {
  24927. var extent = this._extent;
  24928. if (extent[1] === extent[0]) {
  24929. return 0.5;
  24930. }
  24931. return (val - extent[0]) / (extent[1] - extent[0]);
  24932. };
  24933. /**
  24934. * Scale normalized value
  24935. * @param {number} val
  24936. * @return {number}
  24937. */
  24938. Scale.prototype.scale = function (val) {
  24939. var extent = this._extent;
  24940. return val * (extent[1] - extent[0]) + extent[0];
  24941. };
  24942. /**
  24943. * Set extent from data
  24944. * @param {Array.<number>} other
  24945. */
  24946. Scale.prototype.unionExtent = function (other) {
  24947. var extent = this._extent;
  24948. other[0] < extent[0] && (extent[0] = other[0]);
  24949. other[1] > extent[1] && (extent[1] = other[1]);
  24950. // not setExtent because in log axis it may transformed to power
  24951. // this.setExtent(extent[0], extent[1]);
  24952. };
  24953. /**
  24954. * Set extent from data
  24955. * @param {module:echarts/data/List} data
  24956. * @param {string} dim
  24957. */
  24958. Scale.prototype.unionExtentFromData = function (data, dim) {
  24959. this.unionExtent(data.getApproximateExtent(dim));
  24960. };
  24961. /**
  24962. * Get extent
  24963. * @return {Array.<number>}
  24964. */
  24965. Scale.prototype.getExtent = function () {
  24966. return this._extent.slice();
  24967. };
  24968. /**
  24969. * Set extent
  24970. * @param {number} start
  24971. * @param {number} end
  24972. */
  24973. Scale.prototype.setExtent = function (start, end) {
  24974. var thisExtent = this._extent;
  24975. if (!isNaN(start)) {
  24976. thisExtent[0] = start;
  24977. }
  24978. if (!isNaN(end)) {
  24979. thisExtent[1] = end;
  24980. }
  24981. };
  24982. /**
  24983. * @return {Array.<string>}
  24984. */
  24985. Scale.prototype.getTicksLabels = function () {
  24986. var labels = [];
  24987. var ticks = this.getTicks();
  24988. for (var i = 0; i < ticks.length; i++) {
  24989. labels.push(this.getLabel(ticks[i]));
  24990. }
  24991. return labels;
  24992. };
  24993. /**
  24994. * When axis extent depends on data and no data exists,
  24995. * axis ticks should not be drawn, which is named 'blank'.
  24996. */
  24997. Scale.prototype.isBlank = function () {
  24998. return this._isBlank;
  24999. },
  25000. /**
  25001. * When axis extent depends on data and no data exists,
  25002. * axis ticks should not be drawn, which is named 'blank'.
  25003. */
  25004. Scale.prototype.setBlank = function (isBlank) {
  25005. this._isBlank = isBlank;
  25006. };
  25007. enableClassExtend(Scale);
  25008. enableClassManagement(Scale, {
  25009. registerWhenExtend: true
  25010. });
  25011. /**
  25012. * @constructor
  25013. * @param {Object} [opt]
  25014. * @param {Object} [opt.categories=[]]
  25015. * @param {Object} [opt.needCollect=false]
  25016. * @param {Object} [opt.deduplication=false]
  25017. */
  25018. function OrdinalMeta(opt) {
  25019. /**
  25020. * @readOnly
  25021. * @type {Array.<string>}
  25022. */
  25023. this.categories = opt.categories || [];
  25024. /**
  25025. * @private
  25026. * @type {boolean}
  25027. */
  25028. this._needCollect = opt.needCollect;
  25029. /**
  25030. * @private
  25031. * @type {boolean}
  25032. */
  25033. this._deduplication = opt.deduplication;
  25034. /**
  25035. * @private
  25036. * @type {boolean}
  25037. */
  25038. this._map;
  25039. }
  25040. /**
  25041. * @param {module:echarts/model/Model} axisModel
  25042. * @return {module:echarts/data/OrdinalMeta}
  25043. */
  25044. OrdinalMeta.createByAxisModel = function (axisModel) {
  25045. var option = axisModel.option;
  25046. var data = option.data;
  25047. var categories = data && map(data, getName);
  25048. return new OrdinalMeta({
  25049. categories: categories,
  25050. needCollect: !categories,
  25051. // deduplication is default in axis.
  25052. deduplication: option.dedplication !== false
  25053. });
  25054. };
  25055. var proto$1 = OrdinalMeta.prototype;
  25056. /**
  25057. * @param {string} category
  25058. * @return {number} ordinal
  25059. */
  25060. proto$1.getOrdinal = function (category) {
  25061. return getOrCreateMap(this).get(category);
  25062. };
  25063. /**
  25064. * @param {*} category
  25065. * @return {number} The ordinal. If not found, return NaN.
  25066. */
  25067. proto$1.parseAndCollect = function (category) {
  25068. var index;
  25069. var needCollect = this._needCollect;
  25070. // The value of category dim can be the index of the given category set.
  25071. // This feature is only supported when !needCollect, because we should
  25072. // consider a common case: a value is 2017, which is a number but is
  25073. // expected to be tread as a category. This case usually happen in dataset,
  25074. // where it happent to be no need of the index feature.
  25075. if (typeof category !== 'string' && !needCollect) {
  25076. return category;
  25077. }
  25078. // Optimize for the scenario:
  25079. // category is ['2012-01-01', '2012-01-02', ...], where the input
  25080. // data has been ensured not duplicate and is large data.
  25081. // Notice, if a dataset dimension provide categroies, usually echarts
  25082. // should remove duplication except user tell echarts dont do that
  25083. // (set axis.deduplication = false), because echarts do not know whether
  25084. // the values in the category dimension has duplication (consider the
  25085. // parallel-aqi example)
  25086. if (needCollect && !this._deduplication) {
  25087. index = this.categories.length;
  25088. this.categories[index] = category;
  25089. return index;
  25090. }
  25091. var map$$1 = getOrCreateMap(this);
  25092. index = map$$1.get(category);
  25093. if (index == null) {
  25094. if (needCollect) {
  25095. index = this.categories.length;
  25096. this.categories[index] = category;
  25097. map$$1.set(category, index);
  25098. }
  25099. else {
  25100. index = NaN;
  25101. }
  25102. }
  25103. return index;
  25104. };
  25105. // Consider big data, do not create map until needed.
  25106. function getOrCreateMap(ordinalMeta) {
  25107. return ordinalMeta._map || (
  25108. ordinalMeta._map = createHashMap(ordinalMeta.categories)
  25109. );
  25110. }
  25111. function getName(obj) {
  25112. if (isObject$1(obj) && obj.value != null) {
  25113. return obj.value;
  25114. }
  25115. else {
  25116. return obj + '';
  25117. }
  25118. }
  25119. /**
  25120. * Linear continuous scale
  25121. * @module echarts/coord/scale/Ordinal
  25122. *
  25123. * http://en.wikipedia.org/wiki/Level_of_measurement
  25124. */
  25125. // FIXME only one data
  25126. var scaleProto = Scale.prototype;
  25127. var OrdinalScale = Scale.extend({
  25128. type: 'ordinal',
  25129. /**
  25130. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  25131. */
  25132. init: function (ordinalMeta, extent) {
  25133. // Caution: Should not use instanceof, consider ec-extensions using
  25134. // import approach to get OrdinalMeta class.
  25135. if (!ordinalMeta || isArray(ordinalMeta)) {
  25136. ordinalMeta = new OrdinalMeta({categories: ordinalMeta});
  25137. }
  25138. this._ordinalMeta = ordinalMeta;
  25139. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  25140. },
  25141. parse: function (val) {
  25142. return typeof val === 'string'
  25143. ? this._ordinalMeta.getOrdinal(val)
  25144. // val might be float.
  25145. : Math.round(val);
  25146. },
  25147. contain: function (rank) {
  25148. rank = this.parse(rank);
  25149. return scaleProto.contain.call(this, rank)
  25150. && this._ordinalMeta.categories[rank] != null;
  25151. },
  25152. /**
  25153. * Normalize given rank or name to linear [0, 1]
  25154. * @param {number|string} [val]
  25155. * @return {number}
  25156. */
  25157. normalize: function (val) {
  25158. return scaleProto.normalize.call(this, this.parse(val));
  25159. },
  25160. scale: function (val) {
  25161. return Math.round(scaleProto.scale.call(this, val));
  25162. },
  25163. /**
  25164. * @return {Array}
  25165. */
  25166. getTicks: function () {
  25167. var ticks = [];
  25168. var extent = this._extent;
  25169. var rank = extent[0];
  25170. while (rank <= extent[1]) {
  25171. ticks.push(rank);
  25172. rank++;
  25173. }
  25174. return ticks;
  25175. },
  25176. /**
  25177. * Get item on rank n
  25178. * @param {number} n
  25179. * @return {string}
  25180. */
  25181. getLabel: function (n) {
  25182. return this._ordinalMeta.categories[n];
  25183. },
  25184. /**
  25185. * @return {number}
  25186. */
  25187. count: function () {
  25188. return this._extent[1] - this._extent[0] + 1;
  25189. },
  25190. /**
  25191. * @override
  25192. */
  25193. unionExtentFromData: function (data, dim) {
  25194. this.unionExtent(data.getApproximateExtent(dim));
  25195. },
  25196. niceTicks: noop,
  25197. niceExtent: noop
  25198. });
  25199. /**
  25200. * @return {module:echarts/scale/Time}
  25201. */
  25202. OrdinalScale.create = function () {
  25203. return new OrdinalScale();
  25204. };
  25205. /**
  25206. * For testable.
  25207. */
  25208. var roundNumber$1 = round$1;
  25209. /**
  25210. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  25211. * Should be extent[0] < extent[1].
  25212. * @param {number} splitNumber splitNumber should be >= 1.
  25213. * @param {number} [minInterval]
  25214. * @param {number} [maxInterval]
  25215. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  25216. */
  25217. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  25218. var result = {};
  25219. var span = extent[1] - extent[0];
  25220. var interval = result.interval = nice(span / splitNumber, true);
  25221. if (minInterval != null && interval < minInterval) {
  25222. interval = result.interval = minInterval;
  25223. }
  25224. if (maxInterval != null && interval > maxInterval) {
  25225. interval = result.interval = maxInterval;
  25226. }
  25227. // Tow more digital for tick.
  25228. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  25229. // Niced extent inside original extent
  25230. var niceTickExtent = result.niceTickExtent = [
  25231. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  25232. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  25233. ];
  25234. fixExtent(niceTickExtent, extent);
  25235. return result;
  25236. }
  25237. /**
  25238. * @param {number} interval
  25239. * @return {number} interval precision
  25240. */
  25241. function getIntervalPrecision(interval) {
  25242. // Tow more digital for tick.
  25243. return getPrecisionSafe(interval) + 2;
  25244. }
  25245. function clamp(niceTickExtent, idx, extent) {
  25246. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  25247. }
  25248. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  25249. function fixExtent(niceTickExtent, extent) {
  25250. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  25251. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  25252. clamp(niceTickExtent, 0, extent);
  25253. clamp(niceTickExtent, 1, extent);
  25254. if (niceTickExtent[0] > niceTickExtent[1]) {
  25255. niceTickExtent[0] = niceTickExtent[1];
  25256. }
  25257. }
  25258. function intervalScaleGetTicks(interval, extent, niceTickExtent, intervalPrecision) {
  25259. var ticks = [];
  25260. // If interval is 0, return [];
  25261. if (!interval) {
  25262. return ticks;
  25263. }
  25264. // Consider this case: using dataZoom toolbox, zoom and zoom.
  25265. var safeLimit = 10000;
  25266. if (extent[0] < niceTickExtent[0]) {
  25267. ticks.push(extent[0]);
  25268. }
  25269. var tick = niceTickExtent[0];
  25270. while (tick <= niceTickExtent[1]) {
  25271. ticks.push(tick);
  25272. // Avoid rounding error
  25273. tick = roundNumber$1(tick + interval, intervalPrecision);
  25274. if (tick === ticks[ticks.length - 1]) {
  25275. // Consider out of safe float point, e.g.,
  25276. // -3711126.9907707 + 2e-10 === -3711126.9907707
  25277. break;
  25278. }
  25279. if (ticks.length > safeLimit) {
  25280. return [];
  25281. }
  25282. }
  25283. // Consider this case: the last item of ticks is smaller
  25284. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  25285. if (extent[1] > (ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1])) {
  25286. ticks.push(extent[1]);
  25287. }
  25288. return ticks;
  25289. }
  25290. /**
  25291. * Interval scale
  25292. * @module echarts/scale/Interval
  25293. */
  25294. var roundNumber = round$1;
  25295. /**
  25296. * @alias module:echarts/coord/scale/Interval
  25297. * @constructor
  25298. */
  25299. var IntervalScale = Scale.extend({
  25300. type: 'interval',
  25301. _interval: 0,
  25302. _intervalPrecision: 2,
  25303. setExtent: function (start, end) {
  25304. var thisExtent = this._extent;
  25305. //start,end may be a Number like '25',so...
  25306. if (!isNaN(start)) {
  25307. thisExtent[0] = parseFloat(start);
  25308. }
  25309. if (!isNaN(end)) {
  25310. thisExtent[1] = parseFloat(end);
  25311. }
  25312. },
  25313. unionExtent: function (other) {
  25314. var extent = this._extent;
  25315. other[0] < extent[0] && (extent[0] = other[0]);
  25316. other[1] > extent[1] && (extent[1] = other[1]);
  25317. // unionExtent may called by it's sub classes
  25318. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  25319. },
  25320. /**
  25321. * Get interval
  25322. */
  25323. getInterval: function () {
  25324. return this._interval;
  25325. },
  25326. /**
  25327. * Set interval
  25328. */
  25329. setInterval: function (interval) {
  25330. this._interval = interval;
  25331. // Dropped auto calculated niceExtent and use user setted extent
  25332. // We assume user wan't to set both interval, min, max to get a better result
  25333. this._niceExtent = this._extent.slice();
  25334. this._intervalPrecision = getIntervalPrecision(interval);
  25335. },
  25336. /**
  25337. * @return {Array.<number>}
  25338. */
  25339. getTicks: function () {
  25340. return intervalScaleGetTicks(
  25341. this._interval, this._extent, this._niceExtent, this._intervalPrecision
  25342. );
  25343. },
  25344. /**
  25345. * @return {Array.<string>}
  25346. */
  25347. getTicksLabels: function () {
  25348. var labels = [];
  25349. var ticks = this.getTicks();
  25350. for (var i = 0; i < ticks.length; i++) {
  25351. labels.push(this.getLabel(ticks[i]));
  25352. }
  25353. return labels;
  25354. },
  25355. /**
  25356. * @param {number} data
  25357. * @param {Object} [opt]
  25358. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  25359. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  25360. * @return {string}
  25361. */
  25362. getLabel: function (data, opt) {
  25363. if (data == null) {
  25364. return '';
  25365. }
  25366. var precision = opt && opt.precision;
  25367. if (precision == null) {
  25368. precision = getPrecisionSafe(data) || 0;
  25369. }
  25370. else if (precision === 'auto') {
  25371. // Should be more precise then tick.
  25372. precision = this._intervalPrecision;
  25373. }
  25374. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  25375. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  25376. data = roundNumber(data, precision, true);
  25377. return addCommas(data);
  25378. },
  25379. /**
  25380. * Update interval and extent of intervals for nice ticks
  25381. *
  25382. * @param {number} [splitNumber = 5] Desired number of ticks
  25383. * @param {number} [minInterval]
  25384. * @param {number} [maxInterval]
  25385. */
  25386. niceTicks: function (splitNumber, minInterval, maxInterval) {
  25387. splitNumber = splitNumber || 5;
  25388. var extent = this._extent;
  25389. var span = extent[1] - extent[0];
  25390. if (!isFinite(span)) {
  25391. return;
  25392. }
  25393. // User may set axis min 0 and data are all negative
  25394. // FIXME If it needs to reverse ?
  25395. if (span < 0) {
  25396. span = -span;
  25397. extent.reverse();
  25398. }
  25399. var result = intervalScaleNiceTicks(
  25400. extent, splitNumber, minInterval, maxInterval
  25401. );
  25402. this._intervalPrecision = result.intervalPrecision;
  25403. this._interval = result.interval;
  25404. this._niceExtent = result.niceTickExtent;
  25405. },
  25406. /**
  25407. * Nice extent.
  25408. * @param {Object} opt
  25409. * @param {number} [opt.splitNumber = 5] Given approx tick number
  25410. * @param {boolean} [opt.fixMin=false]
  25411. * @param {boolean} [opt.fixMax=false]
  25412. * @param {boolean} [opt.minInterval]
  25413. * @param {boolean} [opt.maxInterval]
  25414. */
  25415. niceExtent: function (opt) {
  25416. var extent = this._extent;
  25417. // If extent start and end are same, expand them
  25418. if (extent[0] === extent[1]) {
  25419. if (extent[0] !== 0) {
  25420. // Expand extent
  25421. var expandSize = extent[0];
  25422. // In the fowllowing case
  25423. // Axis has been fixed max 100
  25424. // Plus data are all 100 and axis extent are [100, 100].
  25425. // Extend to the both side will cause expanded max is larger than fixed max.
  25426. // So only expand to the smaller side.
  25427. if (!opt.fixMax) {
  25428. extent[1] += expandSize / 2;
  25429. extent[0] -= expandSize / 2;
  25430. }
  25431. else {
  25432. extent[0] -= expandSize / 2;
  25433. }
  25434. }
  25435. else {
  25436. extent[1] = 1;
  25437. }
  25438. }
  25439. var span = extent[1] - extent[0];
  25440. // If there are no data and extent are [Infinity, -Infinity]
  25441. if (!isFinite(span)) {
  25442. extent[0] = 0;
  25443. extent[1] = 1;
  25444. }
  25445. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  25446. // var extent = this._extent;
  25447. var interval = this._interval;
  25448. if (!opt.fixMin) {
  25449. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  25450. }
  25451. if (!opt.fixMax) {
  25452. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  25453. }
  25454. }
  25455. });
  25456. /**
  25457. * @return {module:echarts/scale/Time}
  25458. */
  25459. IntervalScale.create = function () {
  25460. return new IntervalScale();
  25461. };
  25462. var STACK_PREFIX = '__ec_stack_';
  25463. function getSeriesStackId(seriesModel) {
  25464. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  25465. }
  25466. function getAxisKey(axis) {
  25467. return axis.dim + axis.index;
  25468. }
  25469. /**
  25470. * @param {Object} opt
  25471. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  25472. * @param {number} opt.count Positive interger.
  25473. * @param {number} [opt.barWidth]
  25474. * @param {number} [opt.barMaxWidth]
  25475. * @param {number} [opt.barGap]
  25476. * @param {number} [opt.barCategoryGap]
  25477. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  25478. */
  25479. function calBarWidthAndOffset(barSeries, api) {
  25480. var seriesInfoList = map(barSeries, function (seriesModel) {
  25481. var data = seriesModel.getData();
  25482. var cartesian = seriesModel.coordinateSystem;
  25483. var baseAxis = cartesian.getBaseAxis();
  25484. var axisExtent = baseAxis.getExtent();
  25485. var bandWidth = baseAxis.type === 'category'
  25486. ? baseAxis.getBandWidth()
  25487. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  25488. var barWidth = parsePercent$1(
  25489. seriesModel.get('barWidth'), bandWidth
  25490. );
  25491. var barMaxWidth = parsePercent$1(
  25492. seriesModel.get('barMaxWidth'), bandWidth
  25493. );
  25494. var barGap = seriesModel.get('barGap');
  25495. var barCategoryGap = seriesModel.get('barCategoryGap');
  25496. return {
  25497. bandWidth: bandWidth,
  25498. barWidth: barWidth,
  25499. barMaxWidth: barMaxWidth,
  25500. barGap: barGap,
  25501. barCategoryGap: barCategoryGap,
  25502. axisKey: getAxisKey(baseAxis),
  25503. stackId: getSeriesStackId(seriesModel)
  25504. };
  25505. });
  25506. return doCalBarWidthAndOffset(seriesInfoList, api);
  25507. }
  25508. function doCalBarWidthAndOffset(seriesInfoList, api) {
  25509. // Columns info on each category axis. Key is cartesian name
  25510. var columnsMap = {};
  25511. each$1(seriesInfoList, function (seriesInfo, idx) {
  25512. var axisKey = seriesInfo.axisKey;
  25513. var bandWidth = seriesInfo.bandWidth;
  25514. var columnsOnAxis = columnsMap[axisKey] || {
  25515. bandWidth: bandWidth,
  25516. remainedWidth: bandWidth,
  25517. autoWidthCount: 0,
  25518. categoryGap: '20%',
  25519. gap: '30%',
  25520. stacks: {}
  25521. };
  25522. var stacks = columnsOnAxis.stacks;
  25523. columnsMap[axisKey] = columnsOnAxis;
  25524. var stackId = seriesInfo.stackId;
  25525. if (!stacks[stackId]) {
  25526. columnsOnAxis.autoWidthCount++;
  25527. }
  25528. stacks[stackId] = stacks[stackId] || {
  25529. width: 0,
  25530. maxWidth: 0
  25531. };
  25532. // Caution: In a single coordinate system, these barGrid attributes
  25533. // will be shared by series. Consider that they have default values,
  25534. // only the attributes set on the last series will work.
  25535. // Do not change this fact unless there will be a break change.
  25536. // TODO
  25537. var barWidth = seriesInfo.barWidth;
  25538. if (barWidth && !stacks[stackId].width) {
  25539. // See #6312, do not restrict width.
  25540. stacks[stackId].width = barWidth;
  25541. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  25542. columnsOnAxis.remainedWidth -= barWidth;
  25543. }
  25544. var barMaxWidth = seriesInfo.barMaxWidth;
  25545. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  25546. var barGap = seriesInfo.barGap;
  25547. (barGap != null) && (columnsOnAxis.gap = barGap);
  25548. var barCategoryGap = seriesInfo.barCategoryGap;
  25549. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  25550. });
  25551. var result = {};
  25552. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  25553. result[coordSysName] = {};
  25554. var stacks = columnsOnAxis.stacks;
  25555. var bandWidth = columnsOnAxis.bandWidth;
  25556. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  25557. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  25558. var remainedWidth = columnsOnAxis.remainedWidth;
  25559. var autoWidthCount = columnsOnAxis.autoWidthCount;
  25560. var autoWidth = (remainedWidth - categoryGap)
  25561. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  25562. autoWidth = Math.max(autoWidth, 0);
  25563. // Find if any auto calculated bar exceeded maxBarWidth
  25564. each$1(stacks, function (column, stack) {
  25565. var maxWidth = column.maxWidth;
  25566. if (maxWidth && maxWidth < autoWidth) {
  25567. maxWidth = Math.min(maxWidth, remainedWidth);
  25568. if (column.width) {
  25569. maxWidth = Math.min(maxWidth, column.width);
  25570. }
  25571. remainedWidth -= maxWidth;
  25572. column.width = maxWidth;
  25573. autoWidthCount--;
  25574. }
  25575. });
  25576. // Recalculate width again
  25577. autoWidth = (remainedWidth - categoryGap)
  25578. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  25579. autoWidth = Math.max(autoWidth, 0);
  25580. var widthSum = 0;
  25581. var lastColumn;
  25582. each$1(stacks, function (column, idx) {
  25583. if (!column.width) {
  25584. column.width = autoWidth;
  25585. }
  25586. lastColumn = column;
  25587. widthSum += column.width * (1 + barGapPercent);
  25588. });
  25589. if (lastColumn) {
  25590. widthSum -= lastColumn.width * barGapPercent;
  25591. }
  25592. var offset = -widthSum / 2;
  25593. each$1(stacks, function (column, stackId) {
  25594. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  25595. offset: offset,
  25596. width: column.width
  25597. };
  25598. offset += column.width * (1 + barGapPercent);
  25599. });
  25600. });
  25601. return result;
  25602. }
  25603. /**
  25604. * @param {string} seriesType
  25605. * @param {module:echarts/model/Global} ecModel
  25606. * @param {module:echarts/ExtensionAPI} api
  25607. */
  25608. function layout(seriesType, ecModel, api) {
  25609. var seriesModels = [];
  25610. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  25611. // Check series coordinate, do layout for cartesian2d only
  25612. if (seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d') {
  25613. seriesModels.push(seriesModel);
  25614. }
  25615. });
  25616. var barWidthAndOffset = calBarWidthAndOffset(seriesModels);
  25617. var lastStackCoords = {};
  25618. each$1(seriesModels, function (seriesModel) {
  25619. var data = seriesModel.getData();
  25620. var cartesian = seriesModel.coordinateSystem;
  25621. var baseAxis = cartesian.getBaseAxis();
  25622. var stackId = getSeriesStackId(seriesModel);
  25623. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  25624. var columnOffset = columnLayoutInfo.offset;
  25625. var columnWidth = columnLayoutInfo.width;
  25626. var valueAxis = cartesian.getOtherAxis(baseAxis);
  25627. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  25628. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  25629. data.setLayout({
  25630. offset: columnOffset,
  25631. size: columnWidth
  25632. });
  25633. var valueDim = data.mapDimension(valueAxis.dim);
  25634. var baseDim = data.mapDimension(baseAxis.dim);
  25635. var stacked = isDimensionStacked(data, valueDim, baseDim);
  25636. var isValueAxisH = valueAxis.isHorizontal();
  25637. var valueAxisStart = (baseAxis.onZero || stacked)
  25638. ? valueAxis.toGlobalCoord(valueAxis.dataToCoord(0))
  25639. : valueAxis.getGlobalExtent()[0];
  25640. for (var idx = 0, len = data.count(); idx < len; idx++) {
  25641. var value = data.get(valueDim, idx);
  25642. var baseValue = data.get(baseDim, idx);
  25643. if (isNaN(value)) {
  25644. continue;
  25645. }
  25646. var sign = value >= 0 ? 'p' : 'n';
  25647. var baseCoord = valueAxisStart;
  25648. // Because of the barMinHeight, we can not use the value in
  25649. // stackResultDimension directly.
  25650. if (stacked) {
  25651. // Only ordinal axis can be stacked.
  25652. if (!lastStackCoords[stackId][baseValue]) {
  25653. lastStackCoords[stackId][baseValue] = {
  25654. p: valueAxisStart, // Positive stack
  25655. n: valueAxisStart // Negative stack
  25656. };
  25657. }
  25658. // Should also consider #4243
  25659. baseCoord = lastStackCoords[stackId][baseValue][sign];
  25660. }
  25661. var x;
  25662. var y;
  25663. var width;
  25664. var height;
  25665. if (isValueAxisH) {
  25666. var coord = cartesian.dataToPoint([value, baseValue]);
  25667. x = baseCoord;
  25668. y = coord[1] + columnOffset;
  25669. width = coord[0] - valueAxisStart;
  25670. height = columnWidth;
  25671. if (Math.abs(width) < barMinHeight) {
  25672. width = (width < 0 ? -1 : 1) * barMinHeight;
  25673. }
  25674. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  25675. }
  25676. else {
  25677. var coord = cartesian.dataToPoint([baseValue, value]);
  25678. x = coord[0] + columnOffset;
  25679. y = baseCoord;
  25680. width = columnWidth;
  25681. height = coord[1] - valueAxisStart;
  25682. if (Math.abs(height) < barMinHeight) {
  25683. // Include zero to has a positive bar
  25684. height = (height <= 0 ? -1 : 1) * barMinHeight;
  25685. }
  25686. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  25687. }
  25688. data.setItemLayout(idx, {
  25689. x: x,
  25690. y: y,
  25691. width: width,
  25692. height: height
  25693. });
  25694. }
  25695. }, this);
  25696. }
  25697. // [About UTC and local time zone]:
  25698. // In most cases, `number.parseDate` will treat input data string as local time
  25699. // (except time zone is specified in time string). And `format.formateTime` returns
  25700. // local time by default. option.useUTC is false by default. This design have
  25701. // concidered these common case:
  25702. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  25703. // in local time by default.
  25704. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  25705. // as its original time, without any time difference.
  25706. var intervalScaleProto = IntervalScale.prototype;
  25707. var mathCeil = Math.ceil;
  25708. var mathFloor = Math.floor;
  25709. var ONE_SECOND = 1000;
  25710. var ONE_MINUTE = ONE_SECOND * 60;
  25711. var ONE_HOUR = ONE_MINUTE * 60;
  25712. var ONE_DAY = ONE_HOUR * 24;
  25713. // FIXME 公用?
  25714. var bisect = function (a, x, lo, hi) {
  25715. while (lo < hi) {
  25716. var mid = lo + hi >>> 1;
  25717. if (a[mid][1] < x) {
  25718. lo = mid + 1;
  25719. }
  25720. else {
  25721. hi = mid;
  25722. }
  25723. }
  25724. return lo;
  25725. };
  25726. /**
  25727. * @alias module:echarts/coord/scale/Time
  25728. * @constructor
  25729. */
  25730. var TimeScale = IntervalScale.extend({
  25731. type: 'time',
  25732. /**
  25733. * @override
  25734. */
  25735. getLabel: function (val) {
  25736. var stepLvl = this._stepLvl;
  25737. var date = new Date(val);
  25738. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  25739. },
  25740. /**
  25741. * @override
  25742. */
  25743. niceExtent: function (opt) {
  25744. var extent = this._extent;
  25745. // If extent start and end are same, expand them
  25746. if (extent[0] === extent[1]) {
  25747. // Expand extent
  25748. extent[0] -= ONE_DAY;
  25749. extent[1] += ONE_DAY;
  25750. }
  25751. // If there are no data and extent are [Infinity, -Infinity]
  25752. if (extent[1] === -Infinity && extent[0] === Infinity) {
  25753. var d = new Date();
  25754. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  25755. extent[0] = extent[1] - ONE_DAY;
  25756. }
  25757. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  25758. // var extent = this._extent;
  25759. var interval = this._interval;
  25760. if (!opt.fixMin) {
  25761. extent[0] = round$1(mathFloor(extent[0] / interval) * interval);
  25762. }
  25763. if (!opt.fixMax) {
  25764. extent[1] = round$1(mathCeil(extent[1] / interval) * interval);
  25765. }
  25766. },
  25767. /**
  25768. * @override
  25769. */
  25770. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  25771. approxTickNum = approxTickNum || 10;
  25772. var extent = this._extent;
  25773. var span = extent[1] - extent[0];
  25774. var approxInterval = span / approxTickNum;
  25775. if (minInterval != null && approxInterval < minInterval) {
  25776. approxInterval = minInterval;
  25777. }
  25778. if (maxInterval != null && approxInterval > maxInterval) {
  25779. approxInterval = maxInterval;
  25780. }
  25781. var scaleLevelsLen = scaleLevels.length;
  25782. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  25783. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  25784. var interval = level[1];
  25785. // Same with interval scale if span is much larger than 1 year
  25786. if (level[0] === 'year') {
  25787. var yearSpan = span / interval;
  25788. // From "Nice Numbers for Graph Labels" of Graphic Gems
  25789. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  25790. var yearStep = nice(yearSpan / approxTickNum, true);
  25791. interval *= yearStep;
  25792. }
  25793. var timezoneOffset = this.getSetting('useUTC')
  25794. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  25795. var niceExtent = [
  25796. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  25797. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  25798. ];
  25799. fixExtent(niceExtent, extent);
  25800. this._stepLvl = level;
  25801. // Interval will be used in getTicks
  25802. this._interval = interval;
  25803. this._niceExtent = niceExtent;
  25804. },
  25805. parse: function (val) {
  25806. // val might be float.
  25807. return +parseDate(val);
  25808. }
  25809. });
  25810. each$1(['contain', 'normalize'], function (methodName) {
  25811. TimeScale.prototype[methodName] = function (val) {
  25812. return intervalScaleProto[methodName].call(this, this.parse(val));
  25813. };
  25814. });
  25815. // Steps from d3
  25816. var scaleLevels = [
  25817. // Format interval
  25818. ['hh:mm:ss', ONE_SECOND], // 1s
  25819. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  25820. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  25821. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  25822. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  25823. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  25824. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  25825. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  25826. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  25827. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  25828. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  25829. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  25830. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  25831. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  25832. ['MM-dd\nyyyy', ONE_DAY], // 1d
  25833. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  25834. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  25835. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  25836. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  25837. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  25838. ['week', ONE_DAY * 7], // 7d
  25839. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  25840. ['week', ONE_DAY * 14], // 2w
  25841. ['week', ONE_DAY * 21], // 3w
  25842. ['month', ONE_DAY * 31], // 1M
  25843. ['week', ONE_DAY * 42], // 6w
  25844. ['month', ONE_DAY * 62], // 2M
  25845. ['week', ONE_DAY * 42], // 10w
  25846. ['quarter', ONE_DAY * 380 / 4], // 3M
  25847. ['month', ONE_DAY * 31 * 4], // 4M
  25848. ['month', ONE_DAY * 31 * 5], // 5M
  25849. ['half-year', ONE_DAY * 380 / 2], // 6M
  25850. ['month', ONE_DAY * 31 * 8], // 8M
  25851. ['month', ONE_DAY * 31 * 10], // 10M
  25852. ['year', ONE_DAY * 380] // 1Y
  25853. ];
  25854. /**
  25855. * @param {module:echarts/model/Model}
  25856. * @return {module:echarts/scale/Time}
  25857. */
  25858. TimeScale.create = function (model) {
  25859. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  25860. };
  25861. /**
  25862. * Log scale
  25863. * @module echarts/scale/Log
  25864. */
  25865. // Use some method of IntervalScale
  25866. var scaleProto$1 = Scale.prototype;
  25867. var intervalScaleProto$1 = IntervalScale.prototype;
  25868. var getPrecisionSafe$1 = getPrecisionSafe;
  25869. var roundingErrorFix = round$1;
  25870. var mathFloor$1 = Math.floor;
  25871. var mathCeil$1 = Math.ceil;
  25872. var mathPow$1 = Math.pow;
  25873. var mathLog = Math.log;
  25874. var LogScale = Scale.extend({
  25875. type: 'log',
  25876. base: 10,
  25877. $constructor: function () {
  25878. Scale.apply(this, arguments);
  25879. this._originalScale = new IntervalScale();
  25880. },
  25881. /**
  25882. * @return {Array.<number>}
  25883. */
  25884. getTicks: function () {
  25885. var originalScale = this._originalScale;
  25886. var extent = this._extent;
  25887. var originalExtent = originalScale.getExtent();
  25888. return map(intervalScaleProto$1.getTicks.call(this), function (val) {
  25889. var powVal = round$1(mathPow$1(this.base, val));
  25890. // Fix #4158
  25891. powVal = (val === extent[0] && originalScale.__fixMin)
  25892. ? fixRoundingError(powVal, originalExtent[0])
  25893. : powVal;
  25894. powVal = (val === extent[1] && originalScale.__fixMax)
  25895. ? fixRoundingError(powVal, originalExtent[1])
  25896. : powVal;
  25897. return powVal;
  25898. }, this);
  25899. },
  25900. /**
  25901. * @param {number} val
  25902. * @return {string}
  25903. */
  25904. getLabel: intervalScaleProto$1.getLabel,
  25905. /**
  25906. * @param {number} val
  25907. * @return {number}
  25908. */
  25909. scale: function (val) {
  25910. val = scaleProto$1.scale.call(this, val);
  25911. return mathPow$1(this.base, val);
  25912. },
  25913. /**
  25914. * @param {number} start
  25915. * @param {number} end
  25916. */
  25917. setExtent: function (start, end) {
  25918. var base = this.base;
  25919. start = mathLog(start) / mathLog(base);
  25920. end = mathLog(end) / mathLog(base);
  25921. intervalScaleProto$1.setExtent.call(this, start, end);
  25922. },
  25923. /**
  25924. * @return {number} end
  25925. */
  25926. getExtent: function () {
  25927. var base = this.base;
  25928. var extent = scaleProto$1.getExtent.call(this);
  25929. extent[0] = mathPow$1(base, extent[0]);
  25930. extent[1] = mathPow$1(base, extent[1]);
  25931. // Fix #4158
  25932. var originalScale = this._originalScale;
  25933. var originalExtent = originalScale.getExtent();
  25934. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  25935. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  25936. return extent;
  25937. },
  25938. /**
  25939. * @param {Array.<number>} extent
  25940. */
  25941. unionExtent: function (extent) {
  25942. this._originalScale.unionExtent(extent);
  25943. var base = this.base;
  25944. extent[0] = mathLog(extent[0]) / mathLog(base);
  25945. extent[1] = mathLog(extent[1]) / mathLog(base);
  25946. scaleProto$1.unionExtent.call(this, extent);
  25947. },
  25948. /**
  25949. * @override
  25950. */
  25951. unionExtentFromData: function (data, dim) {
  25952. // TODO
  25953. // filter value that <= 0
  25954. this.unionExtent(data.getApproximateExtent(dim));
  25955. },
  25956. /**
  25957. * Update interval and extent of intervals for nice ticks
  25958. * @param {number} [approxTickNum = 10] Given approx tick number
  25959. */
  25960. niceTicks: function (approxTickNum) {
  25961. approxTickNum = approxTickNum || 10;
  25962. var extent = this._extent;
  25963. var span = extent[1] - extent[0];
  25964. if (span === Infinity || span <= 0) {
  25965. return;
  25966. }
  25967. var interval = quantity(span);
  25968. var err = approxTickNum / span * interval;
  25969. // Filter ticks to get closer to the desired count.
  25970. if (err <= 0.5) {
  25971. interval *= 10;
  25972. }
  25973. // Interval should be integer
  25974. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  25975. interval *= 10;
  25976. }
  25977. var niceExtent = [
  25978. round$1(mathCeil$1(extent[0] / interval) * interval),
  25979. round$1(mathFloor$1(extent[1] / interval) * interval)
  25980. ];
  25981. this._interval = interval;
  25982. this._niceExtent = niceExtent;
  25983. },
  25984. /**
  25985. * Nice extent.
  25986. * @override
  25987. */
  25988. niceExtent: function (opt) {
  25989. intervalScaleProto$1.niceExtent.call(this, opt);
  25990. var originalScale = this._originalScale;
  25991. originalScale.__fixMin = opt.fixMin;
  25992. originalScale.__fixMax = opt.fixMax;
  25993. }
  25994. });
  25995. each$1(['contain', 'normalize'], function (methodName) {
  25996. LogScale.prototype[methodName] = function (val) {
  25997. val = mathLog(val) / mathLog(this.base);
  25998. return scaleProto$1[methodName].call(this, val);
  25999. };
  26000. });
  26001. LogScale.create = function () {
  26002. return new LogScale();
  26003. };
  26004. function fixRoundingError(val, originalVal) {
  26005. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  26006. }
  26007. /**
  26008. * Get axis scale extent before niced.
  26009. * Item of returned array can only be number (including Infinity and NaN).
  26010. */
  26011. function getScaleExtent(scale, model) {
  26012. var scaleType = scale.type;
  26013. var min = model.getMin();
  26014. var max = model.getMax();
  26015. var fixMin = min != null;
  26016. var fixMax = max != null;
  26017. var originalExtent = scale.getExtent();
  26018. var axisDataLen;
  26019. var boundaryGap;
  26020. var span;
  26021. if (scaleType === 'ordinal') {
  26022. axisDataLen = model.getCategories().length;
  26023. }
  26024. else {
  26025. boundaryGap = model.get('boundaryGap');
  26026. if (!isArray(boundaryGap)) {
  26027. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  26028. }
  26029. if (typeof boundaryGap[0] === 'boolean') {
  26030. if (__DEV__) {
  26031. console.warn('Boolean type for boundaryGap is only '
  26032. + 'allowed for ordinal axis. Please use string in '
  26033. + 'percentage instead, e.g., "20%". Currently, '
  26034. + 'boundaryGap is set to be 0.');
  26035. }
  26036. boundaryGap = [0, 0];
  26037. }
  26038. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  26039. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  26040. span = (originalExtent[1] - originalExtent[0])
  26041. || Math.abs(originalExtent[0]);
  26042. }
  26043. // Notice: When min/max is not set (that is, when there are null/undefined,
  26044. // which is the most common case), these cases should be ensured:
  26045. // (1) For 'ordinal', show all axis.data.
  26046. // (2) For others:
  26047. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  26048. // disabled).
  26049. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  26050. // be the result that originalExtent enlarged by boundaryGap.
  26051. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  26052. // FIXME
  26053. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  26054. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  26055. // that the results processed by boundaryGap are positive/negative?
  26056. if (min == null) {
  26057. min = scaleType === 'ordinal'
  26058. ? (axisDataLen ? 0 : NaN)
  26059. : originalExtent[0] - boundaryGap[0] * span;
  26060. }
  26061. if (max == null) {
  26062. max = scaleType === 'ordinal'
  26063. ? (axisDataLen ? axisDataLen - 1 : NaN)
  26064. : originalExtent[1] + boundaryGap[1] * span;
  26065. }
  26066. if (min === 'dataMin') {
  26067. min = originalExtent[0];
  26068. }
  26069. else if (typeof min === 'function') {
  26070. min = min({
  26071. min: originalExtent[0],
  26072. max: originalExtent[1]
  26073. });
  26074. }
  26075. if (max === 'dataMax') {
  26076. max = originalExtent[1];
  26077. }
  26078. else if (typeof max === 'function') {
  26079. max = max({
  26080. min: originalExtent[0],
  26081. max: originalExtent[1]
  26082. });
  26083. }
  26084. (min == null || !isFinite(min)) && (min = NaN);
  26085. (max == null || !isFinite(max)) && (max = NaN);
  26086. scale.setBlank(eqNaN(min) || eqNaN(max));
  26087. // Evaluate if axis needs cross zero
  26088. if (model.getNeedCrossZero()) {
  26089. // Axis is over zero and min is not set
  26090. if (min > 0 && max > 0 && !fixMin) {
  26091. min = 0;
  26092. }
  26093. // Axis is under zero and max is not set
  26094. if (min < 0 && max < 0 && !fixMax) {
  26095. max = 0;
  26096. }
  26097. }
  26098. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  26099. // is base axis
  26100. // FIXME
  26101. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  26102. // (2) Refactor the logic with `barGrid`. Is it not need to `calBarWidthAndOffset` twice with different extent?
  26103. // Should not depend on series type `bar`?
  26104. // (3) Fix that might overlap when using dataZoom.
  26105. // (4) Consider other chart types using `barGrid`?
  26106. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  26107. var ecModel = model.ecModel;
  26108. if (ecModel && (scaleType === 'time' /*|| scaleType === 'interval' */)) {
  26109. var barSeriesModels = [];
  26110. var isBaseAxisAndHasBarSeries;
  26111. ecModel.eachSeriesByType('bar', function (seriesModel) {
  26112. if (seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d') {
  26113. barSeriesModels.push(seriesModel);
  26114. isBaseAxisAndHasBarSeries |= seriesModel.getBaseAxis() === model.axis;
  26115. }
  26116. });
  26117. if (isBaseAxisAndHasBarSeries) {
  26118. // Adjust axis min and max to account for overflow
  26119. var adjustedScale = adjustScaleForOverflow(min, max, model, barSeriesModels);
  26120. min = adjustedScale.min;
  26121. max = adjustedScale.max;
  26122. }
  26123. }
  26124. return [min, max];
  26125. }
  26126. function adjustScaleForOverflow(min, max, model, barSeriesModels) {
  26127. // Get Axis Length
  26128. var axisExtent = model.axis.getExtent();
  26129. var axisLength = axisExtent[1] - axisExtent[0];
  26130. // Calculate placement of bars on axis
  26131. var barWidthAndOffset = calBarWidthAndOffset(barSeriesModels);
  26132. // Get bars on current base axis and calculate min and max overflow
  26133. var baseAxisKey = model.axis.dim + model.axis.index;
  26134. var barsOnCurrentAxis = barWidthAndOffset[baseAxisKey];
  26135. if (barsOnCurrentAxis === undefined) {
  26136. return {min: min, max: max};
  26137. }
  26138. var minOverflow = Infinity;
  26139. each$1(barsOnCurrentAxis, function (item) {
  26140. minOverflow = Math.min(item.offset, minOverflow);
  26141. });
  26142. var maxOverflow = -Infinity;
  26143. each$1(barsOnCurrentAxis, function (item) {
  26144. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  26145. });
  26146. minOverflow = Math.abs(minOverflow);
  26147. maxOverflow = Math.abs(maxOverflow);
  26148. var totalOverFlow = minOverflow + maxOverflow;
  26149. // Calulate required buffer based on old range and overflow
  26150. var oldRange = max - min;
  26151. var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength);
  26152. var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange);
  26153. max += overflowBuffer * (maxOverflow / totalOverFlow);
  26154. min -= overflowBuffer * (minOverflow / totalOverFlow);
  26155. return {min: min, max: max};
  26156. }
  26157. function niceScaleExtent(scale, model) {
  26158. var extent = getScaleExtent(scale, model);
  26159. var fixMin = model.getMin() != null;
  26160. var fixMax = model.getMax() != null;
  26161. var splitNumber = model.get('splitNumber');
  26162. if (scale.type === 'log') {
  26163. scale.base = model.get('logBase');
  26164. }
  26165. var scaleType = scale.type;
  26166. scale.setExtent(extent[0], extent[1]);
  26167. scale.niceExtent({
  26168. splitNumber: splitNumber,
  26169. fixMin: fixMin,
  26170. fixMax: fixMax,
  26171. minInterval: (scaleType === 'interval' || scaleType === 'time')
  26172. ? model.get('minInterval') : null,
  26173. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  26174. ? model.get('maxInterval') : null
  26175. });
  26176. // If some one specified the min, max. And the default calculated interval
  26177. // is not good enough. He can specify the interval. It is often appeared
  26178. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  26179. // to be 60.
  26180. // FIXME
  26181. var interval = model.get('interval');
  26182. if (interval != null) {
  26183. scale.setInterval && scale.setInterval(interval);
  26184. }
  26185. }
  26186. /**
  26187. * @param {module:echarts/model/Model} model
  26188. * @param {string} [axisType] Default retrieve from model.type
  26189. * @return {module:echarts/scale/*}
  26190. */
  26191. function createScaleByModel(model, axisType) {
  26192. axisType = axisType || model.get('type');
  26193. if (axisType) {
  26194. switch (axisType) {
  26195. // Buildin scale
  26196. case 'category':
  26197. return new OrdinalScale(
  26198. model.getOrdinalMeta
  26199. ? model.getOrdinalMeta()
  26200. : model.getCategories(),
  26201. [Infinity, -Infinity]
  26202. );
  26203. case 'value':
  26204. return new IntervalScale();
  26205. // Extended scale, like time and log
  26206. default:
  26207. return (Scale.getClass(axisType) || IntervalScale).create(model);
  26208. }
  26209. }
  26210. }
  26211. /**
  26212. * Check if the axis corss 0
  26213. */
  26214. function ifAxisCrossZero(axis) {
  26215. var dataExtent = axis.scale.getExtent();
  26216. var min = dataExtent[0];
  26217. var max = dataExtent[1];
  26218. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  26219. }
  26220. /**
  26221. * @param {Array.<number>} tickCoords In axis self coordinate.
  26222. * @param {Array.<string>} labels
  26223. * @param {string} font
  26224. * @param {number} axisRotate 0: towards right horizontally, clock-wise is negative.
  26225. * @param {number} [labelRotate=0] 0: towards right horizontally, clock-wise is negative.
  26226. * @return {number}
  26227. */
  26228. function getAxisLabelInterval(tickCoords, labels, font, axisRotate, labelRotate) {
  26229. var textSpaceTakenRect;
  26230. var autoLabelInterval = 0;
  26231. var accumulatedLabelInterval = 0;
  26232. var rotation = (axisRotate - labelRotate) / 180 * Math.PI;
  26233. var step = 1;
  26234. if (labels.length > 40) {
  26235. // Simple optimization for large amount of labels
  26236. step = Math.floor(labels.length / 40);
  26237. }
  26238. for (var i = 0; i < tickCoords.length; i += step) {
  26239. var tickCoord = tickCoords[i];
  26240. // Not precise, do not consider align and vertical align
  26241. // and each distance from axis line yet.
  26242. var rect = getBoundingRect(
  26243. labels[i], font, 'center', 'top'
  26244. );
  26245. rect.x += tickCoord * Math.cos(rotation);
  26246. rect.y += tickCoord * Math.sin(rotation);
  26247. // Magic number
  26248. rect.width *= 1.3;
  26249. rect.height *= 1.3;
  26250. if (!textSpaceTakenRect) {
  26251. textSpaceTakenRect = rect.clone();
  26252. }
  26253. // There is no space for current label;
  26254. else if (textSpaceTakenRect.intersect(rect)) {
  26255. accumulatedLabelInterval++;
  26256. autoLabelInterval = Math.max(autoLabelInterval, accumulatedLabelInterval);
  26257. }
  26258. else {
  26259. textSpaceTakenRect.union(rect);
  26260. // Reset
  26261. accumulatedLabelInterval = 0;
  26262. }
  26263. }
  26264. if (autoLabelInterval === 0 && step > 1) {
  26265. return step;
  26266. }
  26267. return (autoLabelInterval + 1) * step - 1;
  26268. }
  26269. /**
  26270. * @param {Object} axis
  26271. * @param {Function} labelFormatter
  26272. * @return {Array.<string>}
  26273. */
  26274. function getFormattedLabels(axis, labelFormatter) {
  26275. var scale = axis.scale;
  26276. var labels = scale.getTicksLabels();
  26277. var ticks = scale.getTicks();
  26278. if (typeof labelFormatter === 'string') {
  26279. labelFormatter = (function (tpl) {
  26280. return function (val) {
  26281. return tpl.replace('{value}', val != null ? val : '');
  26282. };
  26283. })(labelFormatter);
  26284. // Consider empty array
  26285. return map(labels, labelFormatter);
  26286. }
  26287. else if (typeof labelFormatter === 'function') {
  26288. return map(ticks, function (tick, idx) {
  26289. return labelFormatter(
  26290. getAxisRawValue(axis, tick),
  26291. idx
  26292. );
  26293. }, this);
  26294. }
  26295. else {
  26296. return labels;
  26297. }
  26298. }
  26299. function getAxisRawValue(axis, value) {
  26300. // In category axis with data zoom, tick is not the original
  26301. // index of axis.data. So tick should not be exposed to user
  26302. // in category axis.
  26303. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  26304. }
  26305. var axisModelCommonMixin = {
  26306. /**
  26307. * Format labels
  26308. * @return {Array.<string>}
  26309. */
  26310. getFormattedLabels: function () {
  26311. return getFormattedLabels(
  26312. this.axis,
  26313. this.get('axisLabel.formatter')
  26314. );
  26315. },
  26316. /**
  26317. * @param {boolean} origin
  26318. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  26319. */
  26320. getMin: function (origin) {
  26321. var option = this.option;
  26322. var min = (!origin && option.rangeStart != null)
  26323. ? option.rangeStart : option.min;
  26324. if (this.axis
  26325. && min != null
  26326. && min !== 'dataMin'
  26327. && typeof min !== 'function'
  26328. && !eqNaN(min)
  26329. ) {
  26330. min = this.axis.scale.parse(min);
  26331. }
  26332. return min;
  26333. },
  26334. /**
  26335. * @param {boolean} origin
  26336. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  26337. */
  26338. getMax: function (origin) {
  26339. var option = this.option;
  26340. var max = (!origin && option.rangeEnd != null)
  26341. ? option.rangeEnd : option.max;
  26342. if (this.axis
  26343. && max != null
  26344. && max !== 'dataMax'
  26345. && typeof max !== 'function'
  26346. && !eqNaN(max)
  26347. ) {
  26348. max = this.axis.scale.parse(max);
  26349. }
  26350. return max;
  26351. },
  26352. /**
  26353. * @return {boolean}
  26354. */
  26355. getNeedCrossZero: function () {
  26356. var option = this.option;
  26357. return (option.rangeStart != null || option.rangeEnd != null)
  26358. ? false : !option.scale;
  26359. },
  26360. /**
  26361. * Should be implemented by each axis model if necessary.
  26362. * @return {module:echarts/model/Component} coordinate system model
  26363. */
  26364. getCoordSysModel: noop,
  26365. /**
  26366. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  26367. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  26368. */
  26369. setRange: function (rangeStart, rangeEnd) {
  26370. this.option.rangeStart = rangeStart;
  26371. this.option.rangeEnd = rangeEnd;
  26372. },
  26373. /**
  26374. * Reset range
  26375. */
  26376. resetRange: function () {
  26377. // rangeStart and rangeEnd is readonly.
  26378. this.option.rangeStart = this.option.rangeEnd = null;
  26379. }
  26380. };
  26381. // Symbol factory
  26382. /**
  26383. * Triangle shape
  26384. * @inner
  26385. */
  26386. var Triangle = extendShape({
  26387. type: 'triangle',
  26388. shape: {
  26389. cx: 0,
  26390. cy: 0,
  26391. width: 0,
  26392. height: 0
  26393. },
  26394. buildPath: function (path, shape) {
  26395. var cx = shape.cx;
  26396. var cy = shape.cy;
  26397. var width = shape.width / 2;
  26398. var height = shape.height / 2;
  26399. path.moveTo(cx, cy - height);
  26400. path.lineTo(cx + width, cy + height);
  26401. path.lineTo(cx - width, cy + height);
  26402. path.closePath();
  26403. }
  26404. });
  26405. /**
  26406. * Diamond shape
  26407. * @inner
  26408. */
  26409. var Diamond = extendShape({
  26410. type: 'diamond',
  26411. shape: {
  26412. cx: 0,
  26413. cy: 0,
  26414. width: 0,
  26415. height: 0
  26416. },
  26417. buildPath: function (path, shape) {
  26418. var cx = shape.cx;
  26419. var cy = shape.cy;
  26420. var width = shape.width / 2;
  26421. var height = shape.height / 2;
  26422. path.moveTo(cx, cy - height);
  26423. path.lineTo(cx + width, cy);
  26424. path.lineTo(cx, cy + height);
  26425. path.lineTo(cx - width, cy);
  26426. path.closePath();
  26427. }
  26428. });
  26429. /**
  26430. * Pin shape
  26431. * @inner
  26432. */
  26433. var Pin = extendShape({
  26434. type: 'pin',
  26435. shape: {
  26436. // x, y on the cusp
  26437. x: 0,
  26438. y: 0,
  26439. width: 0,
  26440. height: 0
  26441. },
  26442. buildPath: function (path, shape) {
  26443. var x = shape.x;
  26444. var y = shape.y;
  26445. var w = shape.width / 5 * 3;
  26446. // Height must be larger than width
  26447. var h = Math.max(w, shape.height);
  26448. var r = w / 2;
  26449. // Dist on y with tangent point and circle center
  26450. var dy = r * r / (h - r);
  26451. var cy = y - h + r + dy;
  26452. var angle = Math.asin(dy / r);
  26453. // Dist on x with tangent point and circle center
  26454. var dx = Math.cos(angle) * r;
  26455. var tanX = Math.sin(angle);
  26456. var tanY = Math.cos(angle);
  26457. var cpLen = r * 0.6;
  26458. var cpLen2 = r * 0.7;
  26459. path.moveTo(x - dx, cy + dy);
  26460. path.arc(
  26461. x, cy, r,
  26462. Math.PI - angle,
  26463. Math.PI * 2 + angle
  26464. );
  26465. path.bezierCurveTo(
  26466. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  26467. x, y - cpLen2,
  26468. x, y
  26469. );
  26470. path.bezierCurveTo(
  26471. x, y - cpLen2,
  26472. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  26473. x - dx, cy + dy
  26474. );
  26475. path.closePath();
  26476. }
  26477. });
  26478. /**
  26479. * Arrow shape
  26480. * @inner
  26481. */
  26482. var Arrow = extendShape({
  26483. type: 'arrow',
  26484. shape: {
  26485. x: 0,
  26486. y: 0,
  26487. width: 0,
  26488. height: 0
  26489. },
  26490. buildPath: function (ctx, shape) {
  26491. var height = shape.height;
  26492. var width = shape.width;
  26493. var x = shape.x;
  26494. var y = shape.y;
  26495. var dx = width / 3 * 2;
  26496. ctx.moveTo(x, y);
  26497. ctx.lineTo(x + dx, y + height);
  26498. ctx.lineTo(x, y + height / 4 * 3);
  26499. ctx.lineTo(x - dx, y + height);
  26500. ctx.lineTo(x, y);
  26501. ctx.closePath();
  26502. }
  26503. });
  26504. /**
  26505. * Map of path contructors
  26506. * @type {Object.<string, module:zrender/graphic/Path>}
  26507. */
  26508. var symbolCtors = {
  26509. line: Line,
  26510. rect: Rect,
  26511. roundRect: Rect,
  26512. square: Rect,
  26513. circle: Circle,
  26514. diamond: Diamond,
  26515. pin: Pin,
  26516. arrow: Arrow,
  26517. triangle: Triangle
  26518. };
  26519. var symbolShapeMakers = {
  26520. line: function (x, y, w, h, shape) {
  26521. // FIXME
  26522. shape.x1 = x;
  26523. shape.y1 = y + h / 2;
  26524. shape.x2 = x + w;
  26525. shape.y2 = y + h / 2;
  26526. },
  26527. rect: function (x, y, w, h, shape) {
  26528. shape.x = x;
  26529. shape.y = y;
  26530. shape.width = w;
  26531. shape.height = h;
  26532. },
  26533. roundRect: function (x, y, w, h, shape) {
  26534. shape.x = x;
  26535. shape.y = y;
  26536. shape.width = w;
  26537. shape.height = h;
  26538. shape.r = Math.min(w, h) / 4;
  26539. },
  26540. square: function (x, y, w, h, shape) {
  26541. var size = Math.min(w, h);
  26542. shape.x = x;
  26543. shape.y = y;
  26544. shape.width = size;
  26545. shape.height = size;
  26546. },
  26547. circle: function (x, y, w, h, shape) {
  26548. // Put circle in the center of square
  26549. shape.cx = x + w / 2;
  26550. shape.cy = y + h / 2;
  26551. shape.r = Math.min(w, h) / 2;
  26552. },
  26553. diamond: function (x, y, w, h, shape) {
  26554. shape.cx = x + w / 2;
  26555. shape.cy = y + h / 2;
  26556. shape.width = w;
  26557. shape.height = h;
  26558. },
  26559. pin: function (x, y, w, h, shape) {
  26560. shape.x = x + w / 2;
  26561. shape.y = y + h / 2;
  26562. shape.width = w;
  26563. shape.height = h;
  26564. },
  26565. arrow: function (x, y, w, h, shape) {
  26566. shape.x = x + w / 2;
  26567. shape.y = y + h / 2;
  26568. shape.width = w;
  26569. shape.height = h;
  26570. },
  26571. triangle: function (x, y, w, h, shape) {
  26572. shape.cx = x + w / 2;
  26573. shape.cy = y + h / 2;
  26574. shape.width = w;
  26575. shape.height = h;
  26576. }
  26577. };
  26578. var symbolBuildProxies = {};
  26579. each$1(symbolCtors, function (Ctor, name) {
  26580. symbolBuildProxies[name] = new Ctor();
  26581. });
  26582. var SymbolClz = extendShape({
  26583. type: 'symbol',
  26584. shape: {
  26585. symbolType: '',
  26586. x: 0,
  26587. y: 0,
  26588. width: 0,
  26589. height: 0
  26590. },
  26591. beforeBrush: function () {
  26592. var style = this.style;
  26593. var shape = this.shape;
  26594. // FIXME
  26595. if (shape.symbolType === 'pin' && style.textPosition === 'inside') {
  26596. style.textPosition = ['50%', '40%'];
  26597. style.textAlign = 'center';
  26598. style.textVerticalAlign = 'middle';
  26599. }
  26600. },
  26601. buildPath: function (ctx, shape, inBundle) {
  26602. var symbolType = shape.symbolType;
  26603. var proxySymbol = symbolBuildProxies[symbolType];
  26604. if (shape.symbolType !== 'none') {
  26605. if (!proxySymbol) {
  26606. // Default rect
  26607. symbolType = 'rect';
  26608. proxySymbol = symbolBuildProxies[symbolType];
  26609. }
  26610. symbolShapeMakers[symbolType](
  26611. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  26612. );
  26613. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  26614. }
  26615. }
  26616. });
  26617. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  26618. function symbolPathSetColor(color, innerColor) {
  26619. if (this.type !== 'image') {
  26620. var symbolStyle = this.style;
  26621. var symbolShape = this.shape;
  26622. if (symbolShape && symbolShape.symbolType === 'line') {
  26623. symbolStyle.stroke = color;
  26624. }
  26625. else if (this.__isEmptyBrush) {
  26626. symbolStyle.stroke = color;
  26627. symbolStyle.fill = innerColor || '#fff';
  26628. }
  26629. else {
  26630. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  26631. symbolStyle.fill && (symbolStyle.fill = color);
  26632. symbolStyle.stroke && (symbolStyle.stroke = color);
  26633. }
  26634. this.dirty(false);
  26635. }
  26636. }
  26637. /**
  26638. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  26639. * @param {string} symbolType
  26640. * @param {number} x
  26641. * @param {number} y
  26642. * @param {number} w
  26643. * @param {number} h
  26644. * @param {string} color
  26645. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  26646. * for path and image only.
  26647. */
  26648. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  26649. // TODO Support image object, DynamicImage.
  26650. var isEmpty = symbolType.indexOf('empty') === 0;
  26651. if (isEmpty) {
  26652. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  26653. }
  26654. var symbolPath;
  26655. if (symbolType.indexOf('image://') === 0) {
  26656. symbolPath = makeImage(
  26657. symbolType.slice(8),
  26658. new BoundingRect(x, y, w, h),
  26659. keepAspect ? 'center' : 'cover'
  26660. );
  26661. }
  26662. else if (symbolType.indexOf('path://') === 0) {
  26663. symbolPath = makePath(
  26664. symbolType.slice(7),
  26665. {},
  26666. new BoundingRect(x, y, w, h),
  26667. keepAspect ? 'center' : 'cover'
  26668. );
  26669. }
  26670. else {
  26671. symbolPath = new SymbolClz({
  26672. shape: {
  26673. symbolType: symbolType,
  26674. x: x,
  26675. y: y,
  26676. width: w,
  26677. height: h
  26678. }
  26679. });
  26680. }
  26681. symbolPath.__isEmptyBrush = isEmpty;
  26682. symbolPath.setColor = symbolPathSetColor;
  26683. symbolPath.setColor(color);
  26684. return symbolPath;
  26685. }
  26686. // import createGraphFromNodeEdge from './chart/helper/createGraphFromNodeEdge';
  26687. /**
  26688. * Create a muti dimension List structure from seriesModel.
  26689. * @param {module:echarts/model/Model} seriesModel
  26690. * @return {module:echarts/data/List} list
  26691. */
  26692. function createList(seriesModel) {
  26693. return createListFromArray(seriesModel.getSource(), seriesModel);
  26694. }
  26695. var dataStack$1 = {
  26696. isDimensionStacked: isDimensionStacked,
  26697. enableDataStack: enableDataStack
  26698. };
  26699. /**
  26700. * Create scale
  26701. * @param {Array.<number>} dataExtent
  26702. * @param {Object|module:echarts/Model} option
  26703. */
  26704. function createScale(dataExtent, option) {
  26705. var axisModel = option;
  26706. if (!Model.isInstance(option)) {
  26707. axisModel = new Model(option);
  26708. mixin(axisModel, axisModelCommonMixin);
  26709. }
  26710. var scale = createScaleByModel(axisModel);
  26711. scale.setExtent(dataExtent[0], dataExtent[1]);
  26712. niceScaleExtent(scale, axisModel);
  26713. return scale;
  26714. }
  26715. /**
  26716. * Mixin common methods to axis model,
  26717. *
  26718. * Inlcude methods
  26719. * `getFormattedLabels() => Array.<string>`
  26720. * `getCategories() => Array.<string>`
  26721. * `getMin(origin: boolean) => number`
  26722. * `getMax(origin: boolean) => number`
  26723. * `getNeedCrossZero() => boolean`
  26724. * `setRange(start: number, end: number)`
  26725. * `resetRange()`
  26726. */
  26727. function mixinAxisModelCommonMethods(Model$$1) {
  26728. mixin(Model$$1, axisModelCommonMixin);
  26729. }
  26730. var helper = (Object.freeze || Object)({
  26731. createList: createList,
  26732. getLayoutRect: getLayoutRect,
  26733. dataStack: dataStack$1,
  26734. createScale: createScale,
  26735. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  26736. completeDimensions: completeDimensions,
  26737. createDimensions: createDimensions,
  26738. createSymbol: createSymbol
  26739. });
  26740. var EPSILON$3 = 1e-8;
  26741. function isAroundEqual$1(a, b) {
  26742. return Math.abs(a - b) < EPSILON$3;
  26743. }
  26744. function contain$1(points, x, y) {
  26745. var w = 0;
  26746. var p = points[0];
  26747. if (!p) {
  26748. return false;
  26749. }
  26750. for (var i = 1; i < points.length; i++) {
  26751. var p2 = points[i];
  26752. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  26753. p = p2;
  26754. }
  26755. // Close polygon
  26756. var p0 = points[0];
  26757. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  26758. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  26759. }
  26760. return w !== 0;
  26761. }
  26762. /**
  26763. * @module echarts/coord/geo/Region
  26764. */
  26765. /**
  26766. * @param {string} name
  26767. * @param {Array} geometries
  26768. * @param {Array.<number>} cp
  26769. */
  26770. function Region(name, geometries, cp) {
  26771. /**
  26772. * @type {string}
  26773. * @readOnly
  26774. */
  26775. this.name = name;
  26776. /**
  26777. * @type {Array.<Array>}
  26778. * @readOnly
  26779. */
  26780. this.geometries = geometries;
  26781. if (!cp) {
  26782. var rect = this.getBoundingRect();
  26783. cp = [
  26784. rect.x + rect.width / 2,
  26785. rect.y + rect.height / 2
  26786. ];
  26787. }
  26788. else {
  26789. cp = [cp[0], cp[1]];
  26790. }
  26791. /**
  26792. * @type {Array.<number>}
  26793. */
  26794. this.center = cp;
  26795. }
  26796. Region.prototype = {
  26797. constructor: Region,
  26798. properties: null,
  26799. /**
  26800. * @return {module:zrender/core/BoundingRect}
  26801. */
  26802. getBoundingRect: function () {
  26803. var rect = this._rect;
  26804. if (rect) {
  26805. return rect;
  26806. }
  26807. var MAX_NUMBER = Number.MAX_VALUE;
  26808. var min$$1 = [MAX_NUMBER, MAX_NUMBER];
  26809. var max$$1 = [-MAX_NUMBER, -MAX_NUMBER];
  26810. var min2 = [];
  26811. var max2 = [];
  26812. var geometries = this.geometries;
  26813. for (var i = 0; i < geometries.length; i++) {
  26814. // Only support polygon
  26815. if (geometries[i].type !== 'polygon') {
  26816. continue;
  26817. }
  26818. // Doesn't consider hole
  26819. var exterior = geometries[i].exterior;
  26820. fromPoints(exterior, min2, max2);
  26821. min(min$$1, min$$1, min2);
  26822. max(max$$1, max$$1, max2);
  26823. }
  26824. // No data
  26825. if (i === 0) {
  26826. min$$1[0] = min$$1[1] = max$$1[0] = max$$1[1] = 0;
  26827. }
  26828. return (this._rect = new BoundingRect(
  26829. min$$1[0], min$$1[1], max$$1[0] - min$$1[0], max$$1[1] - min$$1[1]
  26830. ));
  26831. },
  26832. /**
  26833. * @param {<Array.<number>} coord
  26834. * @return {boolean}
  26835. */
  26836. contain: function (coord) {
  26837. var rect = this.getBoundingRect();
  26838. var geometries = this.geometries;
  26839. if (!rect.contain(coord[0], coord[1])) {
  26840. return false;
  26841. }
  26842. loopGeo: for (var i = 0, len$$1 = geometries.length; i < len$$1; i++) {
  26843. // Only support polygon.
  26844. if (geometries[i].type !== 'polygon') {
  26845. continue;
  26846. }
  26847. var exterior = geometries[i].exterior;
  26848. var interiors = geometries[i].interiors;
  26849. if (contain$1(exterior, coord[0], coord[1])) {
  26850. // Not in the region if point is in the hole.
  26851. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  26852. if (contain$1(interiors[k])) {
  26853. continue loopGeo;
  26854. }
  26855. }
  26856. return true;
  26857. }
  26858. }
  26859. return false;
  26860. },
  26861. transformTo: function (x, y, width, height) {
  26862. var rect = this.getBoundingRect();
  26863. var aspect = rect.width / rect.height;
  26864. if (!width) {
  26865. width = aspect * height;
  26866. }
  26867. else if (!height) {
  26868. height = width / aspect ;
  26869. }
  26870. var target = new BoundingRect(x, y, width, height);
  26871. var transform = rect.calculateTransform(target);
  26872. var geometries = this.geometries;
  26873. for (var i = 0; i < geometries.length; i++) {
  26874. // Only support polygon.
  26875. if (geometries[i].type !== 'polygon') {
  26876. continue;
  26877. }
  26878. var exterior = geometries[i].exterior;
  26879. var interiors = geometries[i].interiors;
  26880. for (var p = 0; p < exterior.length; p++) {
  26881. applyTransform(exterior[p], exterior[p], transform);
  26882. }
  26883. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  26884. for (var p = 0; p < interiors[h].length; p++) {
  26885. applyTransform(interiors[h][p], interiors[h][p], transform);
  26886. }
  26887. }
  26888. }
  26889. rect = this._rect;
  26890. rect.copy(target);
  26891. // Update center
  26892. this.center = [
  26893. rect.x + rect.width / 2,
  26894. rect.y + rect.height / 2
  26895. ];
  26896. }
  26897. };
  26898. /**
  26899. * Parse and decode geo json
  26900. * @module echarts/coord/geo/parseGeoJson
  26901. */
  26902. function decode(json) {
  26903. if (!json.UTF8Encoding) {
  26904. return json;
  26905. }
  26906. var encodeScale = json.UTF8Scale;
  26907. if (encodeScale == null) {
  26908. encodeScale = 1024;
  26909. }
  26910. var features = json.features;
  26911. for (var f = 0; f < features.length; f++) {
  26912. var feature = features[f];
  26913. var geometry = feature.geometry;
  26914. var coordinates = geometry.coordinates;
  26915. var encodeOffsets = geometry.encodeOffsets;
  26916. for (var c = 0; c < coordinates.length; c++) {
  26917. var coordinate = coordinates[c];
  26918. if (geometry.type === 'Polygon') {
  26919. coordinates[c] = decodePolygon(
  26920. coordinate,
  26921. encodeOffsets[c],
  26922. encodeScale
  26923. );
  26924. }
  26925. else if (geometry.type === 'MultiPolygon') {
  26926. for (var c2 = 0; c2 < coordinate.length; c2++) {
  26927. var polygon = coordinate[c2];
  26928. coordinate[c2] = decodePolygon(
  26929. polygon,
  26930. encodeOffsets[c][c2],
  26931. encodeScale
  26932. );
  26933. }
  26934. }
  26935. }
  26936. }
  26937. // Has been decoded
  26938. json.UTF8Encoding = false;
  26939. return json;
  26940. }
  26941. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  26942. var result = [];
  26943. var prevX = encodeOffsets[0];
  26944. var prevY = encodeOffsets[1];
  26945. for (var i = 0; i < coordinate.length; i += 2) {
  26946. var x = coordinate.charCodeAt(i) - 64;
  26947. var y = coordinate.charCodeAt(i + 1) - 64;
  26948. // ZigZag decoding
  26949. x = (x >> 1) ^ (-(x & 1));
  26950. y = (y >> 1) ^ (-(y & 1));
  26951. // Delta deocding
  26952. x += prevX;
  26953. y += prevY;
  26954. prevX = x;
  26955. prevY = y;
  26956. // Dequantize
  26957. result.push([x / encodeScale, y / encodeScale]);
  26958. }
  26959. return result;
  26960. }
  26961. /**
  26962. * @alias module:echarts/coord/geo/parseGeoJson
  26963. * @param {Object} geoJson
  26964. * @return {module:zrender/container/Group}
  26965. */
  26966. var parseGeoJSON = function (geoJson) {
  26967. decode(geoJson);
  26968. return map(filter(geoJson.features, function (featureObj) {
  26969. // Output of mapshaper may have geometry null
  26970. return featureObj.geometry
  26971. && featureObj.properties
  26972. && featureObj.geometry.coordinates.length > 0;
  26973. }), function (featureObj) {
  26974. var properties = featureObj.properties;
  26975. var geo = featureObj.geometry;
  26976. var coordinates = geo.coordinates;
  26977. var geometries = [];
  26978. if (geo.type === 'Polygon') {
  26979. geometries.push({
  26980. type: 'polygon',
  26981. // According to the GeoJSON specification.
  26982. // First must be exterior, and the rest are all interior(holes).
  26983. exterior: coordinates[0],
  26984. interiors: coordinates.slice(1)
  26985. });
  26986. }
  26987. if (geo.type === 'MultiPolygon') {
  26988. each$1(coordinates, function (item) {
  26989. if (item[0]) {
  26990. geometries.push({
  26991. type: 'polygon',
  26992. exterior: item[0],
  26993. interiors: item.slice(1)
  26994. });
  26995. }
  26996. });
  26997. }
  26998. var region = new Region(
  26999. properties.name,
  27000. geometries,
  27001. properties.cp
  27002. );
  27003. region.properties = properties;
  27004. return region;
  27005. });
  27006. };
  27007. var linearMap$1 = linearMap;
  27008. function fixExtentWithBands(extent, nTick) {
  27009. var size = extent[1] - extent[0];
  27010. var len = nTick;
  27011. var margin = size / len / 2;
  27012. extent[0] += margin;
  27013. extent[1] -= margin;
  27014. }
  27015. var normalizedExtent = [0, 1];
  27016. /**
  27017. * @name module:echarts/coord/CartesianAxis
  27018. * @constructor
  27019. */
  27020. var Axis = function (dim, scale, extent) {
  27021. /**
  27022. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'
  27023. * @type {string}
  27024. */
  27025. this.dim = dim;
  27026. /**
  27027. * Axis scale
  27028. * @type {module:echarts/coord/scale/*}
  27029. */
  27030. this.scale = scale;
  27031. /**
  27032. * @type {Array.<number>}
  27033. * @private
  27034. */
  27035. this._extent = extent || [0, 0];
  27036. /**
  27037. * @type {boolean}
  27038. */
  27039. this.inverse = false;
  27040. /**
  27041. * Usually true when axis has a ordinal scale
  27042. * @type {boolean}
  27043. */
  27044. this.onBand = false;
  27045. /**
  27046. * @private
  27047. * @type {number}
  27048. */
  27049. this._labelInterval;
  27050. };
  27051. Axis.prototype = {
  27052. constructor: Axis,
  27053. /**
  27054. * If axis extent contain given coord
  27055. * @param {number} coord
  27056. * @return {boolean}
  27057. */
  27058. contain: function (coord) {
  27059. var extent = this._extent;
  27060. var min = Math.min(extent[0], extent[1]);
  27061. var max = Math.max(extent[0], extent[1]);
  27062. return coord >= min && coord <= max;
  27063. },
  27064. /**
  27065. * If axis extent contain given data
  27066. * @param {number} data
  27067. * @return {boolean}
  27068. */
  27069. containData: function (data) {
  27070. return this.contain(this.dataToCoord(data));
  27071. },
  27072. /**
  27073. * Get coord extent.
  27074. * @return {Array.<number>}
  27075. */
  27076. getExtent: function () {
  27077. return this._extent.slice();
  27078. },
  27079. /**
  27080. * Get precision used for formatting
  27081. * @param {Array.<number>} [dataExtent]
  27082. * @return {number}
  27083. */
  27084. getPixelPrecision: function (dataExtent) {
  27085. return getPixelPrecision(
  27086. dataExtent || this.scale.getExtent(),
  27087. this._extent
  27088. );
  27089. },
  27090. /**
  27091. * Set coord extent
  27092. * @param {number} start
  27093. * @param {number} end
  27094. */
  27095. setExtent: function (start, end) {
  27096. var extent = this._extent;
  27097. extent[0] = start;
  27098. extent[1] = end;
  27099. },
  27100. /**
  27101. * Convert data to coord. Data is the rank if it has an ordinal scale
  27102. * @param {number} data
  27103. * @param {boolean} clamp
  27104. * @return {number}
  27105. */
  27106. dataToCoord: function (data, clamp) {
  27107. var extent = this._extent;
  27108. var scale = this.scale;
  27109. data = scale.normalize(data);
  27110. if (this.onBand && scale.type === 'ordinal') {
  27111. extent = extent.slice();
  27112. fixExtentWithBands(extent, scale.count());
  27113. }
  27114. return linearMap$1(data, normalizedExtent, extent, clamp);
  27115. },
  27116. /**
  27117. * Convert coord to data. Data is the rank if it has an ordinal scale
  27118. * @param {number} coord
  27119. * @param {boolean} clamp
  27120. * @return {number}
  27121. */
  27122. coordToData: function (coord, clamp) {
  27123. var extent = this._extent;
  27124. var scale = this.scale;
  27125. if (this.onBand && scale.type === 'ordinal') {
  27126. extent = extent.slice();
  27127. fixExtentWithBands(extent, scale.count());
  27128. }
  27129. var t = linearMap$1(coord, extent, normalizedExtent, clamp);
  27130. return this.scale.scale(t);
  27131. },
  27132. /**
  27133. * Convert pixel point to data in axis
  27134. * @param {Array.<number>} point
  27135. * @param {boolean} clamp
  27136. * @return {number} data
  27137. */
  27138. pointToData: function (point, clamp) {
  27139. // Should be implemented in derived class if necessary.
  27140. },
  27141. /**
  27142. * @return {Array.<number>}
  27143. */
  27144. getTicksCoords: function (alignWithLabel) {
  27145. if (this.onBand && !alignWithLabel) {
  27146. var bands = this.getBands();
  27147. var coords = [];
  27148. for (var i = 0; i < bands.length; i++) {
  27149. coords.push(bands[i][0]);
  27150. }
  27151. if (bands[i - 1]) {
  27152. coords.push(bands[i - 1][1]);
  27153. }
  27154. return coords;
  27155. }
  27156. else {
  27157. return map(this.scale.getTicks(), this.dataToCoord, this);
  27158. }
  27159. },
  27160. /**
  27161. * Coords of labels are on the ticks or on the middle of bands
  27162. * @return {Array.<number>}
  27163. */
  27164. getLabelsCoords: function () {
  27165. return map(this.scale.getTicks(), this.dataToCoord, this);
  27166. },
  27167. /**
  27168. * Get bands.
  27169. *
  27170. * If axis has labels [1, 2, 3, 4]. Bands on the axis are
  27171. * |---1---|---2---|---3---|---4---|.
  27172. *
  27173. * @return {Array}
  27174. */
  27175. // FIXME Situation when labels is on ticks
  27176. getBands: function () {
  27177. var extent = this.getExtent();
  27178. var bands = [];
  27179. var len = this.scale.count();
  27180. var start = extent[0];
  27181. var end = extent[1];
  27182. var span = end - start;
  27183. for (var i = 0; i < len; i++) {
  27184. bands.push([
  27185. span * i / len + start,
  27186. span * (i + 1) / len + start
  27187. ]);
  27188. }
  27189. return bands;
  27190. },
  27191. /**
  27192. * Get width of band
  27193. * @return {number}
  27194. */
  27195. getBandWidth: function () {
  27196. var axisExtent = this._extent;
  27197. var dataExtent = this.scale.getExtent();
  27198. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  27199. // Fix #2728, avoid NaN when only one data.
  27200. len === 0 && (len = 1);
  27201. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  27202. return Math.abs(size) / len;
  27203. },
  27204. /**
  27205. * @abstract
  27206. * @return {boolean} Is horizontal
  27207. */
  27208. isHorizontal: null,
  27209. /**
  27210. * @abstract
  27211. * @return {number} Get axis rotate, by degree.
  27212. */
  27213. getRotate: null,
  27214. /**
  27215. * Get interval of the axis label.
  27216. * To get precise result, at least one of `getRotate` and `isHorizontal`
  27217. * should be implemented.
  27218. * @return {number}
  27219. */
  27220. getLabelInterval: function () {
  27221. var labelInterval = this._labelInterval;
  27222. if (!labelInterval) {
  27223. var axisModel = this.model;
  27224. var labelModel = axisModel.getModel('axisLabel');
  27225. labelInterval = labelModel.get('interval');
  27226. if (this.type === 'category'
  27227. && (labelInterval == null || labelInterval === 'auto')
  27228. ) {
  27229. labelInterval = getAxisLabelInterval(
  27230. map(this.scale.getTicks(), this.dataToCoord, this),
  27231. axisModel.getFormattedLabels(),
  27232. labelModel.getFont(),
  27233. this.getRotate
  27234. ? this.getRotate()
  27235. : (this.isHorizontal && !this.isHorizontal())
  27236. ? 90
  27237. : 0,
  27238. labelModel.get('rotate')
  27239. );
  27240. }
  27241. this._labelInterval = labelInterval;
  27242. }
  27243. return labelInterval;
  27244. }
  27245. };
  27246. /**
  27247. * Do not mount those modules on 'src/echarts' for better tree shaking.
  27248. */
  27249. var parseGeoJson = parseGeoJSON;
  27250. var ecUtil = {};
  27251. each$1([
  27252. 'map', 'each', 'filter', 'indexOf', 'inherits', 'reduce', 'filter',
  27253. 'bind', 'curry', 'isArray', 'isString', 'isObject', 'isFunction',
  27254. 'extend', 'defaults', 'clone', 'merge'
  27255. ],
  27256. function (name) {
  27257. ecUtil[name] = zrUtil[name];
  27258. }
  27259. );
  27260. var DatasetModel = extendComponentModel({
  27261. type: 'dataset',
  27262. /**
  27263. * @protected
  27264. */
  27265. defaultOption: {
  27266. // 'row', 'column'
  27267. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  27268. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  27269. sourceHeader: null,
  27270. dimensions: null,
  27271. source: null
  27272. },
  27273. optionUpdated: function () {
  27274. detectSourceFormat(this);
  27275. }
  27276. });
  27277. extendComponentView({type: 'dataset'});
  27278. SeriesModel.extend({
  27279. type: 'series.line',
  27280. dependencies: ['grid', 'polar'],
  27281. getInitialData: function (option, ecModel) {
  27282. if (__DEV__) {
  27283. var coordSys = option.coordinateSystem;
  27284. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  27285. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  27286. }
  27287. }
  27288. return createListFromArray(this.getSource(), this);
  27289. },
  27290. defaultOption: {
  27291. zlevel: 0, // 一级层叠
  27292. z: 2, // 二级层叠
  27293. coordinateSystem: 'cartesian2d',
  27294. legendHoverLink: true,
  27295. hoverAnimation: true,
  27296. // stack: null
  27297. // xAxisIndex: 0,
  27298. // yAxisIndex: 0,
  27299. // polarIndex: 0,
  27300. // If clip the overflow value
  27301. clipOverflow: true,
  27302. // cursor: null,
  27303. label: {
  27304. position: 'top'
  27305. },
  27306. // itemStyle: {
  27307. // },
  27308. lineStyle: {
  27309. width: 2,
  27310. type: 'solid'
  27311. },
  27312. // areaStyle: {
  27313. // origin of areaStyle. Valid values:
  27314. // `'auto'/null/undefined`: from axisLine to data
  27315. // `'start'`: from min to data
  27316. // `'end'`: from data to max
  27317. // origin: 'auto'
  27318. // },
  27319. // false, 'start', 'end', 'middle'
  27320. step: false,
  27321. // Disabled if step is true
  27322. smooth: false,
  27323. smoothMonotone: null,
  27324. // 拐点图形类型
  27325. symbol: 'emptyCircle',
  27326. // 拐点图形大小
  27327. symbolSize: 4,
  27328. // 拐点图形旋转控制
  27329. symbolRotate: null,
  27330. // 是否显示 symbol, 只有在 tooltip hover 的时候显示
  27331. showSymbol: true,
  27332. // 标志图形默认只有主轴显示(随主轴标签间隔隐藏策略)
  27333. showAllSymbol: false,
  27334. // 是否连接断点
  27335. connectNulls: false,
  27336. // 数据过滤,'average', 'max', 'min', 'sum'
  27337. sampling: 'none',
  27338. animationEasing: 'linear',
  27339. // Disable progressive
  27340. progressive: 0,
  27341. hoverLayerThreshold: Infinity
  27342. }
  27343. });
  27344. /**
  27345. * @param {module:echarts/data/List} data
  27346. * @param {number} dataIndex
  27347. * @return {string} label string. Not null/undefined
  27348. */
  27349. function getDefaultLabel(data, dataIndex) {
  27350. var labelDims = data.mapDimension('defaultedLabel', true);
  27351. var len = labelDims.length;
  27352. // Simple optimization (in lots of cases, label dims length is 1)
  27353. if (len === 1) {
  27354. return retrieveRawValue(data, dataIndex, labelDims[0]);
  27355. }
  27356. else if (len) {
  27357. var vals = [];
  27358. for (var i = 0; i < labelDims.length; i++) {
  27359. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  27360. vals.push(val);
  27361. }
  27362. return vals.join(' ');
  27363. }
  27364. }
  27365. /**
  27366. * @module echarts/chart/helper/Symbol
  27367. */
  27368. function getSymbolSize(data, idx) {
  27369. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  27370. return symbolSize instanceof Array
  27371. ? symbolSize.slice()
  27372. : [+symbolSize, +symbolSize];
  27373. }
  27374. function getScale(symbolSize) {
  27375. return [symbolSize[0] / 2, symbolSize[1] / 2];
  27376. }
  27377. /**
  27378. * @constructor
  27379. * @alias {module:echarts/chart/helper/Symbol}
  27380. * @param {module:echarts/data/List} data
  27381. * @param {number} idx
  27382. * @extends {module:zrender/graphic/Group}
  27383. */
  27384. function SymbolClz$1(data, idx, seriesScope) {
  27385. Group.call(this);
  27386. this.updateData(data, idx, seriesScope);
  27387. }
  27388. var symbolProto = SymbolClz$1.prototype;
  27389. function driftSymbol(dx, dy) {
  27390. this.parent.drift(dx, dy);
  27391. }
  27392. symbolProto._createSymbol = function (symbolType, data, idx, symbolSize) {
  27393. // Remove paths created before
  27394. this.removeAll();
  27395. var color = data.getItemVisual(idx, 'color');
  27396. // var symbolPath = createSymbol(
  27397. // symbolType, -0.5, -0.5, 1, 1, color
  27398. // );
  27399. // If width/height are set too small (e.g., set to 1) on ios10
  27400. // and macOS Sierra, a circle stroke become a rect, no matter what
  27401. // the scale is set. So we set width/height as 2. See #4150.
  27402. var symbolPath = createSymbol(
  27403. symbolType, -1, -1, 2, 2, color
  27404. );
  27405. symbolPath.attr({
  27406. z2: 100,
  27407. culling: true,
  27408. scale: getScale(symbolSize)
  27409. });
  27410. // Rewrite drift method
  27411. symbolPath.drift = driftSymbol;
  27412. this._symbolType = symbolType;
  27413. this.add(symbolPath);
  27414. };
  27415. /**
  27416. * Stop animation
  27417. * @param {boolean} toLastFrame
  27418. */
  27419. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  27420. this.childAt(0).stopAnimation(toLastFrame);
  27421. };
  27422. /**
  27423. * FIXME:
  27424. * Caution: This method breaks the encapsulation of this module,
  27425. * but it indeed brings convenience. So do not use the method
  27426. * unless you detailedly know all the implements of `Symbol`,
  27427. * especially animation.
  27428. *
  27429. * Get symbol path element.
  27430. */
  27431. symbolProto.getSymbolPath = function () {
  27432. return this.childAt(0);
  27433. };
  27434. /**
  27435. * Get scale(aka, current symbol size).
  27436. * Including the change caused by animation
  27437. */
  27438. symbolProto.getScale = function () {
  27439. return this.childAt(0).scale;
  27440. };
  27441. /**
  27442. * Highlight symbol
  27443. */
  27444. symbolProto.highlight = function () {
  27445. this.childAt(0).trigger('emphasis');
  27446. };
  27447. /**
  27448. * Downplay symbol
  27449. */
  27450. symbolProto.downplay = function () {
  27451. this.childAt(0).trigger('normal');
  27452. };
  27453. /**
  27454. * @param {number} zlevel
  27455. * @param {number} z
  27456. */
  27457. symbolProto.setZ = function (zlevel, z) {
  27458. var symbolPath = this.childAt(0);
  27459. symbolPath.zlevel = zlevel;
  27460. symbolPath.z = z;
  27461. };
  27462. symbolProto.setDraggable = function (draggable) {
  27463. var symbolPath = this.childAt(0);
  27464. symbolPath.draggable = draggable;
  27465. symbolPath.cursor = draggable ? 'move' : 'pointer';
  27466. };
  27467. /**
  27468. * Update symbol properties
  27469. * @param {module:echarts/data/List} data
  27470. * @param {number} idx
  27471. * @param {Object} [seriesScope]
  27472. * @param {Object} [seriesScope.itemStyle]
  27473. * @param {Object} [seriesScope.hoverItemStyle]
  27474. * @param {Object} [seriesScope.symbolRotate]
  27475. * @param {Object} [seriesScope.symbolOffset]
  27476. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  27477. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  27478. * @param {boolean} [seriesScope.hoverAnimation]
  27479. * @param {Object} [seriesScope.cursorStyle]
  27480. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  27481. * @param {string} [seriesScope.symbolInnerColor]
  27482. * @param {Object} [seriesScope.fadeIn=false]
  27483. */
  27484. symbolProto.updateData = function (data, idx, seriesScope) {
  27485. this.silent = false;
  27486. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  27487. var seriesModel = data.hostModel;
  27488. var symbolSize = getSymbolSize(data, idx);
  27489. var isInit = symbolType !== this._symbolType;
  27490. if (isInit) {
  27491. this._createSymbol(symbolType, data, idx, symbolSize);
  27492. }
  27493. else {
  27494. var symbolPath = this.childAt(0);
  27495. symbolPath.silent = false;
  27496. updateProps(symbolPath, {
  27497. scale: getScale(symbolSize)
  27498. }, seriesModel, idx);
  27499. }
  27500. this._updateCommon(data, idx, symbolSize, seriesScope);
  27501. if (isInit) {
  27502. var symbolPath = this.childAt(0);
  27503. var fadeIn = seriesScope && seriesScope.fadeIn;
  27504. var target = {scale: symbolPath.scale.slice()};
  27505. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  27506. symbolPath.scale = [0, 0];
  27507. fadeIn && (symbolPath.style.opacity = 0);
  27508. initProps(symbolPath, target, seriesModel, idx);
  27509. }
  27510. this._seriesModel = seriesModel;
  27511. };
  27512. // Update common properties
  27513. var normalStyleAccessPath = ['itemStyle'];
  27514. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  27515. var normalLabelAccessPath = ['label'];
  27516. var emphasisLabelAccessPath = ['emphasis', 'label'];
  27517. /**
  27518. * @param {module:echarts/data/List} data
  27519. * @param {number} idx
  27520. * @param {Array.<number>} symbolSize
  27521. * @param {Object} [seriesScope]
  27522. */
  27523. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  27524. var symbolPath = this.childAt(0);
  27525. var seriesModel = data.hostModel;
  27526. var color = data.getItemVisual(idx, 'color');
  27527. // Reset style
  27528. if (symbolPath.type !== 'image') {
  27529. symbolPath.useStyle({
  27530. strokeNoScale: true
  27531. });
  27532. }
  27533. var itemStyle = seriesScope && seriesScope.itemStyle;
  27534. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  27535. var symbolRotate = seriesScope && seriesScope.symbolRotate;
  27536. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  27537. var labelModel = seriesScope && seriesScope.labelModel;
  27538. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  27539. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  27540. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  27541. if (!seriesScope || data.hasItemOption) {
  27542. var itemModel = (seriesScope && seriesScope.itemModel)
  27543. ? seriesScope.itemModel : data.getItemModel(idx);
  27544. // Color must be excluded.
  27545. // Because symbol provide setColor individually to set fill and stroke
  27546. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  27547. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  27548. symbolRotate = itemModel.getShallow('symbolRotate');
  27549. symbolOffset = itemModel.getShallow('symbolOffset');
  27550. labelModel = itemModel.getModel(normalLabelAccessPath);
  27551. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  27552. hoverAnimation = itemModel.getShallow('hoverAnimation');
  27553. cursorStyle = itemModel.getShallow('cursor');
  27554. }
  27555. else {
  27556. hoverItemStyle = extend({}, hoverItemStyle);
  27557. }
  27558. var elStyle = symbolPath.style;
  27559. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  27560. if (symbolOffset) {
  27561. symbolPath.attr('position', [
  27562. parsePercent$1(symbolOffset[0], symbolSize[0]),
  27563. parsePercent$1(symbolOffset[1], symbolSize[1])
  27564. ]);
  27565. }
  27566. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  27567. // PENDING setColor before setStyle!!!
  27568. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  27569. symbolPath.setStyle(itemStyle);
  27570. var opacity = data.getItemVisual(idx, 'opacity');
  27571. if (opacity != null) {
  27572. elStyle.opacity = opacity;
  27573. }
  27574. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  27575. setLabelStyle(
  27576. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  27577. {
  27578. labelFetcher: seriesModel,
  27579. labelDataIndex: idx,
  27580. defaultText: getLabelDefaultText,
  27581. isRectText: true,
  27582. autoColor: color
  27583. }
  27584. );
  27585. // Do not execute util needed.
  27586. function getLabelDefaultText(idx, opt) {
  27587. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  27588. }
  27589. symbolPath.off('mouseover')
  27590. .off('mouseout')
  27591. .off('emphasis')
  27592. .off('normal');
  27593. symbolPath.hoverStyle = hoverItemStyle;
  27594. // FIXME
  27595. // Do not use symbol.trigger('emphasis'), but use symbol.highlight() instead.
  27596. setHoverStyle(symbolPath);
  27597. var scale = getScale(symbolSize);
  27598. if (hoverAnimation && seriesModel.isAnimationEnabled()) {
  27599. var onEmphasis = function() {
  27600. // Do not support this hover animation util some scenario required.
  27601. // Animation can only be supported in hover layer when using `el.incremetal`.
  27602. if (this.incremental) {
  27603. return;
  27604. }
  27605. var ratio = scale[1] / scale[0];
  27606. this.animateTo({
  27607. scale: [
  27608. Math.max(scale[0] * 1.1, scale[0] + 3),
  27609. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  27610. ]
  27611. }, 400, 'elasticOut');
  27612. };
  27613. var onNormal = function() {
  27614. if (this.incremental) {
  27615. return;
  27616. }
  27617. this.animateTo({
  27618. scale: scale
  27619. }, 400, 'elasticOut');
  27620. };
  27621. symbolPath.on('mouseover', onEmphasis)
  27622. .on('mouseout', onNormal)
  27623. .on('emphasis', onEmphasis)
  27624. .on('normal', onNormal);
  27625. }
  27626. };
  27627. /**
  27628. * @param {Function} cb
  27629. * @param {Object} [opt]
  27630. * @param {Object} [opt.keepLabel=true]
  27631. */
  27632. symbolProto.fadeOut = function (cb, opt) {
  27633. var symbolPath = this.childAt(0);
  27634. // Avoid mistaken hover when fading out
  27635. this.silent = symbolPath.silent = true;
  27636. // Not show text when animating
  27637. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  27638. updateProps(
  27639. symbolPath,
  27640. {
  27641. style: {opacity: 0},
  27642. scale: [0, 0]
  27643. },
  27644. this._seriesModel,
  27645. this.dataIndex,
  27646. cb
  27647. );
  27648. };
  27649. inherits(SymbolClz$1, Group);
  27650. /**
  27651. * @module echarts/chart/helper/SymbolDraw
  27652. */
  27653. /**
  27654. * @constructor
  27655. * @alias module:echarts/chart/helper/SymbolDraw
  27656. * @param {module:zrender/graphic/Group} [symbolCtor]
  27657. */
  27658. function SymbolDraw(symbolCtor) {
  27659. this.group = new Group();
  27660. this._symbolCtor = symbolCtor || SymbolClz$1;
  27661. }
  27662. var symbolDrawProto = SymbolDraw.prototype;
  27663. function symbolNeedsDraw(data, point, idx, opt) {
  27664. return point && !isNaN(point[0]) && !isNaN(point[1])
  27665. && !(opt.isIgnore && opt.isIgnore(idx))
  27666. // We do not set clipShape on group, because it will
  27667. // cut part of the symbol element shape.
  27668. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1]))
  27669. && data.getItemVisual(idx, 'symbol') !== 'none';
  27670. }
  27671. /**
  27672. * Update symbols draw by new data
  27673. * @param {module:echarts/data/List} data
  27674. * @param {Object} [opt] Or isIgnore
  27675. * @param {Function} [opt.isIgnore]
  27676. * @param {Object} [opt.clipShape]
  27677. */
  27678. symbolDrawProto.updateData = function (data, opt) {
  27679. opt = normalizeUpdateOpt(opt);
  27680. var group = this.group;
  27681. var seriesModel = data.hostModel;
  27682. var oldData = this._data;
  27683. var SymbolCtor = this._symbolCtor;
  27684. var seriesScope = makeSeriesScope(data);
  27685. // There is no oldLineData only when first rendering or switching from
  27686. // stream mode to normal mode, where previous elements should be removed.
  27687. if (!oldData) {
  27688. group.removeAll();
  27689. }
  27690. data.diff(oldData)
  27691. .add(function (newIdx) {
  27692. var point = data.getItemLayout(newIdx);
  27693. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  27694. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  27695. symbolEl.attr('position', point);
  27696. data.setItemGraphicEl(newIdx, symbolEl);
  27697. group.add(symbolEl);
  27698. }
  27699. })
  27700. .update(function (newIdx, oldIdx) {
  27701. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  27702. var point = data.getItemLayout(newIdx);
  27703. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  27704. group.remove(symbolEl);
  27705. return;
  27706. }
  27707. if (!symbolEl) {
  27708. symbolEl = new SymbolCtor(data, newIdx);
  27709. symbolEl.attr('position', point);
  27710. }
  27711. else {
  27712. symbolEl.updateData(data, newIdx, seriesScope);
  27713. updateProps(symbolEl, {
  27714. position: point
  27715. }, seriesModel);
  27716. }
  27717. // Add back
  27718. group.add(symbolEl);
  27719. data.setItemGraphicEl(newIdx, symbolEl);
  27720. })
  27721. .remove(function (oldIdx) {
  27722. var el = oldData.getItemGraphicEl(oldIdx);
  27723. el && el.fadeOut(function () {
  27724. group.remove(el);
  27725. });
  27726. })
  27727. .execute();
  27728. this._data = data;
  27729. };
  27730. symbolDrawProto.isPersistent = function () {
  27731. return true;
  27732. };
  27733. symbolDrawProto.updateLayout = function () {
  27734. var data = this._data;
  27735. if (data) {
  27736. // Not use animation
  27737. data.eachItemGraphicEl(function (el, idx) {
  27738. var point = data.getItemLayout(idx);
  27739. el.attr('position', point);
  27740. });
  27741. }
  27742. };
  27743. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  27744. this._seriesScope = makeSeriesScope(data);
  27745. this._data = null;
  27746. this.group.removeAll();
  27747. };
  27748. /**
  27749. * Update symbols draw by new data
  27750. * @param {module:echarts/data/List} data
  27751. * @param {Object} [opt] Or isIgnore
  27752. * @param {Function} [opt.isIgnore]
  27753. * @param {Object} [opt.clipShape]
  27754. */
  27755. symbolDrawProto.incrementalUpdate = function (taskParams, data, opt) {
  27756. opt = normalizeUpdateOpt(opt);
  27757. function updateIncrementalAndHover(el) {
  27758. if (!el.isGroup) {
  27759. el.incremental = el.useHoverLayer = true;
  27760. }
  27761. }
  27762. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  27763. var point = data.getItemLayout(idx);
  27764. if (symbolNeedsDraw(data, point, idx, opt)) {
  27765. var el = new this._symbolCtor(data, idx, this._seriesScope);
  27766. el.traverse(updateIncrementalAndHover);
  27767. el.attr('position', point);
  27768. this.group.add(el);
  27769. data.setItemGraphicEl(idx, el);
  27770. }
  27771. }
  27772. };
  27773. function normalizeUpdateOpt(opt) {
  27774. if (opt != null && !isObject$1(opt)) {
  27775. opt = {isIgnore: opt};
  27776. }
  27777. return opt || {};
  27778. }
  27779. symbolDrawProto.remove = function (enableAnimation) {
  27780. var group = this.group;
  27781. var data = this._data;
  27782. // Incremental model do not have this._data.
  27783. if (data && enableAnimation) {
  27784. data.eachItemGraphicEl(function (el) {
  27785. el.fadeOut(function () {
  27786. group.remove(el);
  27787. });
  27788. });
  27789. }
  27790. else {
  27791. group.removeAll();
  27792. }
  27793. };
  27794. function makeSeriesScope(data) {
  27795. var seriesModel = data.hostModel;
  27796. return {
  27797. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  27798. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  27799. symbolRotate: seriesModel.get('symbolRotate'),
  27800. symbolOffset: seriesModel.get('symbolOffset'),
  27801. hoverAnimation: seriesModel.get('hoverAnimation'),
  27802. labelModel: seriesModel.getModel('label'),
  27803. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  27804. cursorStyle: seriesModel.get('cursor')
  27805. };
  27806. }
  27807. /**
  27808. * @param {Object} coordSys
  27809. * @param {module:echarts/data/List} data
  27810. * @param {string} valueOrigin lineSeries.option.areaStyle.origin
  27811. */
  27812. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  27813. var baseAxis = coordSys.getBaseAxis();
  27814. var valueAxis = coordSys.getOtherAxis(baseAxis);
  27815. var valueStart = getValueStart(valueAxis, valueOrigin);
  27816. var baseAxisDim = baseAxis.dim;
  27817. var valueAxisDim = valueAxis.dim;
  27818. var valueDim = data.mapDimension(valueAxisDim);
  27819. var baseDim = data.mapDimension(baseAxisDim);
  27820. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  27821. var stacked = isDimensionStacked(data, valueDim, baseDim);
  27822. var dataDimsForPoint = map(coordSys.dimensions, function (coordDim) {
  27823. return data.mapDimension(coordDim);
  27824. });
  27825. return {
  27826. dataDimsForPoint: dataDimsForPoint,
  27827. valueStart: valueStart,
  27828. valueAxisDim: valueAxisDim,
  27829. baseAxisDim: baseAxisDim,
  27830. stacked: stacked,
  27831. valueDim: valueDim,
  27832. baseDim: baseDim,
  27833. baseDataOffset: baseDataOffset,
  27834. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  27835. };
  27836. }
  27837. function getValueStart(valueAxis, valueOrigin) {
  27838. var valueStart = 0;
  27839. var extent = valueAxis.scale.getExtent();
  27840. if (valueOrigin === 'start') {
  27841. valueStart = extent[0];
  27842. }
  27843. else if (valueOrigin === 'end') {
  27844. valueStart = extent[1];
  27845. }
  27846. // auto
  27847. else {
  27848. // Both positive
  27849. if (extent[0] > 0) {
  27850. valueStart = extent[0];
  27851. }
  27852. // Both negative
  27853. else if (extent[1] < 0) {
  27854. valueStart = extent[1];
  27855. }
  27856. // If is one positive, and one negative, onZero shall be true
  27857. }
  27858. return valueStart;
  27859. }
  27860. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  27861. var value = NaN;
  27862. if (dataCoordInfo.stacked) {
  27863. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  27864. }
  27865. if (isNaN(value)) {
  27866. value = dataCoordInfo.valueStart;
  27867. }
  27868. var baseDataOffset = dataCoordInfo.baseDataOffset;
  27869. var stackedData = [];
  27870. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  27871. stackedData[1 - baseDataOffset] = value;
  27872. return coordSys.dataToPoint(stackedData);
  27873. }
  27874. // var arrayDiff = require('zrender/src/core/arrayDiff');
  27875. // 'zrender/src/core/arrayDiff' has been used before, but it did
  27876. // not do well in performance when roam with fixed dataZoom window.
  27877. // function convertToIntId(newIdList, oldIdList) {
  27878. // // Generate int id instead of string id.
  27879. // // Compare string maybe slow in score function of arrDiff
  27880. // // Assume id in idList are all unique
  27881. // var idIndicesMap = {};
  27882. // var idx = 0;
  27883. // for (var i = 0; i < newIdList.length; i++) {
  27884. // idIndicesMap[newIdList[i]] = idx;
  27885. // newIdList[i] = idx++;
  27886. // }
  27887. // for (var i = 0; i < oldIdList.length; i++) {
  27888. // var oldId = oldIdList[i];
  27889. // // Same with newIdList
  27890. // if (idIndicesMap[oldId]) {
  27891. // oldIdList[i] = idIndicesMap[oldId];
  27892. // }
  27893. // else {
  27894. // oldIdList[i] = idx++;
  27895. // }
  27896. // }
  27897. // }
  27898. function diffData(oldData, newData) {
  27899. var diffResult = [];
  27900. newData.diff(oldData)
  27901. .add(function (idx) {
  27902. diffResult.push({cmd: '+', idx: idx});
  27903. })
  27904. .update(function (newIdx, oldIdx) {
  27905. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  27906. })
  27907. .remove(function (idx) {
  27908. diffResult.push({cmd: '-', idx: idx});
  27909. })
  27910. .execute();
  27911. return diffResult;
  27912. }
  27913. var lineAnimationDiff = function (
  27914. oldData, newData,
  27915. oldStackedOnPoints, newStackedOnPoints,
  27916. oldCoordSys, newCoordSys,
  27917. oldValueOrigin, newValueOrigin
  27918. ) {
  27919. var diff = diffData(oldData, newData);
  27920. // var newIdList = newData.mapArray(newData.getId);
  27921. // var oldIdList = oldData.mapArray(oldData.getId);
  27922. // convertToIntId(newIdList, oldIdList);
  27923. // // FIXME One data ?
  27924. // diff = arrayDiff(oldIdList, newIdList);
  27925. var currPoints = [];
  27926. var nextPoints = [];
  27927. // Points for stacking base line
  27928. var currStackedPoints = [];
  27929. var nextStackedPoints = [];
  27930. var status = [];
  27931. var sortedIndices = [];
  27932. var rawIndices = [];
  27933. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  27934. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  27935. for (var i = 0; i < diff.length; i++) {
  27936. var diffItem = diff[i];
  27937. var pointAdded = true;
  27938. // FIXME, animation is not so perfect when dataZoom window moves fast
  27939. // Which is in case remvoing or add more than one data in the tail or head
  27940. switch (diffItem.cmd) {
  27941. case '=':
  27942. var currentPt = oldData.getItemLayout(diffItem.idx);
  27943. var nextPt = newData.getItemLayout(diffItem.idx1);
  27944. // If previous data is NaN, use next point directly
  27945. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  27946. currentPt = nextPt.slice();
  27947. }
  27948. currPoints.push(currentPt);
  27949. nextPoints.push(nextPt);
  27950. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  27951. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  27952. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  27953. break;
  27954. case '+':
  27955. var idx = diffItem.idx;
  27956. currPoints.push(
  27957. oldCoordSys.dataToPoint([
  27958. newData.get(newDataOldCoordInfo.dataDimsForPoint[0], idx),
  27959. newData.get(newDataOldCoordInfo.dataDimsForPoint[1], idx)
  27960. ])
  27961. );
  27962. nextPoints.push(newData.getItemLayout(idx).slice());
  27963. currStackedPoints.push(
  27964. getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, idx)
  27965. );
  27966. nextStackedPoints.push(newStackedOnPoints[idx]);
  27967. rawIndices.push(newData.getRawIndex(idx));
  27968. break;
  27969. case '-':
  27970. var idx = diffItem.idx;
  27971. var rawIndex = oldData.getRawIndex(idx);
  27972. // Data is replaced. In the case of dynamic data queue
  27973. // FIXME FIXME FIXME
  27974. if (rawIndex !== idx) {
  27975. currPoints.push(oldData.getItemLayout(idx));
  27976. nextPoints.push(newCoordSys.dataToPoint([
  27977. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[0], idx),
  27978. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[1], idx)
  27979. ]));
  27980. currStackedPoints.push(oldStackedOnPoints[idx]);
  27981. nextStackedPoints.push(
  27982. getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, idx)
  27983. );
  27984. rawIndices.push(rawIndex);
  27985. }
  27986. else {
  27987. pointAdded = false;
  27988. }
  27989. }
  27990. // Original indices
  27991. if (pointAdded) {
  27992. status.push(diffItem);
  27993. sortedIndices.push(sortedIndices.length);
  27994. }
  27995. }
  27996. // Diff result may be crossed if all items are changed
  27997. // Sort by data index
  27998. sortedIndices.sort(function (a, b) {
  27999. return rawIndices[a] - rawIndices[b];
  28000. });
  28001. var sortedCurrPoints = [];
  28002. var sortedNextPoints = [];
  28003. var sortedCurrStackedPoints = [];
  28004. var sortedNextStackedPoints = [];
  28005. var sortedStatus = [];
  28006. for (var i = 0; i < sortedIndices.length; i++) {
  28007. var idx = sortedIndices[i];
  28008. sortedCurrPoints[i] = currPoints[idx];
  28009. sortedNextPoints[i] = nextPoints[idx];
  28010. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  28011. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  28012. sortedStatus[i] = status[idx];
  28013. }
  28014. return {
  28015. current: sortedCurrPoints,
  28016. next: sortedNextPoints,
  28017. stackedOnCurrent: sortedCurrStackedPoints,
  28018. stackedOnNext: sortedNextStackedPoints,
  28019. status: sortedStatus
  28020. };
  28021. };
  28022. // Poly path support NaN point
  28023. var vec2Min = min;
  28024. var vec2Max = max;
  28025. var scaleAndAdd$1 = scaleAndAdd;
  28026. var v2Copy = copy;
  28027. // Temporary variable
  28028. var v = [];
  28029. var cp0 = [];
  28030. var cp1 = [];
  28031. function isPointNull(p) {
  28032. return isNaN(p[0]) || isNaN(p[1]);
  28033. }
  28034. function drawSegment(
  28035. ctx, points, start, segLen, allLen,
  28036. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  28037. ) {
  28038. if (smoothMonotone == null) {
  28039. if (isMono(points, 'x')) {
  28040. return drawMono(ctx, points, start, segLen, allLen,
  28041. dir, smoothMin, smoothMax, smooth, 'x', connectNulls);
  28042. }
  28043. else if (isMono(points, 'y')) {
  28044. return drawMono(ctx, points, start, segLen, allLen,
  28045. dir, smoothMin, smoothMax, smooth, 'y', connectNulls);
  28046. }
  28047. else {
  28048. return drawNonMono.apply(this, arguments);
  28049. }
  28050. }
  28051. else if (smoothMonotone !== 'none' && isMono(points, smoothMonotone)) {
  28052. return drawMono.apply(this, arguments);
  28053. }
  28054. else {
  28055. return drawNonMono.apply(this, arguments);
  28056. }
  28057. }
  28058. /**
  28059. * Check if points is in monotone.
  28060. *
  28061. * @param {number[][]} points Array of points which is in [x, y] form
  28062. * @param {string} smoothMonotone 'x', 'y', or 'none', stating for which
  28063. * dimension that is checking.
  28064. * If is 'none', `drawNonMono` should be
  28065. * called.
  28066. * If is undefined, either being monotone
  28067. * in 'x' or 'y' will call `drawMono`.
  28068. */
  28069. function isMono(points, smoothMonotone) {
  28070. if (points.length <= 1) {
  28071. return true;
  28072. }
  28073. var dim = smoothMonotone === 'x' ? 0 : 1;
  28074. var last = points[0][dim];
  28075. var lastDiff = 0;
  28076. for (var i = 1; i < points.length; ++i) {
  28077. var diff = points[i][dim] - last;
  28078. if (!isNaN(diff) && !isNaN(lastDiff)
  28079. && diff !== 0 && lastDiff !== 0
  28080. && ((diff >= 0) !== (lastDiff >= 0))
  28081. ) {
  28082. return false;
  28083. }
  28084. if (!isNaN(diff) && diff !== 0) {
  28085. lastDiff = diff;
  28086. last = points[i][dim];
  28087. }
  28088. }
  28089. return true;
  28090. }
  28091. /**
  28092. * Draw smoothed line in monotone, in which only vertical or horizontal bezier
  28093. * control points will be used. This should be used when points are monotone
  28094. * either in x or y dimension.
  28095. */
  28096. function drawMono(
  28097. ctx, points, start, segLen, allLen,
  28098. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  28099. ) {
  28100. var prevIdx = 0;
  28101. var idx = start;
  28102. for (var k = 0; k < segLen; k++) {
  28103. var p = points[idx];
  28104. if (idx >= allLen || idx < 0) {
  28105. break;
  28106. }
  28107. if (isPointNull(p)) {
  28108. if (connectNulls) {
  28109. idx += dir;
  28110. continue;
  28111. }
  28112. break;
  28113. }
  28114. if (idx === start) {
  28115. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  28116. }
  28117. else {
  28118. if (smooth > 0) {
  28119. var prevP = points[prevIdx];
  28120. var dim = smoothMonotone === 'y' ? 1 : 0;
  28121. // Length of control point to p, either in x or y, but not both
  28122. var ctrlLen = (p[dim] - prevP[dim]) * smooth;
  28123. v2Copy(cp0, prevP);
  28124. cp0[dim] = prevP[dim] + ctrlLen;
  28125. v2Copy(cp1, p);
  28126. cp1[dim] = p[dim] - ctrlLen;
  28127. ctx.bezierCurveTo(
  28128. cp0[0], cp0[1],
  28129. cp1[0], cp1[1],
  28130. p[0], p[1]
  28131. );
  28132. }
  28133. else {
  28134. ctx.lineTo(p[0], p[1]);
  28135. }
  28136. }
  28137. prevIdx = idx;
  28138. idx += dir;
  28139. }
  28140. return k;
  28141. }
  28142. /**
  28143. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  28144. * situations. This should be used when points are non-monotone neither in x or
  28145. * y dimension.
  28146. */
  28147. function drawNonMono(
  28148. ctx, points, start, segLen, allLen,
  28149. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  28150. ) {
  28151. var prevIdx = 0;
  28152. var idx = start;
  28153. for (var k = 0; k < segLen; k++) {
  28154. var p = points[idx];
  28155. if (idx >= allLen || idx < 0) {
  28156. break;
  28157. }
  28158. if (isPointNull(p)) {
  28159. if (connectNulls) {
  28160. idx += dir;
  28161. continue;
  28162. }
  28163. break;
  28164. }
  28165. if (idx === start) {
  28166. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  28167. v2Copy(cp0, p);
  28168. }
  28169. else {
  28170. if (smooth > 0) {
  28171. var nextIdx = idx + dir;
  28172. var nextP = points[nextIdx];
  28173. if (connectNulls) {
  28174. // Find next point not null
  28175. while (nextP && isPointNull(points[nextIdx])) {
  28176. nextIdx += dir;
  28177. nextP = points[nextIdx];
  28178. }
  28179. }
  28180. var ratioNextSeg = 0.5;
  28181. var prevP = points[prevIdx];
  28182. var nextP = points[nextIdx];
  28183. // Last point
  28184. if (!nextP || isPointNull(nextP)) {
  28185. v2Copy(cp1, p);
  28186. }
  28187. else {
  28188. // If next data is null in not connect case
  28189. if (isPointNull(nextP) && !connectNulls) {
  28190. nextP = p;
  28191. }
  28192. sub(v, nextP, prevP);
  28193. var lenPrevSeg;
  28194. var lenNextSeg;
  28195. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  28196. var dim = smoothMonotone === 'x' ? 0 : 1;
  28197. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  28198. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  28199. }
  28200. else {
  28201. lenPrevSeg = dist(p, prevP);
  28202. lenNextSeg = dist(p, nextP);
  28203. }
  28204. // Use ratio of seg length
  28205. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  28206. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  28207. }
  28208. // Smooth constraint
  28209. vec2Min(cp0, cp0, smoothMax);
  28210. vec2Max(cp0, cp0, smoothMin);
  28211. vec2Min(cp1, cp1, smoothMax);
  28212. vec2Max(cp1, cp1, smoothMin);
  28213. ctx.bezierCurveTo(
  28214. cp0[0], cp0[1],
  28215. cp1[0], cp1[1],
  28216. p[0], p[1]
  28217. );
  28218. // cp0 of next segment
  28219. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  28220. }
  28221. else {
  28222. ctx.lineTo(p[0], p[1]);
  28223. }
  28224. }
  28225. prevIdx = idx;
  28226. idx += dir;
  28227. }
  28228. return k;
  28229. }
  28230. function getBoundingBox(points, smoothConstraint) {
  28231. var ptMin = [Infinity, Infinity];
  28232. var ptMax = [-Infinity, -Infinity];
  28233. if (smoothConstraint) {
  28234. for (var i = 0; i < points.length; i++) {
  28235. var pt = points[i];
  28236. if (pt[0] < ptMin[0]) { ptMin[0] = pt[0]; }
  28237. if (pt[1] < ptMin[1]) { ptMin[1] = pt[1]; }
  28238. if (pt[0] > ptMax[0]) { ptMax[0] = pt[0]; }
  28239. if (pt[1] > ptMax[1]) { ptMax[1] = pt[1]; }
  28240. }
  28241. }
  28242. return {
  28243. min: smoothConstraint ? ptMin : ptMax,
  28244. max: smoothConstraint ? ptMax : ptMin
  28245. };
  28246. }
  28247. var Polyline$1 = Path.extend({
  28248. type: 'ec-polyline',
  28249. shape: {
  28250. points: [],
  28251. smooth: 0,
  28252. smoothConstraint: true,
  28253. smoothMonotone: null,
  28254. connectNulls: false
  28255. },
  28256. style: {
  28257. fill: null,
  28258. stroke: '#000'
  28259. },
  28260. brush: fixClipWithShadow(Path.prototype.brush),
  28261. buildPath: function (ctx, shape) {
  28262. var points = shape.points;
  28263. var i = 0;
  28264. var len$$1 = points.length;
  28265. var result = getBoundingBox(points, shape.smoothConstraint);
  28266. if (shape.connectNulls) {
  28267. // Must remove first and last null values avoid draw error in polygon
  28268. for (; len$$1 > 0; len$$1--) {
  28269. if (!isPointNull(points[len$$1 - 1])) {
  28270. break;
  28271. }
  28272. }
  28273. for (; i < len$$1; i++) {
  28274. if (!isPointNull(points[i])) {
  28275. break;
  28276. }
  28277. }
  28278. }
  28279. while (i < len$$1) {
  28280. i += drawSegment(
  28281. ctx, points, i, len$$1, len$$1,
  28282. 1, result.min, result.max, shape.smooth,
  28283. shape.smoothMonotone, shape.connectNulls
  28284. ) + 1;
  28285. }
  28286. }
  28287. });
  28288. var Polygon$1 = Path.extend({
  28289. type: 'ec-polygon',
  28290. shape: {
  28291. points: [],
  28292. // Offset between stacked base points and points
  28293. stackedOnPoints: [],
  28294. smooth: 0,
  28295. stackedOnSmooth: 0,
  28296. smoothConstraint: true,
  28297. smoothMonotone: null,
  28298. connectNulls: false
  28299. },
  28300. brush: fixClipWithShadow(Path.prototype.brush),
  28301. buildPath: function (ctx, shape) {
  28302. var points = shape.points;
  28303. var stackedOnPoints = shape.stackedOnPoints;
  28304. var i = 0;
  28305. var len$$1 = points.length;
  28306. var smoothMonotone = shape.smoothMonotone;
  28307. var bbox = getBoundingBox(points, shape.smoothConstraint);
  28308. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  28309. if (shape.connectNulls) {
  28310. // Must remove first and last null values avoid draw error in polygon
  28311. for (; len$$1 > 0; len$$1--) {
  28312. if (!isPointNull(points[len$$1 - 1])) {
  28313. break;
  28314. }
  28315. }
  28316. for (; i < len$$1; i++) {
  28317. if (!isPointNull(points[i])) {
  28318. break;
  28319. }
  28320. }
  28321. }
  28322. while (i < len$$1) {
  28323. var k = drawSegment(
  28324. ctx, points, i, len$$1, len$$1,
  28325. 1, bbox.min, bbox.max, shape.smooth,
  28326. smoothMonotone, shape.connectNulls
  28327. );
  28328. drawSegment(
  28329. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  28330. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  28331. smoothMonotone, shape.connectNulls
  28332. );
  28333. i += k + 1;
  28334. ctx.closePath();
  28335. }
  28336. }
  28337. });
  28338. // FIXME step not support polar
  28339. function isPointsSame(points1, points2) {
  28340. if (points1.length !== points2.length) {
  28341. return;
  28342. }
  28343. for (var i = 0; i < points1.length; i++) {
  28344. var p1 = points1[i];
  28345. var p2 = points2[i];
  28346. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  28347. return;
  28348. }
  28349. }
  28350. return true;
  28351. }
  28352. function getSmooth(smooth) {
  28353. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.5 : 0);
  28354. }
  28355. function getAxisExtentWithGap(axis) {
  28356. var extent = axis.getGlobalExtent();
  28357. if (axis.onBand) {
  28358. // Remove extra 1px to avoid line miter in clipped edge
  28359. var halfBandWidth = axis.getBandWidth() / 2 - 1;
  28360. var dir = extent[1] > extent[0] ? 1 : -1;
  28361. extent[0] += dir * halfBandWidth;
  28362. extent[1] -= dir * halfBandWidth;
  28363. }
  28364. return extent;
  28365. }
  28366. /**
  28367. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  28368. * @param {module:echarts/data/List} data
  28369. * @param {Object} dataCoordInfo
  28370. * @param {Array.<Array.<number>>} points
  28371. */
  28372. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  28373. if (!dataCoordInfo.valueDim) {
  28374. return [];
  28375. }
  28376. var points = [];
  28377. for (var idx = 0, len = data.count(); idx < len; idx++) {
  28378. points.push(getStackedOnPoint(dataCoordInfo, coordSys, data, idx));
  28379. }
  28380. return points;
  28381. }
  28382. function createGridClipShape(cartesian, hasAnimation, seriesModel) {
  28383. var xExtent = getAxisExtentWithGap(cartesian.getAxis('x'));
  28384. var yExtent = getAxisExtentWithGap(cartesian.getAxis('y'));
  28385. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  28386. var x = Math.min(xExtent[0], xExtent[1]);
  28387. var y = Math.min(yExtent[0], yExtent[1]);
  28388. var width = Math.max(xExtent[0], xExtent[1]) - x;
  28389. var height = Math.max(yExtent[0], yExtent[1]) - y;
  28390. var lineWidth = seriesModel.get('lineStyle.width') || 2;
  28391. // Expand clip shape to avoid clipping when line value exceeds axis
  28392. var expandSize = seriesModel.get('clipOverflow') ? lineWidth / 2 : Math.max(width, height);
  28393. if (isHorizontal) {
  28394. y -= expandSize;
  28395. height += expandSize * 2;
  28396. }
  28397. else {
  28398. x -= expandSize;
  28399. width += expandSize * 2;
  28400. }
  28401. var clipPath = new Rect({
  28402. shape: {
  28403. x: x,
  28404. y: y,
  28405. width: width,
  28406. height: height
  28407. }
  28408. });
  28409. if (hasAnimation) {
  28410. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  28411. initProps(clipPath, {
  28412. shape: {
  28413. width: width,
  28414. height: height
  28415. }
  28416. }, seriesModel);
  28417. }
  28418. return clipPath;
  28419. }
  28420. function createPolarClipShape(polar, hasAnimation, seriesModel) {
  28421. var angleAxis = polar.getAngleAxis();
  28422. var radiusAxis = polar.getRadiusAxis();
  28423. var radiusExtent = radiusAxis.getExtent();
  28424. var angleExtent = angleAxis.getExtent();
  28425. var RADIAN = Math.PI / 180;
  28426. var clipPath = new Sector({
  28427. shape: {
  28428. cx: polar.cx,
  28429. cy: polar.cy,
  28430. r0: radiusExtent[0],
  28431. r: radiusExtent[1],
  28432. startAngle: -angleExtent[0] * RADIAN,
  28433. endAngle: -angleExtent[1] * RADIAN,
  28434. clockwise: angleAxis.inverse
  28435. }
  28436. });
  28437. if (hasAnimation) {
  28438. clipPath.shape.endAngle = -angleExtent[0] * RADIAN;
  28439. initProps(clipPath, {
  28440. shape: {
  28441. endAngle: -angleExtent[1] * RADIAN
  28442. }
  28443. }, seriesModel);
  28444. }
  28445. return clipPath;
  28446. }
  28447. function createClipShape(coordSys, hasAnimation, seriesModel) {
  28448. return coordSys.type === 'polar'
  28449. ? createPolarClipShape(coordSys, hasAnimation, seriesModel)
  28450. : createGridClipShape(coordSys, hasAnimation, seriesModel);
  28451. }
  28452. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  28453. var baseAxis = coordSys.getBaseAxis();
  28454. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  28455. var stepPoints = [];
  28456. for (var i = 0; i < points.length - 1; i++) {
  28457. var nextPt = points[i + 1];
  28458. var pt = points[i];
  28459. stepPoints.push(pt);
  28460. var stepPt = [];
  28461. switch (stepTurnAt) {
  28462. case 'end':
  28463. stepPt[baseIndex] = nextPt[baseIndex];
  28464. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  28465. // default is start
  28466. stepPoints.push(stepPt);
  28467. break;
  28468. case 'middle':
  28469. // default is start
  28470. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  28471. var stepPt2 = [];
  28472. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  28473. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  28474. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  28475. stepPoints.push(stepPt);
  28476. stepPoints.push(stepPt2);
  28477. break;
  28478. default:
  28479. stepPt[baseIndex] = pt[baseIndex];
  28480. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  28481. // default is start
  28482. stepPoints.push(stepPt);
  28483. }
  28484. }
  28485. // Last points
  28486. points[i] && stepPoints.push(points[i]);
  28487. return stepPoints;
  28488. }
  28489. function getVisualGradient(data, coordSys) {
  28490. var visualMetaList = data.getVisual('visualMeta');
  28491. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  28492. // When data.count() is 0, gradient range can not be calculated.
  28493. return;
  28494. }
  28495. if (coordSys.type !== 'cartesian2d') {
  28496. if (__DEV__) {
  28497. console.warn('Visual map on line style is only supported on cartesian2d.');
  28498. }
  28499. return;
  28500. }
  28501. var coordDim;
  28502. var visualMeta;
  28503. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  28504. var dimIndex = visualMetaList[i].dimension;
  28505. var dimName = data.dimensions[dimIndex];
  28506. var dimInfo = data.getDimensionInfo(dimName);
  28507. coordDim = dimInfo && dimInfo.coordDim;
  28508. // Can only be x or y
  28509. if (coordDim === 'x' || coordDim === 'y') {
  28510. visualMeta = visualMetaList[i];
  28511. break;
  28512. }
  28513. }
  28514. if (!visualMeta) {
  28515. if (__DEV__) {
  28516. console.warn('Visual map on line style only support x or y dimension.');
  28517. }
  28518. return;
  28519. }
  28520. // If the area to be rendered is bigger than area defined by LinearGradient,
  28521. // the canvas spec prescribes that the color of the first stop and the last
  28522. // stop should be used. But if two stops are added at offset 0, in effect
  28523. // browsers use the color of the second stop to render area outside
  28524. // LinearGradient. So we can only infinitesimally extend area defined in
  28525. // LinearGradient to render `outerColors`.
  28526. var axis = coordSys.getAxis(coordDim);
  28527. // dataToCoor mapping may not be linear, but must be monotonic.
  28528. var colorStops = map(visualMeta.stops, function (stop) {
  28529. return {
  28530. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  28531. color: stop.color
  28532. };
  28533. });
  28534. var stopLen = colorStops.length;
  28535. var outerColors = visualMeta.outerColors.slice();
  28536. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  28537. colorStops.reverse();
  28538. outerColors.reverse();
  28539. }
  28540. var tinyExtent = 10; // Arbitrary value: 10px
  28541. var minCoord = colorStops[0].coord - tinyExtent;
  28542. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  28543. var coordSpan = maxCoord - minCoord;
  28544. if (coordSpan < 1e-3) {
  28545. return 'transparent';
  28546. }
  28547. each$1(colorStops, function (stop) {
  28548. stop.offset = (stop.coord - minCoord) / coordSpan;
  28549. });
  28550. colorStops.push({
  28551. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  28552. color: outerColors[1] || 'transparent'
  28553. });
  28554. colorStops.unshift({ // notice colorStops.length have been changed.
  28555. offset: stopLen ? colorStops[0].offset : 0.5,
  28556. color: outerColors[0] || 'transparent'
  28557. });
  28558. // zrUtil.each(colorStops, function (colorStop) {
  28559. // // Make sure each offset has rounded px to avoid not sharp edge
  28560. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  28561. // });
  28562. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  28563. gradient[coordDim] = minCoord;
  28564. gradient[coordDim + '2'] = maxCoord;
  28565. return gradient;
  28566. }
  28567. Chart.extend({
  28568. type: 'line',
  28569. init: function () {
  28570. var lineGroup = new Group();
  28571. var symbolDraw = new SymbolDraw();
  28572. this.group.add(symbolDraw.group);
  28573. this._symbolDraw = symbolDraw;
  28574. this._lineGroup = lineGroup;
  28575. },
  28576. render: function (seriesModel, ecModel, api) {
  28577. var coordSys = seriesModel.coordinateSystem;
  28578. var group = this.group;
  28579. var data = seriesModel.getData();
  28580. var lineStyleModel = seriesModel.getModel('lineStyle');
  28581. var areaStyleModel = seriesModel.getModel('areaStyle');
  28582. var points = data.mapArray(data.getItemLayout);
  28583. var isCoordSysPolar = coordSys.type === 'polar';
  28584. var prevCoordSys = this._coordSys;
  28585. var symbolDraw = this._symbolDraw;
  28586. var polyline = this._polyline;
  28587. var polygon = this._polygon;
  28588. var lineGroup = this._lineGroup;
  28589. var hasAnimation = seriesModel.get('animation');
  28590. var isAreaChart = !areaStyleModel.isEmpty();
  28591. var valueOrigin = areaStyleModel.get('origin');
  28592. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  28593. var stackedOnPoints = getStackedOnPoints(coordSys, data, dataCoordInfo);
  28594. var showSymbol = seriesModel.get('showSymbol');
  28595. var isSymbolIgnore = showSymbol && !isCoordSysPolar && !seriesModel.get('showAllSymbol')
  28596. && this._getSymbolIgnoreFunc(data, coordSys);
  28597. // Remove temporary symbols
  28598. var oldData = this._data;
  28599. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  28600. if (el.__temp) {
  28601. group.remove(el);
  28602. oldData.setItemGraphicEl(idx, null);
  28603. }
  28604. });
  28605. // Remove previous created symbols if showSymbol changed to false
  28606. if (!showSymbol) {
  28607. symbolDraw.remove();
  28608. }
  28609. group.add(lineGroup);
  28610. // FIXME step not support polar
  28611. var step = !isCoordSysPolar && seriesModel.get('step');
  28612. // Initialization animation or coordinate system changed
  28613. if (
  28614. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  28615. ) {
  28616. showSymbol && symbolDraw.updateData(data, {
  28617. isIgnore: isSymbolIgnore,
  28618. clipShape: createClipShape(coordSys, false, seriesModel)
  28619. });
  28620. if (step) {
  28621. // TODO If stacked series is not step
  28622. points = turnPointsIntoStep(points, coordSys, step);
  28623. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  28624. }
  28625. polyline = this._newPolyline(points, coordSys, hasAnimation);
  28626. if (isAreaChart) {
  28627. polygon = this._newPolygon(
  28628. points, stackedOnPoints,
  28629. coordSys, hasAnimation
  28630. );
  28631. }
  28632. lineGroup.setClipPath(createClipShape(coordSys, true, seriesModel));
  28633. }
  28634. else {
  28635. if (isAreaChart && !polygon) {
  28636. // If areaStyle is added
  28637. polygon = this._newPolygon(
  28638. points, stackedOnPoints,
  28639. coordSys, hasAnimation
  28640. );
  28641. }
  28642. else if (polygon && !isAreaChart) {
  28643. // If areaStyle is removed
  28644. lineGroup.remove(polygon);
  28645. polygon = this._polygon = null;
  28646. }
  28647. var coordSysClipShape = createClipShape(coordSys, false, seriesModel);
  28648. // Update clipPath
  28649. lineGroup.setClipPath(coordSysClipShape);
  28650. // Always update, or it is wrong in the case turning on legend
  28651. // because points are not changed
  28652. showSymbol && symbolDraw.updateData(data, {
  28653. isIgnore: isSymbolIgnore,
  28654. clipShape: coordSysClipShape
  28655. });
  28656. // Stop symbol animation and sync with line points
  28657. // FIXME performance?
  28658. data.eachItemGraphicEl(function (el) {
  28659. el.stopAnimation(true);
  28660. });
  28661. // In the case data zoom triggerred refreshing frequently
  28662. // Data may not change if line has a category axis. So it should animate nothing
  28663. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  28664. || !isPointsSame(this._points, points)
  28665. ) {
  28666. if (hasAnimation) {
  28667. this._updateAnimation(
  28668. data, stackedOnPoints, coordSys, api, step, valueOrigin
  28669. );
  28670. }
  28671. else {
  28672. // Not do it in update with animation
  28673. if (step) {
  28674. // TODO If stacked series is not step
  28675. points = turnPointsIntoStep(points, coordSys, step);
  28676. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  28677. }
  28678. polyline.setShape({
  28679. points: points
  28680. });
  28681. polygon && polygon.setShape({
  28682. points: points,
  28683. stackedOnPoints: stackedOnPoints
  28684. });
  28685. }
  28686. }
  28687. }
  28688. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  28689. polyline.useStyle(defaults(
  28690. // Use color in lineStyle first
  28691. lineStyleModel.getLineStyle(),
  28692. {
  28693. fill: 'none',
  28694. stroke: visualColor,
  28695. lineJoin: 'bevel'
  28696. }
  28697. ));
  28698. var smooth = seriesModel.get('smooth');
  28699. smooth = getSmooth(seriesModel.get('smooth'));
  28700. polyline.setShape({
  28701. smooth: smooth,
  28702. smoothMonotone: seriesModel.get('smoothMonotone'),
  28703. connectNulls: seriesModel.get('connectNulls')
  28704. });
  28705. if (polygon) {
  28706. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  28707. var stackedOnSmooth = 0;
  28708. polygon.useStyle(defaults(
  28709. areaStyleModel.getAreaStyle(),
  28710. {
  28711. fill: visualColor,
  28712. opacity: 0.7,
  28713. lineJoin: 'bevel'
  28714. }
  28715. ));
  28716. if (stackedOnSeries) {
  28717. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  28718. }
  28719. polygon.setShape({
  28720. smooth: smooth,
  28721. stackedOnSmooth: stackedOnSmooth,
  28722. smoothMonotone: seriesModel.get('smoothMonotone'),
  28723. connectNulls: seriesModel.get('connectNulls')
  28724. });
  28725. }
  28726. this._data = data;
  28727. // Save the coordinate system for transition animation when data changed
  28728. this._coordSys = coordSys;
  28729. this._stackedOnPoints = stackedOnPoints;
  28730. this._points = points;
  28731. this._step = step;
  28732. this._valueOrigin = valueOrigin;
  28733. },
  28734. dispose: function () {},
  28735. highlight: function (seriesModel, ecModel, api, payload) {
  28736. var data = seriesModel.getData();
  28737. var dataIndex = queryDataIndex(data, payload);
  28738. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  28739. var symbol = data.getItemGraphicEl(dataIndex);
  28740. if (!symbol) {
  28741. // Create a temporary symbol if it is not exists
  28742. var pt = data.getItemLayout(dataIndex);
  28743. if (!pt) {
  28744. // Null data
  28745. return;
  28746. }
  28747. symbol = new SymbolClz$1(data, dataIndex);
  28748. symbol.position = pt;
  28749. symbol.setZ(
  28750. seriesModel.get('zlevel'),
  28751. seriesModel.get('z')
  28752. );
  28753. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  28754. symbol.__temp = true;
  28755. data.setItemGraphicEl(dataIndex, symbol);
  28756. // Stop scale animation
  28757. symbol.stopSymbolAnimation(true);
  28758. this.group.add(symbol);
  28759. }
  28760. symbol.highlight();
  28761. }
  28762. else {
  28763. // Highlight whole series
  28764. Chart.prototype.highlight.call(
  28765. this, seriesModel, ecModel, api, payload
  28766. );
  28767. }
  28768. },
  28769. downplay: function (seriesModel, ecModel, api, payload) {
  28770. var data = seriesModel.getData();
  28771. var dataIndex = queryDataIndex(data, payload);
  28772. if (dataIndex != null && dataIndex >= 0) {
  28773. var symbol = data.getItemGraphicEl(dataIndex);
  28774. if (symbol) {
  28775. if (symbol.__temp) {
  28776. data.setItemGraphicEl(dataIndex, null);
  28777. this.group.remove(symbol);
  28778. }
  28779. else {
  28780. symbol.downplay();
  28781. }
  28782. }
  28783. }
  28784. else {
  28785. // FIXME
  28786. // can not downplay completely.
  28787. // Downplay whole series
  28788. Chart.prototype.downplay.call(
  28789. this, seriesModel, ecModel, api, payload
  28790. );
  28791. }
  28792. },
  28793. /**
  28794. * @param {module:zrender/container/Group} group
  28795. * @param {Array.<Array.<number>>} points
  28796. * @private
  28797. */
  28798. _newPolyline: function (points) {
  28799. var polyline = this._polyline;
  28800. // Remove previous created polyline
  28801. if (polyline) {
  28802. this._lineGroup.remove(polyline);
  28803. }
  28804. polyline = new Polyline$1({
  28805. shape: {
  28806. points: points
  28807. },
  28808. silent: true,
  28809. z2: 10
  28810. });
  28811. this._lineGroup.add(polyline);
  28812. this._polyline = polyline;
  28813. return polyline;
  28814. },
  28815. /**
  28816. * @param {module:zrender/container/Group} group
  28817. * @param {Array.<Array.<number>>} stackedOnPoints
  28818. * @param {Array.<Array.<number>>} points
  28819. * @private
  28820. */
  28821. _newPolygon: function (points, stackedOnPoints) {
  28822. var polygon = this._polygon;
  28823. // Remove previous created polygon
  28824. if (polygon) {
  28825. this._lineGroup.remove(polygon);
  28826. }
  28827. polygon = new Polygon$1({
  28828. shape: {
  28829. points: points,
  28830. stackedOnPoints: stackedOnPoints
  28831. },
  28832. silent: true
  28833. });
  28834. this._lineGroup.add(polygon);
  28835. this._polygon = polygon;
  28836. return polygon;
  28837. },
  28838. /**
  28839. * @private
  28840. */
  28841. _getSymbolIgnoreFunc: function (data, coordSys) {
  28842. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  28843. // `getLabelInterval` is provided by echarts/component/axis
  28844. if (categoryAxis && categoryAxis.isLabelIgnored) {
  28845. return bind(categoryAxis.isLabelIgnored, categoryAxis);
  28846. }
  28847. },
  28848. /**
  28849. * @private
  28850. */
  28851. // FIXME Two value axis
  28852. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  28853. var polyline = this._polyline;
  28854. var polygon = this._polygon;
  28855. var seriesModel = data.hostModel;
  28856. var diff = lineAnimationDiff(
  28857. this._data, data,
  28858. this._stackedOnPoints, stackedOnPoints,
  28859. this._coordSys, coordSys,
  28860. this._valueOrigin, valueOrigin
  28861. );
  28862. var current = diff.current;
  28863. var stackedOnCurrent = diff.stackedOnCurrent;
  28864. var next = diff.next;
  28865. var stackedOnNext = diff.stackedOnNext;
  28866. if (step) {
  28867. // TODO If stacked series is not step
  28868. current = turnPointsIntoStep(diff.current, coordSys, step);
  28869. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  28870. next = turnPointsIntoStep(diff.next, coordSys, step);
  28871. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  28872. }
  28873. // `diff.current` is subset of `current` (which should be ensured by
  28874. // turnPointsIntoStep), so points in `__points` can be updated when
  28875. // points in `current` are update during animation.
  28876. polyline.shape.__points = diff.current;
  28877. polyline.shape.points = current;
  28878. updateProps(polyline, {
  28879. shape: {
  28880. points: next
  28881. }
  28882. }, seriesModel);
  28883. if (polygon) {
  28884. polygon.setShape({
  28885. points: current,
  28886. stackedOnPoints: stackedOnCurrent
  28887. });
  28888. updateProps(polygon, {
  28889. shape: {
  28890. points: next,
  28891. stackedOnPoints: stackedOnNext
  28892. }
  28893. }, seriesModel);
  28894. }
  28895. var updatedDataInfo = [];
  28896. var diffStatus = diff.status;
  28897. for (var i = 0; i < diffStatus.length; i++) {
  28898. var cmd = diffStatus[i].cmd;
  28899. if (cmd === '=') {
  28900. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  28901. if (el) {
  28902. updatedDataInfo.push({
  28903. el: el,
  28904. ptIdx: i // Index of points
  28905. });
  28906. }
  28907. }
  28908. }
  28909. if (polyline.animators && polyline.animators.length) {
  28910. polyline.animators[0].during(function () {
  28911. for (var i = 0; i < updatedDataInfo.length; i++) {
  28912. var el = updatedDataInfo[i].el;
  28913. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  28914. }
  28915. });
  28916. }
  28917. },
  28918. remove: function (ecModel) {
  28919. var group = this.group;
  28920. var oldData = this._data;
  28921. this._lineGroup.removeAll();
  28922. this._symbolDraw.remove(true);
  28923. // Remove temporary created elements when highlighting
  28924. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  28925. if (el.__temp) {
  28926. group.remove(el);
  28927. oldData.setItemGraphicEl(idx, null);
  28928. }
  28929. });
  28930. this._polyline =
  28931. this._polygon =
  28932. this._coordSys =
  28933. this._points =
  28934. this._stackedOnPoints =
  28935. this._data = null;
  28936. }
  28937. });
  28938. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  28939. // Encoding visual for all series include which is filtered for legend drawing
  28940. return {
  28941. seriesType: seriesType,
  28942. performRawSeries: true,
  28943. reset: function (seriesModel, ecModel, api) {
  28944. var data = seriesModel.getData();
  28945. var symbolType = seriesModel.get('symbol') || defaultSymbolType;
  28946. var symbolSize = seriesModel.get('symbolSize');
  28947. data.setVisual({
  28948. legendSymbol: legendSymbol || symbolType,
  28949. symbol: symbolType,
  28950. symbolSize: symbolSize
  28951. });
  28952. // Only visible series has each data be visual encoded
  28953. if (ecModel.isSeriesFiltered(seriesModel)) {
  28954. return;
  28955. }
  28956. var hasCallback = typeof symbolSize === 'function';
  28957. function dataEach(data, idx) {
  28958. if (typeof symbolSize === 'function') {
  28959. var rawValue = seriesModel.getRawValue(idx);
  28960. // FIXME
  28961. var params = seriesModel.getDataParams(idx);
  28962. data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  28963. }
  28964. if (data.hasItemOption) {
  28965. var itemModel = data.getItemModel(idx);
  28966. var itemSymbolType = itemModel.getShallow('symbol', true);
  28967. var itemSymbolSize = itemModel.getShallow('symbolSize', true);
  28968. // If has item symbol
  28969. if (itemSymbolType != null) {
  28970. data.setItemVisual(idx, 'symbol', itemSymbolType);
  28971. }
  28972. if (itemSymbolSize != null) {
  28973. // PENDING Transform symbolSize ?
  28974. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  28975. }
  28976. }
  28977. }
  28978. return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null };
  28979. }
  28980. };
  28981. };
  28982. var pointsLayout = function (seriesType) {
  28983. return {
  28984. seriesType: seriesType,
  28985. plan: createRenderPlanner(),
  28986. reset: function (seriesModel) {
  28987. var data = seriesModel.getData();
  28988. var coordSys = seriesModel.coordinateSystem;
  28989. var pipelineContext = seriesModel.pipelineContext;
  28990. var isLargeRender = pipelineContext.large;
  28991. if (!coordSys) {
  28992. return;
  28993. }
  28994. var dims = map(coordSys.dimensions, function (dim) {
  28995. return data.mapDimension(dim);
  28996. }).slice(0, 2);
  28997. var dimLen = dims.length;
  28998. if (isDimensionStacked(data, dims[0], dims[1])) {
  28999. dims[0] = data.getCalculationInfo('stackResultDimension');
  29000. }
  29001. if (isDimensionStacked(data, dims[1], dims[0])) {
  29002. dims[1] = data.getCalculationInfo('stackResultDimension');
  29003. }
  29004. function progress(params, data) {
  29005. var segCount = params.end - params.start;
  29006. var points = isLargeRender && new Float32Array(segCount * dimLen);
  29007. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  29008. var point;
  29009. if (dimLen === 1) {
  29010. var x = data.get(dims[0], i, true);
  29011. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  29012. }
  29013. else {
  29014. var x = tmpIn[0] = data.get(dims[0], i, true);
  29015. var y = tmpIn[1] = data.get(dims[1], i, true);
  29016. // Also {Array.<number>}, not undefined to avoid if...else... statement
  29017. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  29018. }
  29019. if (isLargeRender) {
  29020. points[offset++] = point ? point[0] : NaN;
  29021. points[offset++] = point ? point[1] : NaN;
  29022. }
  29023. else {
  29024. data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]);
  29025. }
  29026. }
  29027. isLargeRender && data.setLayout('symbolPoints', points);
  29028. }
  29029. return dimLen && {progress: progress};
  29030. }
  29031. };
  29032. };
  29033. var samplers = {
  29034. average: function (frame) {
  29035. var sum = 0;
  29036. var count = 0;
  29037. for (var i = 0; i < frame.length; i++) {
  29038. if (!isNaN(frame[i])) {
  29039. sum += frame[i];
  29040. count++;
  29041. }
  29042. }
  29043. // Return NaN if count is 0
  29044. return count === 0 ? NaN : sum / count;
  29045. },
  29046. sum: function (frame) {
  29047. var sum = 0;
  29048. for (var i = 0; i < frame.length; i++) {
  29049. // Ignore NaN
  29050. sum += frame[i] || 0;
  29051. }
  29052. return sum;
  29053. },
  29054. max: function (frame) {
  29055. var max = -Infinity;
  29056. for (var i = 0; i < frame.length; i++) {
  29057. frame[i] > max && (max = frame[i]);
  29058. }
  29059. return max;
  29060. },
  29061. min: function (frame) {
  29062. var min = Infinity;
  29063. for (var i = 0; i < frame.length; i++) {
  29064. frame[i] < min && (min = frame[i]);
  29065. }
  29066. return min;
  29067. },
  29068. // TODO
  29069. // Median
  29070. nearest: function (frame) {
  29071. return frame[0];
  29072. }
  29073. };
  29074. var indexSampler = function (frame, value) {
  29075. return Math.round(frame.length / 2);
  29076. };
  29077. var dataSample = function (seriesType) {
  29078. return {
  29079. seriesType: seriesType,
  29080. reset: function (seriesModel, ecModel, api) {
  29081. var data = seriesModel.getData();
  29082. var sampling = seriesModel.get('sampling');
  29083. var coordSys = seriesModel.coordinateSystem;
  29084. // Only cartesian2d support down sampling
  29085. if (coordSys.type === 'cartesian2d' && sampling) {
  29086. var baseAxis = coordSys.getBaseAxis();
  29087. var valueAxis = coordSys.getOtherAxis(baseAxis);
  29088. var extent = baseAxis.getExtent();
  29089. // Coordinste system has been resized
  29090. var size = extent[1] - extent[0];
  29091. var rate = Math.round(data.count() / size);
  29092. if (rate > 1) {
  29093. var sampler;
  29094. if (typeof sampling === 'string') {
  29095. sampler = samplers[sampling];
  29096. }
  29097. else if (typeof sampling === 'function') {
  29098. sampler = sampling;
  29099. }
  29100. if (sampler) {
  29101. seriesModel.setData(data.downSample(
  29102. valueAxis.dim, 1 / rate, sampler, indexSampler
  29103. ));
  29104. }
  29105. }
  29106. }
  29107. }
  29108. };
  29109. };
  29110. /**
  29111. * Cartesian coordinate system
  29112. * @module echarts/coord/Cartesian
  29113. *
  29114. */
  29115. function dimAxisMapper(dim) {
  29116. return this._axes[dim];
  29117. }
  29118. /**
  29119. * @alias module:echarts/coord/Cartesian
  29120. * @constructor
  29121. */
  29122. var Cartesian = function (name) {
  29123. this._axes = {};
  29124. this._dimList = [];
  29125. /**
  29126. * @type {string}
  29127. */
  29128. this.name = name || '';
  29129. };
  29130. Cartesian.prototype = {
  29131. constructor: Cartesian,
  29132. type: 'cartesian',
  29133. /**
  29134. * Get axis
  29135. * @param {number|string} dim
  29136. * @return {module:echarts/coord/Cartesian~Axis}
  29137. */
  29138. getAxis: function (dim) {
  29139. return this._axes[dim];
  29140. },
  29141. /**
  29142. * Get axes list
  29143. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  29144. */
  29145. getAxes: function () {
  29146. return map(this._dimList, dimAxisMapper, this);
  29147. },
  29148. /**
  29149. * Get axes list by given scale type
  29150. */
  29151. getAxesByScale: function (scaleType) {
  29152. scaleType = scaleType.toLowerCase();
  29153. return filter(
  29154. this.getAxes(),
  29155. function (axis) {
  29156. return axis.scale.type === scaleType;
  29157. }
  29158. );
  29159. },
  29160. /**
  29161. * Add axis
  29162. * @param {module:echarts/coord/Cartesian.Axis}
  29163. */
  29164. addAxis: function (axis) {
  29165. var dim = axis.dim;
  29166. this._axes[dim] = axis;
  29167. this._dimList.push(dim);
  29168. },
  29169. /**
  29170. * Convert data to coord in nd space
  29171. * @param {Array.<number>|Object.<string, number>} val
  29172. * @return {Array.<number>|Object.<string, number>}
  29173. */
  29174. dataToCoord: function (val) {
  29175. return this._dataCoordConvert(val, 'dataToCoord');
  29176. },
  29177. /**
  29178. * Convert coord in nd space to data
  29179. * @param {Array.<number>|Object.<string, number>} val
  29180. * @return {Array.<number>|Object.<string, number>}
  29181. */
  29182. coordToData: function (val) {
  29183. return this._dataCoordConvert(val, 'coordToData');
  29184. },
  29185. _dataCoordConvert: function (input, method) {
  29186. var dimList = this._dimList;
  29187. var output = input instanceof Array ? [] : {};
  29188. for (var i = 0; i < dimList.length; i++) {
  29189. var dim = dimList[i];
  29190. var axis = this._axes[dim];
  29191. output[dim] = axis[method](input[dim]);
  29192. }
  29193. return output;
  29194. }
  29195. };
  29196. function Cartesian2D(name) {
  29197. Cartesian.call(this, name);
  29198. }
  29199. Cartesian2D.prototype = {
  29200. constructor: Cartesian2D,
  29201. type: 'cartesian2d',
  29202. /**
  29203. * @type {Array.<string>}
  29204. * @readOnly
  29205. */
  29206. dimensions: ['x', 'y'],
  29207. /**
  29208. * Base axis will be used on stacking.
  29209. *
  29210. * @return {module:echarts/coord/cartesian/Axis2D}
  29211. */
  29212. getBaseAxis: function () {
  29213. return this.getAxesByScale('ordinal')[0]
  29214. || this.getAxesByScale('time')[0]
  29215. || this.getAxis('x');
  29216. },
  29217. /**
  29218. * If contain point
  29219. * @param {Array.<number>} point
  29220. * @return {boolean}
  29221. */
  29222. containPoint: function (point) {
  29223. var axisX = this.getAxis('x');
  29224. var axisY = this.getAxis('y');
  29225. return axisX.contain(axisX.toLocalCoord(point[0]))
  29226. && axisY.contain(axisY.toLocalCoord(point[1]));
  29227. },
  29228. /**
  29229. * If contain data
  29230. * @param {Array.<number>} data
  29231. * @return {boolean}
  29232. */
  29233. containData: function (data) {
  29234. return this.getAxis('x').containData(data[0])
  29235. && this.getAxis('y').containData(data[1]);
  29236. },
  29237. /**
  29238. * @param {Array.<number>} data
  29239. * @param {Array.<number>} out
  29240. * @return {Array.<number>}
  29241. */
  29242. dataToPoint: function (data, reserved, out) {
  29243. var xAxis = this.getAxis('x');
  29244. var yAxis = this.getAxis('y');
  29245. out = out || [];
  29246. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  29247. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  29248. return out;
  29249. },
  29250. /**
  29251. * @param {Array.<number>} data
  29252. * @param {Array.<number>} out
  29253. * @return {Array.<number>}
  29254. */
  29255. clampData: function (data, out) {
  29256. var xAxisExtent = this.getAxis('x').scale.getExtent();
  29257. var yAxisExtent = this.getAxis('y').scale.getExtent();
  29258. out = out || [];
  29259. out[0] = Math.min(
  29260. Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), data[0]),
  29261. Math.max(xAxisExtent[0], xAxisExtent[1])
  29262. );
  29263. out[1] = Math.min(
  29264. Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), data[1]),
  29265. Math.max(yAxisExtent[0], yAxisExtent[1])
  29266. );
  29267. return out;
  29268. },
  29269. /**
  29270. * @param {Array.<number>} point
  29271. * @param {Array.<number>} out
  29272. * @return {Array.<number>}
  29273. */
  29274. pointToData: function (point, out) {
  29275. var xAxis = this.getAxis('x');
  29276. var yAxis = this.getAxis('y');
  29277. out = out || [];
  29278. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  29279. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  29280. return out;
  29281. },
  29282. /**
  29283. * Get other axis
  29284. * @param {module:echarts/coord/cartesian/Axis2D} axis
  29285. */
  29286. getOtherAxis: function (axis) {
  29287. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  29288. }
  29289. };
  29290. inherits(Cartesian2D, Cartesian);
  29291. /**
  29292. * Extend axis 2d
  29293. * @constructor module:echarts/coord/cartesian/Axis2D
  29294. * @extends {module:echarts/coord/cartesian/Axis}
  29295. * @param {string} dim
  29296. * @param {*} scale
  29297. * @param {Array.<number>} coordExtent
  29298. * @param {string} axisType
  29299. * @param {string} position
  29300. */
  29301. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  29302. Axis.call(this, dim, scale, coordExtent);
  29303. /**
  29304. * Axis type
  29305. * - 'category'
  29306. * - 'value'
  29307. * - 'time'
  29308. * - 'log'
  29309. * @type {string}
  29310. */
  29311. this.type = axisType || 'value';
  29312. /**
  29313. * Axis position
  29314. * - 'top'
  29315. * - 'bottom'
  29316. * - 'left'
  29317. * - 'right'
  29318. */
  29319. this.position = position || 'bottom';
  29320. };
  29321. Axis2D.prototype = {
  29322. constructor: Axis2D,
  29323. /**
  29324. * Index of axis, can be used as key
  29325. */
  29326. index: 0,
  29327. /**
  29328. * If axis is on the zero position of the other axis
  29329. * @type {boolean}
  29330. */
  29331. onZero: false,
  29332. /**
  29333. * Axis model
  29334. * @param {module:echarts/coord/cartesian/AxisModel}
  29335. */
  29336. model: null,
  29337. isHorizontal: function () {
  29338. var position = this.position;
  29339. return position === 'top' || position === 'bottom';
  29340. },
  29341. /**
  29342. * Each item cooresponds to this.getExtent(), which
  29343. * means globalExtent[0] may greater than globalExtent[1],
  29344. * unless `asc` is input.
  29345. *
  29346. * @param {boolean} [asc]
  29347. * @return {Array.<number>}
  29348. */
  29349. getGlobalExtent: function (asc) {
  29350. var ret = this.getExtent();
  29351. ret[0] = this.toGlobalCoord(ret[0]);
  29352. ret[1] = this.toGlobalCoord(ret[1]);
  29353. asc && ret[0] > ret[1] && ret.reverse();
  29354. return ret;
  29355. },
  29356. getOtherAxis: function () {
  29357. this.grid.getOtherAxis();
  29358. },
  29359. /**
  29360. * If label is ignored.
  29361. * Automatically used when axis is category and label can not be all shown
  29362. * @param {number} idx
  29363. * @return {boolean}
  29364. */
  29365. isLabelIgnored: function (idx) {
  29366. if (this.type === 'category') {
  29367. var labelInterval = this.getLabelInterval();
  29368. return ((typeof labelInterval === 'function')
  29369. && !labelInterval(idx, this.scale.getLabel(idx)))
  29370. || idx % (labelInterval + 1);
  29371. }
  29372. },
  29373. /**
  29374. * @override
  29375. */
  29376. pointToData: function (point, clamp) {
  29377. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  29378. },
  29379. /**
  29380. * Transform global coord to local coord,
  29381. * i.e. var localCoord = axis.toLocalCoord(80);
  29382. * designate by module:echarts/coord/cartesian/Grid.
  29383. * @type {Function}
  29384. */
  29385. toLocalCoord: null,
  29386. /**
  29387. * Transform global coord to local coord,
  29388. * i.e. var globalCoord = axis.toLocalCoord(40);
  29389. * designate by module:echarts/coord/cartesian/Grid.
  29390. * @type {Function}
  29391. */
  29392. toGlobalCoord: null
  29393. };
  29394. inherits(Axis2D, Axis);
  29395. var defaultOption = {
  29396. show: true,
  29397. zlevel: 0, // 一级层叠
  29398. z: 0, // 二级层叠
  29399. // 反向坐标轴
  29400. inverse: false,
  29401. // 坐标轴名字,默认为空
  29402. name: '',
  29403. // 坐标轴名字位置,支持'start' | 'middle' | 'end'
  29404. nameLocation: 'end',
  29405. // 坐标轴名字旋转,degree。
  29406. nameRotate: null, // Adapt to axis rotate, when nameLocation is 'middle'.
  29407. nameTruncate: {
  29408. maxWidth: null,
  29409. ellipsis: '...',
  29410. placeholder: '.'
  29411. },
  29412. // 坐标轴文字样式,默认取全局样式
  29413. nameTextStyle: {},
  29414. // 文字与轴线距离
  29415. nameGap: 15,
  29416. silent: false, // Default false to support tooltip.
  29417. triggerEvent: false, // Default false to avoid legacy user event listener fail.
  29418. tooltip: {
  29419. show: false
  29420. },
  29421. axisPointer: {},
  29422. // 坐标轴线
  29423. axisLine: {
  29424. // 默认显示,属性show控制显示与否
  29425. show: true,
  29426. onZero: true,
  29427. onZeroAxisIndex: null,
  29428. // 属性lineStyle控制线条样式
  29429. lineStyle: {
  29430. color: '#333',
  29431. width: 1,
  29432. type: 'solid'
  29433. },
  29434. // 坐标轴两端的箭头
  29435. symbol: ['none', 'none'],
  29436. symbolSize: [10, 15]
  29437. },
  29438. // 坐标轴小标记
  29439. axisTick: {
  29440. // 属性show控制显示与否,默认显示
  29441. show: true,
  29442. // 控制小标记是否在grid里
  29443. inside: false,
  29444. // 属性length控制线长
  29445. length: 5,
  29446. // 属性lineStyle控制线条样式
  29447. lineStyle: {
  29448. width: 1
  29449. }
  29450. },
  29451. // 坐标轴文本标签,详见axis.axisLabel
  29452. axisLabel: {
  29453. show: true,
  29454. // 控制文本标签是否在grid里
  29455. inside: false,
  29456. rotate: 0,
  29457. showMinLabel: null, // true | false | null (auto)
  29458. showMaxLabel: null, // true | false | null (auto)
  29459. margin: 8,
  29460. // formatter: null,
  29461. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  29462. fontSize: 12
  29463. },
  29464. // 分隔线
  29465. splitLine: {
  29466. // 默认显示,属性show控制显示与否
  29467. show: true,
  29468. // 属性lineStyle(详见lineStyle)控制线条样式
  29469. lineStyle: {
  29470. color: ['#ccc'],
  29471. width: 1,
  29472. type: 'solid'
  29473. }
  29474. },
  29475. // 分隔区域
  29476. splitArea: {
  29477. // 默认不显示,属性show控制显示与否
  29478. show: false,
  29479. // 属性areaStyle(详见areaStyle)控制区域样式
  29480. areaStyle: {
  29481. color: ['rgba(250,250,250,0.3)','rgba(200,200,200,0.3)']
  29482. }
  29483. }
  29484. };
  29485. var axisDefault = {};
  29486. axisDefault.categoryAxis = merge({
  29487. // 类目起始和结束两端空白策略
  29488. boundaryGap: true,
  29489. // Set false to faster category collection.
  29490. // Only usefull in the case like: category is
  29491. // ['2012-01-01', '2012-01-02', ...], where the input
  29492. // data has been ensured not duplicate and is large data.
  29493. // null means "auto":
  29494. // if axis.data provided, do not deduplication,
  29495. // else do deduplication.
  29496. deduplication: null,
  29497. // splitArea: {
  29498. // show: false
  29499. // },
  29500. splitLine: {
  29501. show: false
  29502. },
  29503. // 坐标轴小标记
  29504. axisTick: {
  29505. // If tick is align with label when boundaryGap is true
  29506. alignWithLabel: false,
  29507. interval: 'auto'
  29508. },
  29509. // 坐标轴文本标签,详见axis.axisLabel
  29510. axisLabel: {
  29511. interval: 'auto'
  29512. }
  29513. }, defaultOption);
  29514. axisDefault.valueAxis = merge({
  29515. // 数值起始和结束两端空白策略
  29516. boundaryGap: [0, 0],
  29517. // TODO
  29518. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  29519. // 最小值, 设置成 'dataMin' 则从数据中计算最小值
  29520. // min: null,
  29521. // 最大值,设置成 'dataMax' 则从数据中计算最大值
  29522. // max: null,
  29523. // Readonly prop, specifies start value of the range when using data zoom.
  29524. // rangeStart: null
  29525. // Readonly prop, specifies end value of the range when using data zoom.
  29526. // rangeEnd: null
  29527. // 脱离0值比例,放大聚焦到最终_min,_max区间
  29528. // scale: false,
  29529. // 分割段数,默认为5
  29530. splitNumber: 5
  29531. // Minimum interval
  29532. // minInterval: null
  29533. // maxInterval: null
  29534. }, defaultOption);
  29535. // FIXME
  29536. axisDefault.timeAxis = defaults({
  29537. scale: true,
  29538. min: 'dataMin',
  29539. max: 'dataMax'
  29540. }, axisDefault.valueAxis);
  29541. axisDefault.logAxis = defaults({
  29542. scale: true,
  29543. logBase: 10
  29544. }, axisDefault.valueAxis);
  29545. // FIXME axisType is fixed ?
  29546. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  29547. /**
  29548. * Generate sub axis model class
  29549. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  29550. * @param {module:echarts/model/Component} BaseAxisModelClass
  29551. * @param {Function} axisTypeDefaulter
  29552. * @param {Object} [extraDefaultOption]
  29553. */
  29554. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  29555. each$1(AXIS_TYPES, function (axisType) {
  29556. BaseAxisModelClass.extend({
  29557. /**
  29558. * @readOnly
  29559. */
  29560. type: axisName + 'Axis.' + axisType,
  29561. mergeDefaultAndTheme: function (option, ecModel) {
  29562. var layoutMode = this.layoutMode;
  29563. var inputPositionParams = layoutMode
  29564. ? getLayoutParams(option) : {};
  29565. var themeModel = ecModel.getTheme();
  29566. merge(option, themeModel.get(axisType + 'Axis'));
  29567. merge(option, this.getDefaultOption());
  29568. option.type = axisTypeDefaulter(axisName, option);
  29569. if (layoutMode) {
  29570. mergeLayoutParam(option, inputPositionParams, layoutMode);
  29571. }
  29572. },
  29573. /**
  29574. * @override
  29575. */
  29576. optionUpdated: function () {
  29577. var thisOption = this.option;
  29578. if (thisOption.type === 'category') {
  29579. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  29580. }
  29581. },
  29582. /**
  29583. * Should not be called before all of 'getInitailData' finished.
  29584. * Because categories are collected during initializing data.
  29585. */
  29586. getCategories: function () {
  29587. // FIXME
  29588. // warning if called before all of 'getInitailData' finished.
  29589. if (this.option.type === 'category') {
  29590. return this.__ordinalMeta.categories;
  29591. }
  29592. },
  29593. getOrdinalMeta: function () {
  29594. return this.__ordinalMeta;
  29595. },
  29596. defaultOption: mergeAll(
  29597. [
  29598. {},
  29599. axisDefault[axisType + 'Axis'],
  29600. extraDefaultOption
  29601. ],
  29602. true
  29603. )
  29604. });
  29605. });
  29606. ComponentModel.registerSubTypeDefaulter(
  29607. axisName + 'Axis',
  29608. curry(axisTypeDefaulter, axisName)
  29609. );
  29610. };
  29611. var AxisModel = ComponentModel.extend({
  29612. type: 'cartesian2dAxis',
  29613. /**
  29614. * @type {module:echarts/coord/cartesian/Axis2D}
  29615. */
  29616. axis: null,
  29617. /**
  29618. * @override
  29619. */
  29620. init: function () {
  29621. AxisModel.superApply(this, 'init', arguments);
  29622. this.resetRange();
  29623. },
  29624. /**
  29625. * @override
  29626. */
  29627. mergeOption: function () {
  29628. AxisModel.superApply(this, 'mergeOption', arguments);
  29629. this.resetRange();
  29630. },
  29631. /**
  29632. * @override
  29633. */
  29634. restoreData: function () {
  29635. AxisModel.superApply(this, 'restoreData', arguments);
  29636. this.resetRange();
  29637. },
  29638. /**
  29639. * @override
  29640. * @return {module:echarts/model/Component}
  29641. */
  29642. getCoordSysModel: function () {
  29643. return this.ecModel.queryComponents({
  29644. mainType: 'grid',
  29645. index: this.option.gridIndex,
  29646. id: this.option.gridId
  29647. })[0];
  29648. }
  29649. });
  29650. function getAxisType(axisDim, option) {
  29651. // Default axis with data is category axis
  29652. return option.type || (option.data ? 'category' : 'value');
  29653. }
  29654. merge(AxisModel.prototype, axisModelCommonMixin);
  29655. var extraOption = {
  29656. // gridIndex: 0,
  29657. // gridId: '',
  29658. // Offset is for multiple axis on the same position
  29659. offset: 0
  29660. };
  29661. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  29662. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  29663. // Grid 是在有直角坐标系的时候必须要存在的
  29664. // 所以这里也要被 Cartesian2D 依赖
  29665. ComponentModel.extend({
  29666. type: 'grid',
  29667. dependencies: ['xAxis', 'yAxis'],
  29668. layoutMode: 'box',
  29669. /**
  29670. * @type {module:echarts/coord/cartesian/Grid}
  29671. */
  29672. coordinateSystem: null,
  29673. defaultOption: {
  29674. show: false,
  29675. zlevel: 0,
  29676. z: 0,
  29677. left: '10%',
  29678. top: 60,
  29679. right: '10%',
  29680. bottom: 60,
  29681. // If grid size contain label
  29682. containLabel: false,
  29683. // width: {totalWidth} - left - right,
  29684. // height: {totalHeight} - top - bottom,
  29685. backgroundColor: 'rgba(0,0,0,0)',
  29686. borderWidth: 1,
  29687. borderColor: '#ccc'
  29688. }
  29689. });
  29690. /**
  29691. * Grid is a region which contains at most 4 cartesian systems
  29692. *
  29693. * TODO Default cartesian
  29694. */
  29695. // Depends on GridModel, AxisModel, which performs preprocess.
  29696. var each$6 = each$1;
  29697. var ifAxisCrossZero$1 = ifAxisCrossZero;
  29698. var niceScaleExtent$1 = niceScaleExtent;
  29699. /**
  29700. * Check if the axis is used in the specified grid
  29701. * @inner
  29702. */
  29703. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  29704. return axisModel.getCoordSysModel() === gridModel;
  29705. }
  29706. function rotateTextRect(textRect, rotate) {
  29707. var rotateRadians = rotate * Math.PI / 180;
  29708. var boundingBox = textRect.plain();
  29709. var beforeWidth = boundingBox.width;
  29710. var beforeHeight = boundingBox.height;
  29711. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  29712. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  29713. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  29714. return rotatedRect;
  29715. }
  29716. function getLabelUnionRect(axis) {
  29717. var axisModel = axis.model;
  29718. var labels = axisModel.get('axisLabel.show') ? axisModel.getFormattedLabels() : [];
  29719. var axisLabelModel = axisModel.getModel('axisLabel');
  29720. var rect;
  29721. var step = 1;
  29722. var labelCount = labels.length;
  29723. if (labelCount > 40) {
  29724. // Simple optimization for large amount of labels
  29725. step = Math.ceil(labelCount / 40);
  29726. }
  29727. for (var i = 0; i < labelCount; i += step) {
  29728. if (!axis.isLabelIgnored(i)) {
  29729. var unrotatedSingleRect = axisLabelModel.getTextRect(labels[i]);
  29730. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  29731. rect ? rect.union(singleRect) : (rect = singleRect);
  29732. }
  29733. }
  29734. return rect;
  29735. }
  29736. function Grid(gridModel, ecModel, api) {
  29737. /**
  29738. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  29739. * @private
  29740. */
  29741. this._coordsMap = {};
  29742. /**
  29743. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  29744. * @private
  29745. */
  29746. this._coordsList = [];
  29747. /**
  29748. * @type {Object.<string, module:echarts/coord/cartesian/Axis2D>}
  29749. * @private
  29750. */
  29751. this._axesMap = {};
  29752. /**
  29753. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  29754. * @private
  29755. */
  29756. this._axesList = [];
  29757. this._initCartesian(gridModel, ecModel, api);
  29758. this.model = gridModel;
  29759. }
  29760. var gridProto = Grid.prototype;
  29761. gridProto.type = 'grid';
  29762. gridProto.axisPointerEnabled = true;
  29763. gridProto.getRect = function () {
  29764. return this._rect;
  29765. };
  29766. gridProto.update = function (ecModel, api) {
  29767. var axesMap = this._axesMap;
  29768. this._updateScale(ecModel, this.model);
  29769. each$6(axesMap.x, function (xAxis) {
  29770. niceScaleExtent$1(xAxis.scale, xAxis.model);
  29771. });
  29772. each$6(axesMap.y, function (yAxis) {
  29773. niceScaleExtent$1(yAxis.scale, yAxis.model);
  29774. });
  29775. each$6(axesMap.x, function (xAxis) {
  29776. fixAxisOnZero(axesMap, 'y', xAxis);
  29777. });
  29778. each$6(axesMap.y, function (yAxis) {
  29779. fixAxisOnZero(axesMap, 'x', yAxis);
  29780. });
  29781. // Resize again if containLabel is enabled
  29782. // FIXME It may cause getting wrong grid size in data processing stage
  29783. this.resize(this.model, api);
  29784. };
  29785. function fixAxisOnZero(axesMap, otherAxisDim, axis) {
  29786. // onZero can not be enabled in these two situations:
  29787. // 1. When any other axis is a category axis.
  29788. // 2. When no axis is cross 0 point.
  29789. var axes = axesMap[otherAxisDim];
  29790. if (!axis.onZero) {
  29791. return;
  29792. }
  29793. var onZeroAxisIndex = axis.onZeroAxisIndex;
  29794. // If target axis is specified.
  29795. if (onZeroAxisIndex != null) {
  29796. var otherAxis = axes[onZeroAxisIndex];
  29797. if (otherAxis && canNotOnZeroToAxis(otherAxis)) {
  29798. axis.onZero = false;
  29799. }
  29800. return;
  29801. }
  29802. for (var idx in axes) {
  29803. if (axes.hasOwnProperty(idx)) {
  29804. var otherAxis = axes[idx];
  29805. if (otherAxis && !canNotOnZeroToAxis(otherAxis)) {
  29806. onZeroAxisIndex = +idx;
  29807. break;
  29808. }
  29809. }
  29810. }
  29811. if (onZeroAxisIndex == null) {
  29812. axis.onZero = false;
  29813. }
  29814. axis.onZeroAxisIndex = onZeroAxisIndex;
  29815. }
  29816. function canNotOnZeroToAxis(axis) {
  29817. return axis.type === 'category' || axis.type === 'time' || !ifAxisCrossZero$1(axis);
  29818. }
  29819. /**
  29820. * Resize the grid
  29821. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  29822. * @param {module:echarts/ExtensionAPI} api
  29823. */
  29824. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  29825. var gridRect = getLayoutRect(
  29826. gridModel.getBoxLayoutParams(), {
  29827. width: api.getWidth(),
  29828. height: api.getHeight()
  29829. });
  29830. this._rect = gridRect;
  29831. var axesList = this._axesList;
  29832. adjustAxes();
  29833. // Minus label size
  29834. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  29835. each$6(axesList, function (axis) {
  29836. if (!axis.model.get('axisLabel.inside')) {
  29837. var labelUnionRect = getLabelUnionRect(axis);
  29838. if (labelUnionRect) {
  29839. var dim = axis.isHorizontal() ? 'height' : 'width';
  29840. var margin = axis.model.get('axisLabel.margin');
  29841. gridRect[dim] -= labelUnionRect[dim] + margin;
  29842. if (axis.position === 'top') {
  29843. gridRect.y += labelUnionRect.height + margin;
  29844. }
  29845. else if (axis.position === 'left') {
  29846. gridRect.x += labelUnionRect.width + margin;
  29847. }
  29848. }
  29849. }
  29850. });
  29851. adjustAxes();
  29852. }
  29853. function adjustAxes() {
  29854. each$6(axesList, function (axis) {
  29855. var isHorizontal = axis.isHorizontal();
  29856. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  29857. var idx = axis.inverse ? 1 : 0;
  29858. axis.setExtent(extent[idx], extent[1 - idx]);
  29859. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  29860. });
  29861. }
  29862. };
  29863. /**
  29864. * @param {string} axisType
  29865. * @param {number} [axisIndex]
  29866. */
  29867. gridProto.getAxis = function (axisType, axisIndex) {
  29868. var axesMapOnDim = this._axesMap[axisType];
  29869. if (axesMapOnDim != null) {
  29870. if (axisIndex == null) {
  29871. // Find first axis
  29872. for (var name in axesMapOnDim) {
  29873. if (axesMapOnDim.hasOwnProperty(name)) {
  29874. return axesMapOnDim[name];
  29875. }
  29876. }
  29877. }
  29878. return axesMapOnDim[axisIndex];
  29879. }
  29880. };
  29881. /**
  29882. * @return {Array.<module:echarts/coord/Axis>}
  29883. */
  29884. gridProto.getAxes = function () {
  29885. return this._axesList.slice();
  29886. };
  29887. /**
  29888. * Usage:
  29889. * grid.getCartesian(xAxisIndex, yAxisIndex);
  29890. * grid.getCartesian(xAxisIndex);
  29891. * grid.getCartesian(null, yAxisIndex);
  29892. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  29893. *
  29894. * @param {number|Object} [xAxisIndex]
  29895. * @param {number} [yAxisIndex]
  29896. */
  29897. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  29898. if (xAxisIndex != null && yAxisIndex != null) {
  29899. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  29900. return this._coordsMap[key];
  29901. }
  29902. if (isObject$1(xAxisIndex)) {
  29903. yAxisIndex = xAxisIndex.yAxisIndex;
  29904. xAxisIndex = xAxisIndex.xAxisIndex;
  29905. }
  29906. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  29907. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  29908. if (coordList[i].getAxis('x').index === xAxisIndex
  29909. || coordList[i].getAxis('y').index === yAxisIndex
  29910. ) {
  29911. return coordList[i];
  29912. }
  29913. }
  29914. };
  29915. gridProto.getCartesians = function () {
  29916. return this._coordsList.slice();
  29917. };
  29918. /**
  29919. * @implements
  29920. * see {module:echarts/CoodinateSystem}
  29921. */
  29922. gridProto.convertToPixel = function (ecModel, finder, value) {
  29923. var target = this._findConvertTarget(ecModel, finder);
  29924. return target.cartesian
  29925. ? target.cartesian.dataToPoint(value)
  29926. : target.axis
  29927. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  29928. : null;
  29929. };
  29930. /**
  29931. * @implements
  29932. * see {module:echarts/CoodinateSystem}
  29933. */
  29934. gridProto.convertFromPixel = function (ecModel, finder, value) {
  29935. var target = this._findConvertTarget(ecModel, finder);
  29936. return target.cartesian
  29937. ? target.cartesian.pointToData(value)
  29938. : target.axis
  29939. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  29940. : null;
  29941. };
  29942. /**
  29943. * @inner
  29944. */
  29945. gridProto._findConvertTarget = function (ecModel, finder) {
  29946. var seriesModel = finder.seriesModel;
  29947. var xAxisModel = finder.xAxisModel
  29948. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  29949. var yAxisModel = finder.yAxisModel
  29950. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  29951. var gridModel = finder.gridModel;
  29952. var coordsList = this._coordsList;
  29953. var cartesian;
  29954. var axis;
  29955. if (seriesModel) {
  29956. cartesian = seriesModel.coordinateSystem;
  29957. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  29958. }
  29959. else if (xAxisModel && yAxisModel) {
  29960. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  29961. }
  29962. else if (xAxisModel) {
  29963. axis = this.getAxis('x', xAxisModel.componentIndex);
  29964. }
  29965. else if (yAxisModel) {
  29966. axis = this.getAxis('y', yAxisModel.componentIndex);
  29967. }
  29968. // Lowest priority.
  29969. else if (gridModel) {
  29970. var grid = gridModel.coordinateSystem;
  29971. if (grid === this) {
  29972. cartesian = this._coordsList[0];
  29973. }
  29974. }
  29975. return {cartesian: cartesian, axis: axis};
  29976. };
  29977. /**
  29978. * @implements
  29979. * see {module:echarts/CoodinateSystem}
  29980. */
  29981. gridProto.containPoint = function (point) {
  29982. var coord = this._coordsList[0];
  29983. if (coord) {
  29984. return coord.containPoint(point);
  29985. }
  29986. };
  29987. /**
  29988. * Initialize cartesian coordinate systems
  29989. * @private
  29990. */
  29991. gridProto._initCartesian = function (gridModel, ecModel, api) {
  29992. var axisPositionUsed = {
  29993. left: false,
  29994. right: false,
  29995. top: false,
  29996. bottom: false
  29997. };
  29998. var axesMap = {
  29999. x: {},
  30000. y: {}
  30001. };
  30002. var axesCount = {
  30003. x: 0,
  30004. y: 0
  30005. };
  30006. /// Create axis
  30007. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  30008. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  30009. if (!axesCount.x || !axesCount.y) {
  30010. // Roll back when there no either x or y axis
  30011. this._axesMap = {};
  30012. this._axesList = [];
  30013. return;
  30014. }
  30015. this._axesMap = axesMap;
  30016. /// Create cartesian2d
  30017. each$6(axesMap.x, function (xAxis, xAxisIndex) {
  30018. each$6(axesMap.y, function (yAxis, yAxisIndex) {
  30019. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  30020. var cartesian = new Cartesian2D(key);
  30021. cartesian.grid = this;
  30022. cartesian.model = gridModel;
  30023. this._coordsMap[key] = cartesian;
  30024. this._coordsList.push(cartesian);
  30025. cartesian.addAxis(xAxis);
  30026. cartesian.addAxis(yAxis);
  30027. }, this);
  30028. }, this);
  30029. function createAxisCreator(axisType) {
  30030. return function (axisModel, idx) {
  30031. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  30032. return;
  30033. }
  30034. var axisPosition = axisModel.get('position');
  30035. if (axisType === 'x') {
  30036. // Fix position
  30037. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  30038. // Default bottom of X
  30039. axisPosition = 'bottom';
  30040. if (axisPositionUsed[axisPosition]) {
  30041. axisPosition = axisPosition === 'top' ? 'bottom' : 'top';
  30042. }
  30043. }
  30044. }
  30045. else {
  30046. // Fix position
  30047. if (axisPosition !== 'left' && axisPosition !== 'right') {
  30048. // Default left of Y
  30049. axisPosition = 'left';
  30050. if (axisPositionUsed[axisPosition]) {
  30051. axisPosition = axisPosition === 'left' ? 'right' : 'left';
  30052. }
  30053. }
  30054. }
  30055. axisPositionUsed[axisPosition] = true;
  30056. var axis = new Axis2D(
  30057. axisType, createScaleByModel(axisModel),
  30058. [0, 0],
  30059. axisModel.get('type'),
  30060. axisPosition
  30061. );
  30062. var isCategory = axis.type === 'category';
  30063. axis.onBand = isCategory && axisModel.get('boundaryGap');
  30064. axis.inverse = axisModel.get('inverse');
  30065. axis.onZero = axisModel.get('axisLine.onZero');
  30066. axis.onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  30067. // Inject axis into axisModel
  30068. axisModel.axis = axis;
  30069. // Inject axisModel into axis
  30070. axis.model = axisModel;
  30071. // Inject grid info axis
  30072. axis.grid = this;
  30073. // Index of axis, can be used as key
  30074. axis.index = idx;
  30075. this._axesList.push(axis);
  30076. axesMap[axisType][idx] = axis;
  30077. axesCount[axisType]++;
  30078. };
  30079. }
  30080. };
  30081. /**
  30082. * Update cartesian properties from series
  30083. * @param {module:echarts/model/Option} option
  30084. * @private
  30085. */
  30086. gridProto._updateScale = function (ecModel, gridModel) {
  30087. // Reset scale
  30088. each$1(this._axesList, function (axis) {
  30089. axis.scale.setExtent(Infinity, -Infinity);
  30090. });
  30091. ecModel.eachSeries(function (seriesModel) {
  30092. if (isCartesian2D(seriesModel)) {
  30093. var axesModels = findAxesModels(seriesModel, ecModel);
  30094. var xAxisModel = axesModels[0];
  30095. var yAxisModel = axesModels[1];
  30096. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  30097. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  30098. ) {
  30099. return;
  30100. }
  30101. var cartesian = this.getCartesian(
  30102. xAxisModel.componentIndex, yAxisModel.componentIndex
  30103. );
  30104. var data = seriesModel.getData();
  30105. var xAxis = cartesian.getAxis('x');
  30106. var yAxis = cartesian.getAxis('y');
  30107. if (data.type === 'list') {
  30108. unionExtent(data, xAxis, seriesModel);
  30109. unionExtent(data, yAxis, seriesModel);
  30110. }
  30111. }
  30112. }, this);
  30113. function unionExtent(data, axis, seriesModel) {
  30114. each$6(data.mapDimension(axis.dim, true), function (dim) {
  30115. axis.scale.unionExtentFromData(data, dim);
  30116. });
  30117. }
  30118. };
  30119. /**
  30120. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  30121. * @return {Object} {baseAxes: [], otherAxes: []}
  30122. */
  30123. gridProto.getTooltipAxes = function (dim) {
  30124. var baseAxes = [];
  30125. var otherAxes = [];
  30126. each$6(this.getCartesians(), function (cartesian) {
  30127. var baseAxis = (dim != null && dim !== 'auto')
  30128. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  30129. var otherAxis = cartesian.getOtherAxis(baseAxis);
  30130. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  30131. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  30132. });
  30133. return {baseAxes: baseAxes, otherAxes: otherAxes};
  30134. };
  30135. /**
  30136. * @inner
  30137. */
  30138. function updateAxisTransform(axis, coordBase) {
  30139. var axisExtent = axis.getExtent();
  30140. var axisExtentSum = axisExtent[0] + axisExtent[1];
  30141. // Fast transform
  30142. axis.toGlobalCoord = axis.dim === 'x'
  30143. ? function (coord) {
  30144. return coord + coordBase;
  30145. }
  30146. : function (coord) {
  30147. return axisExtentSum - coord + coordBase;
  30148. };
  30149. axis.toLocalCoord = axis.dim === 'x'
  30150. ? function (coord) {
  30151. return coord - coordBase;
  30152. }
  30153. : function (coord) {
  30154. return axisExtentSum - coord + coordBase;
  30155. };
  30156. }
  30157. var axesTypes = ['xAxis', 'yAxis'];
  30158. /**
  30159. * @inner
  30160. */
  30161. function findAxesModels(seriesModel, ecModel) {
  30162. return map(axesTypes, function (axisType) {
  30163. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  30164. if (__DEV__) {
  30165. if (!axisModel) {
  30166. throw new Error(axisType + ' "' + retrieve(
  30167. seriesModel.get(axisType + 'Index'),
  30168. seriesModel.get(axisType + 'Id'),
  30169. 0
  30170. ) + '" not found');
  30171. }
  30172. }
  30173. return axisModel;
  30174. });
  30175. }
  30176. /**
  30177. * @inner
  30178. */
  30179. function isCartesian2D(seriesModel) {
  30180. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  30181. }
  30182. Grid.create = function (ecModel, api) {
  30183. var grids = [];
  30184. ecModel.eachComponent('grid', function (gridModel, idx) {
  30185. var grid = new Grid(gridModel, ecModel, api);
  30186. grid.name = 'grid_' + idx;
  30187. // dataSampling requires axis extent, so resize
  30188. // should be performed in create stage.
  30189. grid.resize(gridModel, api, true);
  30190. gridModel.coordinateSystem = grid;
  30191. grids.push(grid);
  30192. });
  30193. // Inject the coordinateSystems into seriesModel
  30194. ecModel.eachSeries(function (seriesModel) {
  30195. if (!isCartesian2D(seriesModel)) {
  30196. return;
  30197. }
  30198. var axesModels = findAxesModels(seriesModel, ecModel);
  30199. var xAxisModel = axesModels[0];
  30200. var yAxisModel = axesModels[1];
  30201. var gridModel = xAxisModel.getCoordSysModel();
  30202. if (__DEV__) {
  30203. if (!gridModel) {
  30204. throw new Error(
  30205. 'Grid "' + retrieve(
  30206. xAxisModel.get('gridIndex'),
  30207. xAxisModel.get('gridId'),
  30208. 0
  30209. ) + '" not found'
  30210. );
  30211. }
  30212. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  30213. throw new Error('xAxis and yAxis must use the same grid');
  30214. }
  30215. }
  30216. var grid = gridModel.coordinateSystem;
  30217. seriesModel.coordinateSystem = grid.getCartesian(
  30218. xAxisModel.componentIndex, yAxisModel.componentIndex
  30219. );
  30220. });
  30221. return grids;
  30222. };
  30223. // For deciding which dimensions to use when creating list data
  30224. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  30225. CoordinateSystemManager.register('cartesian2d', Grid);
  30226. var PI$2 = Math.PI;
  30227. function makeAxisEventDataBase(axisModel) {
  30228. var eventData = {
  30229. componentType: axisModel.mainType
  30230. };
  30231. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  30232. return eventData;
  30233. }
  30234. /**
  30235. * A final axis is translated and rotated from a "standard axis".
  30236. * So opt.position and opt.rotation is required.
  30237. *
  30238. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  30239. * for example: (0, 0) ------------> (0, 50)
  30240. *
  30241. * nameDirection or tickDirection or labelDirection is 1 means tick
  30242. * or label is below the standard axis, whereas is -1 means above
  30243. * the standard axis. labelOffset means offset between label and axis,
  30244. * which is useful when 'onZero', where axisLabel is in the grid and
  30245. * label in outside grid.
  30246. *
  30247. * Tips: like always,
  30248. * positive rotation represents anticlockwise, and negative rotation
  30249. * represents clockwise.
  30250. * The direction of position coordinate is the same as the direction
  30251. * of screen coordinate.
  30252. *
  30253. * Do not need to consider axis 'inverse', which is auto processed by
  30254. * axis extent.
  30255. *
  30256. * @param {module:zrender/container/Group} group
  30257. * @param {Object} axisModel
  30258. * @param {Object} opt Standard axis parameters.
  30259. * @param {Array.<number>} opt.position [x, y]
  30260. * @param {number} opt.rotation by radian
  30261. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  30262. * @param {number} [opt.tickDirection=1] 1 or -1
  30263. * @param {number} [opt.labelDirection=1] 1 or -1
  30264. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  30265. * @param {string} [opt.axisLabelShow] default get from axisModel.
  30266. * @param {string} [opt.axisName] default get from axisModel.
  30267. * @param {number} [opt.axisNameAvailableWidth]
  30268. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  30269. * @param {number} [opt.labelInterval] Default label interval when label
  30270. * interval from model is null or 'auto'.
  30271. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  30272. * @param {number} [opt.nameTruncateMaxWidth]
  30273. */
  30274. var AxisBuilder = function (axisModel, opt) {
  30275. /**
  30276. * @readOnly
  30277. */
  30278. this.opt = opt;
  30279. /**
  30280. * @readOnly
  30281. */
  30282. this.axisModel = axisModel;
  30283. // Default value
  30284. defaults(
  30285. opt,
  30286. {
  30287. labelOffset: 0,
  30288. nameDirection: 1,
  30289. tickDirection: 1,
  30290. labelDirection: 1,
  30291. silent: true
  30292. }
  30293. );
  30294. /**
  30295. * @readOnly
  30296. */
  30297. this.group = new Group();
  30298. // FIXME Not use a seperate text group?
  30299. var dumbGroup = new Group({
  30300. position: opt.position.slice(),
  30301. rotation: opt.rotation
  30302. });
  30303. // this.group.add(dumbGroup);
  30304. // this._dumbGroup = dumbGroup;
  30305. dumbGroup.updateTransform();
  30306. this._transform = dumbGroup.transform;
  30307. this._dumbGroup = dumbGroup;
  30308. };
  30309. AxisBuilder.prototype = {
  30310. constructor: AxisBuilder,
  30311. hasBuilder: function (name) {
  30312. return !!builders[name];
  30313. },
  30314. add: function (name) {
  30315. builders[name].call(this);
  30316. },
  30317. getGroup: function () {
  30318. return this.group;
  30319. }
  30320. };
  30321. var builders = {
  30322. /**
  30323. * @private
  30324. */
  30325. axisLine: function () {
  30326. var opt = this.opt;
  30327. var axisModel = this.axisModel;
  30328. if (!axisModel.get('axisLine.show')) {
  30329. return;
  30330. }
  30331. var extent = this.axisModel.axis.getExtent();
  30332. var matrix = this._transform;
  30333. var pt1 = [extent[0], 0];
  30334. var pt2 = [extent[1], 0];
  30335. if (matrix) {
  30336. applyTransform(pt1, pt1, matrix);
  30337. applyTransform(pt2, pt2, matrix);
  30338. }
  30339. var lineStyle = extend(
  30340. {
  30341. lineCap: 'round'
  30342. },
  30343. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  30344. );
  30345. this.group.add(new Line(subPixelOptimizeLine({
  30346. // Id for animation
  30347. anid: 'line',
  30348. shape: {
  30349. x1: pt1[0],
  30350. y1: pt1[1],
  30351. x2: pt2[0],
  30352. y2: pt2[1]
  30353. },
  30354. style: lineStyle,
  30355. strokeContainThreshold: opt.strokeContainThreshold || 5,
  30356. silent: true,
  30357. z2: 1
  30358. })));
  30359. var arrows = axisModel.get('axisLine.symbol');
  30360. var arrowSize = axisModel.get('axisLine.symbolSize');
  30361. var arrowOffset = axisModel.get('axisLine.symbolOffset') || 0;
  30362. if (typeof arrowOffset === 'number') {
  30363. arrowOffset = [arrowOffset, arrowOffset];
  30364. }
  30365. if (arrows != null) {
  30366. if (typeof arrows === 'string') {
  30367. // Use the same arrow for start and end point
  30368. arrows = [arrows, arrows];
  30369. }
  30370. if (typeof arrowSize === 'string'
  30371. || typeof arrowSize === 'number'
  30372. ) {
  30373. // Use the same size for width and height
  30374. arrowSize = [arrowSize, arrowSize];
  30375. }
  30376. var symbolWidth = arrowSize[0];
  30377. var symbolHeight = arrowSize[1];
  30378. each$1([{
  30379. rotate: opt.rotation + Math.PI / 2,
  30380. offset: arrowOffset[0],
  30381. r: 0
  30382. }, {
  30383. rotate: opt.rotation - Math.PI / 2,
  30384. offset: arrowOffset[1],
  30385. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0])
  30386. + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  30387. }], function (point, index) {
  30388. if (arrows[index] !== 'none' && arrows[index] != null) {
  30389. var symbol = createSymbol(
  30390. arrows[index],
  30391. -symbolWidth / 2,
  30392. -symbolHeight / 2,
  30393. symbolWidth,
  30394. symbolHeight,
  30395. lineStyle.stroke,
  30396. true
  30397. );
  30398. // Calculate arrow position with offset
  30399. var r = point.r + point.offset;
  30400. var pos = [
  30401. pt1[0] + r * Math.cos(opt.rotation),
  30402. pt1[1] - r * Math.sin(opt.rotation)
  30403. ];
  30404. symbol.attr({
  30405. rotation: point.rotate,
  30406. position: pos,
  30407. silent: true
  30408. });
  30409. this.group.add(symbol);
  30410. }
  30411. }, this);
  30412. }
  30413. },
  30414. /**
  30415. * @private
  30416. */
  30417. axisTickLabel: function () {
  30418. var axisModel = this.axisModel;
  30419. var opt = this.opt;
  30420. var tickEls = buildAxisTick(this, axisModel, opt);
  30421. var labelEls = buildAxisLabel(this, axisModel, opt);
  30422. fixMinMaxLabelShow(axisModel, labelEls, tickEls);
  30423. },
  30424. /**
  30425. * @private
  30426. */
  30427. axisName: function () {
  30428. var opt = this.opt;
  30429. var axisModel = this.axisModel;
  30430. var name = retrieve(opt.axisName, axisModel.get('name'));
  30431. if (!name) {
  30432. return;
  30433. }
  30434. var nameLocation = axisModel.get('nameLocation');
  30435. var nameDirection = opt.nameDirection;
  30436. var textStyleModel = axisModel.getModel('nameTextStyle');
  30437. var gap = axisModel.get('nameGap') || 0;
  30438. var extent = this.axisModel.axis.getExtent();
  30439. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  30440. var pos = [
  30441. nameLocation === 'start'
  30442. ? extent[0] - gapSignal * gap
  30443. : nameLocation === 'end'
  30444. ? extent[1] + gapSignal * gap
  30445. : (extent[0] + extent[1]) / 2, // 'middle'
  30446. // Reuse labelOffset.
  30447. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  30448. ];
  30449. var labelLayout;
  30450. var nameRotation = axisModel.get('nameRotate');
  30451. if (nameRotation != null) {
  30452. nameRotation = nameRotation * PI$2 / 180; // To radian.
  30453. }
  30454. var axisNameAvailableWidth;
  30455. if (isNameLocationCenter(nameLocation)) {
  30456. labelLayout = innerTextLayout(
  30457. opt.rotation,
  30458. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  30459. nameDirection
  30460. );
  30461. }
  30462. else {
  30463. labelLayout = endTextLayout(
  30464. opt, nameLocation, nameRotation || 0, extent
  30465. );
  30466. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  30467. if (axisNameAvailableWidth != null) {
  30468. axisNameAvailableWidth = Math.abs(
  30469. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  30470. );
  30471. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  30472. }
  30473. }
  30474. var textFont = textStyleModel.getFont();
  30475. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  30476. var ellipsis = truncateOpt.ellipsis;
  30477. var maxWidth = retrieve(
  30478. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  30479. );
  30480. // FIXME
  30481. // truncate rich text? (consider performance)
  30482. var truncatedText = (ellipsis != null && maxWidth != null)
  30483. ? truncateText$1(
  30484. name, maxWidth, textFont, ellipsis,
  30485. {minChar: 2, placeholder: truncateOpt.placeholder}
  30486. )
  30487. : name;
  30488. var tooltipOpt = axisModel.get('tooltip', true);
  30489. var mainType = axisModel.mainType;
  30490. var formatterParams = {
  30491. componentType: mainType,
  30492. name: name,
  30493. $vars: ['name']
  30494. };
  30495. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  30496. var textEl = new Text({
  30497. // Id for animation
  30498. anid: 'name',
  30499. __fullText: name,
  30500. __truncatedText: truncatedText,
  30501. position: pos,
  30502. rotation: labelLayout.rotation,
  30503. silent: isSilent(axisModel),
  30504. z2: 1,
  30505. tooltip: (tooltipOpt && tooltipOpt.show)
  30506. ? extend({
  30507. content: name,
  30508. formatter: function () {
  30509. return name;
  30510. },
  30511. formatterParams: formatterParams
  30512. }, tooltipOpt)
  30513. : null
  30514. });
  30515. setTextStyle(textEl.style, textStyleModel, {
  30516. text: truncatedText,
  30517. textFont: textFont,
  30518. textFill: textStyleModel.getTextColor()
  30519. || axisModel.get('axisLine.lineStyle.color'),
  30520. textAlign: labelLayout.textAlign,
  30521. textVerticalAlign: labelLayout.textVerticalAlign
  30522. });
  30523. if (axisModel.get('triggerEvent')) {
  30524. textEl.eventData = makeAxisEventDataBase(axisModel);
  30525. textEl.eventData.targetType = 'axisName';
  30526. textEl.eventData.name = name;
  30527. }
  30528. // FIXME
  30529. this._dumbGroup.add(textEl);
  30530. textEl.updateTransform();
  30531. this.group.add(textEl);
  30532. textEl.decomposeTransform();
  30533. }
  30534. };
  30535. /**
  30536. * @public
  30537. * @static
  30538. * @param {Object} opt
  30539. * @param {number} axisRotation in radian
  30540. * @param {number} textRotation in radian
  30541. * @param {number} direction
  30542. * @return {Object} {
  30543. * rotation, // according to axis
  30544. * textAlign,
  30545. * textVerticalAlign
  30546. * }
  30547. */
  30548. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  30549. var rotationDiff = remRadian(textRotation - axisRotation);
  30550. var textAlign;
  30551. var textVerticalAlign;
  30552. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  30553. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  30554. textAlign = 'center';
  30555. }
  30556. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  30557. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  30558. textAlign = 'center';
  30559. }
  30560. else {
  30561. textVerticalAlign = 'middle';
  30562. if (rotationDiff > 0 && rotationDiff < PI$2) {
  30563. textAlign = direction > 0 ? 'right' : 'left';
  30564. }
  30565. else {
  30566. textAlign = direction > 0 ? 'left' : 'right';
  30567. }
  30568. }
  30569. return {
  30570. rotation: rotationDiff,
  30571. textAlign: textAlign,
  30572. textVerticalAlign: textVerticalAlign
  30573. };
  30574. };
  30575. function endTextLayout(opt, textPosition, textRotate, extent) {
  30576. var rotationDiff = remRadian(textRotate - opt.rotation);
  30577. var textAlign;
  30578. var textVerticalAlign;
  30579. var inverse = extent[0] > extent[1];
  30580. var onLeft = (textPosition === 'start' && !inverse)
  30581. || (textPosition !== 'start' && inverse);
  30582. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  30583. textVerticalAlign = onLeft ? 'bottom' : 'top';
  30584. textAlign = 'center';
  30585. }
  30586. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  30587. textVerticalAlign = onLeft ? 'top' : 'bottom';
  30588. textAlign = 'center';
  30589. }
  30590. else {
  30591. textVerticalAlign = 'middle';
  30592. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  30593. textAlign = onLeft ? 'left' : 'right';
  30594. }
  30595. else {
  30596. textAlign = onLeft ? 'right' : 'left';
  30597. }
  30598. }
  30599. return {
  30600. rotation: rotationDiff,
  30601. textAlign: textAlign,
  30602. textVerticalAlign: textVerticalAlign
  30603. };
  30604. }
  30605. function isSilent(axisModel) {
  30606. var tooltipOpt = axisModel.get('tooltip');
  30607. return axisModel.get('silent')
  30608. // Consider mouse cursor, add these restrictions.
  30609. || !(
  30610. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  30611. );
  30612. }
  30613. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  30614. // If min or max are user set, we need to check
  30615. // If the tick on min(max) are overlap on their neighbour tick
  30616. // If they are overlapped, we need to hide the min(max) tick label
  30617. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  30618. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  30619. // FIXME
  30620. // Have not consider onBand yet, where tick els is more than label els.
  30621. labelEls = labelEls || [];
  30622. tickEls = tickEls || [];
  30623. var firstLabel = labelEls[0];
  30624. var nextLabel = labelEls[1];
  30625. var lastLabel = labelEls[labelEls.length - 1];
  30626. var prevLabel = labelEls[labelEls.length - 2];
  30627. var firstTick = tickEls[0];
  30628. var nextTick = tickEls[1];
  30629. var lastTick = tickEls[tickEls.length - 1];
  30630. var prevTick = tickEls[tickEls.length - 2];
  30631. if (showMinLabel === false) {
  30632. ignoreEl(firstLabel);
  30633. ignoreEl(firstTick);
  30634. }
  30635. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  30636. if (showMinLabel) {
  30637. ignoreEl(nextLabel);
  30638. ignoreEl(nextTick);
  30639. }
  30640. else {
  30641. ignoreEl(firstLabel);
  30642. ignoreEl(firstTick);
  30643. }
  30644. }
  30645. if (showMaxLabel === false) {
  30646. ignoreEl(lastLabel);
  30647. ignoreEl(lastTick);
  30648. }
  30649. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  30650. if (showMaxLabel) {
  30651. ignoreEl(prevLabel);
  30652. ignoreEl(prevTick);
  30653. }
  30654. else {
  30655. ignoreEl(lastLabel);
  30656. ignoreEl(lastTick);
  30657. }
  30658. }
  30659. }
  30660. function ignoreEl(el) {
  30661. el && (el.ignore = true);
  30662. }
  30663. function isTwoLabelOverlapped(current, next, labelLayout) {
  30664. // current and next has the same rotation.
  30665. var firstRect = current && current.getBoundingRect().clone();
  30666. var nextRect = next && next.getBoundingRect().clone();
  30667. if (!firstRect || !nextRect) {
  30668. return;
  30669. }
  30670. // When checking intersect of two rotated labels, we use mRotationBack
  30671. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  30672. var mRotationBack = identity([]);
  30673. rotate(mRotationBack, mRotationBack, -current.rotation);
  30674. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  30675. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  30676. return firstRect.intersect(nextRect);
  30677. }
  30678. function isNameLocationCenter(nameLocation) {
  30679. return nameLocation === 'middle' || nameLocation === 'center';
  30680. }
  30681. /**
  30682. * @static
  30683. */
  30684. var ifIgnoreOnTick$1 = AxisBuilder.ifIgnoreOnTick = function (
  30685. axis,
  30686. i,
  30687. interval,
  30688. ticksCnt,
  30689. showMinLabel,
  30690. showMaxLabel
  30691. ) {
  30692. if (i === 0 && showMinLabel || i === ticksCnt - 1 && showMaxLabel) {
  30693. return false;
  30694. }
  30695. // FIXME
  30696. // Have not consider label overlap (if label is too long) yet.
  30697. var rawTick;
  30698. var scale$$1 = axis.scale;
  30699. return scale$$1.type === 'ordinal'
  30700. && (
  30701. typeof interval === 'function'
  30702. ? (
  30703. rawTick = scale$$1.getTicks()[i],
  30704. !interval(rawTick, scale$$1.getLabel(rawTick))
  30705. )
  30706. : i % (interval + 1)
  30707. );
  30708. };
  30709. /**
  30710. * @static
  30711. */
  30712. var getInterval$1 = AxisBuilder.getInterval = function (model, labelInterval) {
  30713. var interval = model.get('interval');
  30714. if (interval == null || interval == 'auto') {
  30715. interval = labelInterval;
  30716. }
  30717. return interval;
  30718. };
  30719. function buildAxisTick(axisBuilder, axisModel, opt) {
  30720. var axis = axisModel.axis;
  30721. if (!axisModel.get('axisTick.show') || axis.scale.isBlank()) {
  30722. return;
  30723. }
  30724. var tickModel = axisModel.getModel('axisTick');
  30725. var lineStyleModel = tickModel.getModel('lineStyle');
  30726. var tickLen = tickModel.get('length');
  30727. var tickInterval = getInterval$1(tickModel, opt.labelInterval);
  30728. var ticksCoords = axis.getTicksCoords(tickModel.get('alignWithLabel'));
  30729. // FIXME
  30730. // Corresponds to ticksCoords ?
  30731. var ticks = axis.scale.getTicks();
  30732. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  30733. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  30734. var pt1 = [];
  30735. var pt2 = [];
  30736. var matrix = axisBuilder._transform;
  30737. var tickEls = [];
  30738. var ticksCnt = ticksCoords.length;
  30739. for (var i = 0; i < ticksCnt; i++) {
  30740. // Only ordinal scale support tick interval
  30741. if (ifIgnoreOnTick$1(
  30742. axis, i, tickInterval, ticksCnt,
  30743. showMinLabel, showMaxLabel
  30744. )) {
  30745. continue;
  30746. }
  30747. var tickCoord = ticksCoords[i];
  30748. pt1[0] = tickCoord;
  30749. pt1[1] = 0;
  30750. pt2[0] = tickCoord;
  30751. pt2[1] = opt.tickDirection * tickLen;
  30752. if (matrix) {
  30753. applyTransform(pt1, pt1, matrix);
  30754. applyTransform(pt2, pt2, matrix);
  30755. }
  30756. // Tick line, Not use group transform to have better line draw
  30757. var tickEl = new Line(subPixelOptimizeLine({
  30758. // Id for animation
  30759. anid: 'tick_' + ticks[i],
  30760. shape: {
  30761. x1: pt1[0],
  30762. y1: pt1[1],
  30763. x2: pt2[0],
  30764. y2: pt2[1]
  30765. },
  30766. style: defaults(
  30767. lineStyleModel.getLineStyle(),
  30768. {
  30769. stroke: axisModel.get('axisLine.lineStyle.color')
  30770. }
  30771. ),
  30772. z2: 2,
  30773. silent: true
  30774. }));
  30775. axisBuilder.group.add(tickEl);
  30776. tickEls.push(tickEl);
  30777. }
  30778. return tickEls;
  30779. }
  30780. function buildAxisLabel(axisBuilder, axisModel, opt) {
  30781. var axis = axisModel.axis;
  30782. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  30783. if (!show || axis.scale.isBlank()) {
  30784. return;
  30785. }
  30786. var labelModel = axisModel.getModel('axisLabel');
  30787. var labelMargin = labelModel.get('margin');
  30788. var ticks = axis.scale.getTicks();
  30789. var labels = axisModel.getFormattedLabels();
  30790. // Special label rotate.
  30791. var labelRotation = (
  30792. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  30793. ) * PI$2 / 180;
  30794. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  30795. var categoryData = axisModel.getCategories();
  30796. var labelEls = [];
  30797. var silent = isSilent(axisModel);
  30798. var triggerEvent = axisModel.get('triggerEvent');
  30799. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  30800. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  30801. each$1(ticks, function (tickVal, index) {
  30802. if (ifIgnoreOnTick$1(
  30803. axis, index, opt.labelInterval, ticks.length,
  30804. showMinLabel, showMaxLabel
  30805. )) {
  30806. return;
  30807. }
  30808. var itemLabelModel = labelModel;
  30809. if (categoryData && categoryData[tickVal] && categoryData[tickVal].textStyle) {
  30810. itemLabelModel = new Model(
  30811. categoryData[tickVal].textStyle, labelModel, axisModel.ecModel
  30812. );
  30813. }
  30814. var textColor = itemLabelModel.getTextColor()
  30815. || axisModel.get('axisLine.lineStyle.color');
  30816. var tickCoord = axis.dataToCoord(tickVal);
  30817. var pos = [
  30818. tickCoord,
  30819. opt.labelOffset + opt.labelDirection * labelMargin
  30820. ];
  30821. var labelStr = axis.scale.getLabel(tickVal);
  30822. var textEl = new Text({
  30823. // Id for animation
  30824. anid: 'label_' + tickVal,
  30825. position: pos,
  30826. rotation: labelLayout.rotation,
  30827. silent: silent,
  30828. z2: 10
  30829. });
  30830. setTextStyle(textEl.style, itemLabelModel, {
  30831. text: labels[index],
  30832. textAlign: itemLabelModel.getShallow('align', true)
  30833. || labelLayout.textAlign,
  30834. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  30835. || itemLabelModel.getShallow('baseline', true)
  30836. || labelLayout.textVerticalAlign,
  30837. textFill: typeof textColor === 'function'
  30838. ? textColor(
  30839. // (1) In category axis with data zoom, tick is not the original
  30840. // index of axis.data. So tick should not be exposed to user
  30841. // in category axis.
  30842. // (2) Compatible with previous version, which always returns labelStr.
  30843. // But in interval scale labelStr is like '223,445', which maked
  30844. // user repalce ','. So we modify it to return original val but remain
  30845. // it as 'string' to avoid error in replacing.
  30846. axis.type === 'category' ? labelStr : axis.type === 'value' ? tickVal + '' : tickVal,
  30847. index
  30848. )
  30849. : textColor
  30850. });
  30851. // Pack data for mouse event
  30852. if (triggerEvent) {
  30853. textEl.eventData = makeAxisEventDataBase(axisModel);
  30854. textEl.eventData.targetType = 'axisLabel';
  30855. textEl.eventData.value = labelStr;
  30856. }
  30857. // FIXME
  30858. axisBuilder._dumbGroup.add(textEl);
  30859. textEl.updateTransform();
  30860. labelEls.push(textEl);
  30861. axisBuilder.group.add(textEl);
  30862. textEl.decomposeTransform();
  30863. });
  30864. return labelEls;
  30865. }
  30866. var each$7 = each$1;
  30867. var curry$1 = curry;
  30868. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  30869. // allAxesInfo should be updated when setOption performed.
  30870. function collect(ecModel, api) {
  30871. var result = {
  30872. /**
  30873. * key: makeKey(axis.model)
  30874. * value: {
  30875. * axis,
  30876. * coordSys,
  30877. * axisPointerModel,
  30878. * triggerTooltip,
  30879. * involveSeries,
  30880. * snap,
  30881. * seriesModels,
  30882. * seriesDataCount
  30883. * }
  30884. */
  30885. axesInfo: {},
  30886. seriesInvolved: false,
  30887. /**
  30888. * key: makeKey(coordSys.model)
  30889. * value: Object: key makeKey(axis.model), value: axisInfo
  30890. */
  30891. coordSysAxesInfo: {},
  30892. coordSysMap: {}
  30893. };
  30894. collectAxesInfo(result, ecModel, api);
  30895. // Check seriesInvolved for performance, in case too many series in some chart.
  30896. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  30897. return result;
  30898. }
  30899. function collectAxesInfo(result, ecModel, api) {
  30900. var globalTooltipModel = ecModel.getComponent('tooltip');
  30901. var globalAxisPointerModel = ecModel.getComponent('axisPointer');
  30902. // links can only be set on global.
  30903. var linksOption = globalAxisPointerModel.get('link', true) || [];
  30904. var linkGroups = [];
  30905. // Collect axes info.
  30906. each$7(api.getCoordinateSystems(), function (coordSys) {
  30907. // Some coordinate system do not support axes, like geo.
  30908. if (!coordSys.axisPointerEnabled) {
  30909. return;
  30910. }
  30911. var coordSysKey = makeKey(coordSys.model);
  30912. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  30913. result.coordSysMap[coordSysKey] = coordSys;
  30914. // Set tooltip (like 'cross') is a convienent way to show axisPointer
  30915. // for user. So we enable seting tooltip on coordSys model.
  30916. var coordSysModel = coordSys.model;
  30917. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  30918. each$7(coordSys.getAxes(), curry$1(saveTooltipAxisInfo, false, null));
  30919. // If axis tooltip used, choose tooltip axis for each coordSys.
  30920. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  30921. if (coordSys.getTooltipAxes
  30922. && globalTooltipModel
  30923. // If tooltip.showContent is set as false, tooltip will not
  30924. // show but axisPointer will show as normal.
  30925. && baseTooltipModel.get('show')
  30926. ) {
  30927. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  30928. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  30929. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  30930. var cross = baseTooltipModel.get('axisPointer.type') === 'cross';
  30931. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get('axisPointer.axis'));
  30932. if (triggerAxis || cross) {
  30933. each$7(tooltipAxes.baseAxes, curry$1(
  30934. saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis
  30935. ));
  30936. }
  30937. if (cross) {
  30938. each$7(tooltipAxes.otherAxes, curry$1(saveTooltipAxisInfo, 'cross', false));
  30939. }
  30940. }
  30941. // fromTooltip: true | false | 'cross'
  30942. // triggerTooltip: true | false | null
  30943. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  30944. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  30945. var axisPointerShow = axisPointerModel.get('show');
  30946. if (!axisPointerShow || (
  30947. axisPointerShow === 'auto'
  30948. && !fromTooltip
  30949. && !isHandleTrigger(axisPointerModel)
  30950. )) {
  30951. return;
  30952. }
  30953. if (triggerTooltip == null) {
  30954. triggerTooltip = axisPointerModel.get('triggerTooltip');
  30955. }
  30956. axisPointerModel = fromTooltip
  30957. ? makeAxisPointerModel(
  30958. axis, baseTooltipModel, globalAxisPointerModel, ecModel,
  30959. fromTooltip, triggerTooltip
  30960. )
  30961. : axisPointerModel;
  30962. var snap = axisPointerModel.get('snap');
  30963. var key = makeKey(axis.model);
  30964. var involveSeries = triggerTooltip || snap || axis.type === 'category';
  30965. // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  30966. var axisInfo = result.axesInfo[key] = {
  30967. key: key,
  30968. axis: axis,
  30969. coordSys: coordSys,
  30970. axisPointerModel: axisPointerModel,
  30971. triggerTooltip: triggerTooltip,
  30972. involveSeries: involveSeries,
  30973. snap: snap,
  30974. useHandle: isHandleTrigger(axisPointerModel),
  30975. seriesModels: []
  30976. };
  30977. axesInfoInCoordSys[key] = axisInfo;
  30978. result.seriesInvolved |= involveSeries;
  30979. var groupIndex = getLinkGroupIndex(linksOption, axis);
  30980. if (groupIndex != null) {
  30981. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {axesInfo: {}});
  30982. linkGroup.axesInfo[key] = axisInfo;
  30983. linkGroup.mapper = linksOption[groupIndex].mapper;
  30984. axisInfo.linkGroup = linkGroup;
  30985. }
  30986. }
  30987. });
  30988. }
  30989. function makeAxisPointerModel(
  30990. axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip
  30991. ) {
  30992. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  30993. var volatileOption = {};
  30994. each$7(
  30995. [
  30996. 'type', 'snap', 'lineStyle', 'shadowStyle', 'label',
  30997. 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'
  30998. ],
  30999. function (field) {
  31000. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  31001. }
  31002. );
  31003. // category axis do not auto snap, otherwise some tick that do not
  31004. // has value can not be hovered. value/time/log axis default snap if
  31005. // triggered from tooltip and trigger tooltip.
  31006. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip;
  31007. // Compatibel with previous behavior, tooltip axis do not show label by default.
  31008. // Only these properties can be overrided from tooltip to axisPointer.
  31009. if (tooltipAxisPointerModel.get('type') === 'cross') {
  31010. volatileOption.type = 'line';
  31011. }
  31012. var labelOption = volatileOption.label || (volatileOption.label = {});
  31013. // Follow the convention, do not show label when triggered by tooltip by default.
  31014. labelOption.show == null && (labelOption.show = false);
  31015. if (fromTooltip === 'cross') {
  31016. // When 'cross', both axes show labels.
  31017. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get('label.show');
  31018. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true;
  31019. // If triggerTooltip, this is a base axis, which should better not use cross style
  31020. // (cross style is dashed by default)
  31021. if (!triggerTooltip) {
  31022. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  31023. crossStyle && defaults(labelOption, crossStyle.textStyle);
  31024. }
  31025. }
  31026. return axis.model.getModel(
  31027. 'axisPointer',
  31028. new Model(volatileOption, globalAxisPointerModel, ecModel)
  31029. );
  31030. }
  31031. function collectSeriesInfo(result, ecModel) {
  31032. // Prepare data for axis trigger
  31033. ecModel.eachSeries(function (seriesModel) {
  31034. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  31035. var coordSys = seriesModel.coordinateSystem;
  31036. var seriesTooltipTrigger = seriesModel.get('tooltip.trigger', true);
  31037. var seriesTooltipShow = seriesModel.get('tooltip.show', true);
  31038. if (!coordSys
  31039. || seriesTooltipTrigger === 'none'
  31040. || seriesTooltipTrigger === false
  31041. || seriesTooltipTrigger === 'item'
  31042. || seriesTooltipShow === false
  31043. || seriesModel.get('axisPointer.show', true) === false
  31044. ) {
  31045. return;
  31046. }
  31047. each$7(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  31048. var axis = axisInfo.axis;
  31049. if (coordSys.getAxis(axis.dim) === axis) {
  31050. axisInfo.seriesModels.push(seriesModel);
  31051. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  31052. axisInfo.seriesDataCount += seriesModel.getData().count();
  31053. }
  31054. });
  31055. }, this);
  31056. }
  31057. /**
  31058. * For example:
  31059. * {
  31060. * axisPointer: {
  31061. * links: [{
  31062. * xAxisIndex: [2, 4],
  31063. * yAxisIndex: 'all'
  31064. * }, {
  31065. * xAxisId: ['a5', 'a7'],
  31066. * xAxisName: 'xxx'
  31067. * }]
  31068. * }
  31069. * }
  31070. */
  31071. function getLinkGroupIndex(linksOption, axis) {
  31072. var axisModel = axis.model;
  31073. var dim = axis.dim;
  31074. for (var i = 0; i < linksOption.length; i++) {
  31075. var linkOption = linksOption[i] || {};
  31076. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id)
  31077. || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex)
  31078. || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)
  31079. ) {
  31080. return i;
  31081. }
  31082. }
  31083. }
  31084. function checkPropInLink(linkPropValue, axisPropValue) {
  31085. return linkPropValue === 'all'
  31086. || (isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0)
  31087. || linkPropValue === axisPropValue;
  31088. }
  31089. function fixValue(axisModel) {
  31090. var axisInfo = getAxisInfo(axisModel);
  31091. if (!axisInfo) {
  31092. return;
  31093. }
  31094. var axisPointerModel = axisInfo.axisPointerModel;
  31095. var scale = axisInfo.axis.scale;
  31096. var option = axisPointerModel.option;
  31097. var status = axisPointerModel.get('status');
  31098. var value = axisPointerModel.get('value');
  31099. // Parse init value for category and time axis.
  31100. if (value != null) {
  31101. value = scale.parse(value);
  31102. }
  31103. var useHandle = isHandleTrigger(axisPointerModel);
  31104. // If `handle` used, `axisPointer` will always be displayed, so value
  31105. // and status should be initialized.
  31106. if (status == null) {
  31107. option.status = useHandle ? 'show' : 'hide';
  31108. }
  31109. var extent = scale.getExtent().slice();
  31110. extent[0] > extent[1] && extent.reverse();
  31111. if (// Pick a value on axis when initializing.
  31112. value == null
  31113. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  31114. // where we should re-pick a value to keep `handle` displaying normally.
  31115. || value > extent[1]
  31116. ) {
  31117. // Make handle displayed on the end of the axis when init, which looks better.
  31118. value = extent[1];
  31119. }
  31120. if (value < extent[0]) {
  31121. value = extent[0];
  31122. }
  31123. option.value = value;
  31124. if (useHandle) {
  31125. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  31126. }
  31127. }
  31128. function getAxisInfo(axisModel) {
  31129. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  31130. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  31131. }
  31132. function getAxisPointerModel(axisModel) {
  31133. var axisInfo = getAxisInfo(axisModel);
  31134. return axisInfo && axisInfo.axisPointerModel;
  31135. }
  31136. function isHandleTrigger(axisPointerModel) {
  31137. return !!axisPointerModel.get('handle.show');
  31138. }
  31139. /**
  31140. * @param {module:echarts/model/Model} model
  31141. * @return {string} unique key
  31142. */
  31143. function makeKey(model) {
  31144. return model.type + '||' + model.id;
  31145. }
  31146. /**
  31147. * Base class of AxisView.
  31148. */
  31149. var AxisView = extendComponentView({
  31150. type: 'axis',
  31151. /**
  31152. * @private
  31153. */
  31154. _axisPointer: null,
  31155. /**
  31156. * @protected
  31157. * @type {string}
  31158. */
  31159. axisPointerClass: null,
  31160. /**
  31161. * @override
  31162. */
  31163. render: function (axisModel, ecModel, api, payload) {
  31164. // FIXME
  31165. // This process should proformed after coordinate systems updated
  31166. // (axis scale updated), and should be performed each time update.
  31167. // So put it here temporarily, although it is not appropriate to
  31168. // put a model-writing procedure in `view`.
  31169. this.axisPointerClass && fixValue(axisModel);
  31170. AxisView.superApply(this, 'render', arguments);
  31171. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  31172. },
  31173. /**
  31174. * Action handler.
  31175. * @public
  31176. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  31177. * @param {module:echarts/model/Global} ecModel
  31178. * @param {module:echarts/ExtensionAPI} api
  31179. * @param {Object} payload
  31180. */
  31181. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  31182. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  31183. },
  31184. /**
  31185. * @override
  31186. */
  31187. remove: function (ecModel, api) {
  31188. var axisPointer = this._axisPointer;
  31189. axisPointer && axisPointer.remove(api);
  31190. AxisView.superApply(this, 'remove', arguments);
  31191. },
  31192. /**
  31193. * @override
  31194. */
  31195. dispose: function (ecModel, api) {
  31196. disposeAxisPointer(this, api);
  31197. AxisView.superApply(this, 'dispose', arguments);
  31198. }
  31199. });
  31200. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  31201. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  31202. if (!Clazz) {
  31203. return;
  31204. }
  31205. var axisPointerModel = getAxisPointerModel(axisModel);
  31206. axisPointerModel
  31207. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  31208. .render(axisModel, axisPointerModel, api, forceRender)
  31209. : disposeAxisPointer(axisView, api);
  31210. }
  31211. function disposeAxisPointer(axisView, ecModel, api) {
  31212. var axisPointer = axisView._axisPointer;
  31213. axisPointer && axisPointer.dispose(ecModel, api);
  31214. axisView._axisPointer = null;
  31215. }
  31216. var axisPointerClazz = [];
  31217. AxisView.registerAxisPointerClass = function (type, clazz) {
  31218. if (__DEV__) {
  31219. if (axisPointerClazz[type]) {
  31220. throw new Error('axisPointer ' + type + ' exists');
  31221. }
  31222. }
  31223. axisPointerClazz[type] = clazz;
  31224. };
  31225. AxisView.getAxisPointerClass = function (type) {
  31226. return type && axisPointerClazz[type];
  31227. };
  31228. /**
  31229. * @param {Object} opt {labelInside}
  31230. * @return {Object} {
  31231. * position, rotation, labelDirection, labelOffset,
  31232. * tickDirection, labelRotate, labelInterval, z2
  31233. * }
  31234. */
  31235. function layout$1(gridModel, axisModel, opt) {
  31236. opt = opt || {};
  31237. var grid = gridModel.coordinateSystem;
  31238. var axis = axisModel.axis;
  31239. var layout = {};
  31240. var rawAxisPosition = axis.position;
  31241. var axisPosition = axis.onZero ? 'onZero' : rawAxisPosition;
  31242. var axisDim = axis.dim;
  31243. var rect = grid.getRect();
  31244. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  31245. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  31246. var axisOffset = axisModel.get('offset') || 0;
  31247. var posBound = axisDim === 'x'
  31248. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  31249. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  31250. if (axis.onZero) {
  31251. var otherAxis = grid.getAxis(axisDim === 'x' ? 'y' : 'x', axis.onZeroAxisIndex);
  31252. var onZeroCoord = otherAxis.toGlobalCoord(otherAxis.dataToCoord(0));
  31253. posBound[idx['onZero']] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  31254. }
  31255. // Axis position
  31256. layout.position = [
  31257. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  31258. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  31259. ];
  31260. // Axis rotation
  31261. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  31262. // Tick and label direction, x y is axisDim
  31263. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  31264. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  31265. layout.labelOffset = axis.onZero ? posBound[idx[rawAxisPosition]] - posBound[idx['onZero']] : 0;
  31266. if (axisModel.get('axisTick.inside')) {
  31267. layout.tickDirection = -layout.tickDirection;
  31268. }
  31269. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  31270. layout.labelDirection = -layout.labelDirection;
  31271. }
  31272. // Special label rotation
  31273. var labelRotate = axisModel.get('axisLabel.rotate');
  31274. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  31275. // label interval when auto mode.
  31276. layout.labelInterval = axis.getLabelInterval();
  31277. // Over splitLine and splitArea
  31278. layout.z2 = 1;
  31279. return layout;
  31280. }
  31281. var ifIgnoreOnTick = AxisBuilder.ifIgnoreOnTick;
  31282. var getInterval = AxisBuilder.getInterval;
  31283. var axisBuilderAttrs = [
  31284. 'axisLine', 'axisTickLabel', 'axisName'
  31285. ];
  31286. var selfBuilderAttrs = [
  31287. 'splitArea', 'splitLine'
  31288. ];
  31289. // function getAlignWithLabel(model, axisModel) {
  31290. // var alignWithLabel = model.get('alignWithLabel');
  31291. // if (alignWithLabel === 'auto') {
  31292. // alignWithLabel = axisModel.get('axisTick.alignWithLabel');
  31293. // }
  31294. // return alignWithLabel;
  31295. // }
  31296. var CartesianAxisView = AxisView.extend({
  31297. type: 'cartesianAxis',
  31298. axisPointerClass: 'CartesianAxisPointer',
  31299. /**
  31300. * @override
  31301. */
  31302. render: function (axisModel, ecModel, api, payload) {
  31303. this.group.removeAll();
  31304. var oldAxisGroup = this._axisGroup;
  31305. this._axisGroup = new Group();
  31306. this.group.add(this._axisGroup);
  31307. if (!axisModel.get('show')) {
  31308. return;
  31309. }
  31310. var gridModel = axisModel.getCoordSysModel();
  31311. var layout = layout$1(gridModel, axisModel);
  31312. var axisBuilder = new AxisBuilder(axisModel, layout);
  31313. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  31314. this._axisGroup.add(axisBuilder.getGroup());
  31315. each$1(selfBuilderAttrs, function (name) {
  31316. if (axisModel.get(name + '.show')) {
  31317. this['_' + name](axisModel, gridModel, layout.labelInterval);
  31318. }
  31319. }, this);
  31320. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  31321. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  31322. },
  31323. /**
  31324. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  31325. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  31326. * @param {number|Function} labelInterval
  31327. * @private
  31328. */
  31329. _splitLine: function (axisModel, gridModel, labelInterval) {
  31330. var axis = axisModel.axis;
  31331. if (axis.scale.isBlank()) {
  31332. return;
  31333. }
  31334. var splitLineModel = axisModel.getModel('splitLine');
  31335. var lineStyleModel = splitLineModel.getModel('lineStyle');
  31336. var lineColors = lineStyleModel.get('color');
  31337. var lineInterval = getInterval(splitLineModel, labelInterval);
  31338. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  31339. var gridRect = gridModel.coordinateSystem.getRect();
  31340. var isHorizontal = axis.isHorizontal();
  31341. var lineCount = 0;
  31342. var ticksCoords = axis.getTicksCoords(
  31343. // splitLineModel.get('alignWithLabel')
  31344. );
  31345. var ticks = axis.scale.getTicks();
  31346. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  31347. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  31348. var p1 = [];
  31349. var p2 = [];
  31350. // Simple optimization
  31351. // Batching the lines if color are the same
  31352. var lineStyle = lineStyleModel.getLineStyle();
  31353. for (var i = 0; i < ticksCoords.length; i++) {
  31354. if (ifIgnoreOnTick(
  31355. axis, i, lineInterval, ticksCoords.length,
  31356. showMinLabel, showMaxLabel
  31357. )) {
  31358. continue;
  31359. }
  31360. var tickCoord = axis.toGlobalCoord(ticksCoords[i]);
  31361. if (isHorizontal) {
  31362. p1[0] = tickCoord;
  31363. p1[1] = gridRect.y;
  31364. p2[0] = tickCoord;
  31365. p2[1] = gridRect.y + gridRect.height;
  31366. }
  31367. else {
  31368. p1[0] = gridRect.x;
  31369. p1[1] = tickCoord;
  31370. p2[0] = gridRect.x + gridRect.width;
  31371. p2[1] = tickCoord;
  31372. }
  31373. var colorIndex = (lineCount++) % lineColors.length;
  31374. this._axisGroup.add(new Line(subPixelOptimizeLine({
  31375. anid: 'line_' + ticks[i],
  31376. shape: {
  31377. x1: p1[0],
  31378. y1: p1[1],
  31379. x2: p2[0],
  31380. y2: p2[1]
  31381. },
  31382. style: defaults({
  31383. stroke: lineColors[colorIndex]
  31384. }, lineStyle),
  31385. silent: true
  31386. })));
  31387. }
  31388. },
  31389. /**
  31390. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  31391. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  31392. * @param {number|Function} labelInterval
  31393. * @private
  31394. */
  31395. _splitArea: function (axisModel, gridModel, labelInterval) {
  31396. var axis = axisModel.axis;
  31397. if (axis.scale.isBlank()) {
  31398. return;
  31399. }
  31400. var splitAreaModel = axisModel.getModel('splitArea');
  31401. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  31402. var areaColors = areaStyleModel.get('color');
  31403. var gridRect = gridModel.coordinateSystem.getRect();
  31404. var ticksCoords = axis.getTicksCoords(
  31405. // splitAreaModel.get('alignWithLabel')
  31406. );
  31407. var ticks = axis.scale.getTicks();
  31408. var prevX = axis.toGlobalCoord(ticksCoords[0]);
  31409. var prevY = axis.toGlobalCoord(ticksCoords[0]);
  31410. var count = 0;
  31411. var areaInterval = getInterval(splitAreaModel, labelInterval);
  31412. var areaStyle = areaStyleModel.getAreaStyle();
  31413. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  31414. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  31415. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  31416. for (var i = 1; i < ticksCoords.length; i++) {
  31417. if (ifIgnoreOnTick(
  31418. axis, i, areaInterval, ticksCoords.length,
  31419. showMinLabel, showMaxLabel
  31420. ) && (i < ticksCoords.length - 1)) {
  31421. continue;
  31422. }
  31423. var tickCoord = axis.toGlobalCoord(ticksCoords[i]);
  31424. var x;
  31425. var y;
  31426. var width;
  31427. var height;
  31428. if (axis.isHorizontal()) {
  31429. x = prevX;
  31430. y = gridRect.y;
  31431. width = tickCoord - x;
  31432. height = gridRect.height;
  31433. }
  31434. else {
  31435. x = gridRect.x;
  31436. y = prevY;
  31437. width = gridRect.width;
  31438. height = tickCoord - y;
  31439. }
  31440. var colorIndex = (count++) % areaColors.length;
  31441. this._axisGroup.add(new Rect({
  31442. anid: 'area_' + ticks[i],
  31443. shape: {
  31444. x: x,
  31445. y: y,
  31446. width: width,
  31447. height: height
  31448. },
  31449. style: defaults({
  31450. fill: areaColors[colorIndex]
  31451. }, areaStyle),
  31452. silent: true
  31453. }));
  31454. prevX = x + width;
  31455. prevY = y + height;
  31456. }
  31457. }
  31458. });
  31459. CartesianAxisView.extend({
  31460. type: 'xAxis'
  31461. });
  31462. CartesianAxisView.extend({
  31463. type: 'yAxis'
  31464. });
  31465. // Grid view
  31466. extendComponentView({
  31467. type: 'grid',
  31468. render: function (gridModel, ecModel) {
  31469. this.group.removeAll();
  31470. if (gridModel.get('show')) {
  31471. this.group.add(new Rect({
  31472. shape: gridModel.coordinateSystem.getRect(),
  31473. style: defaults({
  31474. fill: gridModel.get('backgroundColor')
  31475. }, gridModel.getItemStyle()),
  31476. silent: true,
  31477. z2: -1
  31478. }));
  31479. }
  31480. }
  31481. });
  31482. registerPreprocessor(function (option) {
  31483. // Only create grid when need
  31484. if (option.xAxis && option.yAxis && !option.grid) {
  31485. option.grid = {};
  31486. }
  31487. });
  31488. // In case developer forget to include grid component
  31489. registerVisual(visualSymbol('line', 'circle', 'line'));
  31490. registerLayout(pointsLayout('line'));
  31491. // Down sample after filter
  31492. registerProcessor(
  31493. PRIORITY.PROCESSOR.STATISTIC,
  31494. dataSample('line')
  31495. );
  31496. var BaseBarSeries = SeriesModel.extend({
  31497. type: 'series.__base_bar__',
  31498. getInitialData: function (option, ecModel) {
  31499. return createListFromArray(this.getSource(), this);
  31500. },
  31501. getMarkerPosition: function (value) {
  31502. var coordSys = this.coordinateSystem;
  31503. if (coordSys) {
  31504. // PENDING if clamp ?
  31505. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  31506. var data = this.getData();
  31507. var offset = data.getLayout('offset');
  31508. var size = data.getLayout('size');
  31509. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  31510. pt[offsetIndex] += offset + size / 2;
  31511. return pt;
  31512. }
  31513. return [NaN, NaN];
  31514. },
  31515. defaultOption: {
  31516. zlevel: 0, // 一级层叠
  31517. z: 2, // 二级层叠
  31518. coordinateSystem: 'cartesian2d',
  31519. legendHoverLink: true,
  31520. // stack: null
  31521. // Cartesian coordinate system
  31522. // xAxisIndex: 0,
  31523. // yAxisIndex: 0,
  31524. // 最小高度改为0
  31525. barMinHeight: 0,
  31526. // 最小角度为0,仅对极坐标系下的柱状图有效
  31527. barMinAngle: 0,
  31528. // cursor: null,
  31529. // barMaxWidth: null,
  31530. // 默认自适应
  31531. // barWidth: null,
  31532. // 柱间距离,默认为柱形宽度的30%,可设固定值
  31533. // barGap: '30%',
  31534. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  31535. // barCategoryGap: '20%',
  31536. // label: {
  31537. // show: false
  31538. // },
  31539. itemStyle: {},
  31540. emphasis: {}
  31541. }
  31542. });
  31543. BaseBarSeries.extend({
  31544. type: 'series.bar',
  31545. dependencies: ['grid', 'polar'],
  31546. brushSelector: 'rect'
  31547. });
  31548. function setLabel(
  31549. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  31550. ) {
  31551. var labelModel = itemModel.getModel('label');
  31552. var hoverLabelModel = itemModel.getModel('emphasis.label');
  31553. setLabelStyle(
  31554. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  31555. {
  31556. labelFetcher: seriesModel,
  31557. labelDataIndex: dataIndex,
  31558. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  31559. isRectText: true,
  31560. autoColor: color
  31561. }
  31562. );
  31563. fixPosition(normalStyle);
  31564. fixPosition(hoverStyle);
  31565. }
  31566. function fixPosition(style, labelPositionOutside) {
  31567. if (style.textPosition === 'outside') {
  31568. style.textPosition = labelPositionOutside;
  31569. }
  31570. }
  31571. var getBarItemStyle = makeStyleMapper(
  31572. [
  31573. ['fill', 'color'],
  31574. ['stroke', 'borderColor'],
  31575. ['lineWidth', 'borderWidth'],
  31576. // Compatitable with 2
  31577. ['stroke', 'barBorderColor'],
  31578. ['lineWidth', 'barBorderWidth'],
  31579. ['opacity'],
  31580. ['shadowBlur'],
  31581. ['shadowOffsetX'],
  31582. ['shadowOffsetY'],
  31583. ['shadowColor']
  31584. ]
  31585. );
  31586. var barItemStyle = {
  31587. getBarItemStyle: function (excludes) {
  31588. var style = getBarItemStyle(this, excludes);
  31589. if (this.getBorderLineDash) {
  31590. var lineDash = this.getBorderLineDash();
  31591. lineDash && (style.lineDash = lineDash);
  31592. }
  31593. return style;
  31594. }
  31595. };
  31596. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  31597. // FIXME
  31598. // Just for compatible with ec2.
  31599. extend(Model.prototype, barItemStyle);
  31600. extendChartView({
  31601. type: 'bar',
  31602. render: function (seriesModel, ecModel, api) {
  31603. var coordinateSystemType = seriesModel.get('coordinateSystem');
  31604. if (coordinateSystemType === 'cartesian2d'
  31605. || coordinateSystemType === 'polar'
  31606. ) {
  31607. this._render(seriesModel, ecModel, api);
  31608. }
  31609. else if (__DEV__) {
  31610. console.warn('Only cartesian2d and polar supported for bar.');
  31611. }
  31612. return this.group;
  31613. },
  31614. dispose: noop,
  31615. _render: function (seriesModel, ecModel, api) {
  31616. var group = this.group;
  31617. var data = seriesModel.getData();
  31618. var oldData = this._data;
  31619. var coord = seriesModel.coordinateSystem;
  31620. var baseAxis = coord.getBaseAxis();
  31621. var isHorizontalOrRadial;
  31622. if (coord.type === 'cartesian2d') {
  31623. isHorizontalOrRadial = baseAxis.isHorizontal();
  31624. }
  31625. else if (coord.type === 'polar') {
  31626. isHorizontalOrRadial = baseAxis.dim === 'angle';
  31627. }
  31628. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  31629. data.diff(oldData)
  31630. .add(function (dataIndex) {
  31631. if (!data.hasValue(dataIndex)) {
  31632. return;
  31633. }
  31634. var itemModel = data.getItemModel(dataIndex);
  31635. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  31636. var el = elementCreator[coord.type](
  31637. data, dataIndex, itemModel, layout, isHorizontalOrRadial, animationModel
  31638. );
  31639. data.setItemGraphicEl(dataIndex, el);
  31640. group.add(el);
  31641. updateStyle(
  31642. el, data, dataIndex, itemModel, layout,
  31643. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  31644. );
  31645. })
  31646. .update(function (newIndex, oldIndex) {
  31647. var el = oldData.getItemGraphicEl(oldIndex);
  31648. if (!data.hasValue(newIndex)) {
  31649. group.remove(el);
  31650. return;
  31651. }
  31652. var itemModel = data.getItemModel(newIndex);
  31653. var layout = getLayout[coord.type](data, newIndex, itemModel);
  31654. if (el) {
  31655. updateProps(el, {shape: layout}, animationModel, newIndex);
  31656. }
  31657. else {
  31658. el = elementCreator[coord.type](
  31659. data, newIndex, itemModel, layout, isHorizontalOrRadial, animationModel, true
  31660. );
  31661. }
  31662. data.setItemGraphicEl(newIndex, el);
  31663. // Add back
  31664. group.add(el);
  31665. updateStyle(
  31666. el, data, newIndex, itemModel, layout,
  31667. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  31668. );
  31669. })
  31670. .remove(function (dataIndex) {
  31671. var el = oldData.getItemGraphicEl(dataIndex);
  31672. if (coord.type === 'cartesian2d') {
  31673. el && removeRect(dataIndex, animationModel, el);
  31674. }
  31675. else {
  31676. el && removeSector(dataIndex, animationModel, el);
  31677. }
  31678. })
  31679. .execute();
  31680. this._data = data;
  31681. },
  31682. remove: function (ecModel, api) {
  31683. var group = this.group;
  31684. var data = this._data;
  31685. if (ecModel.get('animation')) {
  31686. if (data) {
  31687. data.eachItemGraphicEl(function (el) {
  31688. if (el.type === 'sector') {
  31689. removeSector(el.dataIndex, ecModel, el);
  31690. }
  31691. else {
  31692. removeRect(el.dataIndex, ecModel, el);
  31693. }
  31694. });
  31695. }
  31696. }
  31697. else {
  31698. group.removeAll();
  31699. }
  31700. }
  31701. });
  31702. var elementCreator = {
  31703. cartesian2d: function (
  31704. data, dataIndex, itemModel, layout, isHorizontal,
  31705. animationModel, isUpdate
  31706. ) {
  31707. var rect = new Rect({shape: extend({}, layout)});
  31708. // Animation
  31709. if (animationModel) {
  31710. var rectShape = rect.shape;
  31711. var animateProperty = isHorizontal ? 'height' : 'width';
  31712. var animateTarget = {};
  31713. rectShape[animateProperty] = 0;
  31714. animateTarget[animateProperty] = layout[animateProperty];
  31715. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  31716. shape: animateTarget
  31717. }, animationModel, dataIndex);
  31718. }
  31719. return rect;
  31720. },
  31721. polar: function (
  31722. data, dataIndex, itemModel, layout, isRadial,
  31723. animationModel, isUpdate
  31724. ) {
  31725. // Keep the same logic with bar in catesion: use end value to control
  31726. // direction. Notice that if clockwise is true (by default), the sector
  31727. // will always draw clockwisely, no matter whether endAngle is greater
  31728. // or less than startAngle.
  31729. var clockwise = layout.startAngle < layout.endAngle;
  31730. var sector = new Sector({
  31731. shape: defaults({clockwise: clockwise}, layout)
  31732. });
  31733. // Animation
  31734. if (animationModel) {
  31735. var sectorShape = sector.shape;
  31736. var animateProperty = isRadial ? 'r' : 'endAngle';
  31737. var animateTarget = {};
  31738. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  31739. animateTarget[animateProperty] = layout[animateProperty];
  31740. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  31741. shape: animateTarget
  31742. }, animationModel, dataIndex);
  31743. }
  31744. return sector;
  31745. }
  31746. };
  31747. function removeRect(dataIndex, animationModel, el) {
  31748. // Not show text when animating
  31749. el.style.text = null;
  31750. updateProps(el, {
  31751. shape: {
  31752. width: 0
  31753. }
  31754. }, animationModel, dataIndex, function () {
  31755. el.parent && el.parent.remove(el);
  31756. });
  31757. }
  31758. function removeSector(dataIndex, animationModel, el) {
  31759. // Not show text when animating
  31760. el.style.text = null;
  31761. updateProps(el, {
  31762. shape: {
  31763. r: el.shape.r0
  31764. }
  31765. }, animationModel, dataIndex, function () {
  31766. el.parent && el.parent.remove(el);
  31767. });
  31768. }
  31769. var getLayout = {
  31770. cartesian2d: function (data, dataIndex, itemModel) {
  31771. var layout = data.getItemLayout(dataIndex);
  31772. var fixedLineWidth = getLineWidth(itemModel, layout);
  31773. // fix layout with lineWidth
  31774. var signX = layout.width > 0 ? 1 : -1;
  31775. var signY = layout.height > 0 ? 1 : -1;
  31776. return {
  31777. x: layout.x + signX * fixedLineWidth / 2,
  31778. y: layout.y + signY * fixedLineWidth / 2,
  31779. width: layout.width - signX * fixedLineWidth,
  31780. height: layout.height - signY * fixedLineWidth
  31781. };
  31782. },
  31783. polar: function (data, dataIndex, itemModel) {
  31784. var layout = data.getItemLayout(dataIndex);
  31785. return {
  31786. cx: layout.cx,
  31787. cy: layout.cy,
  31788. r0: layout.r0,
  31789. r: layout.r,
  31790. startAngle: layout.startAngle,
  31791. endAngle: layout.endAngle
  31792. };
  31793. }
  31794. };
  31795. function updateStyle(
  31796. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  31797. ) {
  31798. var color = data.getItemVisual(dataIndex, 'color');
  31799. var opacity = data.getItemVisual(dataIndex, 'opacity');
  31800. var itemStyleModel = itemModel.getModel('itemStyle');
  31801. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  31802. if (!isPolar) {
  31803. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  31804. }
  31805. el.useStyle(defaults(
  31806. {
  31807. fill: color,
  31808. opacity: opacity
  31809. },
  31810. itemStyleModel.getBarItemStyle()
  31811. ));
  31812. var cursorStyle = itemModel.getShallow('cursor');
  31813. cursorStyle && el.attr('cursor', cursorStyle);
  31814. var labelPositionOutside = isHorizontal
  31815. ? (layout.height > 0 ? 'bottom' : 'top')
  31816. : (layout.width > 0 ? 'left' : 'right');
  31817. if (!isPolar) {
  31818. setLabel(
  31819. el.style, hoverStyle, itemModel, color,
  31820. seriesModel, dataIndex, labelPositionOutside
  31821. );
  31822. }
  31823. setHoverStyle(el, hoverStyle);
  31824. }
  31825. // In case width or height are too small.
  31826. function getLineWidth(itemModel, rawLayout) {
  31827. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  31828. return Math.min(lineWidth, Math.abs(rawLayout.width), Math.abs(rawLayout.height));
  31829. }
  31830. // In case developer forget to include grid component
  31831. registerLayout(curry(layout, 'bar'));
  31832. // Visual coding for legend
  31833. registerVisual(function (ecModel) {
  31834. ecModel.eachSeriesByType('bar', function (seriesModel) {
  31835. var data = seriesModel.getData();
  31836. data.setVisual('legendSymbol', 'roundRect');
  31837. });
  31838. });
  31839. /**
  31840. * [Usage]:
  31841. * (1)
  31842. * createListSimply(seriesModel, ['value']);
  31843. * (2)
  31844. * createListSimply(seriesModel, {
  31845. * coordDimensions: ['value'],
  31846. * dimensionsCount: 5
  31847. * });
  31848. *
  31849. * @param {module:echarts/model/Series} seriesModel
  31850. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  31851. * The options in opt, see `echarts/data/helper/createDimensions`
  31852. * @param {Array.<string>} [nameList]
  31853. * @return {module:echarts/data/List}
  31854. */
  31855. var createListSimply = function (seriesModel, opt, nameList) {
  31856. opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt);
  31857. var source = seriesModel.getSource();
  31858. var dimensionsInfo = createDimensions(source, opt);
  31859. var list = new List(dimensionsInfo, seriesModel);
  31860. list.initData(source, nameList);
  31861. return list;
  31862. };
  31863. /**
  31864. * Data selectable mixin for chart series.
  31865. * To eanble data select, option of series must have `selectedMode`.
  31866. * And each data item will use `selected` to toggle itself selected status
  31867. */
  31868. var dataSelectableMixin = {
  31869. /**
  31870. * @param {Array.<Object>} targetList [{name, value, selected}, ...]
  31871. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  31872. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  31873. */
  31874. updateSelectedMap: function (targetList) {
  31875. this._targetList = isArray(targetList) ? targetList.slice() : [];
  31876. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  31877. targetMap.set(target.name, target);
  31878. return targetMap;
  31879. }, createHashMap());
  31880. },
  31881. /**
  31882. * Either name or id should be passed as input here.
  31883. * If both of them are defined, id is used.
  31884. *
  31885. * @param {string|undefined} name name of data
  31886. * @param {number|undefined} id dataIndex of data
  31887. */
  31888. // PENGING If selectedMode is null ?
  31889. select: function (name, id) {
  31890. var target = id != null
  31891. ? this._targetList[id]
  31892. : this._selectTargetMap.get(name);
  31893. var selectedMode = this.get('selectedMode');
  31894. if (selectedMode === 'single') {
  31895. this._selectTargetMap.each(function (target) {
  31896. target.selected = false;
  31897. });
  31898. }
  31899. target && (target.selected = true);
  31900. },
  31901. /**
  31902. * Either name or id should be passed as input here.
  31903. * If both of them are defined, id is used.
  31904. *
  31905. * @param {string|undefined} name name of data
  31906. * @param {number|undefined} id dataIndex of data
  31907. */
  31908. unSelect: function (name, id) {
  31909. var target = id != null
  31910. ? this._targetList[id]
  31911. : this._selectTargetMap.get(name);
  31912. // var selectedMode = this.get('selectedMode');
  31913. // selectedMode !== 'single' && target && (target.selected = false);
  31914. target && (target.selected = false);
  31915. },
  31916. /**
  31917. * Either name or id should be passed as input here.
  31918. * If both of them are defined, id is used.
  31919. *
  31920. * @param {string|undefined} name name of data
  31921. * @param {number|undefined} id dataIndex of data
  31922. */
  31923. toggleSelected: function (name, id) {
  31924. var target = id != null
  31925. ? this._targetList[id]
  31926. : this._selectTargetMap.get(name);
  31927. if (target != null) {
  31928. this[target.selected ? 'unSelect' : 'select'](name, id);
  31929. return target.selected;
  31930. }
  31931. },
  31932. /**
  31933. * Either name or id should be passed as input here.
  31934. * If both of them are defined, id is used.
  31935. *
  31936. * @param {string|undefined} name name of data
  31937. * @param {number|undefined} id dataIndex of data
  31938. */
  31939. isSelected: function (name, id) {
  31940. var target = id != null
  31941. ? this._targetList[id]
  31942. : this._selectTargetMap.get(name);
  31943. return target && target.selected;
  31944. }
  31945. };
  31946. var PieSeries = extendSeriesModel({
  31947. type: 'series.pie',
  31948. // Overwrite
  31949. init: function (option) {
  31950. PieSeries.superApply(this, 'init', arguments);
  31951. // Enable legend selection for each data item
  31952. // Use a function instead of direct access because data reference may changed
  31953. this.legendDataProvider = function () {
  31954. return this.getRawData();
  31955. };
  31956. this.updateSelectedMap(this._createSelectableList());
  31957. this._defaultLabelLine(option);
  31958. },
  31959. // Overwrite
  31960. mergeOption: function (newOption) {
  31961. PieSeries.superCall(this, 'mergeOption', newOption);
  31962. this.updateSelectedMap(this._createSelectableList());
  31963. },
  31964. getInitialData: function (option, ecModel) {
  31965. return createListSimply(this, ['value']);
  31966. },
  31967. _createSelectableList: function () {
  31968. var data = this.getRawData();
  31969. var valueDim = data.mapDimension('value');
  31970. var targetList = [];
  31971. for (var i = 0, len = data.count(); i < len; i++) {
  31972. targetList.push({
  31973. name: data.getName(i),
  31974. value: data.get(valueDim, i),
  31975. selected: retrieveRawAttr(data, i, 'selected')
  31976. });
  31977. }
  31978. return targetList;
  31979. },
  31980. // Overwrite
  31981. getDataParams: function (dataIndex) {
  31982. var data = this.getData();
  31983. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  31984. // FIXME toFixed?
  31985. var valueList = [];
  31986. data.each(data.mapDimension('value'), function (value) {
  31987. valueList.push(value);
  31988. });
  31989. params.percent = getPercentWithPrecision(
  31990. valueList,
  31991. dataIndex,
  31992. data.hostModel.get('percentPrecision')
  31993. );
  31994. params.$vars.push('percent');
  31995. return params;
  31996. },
  31997. _defaultLabelLine: function (option) {
  31998. // Extend labelLine emphasis
  31999. defaultEmphasis(option, 'labelLine', ['show']);
  32000. var labelLineNormalOpt = option.labelLine;
  32001. var labelLineEmphasisOpt = option.emphasis.labelLine;
  32002. // Not show label line if `label.normal.show = false`
  32003. labelLineNormalOpt.show = labelLineNormalOpt.show
  32004. && option.label.show;
  32005. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  32006. && option.emphasis.label.show;
  32007. },
  32008. defaultOption: {
  32009. zlevel: 0,
  32010. z: 2,
  32011. legendHoverLink: true,
  32012. hoverAnimation: true,
  32013. // 默认全局居中
  32014. center: ['50%', '50%'],
  32015. radius: [0, '75%'],
  32016. // 默认顺时针
  32017. clockwise: true,
  32018. startAngle: 90,
  32019. // 最小角度改为0
  32020. minAngle: 0,
  32021. // 选中时扇区偏移量
  32022. selectedOffset: 10,
  32023. // 高亮扇区偏移量
  32024. hoverOffset: 10,
  32025. // If use strategy to avoid label overlapping
  32026. avoidLabelOverlap: true,
  32027. // 选择模式,默认关闭,可选single,multiple
  32028. // selectedMode: false,
  32029. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  32030. // roseType: null,
  32031. percentPrecision: 2,
  32032. // If still show when all data zero.
  32033. stillShowZeroSum: true,
  32034. // cursor: null,
  32035. label: {
  32036. // If rotate around circle
  32037. rotate: false,
  32038. show: true,
  32039. // 'outer', 'inside', 'center'
  32040. position: 'outer'
  32041. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  32042. // 默认使用全局文本样式,详见TEXTSTYLE
  32043. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  32044. },
  32045. // Enabled when label.normal.position is 'outer'
  32046. labelLine: {
  32047. show: true,
  32048. // 引导线两段中的第一段长度
  32049. length: 15,
  32050. // 引导线两段中的第二段长度
  32051. length2: 15,
  32052. smooth: false,
  32053. lineStyle: {
  32054. // color: 各异,
  32055. width: 1,
  32056. type: 'solid'
  32057. }
  32058. },
  32059. itemStyle: {
  32060. borderWidth: 1
  32061. },
  32062. // Animation type canbe expansion, scale
  32063. animationType: 'expansion',
  32064. animationEasing: 'cubicOut'
  32065. }
  32066. });
  32067. mixin(PieSeries, dataSelectableMixin);
  32068. /**
  32069. * @param {module:echarts/model/Series} seriesModel
  32070. * @param {boolean} hasAnimation
  32071. * @inner
  32072. */
  32073. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  32074. var data = seriesModel.getData();
  32075. var dataIndex = this.dataIndex;
  32076. var name = data.getName(dataIndex);
  32077. var selectedOffset = seriesModel.get('selectedOffset');
  32078. api.dispatchAction({
  32079. type: 'pieToggleSelect',
  32080. from: uid,
  32081. name: name,
  32082. seriesId: seriesModel.id
  32083. });
  32084. data.each(function (idx) {
  32085. toggleItemSelected(
  32086. data.getItemGraphicEl(idx),
  32087. data.getItemLayout(idx),
  32088. seriesModel.isSelected(data.getName(idx)),
  32089. selectedOffset,
  32090. hasAnimation
  32091. );
  32092. });
  32093. }
  32094. /**
  32095. * @param {module:zrender/graphic/Sector} el
  32096. * @param {Object} layout
  32097. * @param {boolean} isSelected
  32098. * @param {number} selectedOffset
  32099. * @param {boolean} hasAnimation
  32100. * @inner
  32101. */
  32102. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  32103. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  32104. var dx = Math.cos(midAngle);
  32105. var dy = Math.sin(midAngle);
  32106. var offset = isSelected ? selectedOffset : 0;
  32107. var position = [dx * offset, dy * offset];
  32108. hasAnimation
  32109. // animateTo will stop revious animation like update transition
  32110. ? el.animate()
  32111. .when(200, {
  32112. position: position
  32113. })
  32114. .start('bounceOut')
  32115. : el.attr('position', position);
  32116. }
  32117. /**
  32118. * Piece of pie including Sector, Label, LabelLine
  32119. * @constructor
  32120. * @extends {module:zrender/graphic/Group}
  32121. */
  32122. function PiePiece(data, idx) {
  32123. Group.call(this);
  32124. var sector = new Sector({
  32125. z2: 2
  32126. });
  32127. var polyline = new Polyline();
  32128. var text = new Text();
  32129. this.add(sector);
  32130. this.add(polyline);
  32131. this.add(text);
  32132. this.updateData(data, idx, true);
  32133. // Hover to change label and labelLine
  32134. function onEmphasis() {
  32135. polyline.ignore = polyline.hoverIgnore;
  32136. text.ignore = text.hoverIgnore;
  32137. }
  32138. function onNormal() {
  32139. polyline.ignore = polyline.normalIgnore;
  32140. text.ignore = text.normalIgnore;
  32141. }
  32142. this.on('emphasis', onEmphasis)
  32143. .on('normal', onNormal)
  32144. .on('mouseover', onEmphasis)
  32145. .on('mouseout', onNormal);
  32146. }
  32147. var piePieceProto = PiePiece.prototype;
  32148. piePieceProto.updateData = function (data, idx, firstCreate) {
  32149. var sector = this.childAt(0);
  32150. var seriesModel = data.hostModel;
  32151. var itemModel = data.getItemModel(idx);
  32152. var layout = data.getItemLayout(idx);
  32153. var sectorShape = extend({}, layout);
  32154. sectorShape.label = null;
  32155. if (firstCreate) {
  32156. sector.setShape(sectorShape);
  32157. var animationType = seriesModel.getShallow('animationType');
  32158. if (animationType === 'scale') {
  32159. sector.shape.r = layout.r0;
  32160. initProps(sector, {
  32161. shape: {
  32162. r: layout.r
  32163. }
  32164. }, seriesModel, idx);
  32165. }
  32166. // Expansion
  32167. else {
  32168. sector.shape.endAngle = layout.startAngle;
  32169. updateProps(sector, {
  32170. shape: {
  32171. endAngle: layout.endAngle
  32172. }
  32173. }, seriesModel, idx);
  32174. }
  32175. }
  32176. else {
  32177. updateProps(sector, {
  32178. shape: sectorShape
  32179. }, seriesModel, idx);
  32180. }
  32181. // Update common style
  32182. var visualColor = data.getItemVisual(idx, 'color');
  32183. sector.useStyle(
  32184. defaults(
  32185. {
  32186. lineJoin: 'bevel',
  32187. fill: visualColor
  32188. },
  32189. itemModel.getModel('itemStyle').getItemStyle()
  32190. )
  32191. );
  32192. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  32193. var cursorStyle = itemModel.getShallow('cursor');
  32194. cursorStyle && sector.attr('cursor', cursorStyle);
  32195. // Toggle selected
  32196. toggleItemSelected(
  32197. this,
  32198. data.getItemLayout(idx),
  32199. seriesModel.isSelected(null, idx),
  32200. seriesModel.get('selectedOffset'),
  32201. seriesModel.get('animation')
  32202. );
  32203. function onEmphasis() {
  32204. // Sector may has animation of updating data. Force to move to the last frame
  32205. // Or it may stopped on the wrong shape
  32206. sector.stopAnimation(true);
  32207. sector.animateTo({
  32208. shape: {
  32209. r: layout.r + seriesModel.get('hoverOffset')
  32210. }
  32211. }, 300, 'elasticOut');
  32212. }
  32213. function onNormal() {
  32214. sector.stopAnimation(true);
  32215. sector.animateTo({
  32216. shape: {
  32217. r: layout.r
  32218. }
  32219. }, 300, 'elasticOut');
  32220. }
  32221. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  32222. if (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled()) {
  32223. sector
  32224. .on('mouseover', onEmphasis)
  32225. .on('mouseout', onNormal)
  32226. .on('emphasis', onEmphasis)
  32227. .on('normal', onNormal);
  32228. }
  32229. this._updateLabel(data, idx);
  32230. setHoverStyle(this);
  32231. };
  32232. piePieceProto._updateLabel = function (data, idx) {
  32233. var labelLine = this.childAt(1);
  32234. var labelText = this.childAt(2);
  32235. var seriesModel = data.hostModel;
  32236. var itemModel = data.getItemModel(idx);
  32237. var layout = data.getItemLayout(idx);
  32238. var labelLayout = layout.label;
  32239. var visualColor = data.getItemVisual(idx, 'color');
  32240. updateProps(labelLine, {
  32241. shape: {
  32242. points: labelLayout.linePoints || [
  32243. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  32244. ]
  32245. }
  32246. }, seriesModel, idx);
  32247. updateProps(labelText, {
  32248. style: {
  32249. x: labelLayout.x,
  32250. y: labelLayout.y
  32251. }
  32252. }, seriesModel, idx);
  32253. labelText.attr({
  32254. rotation: labelLayout.rotation,
  32255. origin: [labelLayout.x, labelLayout.y],
  32256. z2: 10
  32257. });
  32258. var labelModel = itemModel.getModel('label');
  32259. var labelHoverModel = itemModel.getModel('emphasis.label');
  32260. var labelLineModel = itemModel.getModel('labelLine');
  32261. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  32262. var visualColor = data.getItemVisual(idx, 'color');
  32263. setLabelStyle(
  32264. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  32265. {
  32266. labelFetcher: data.hostModel,
  32267. labelDataIndex: idx,
  32268. defaultText: data.getName(idx),
  32269. autoColor: visualColor,
  32270. useInsideStyle: !!labelLayout.inside
  32271. },
  32272. {
  32273. textAlign: labelLayout.textAlign,
  32274. textVerticalAlign: labelLayout.verticalAlign,
  32275. opacity: data.getItemVisual(idx, 'opacity')
  32276. }
  32277. );
  32278. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  32279. labelText.hoverIgnore = !labelHoverModel.get('show');
  32280. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  32281. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  32282. // Default use item visual color
  32283. labelLine.setStyle({
  32284. stroke: visualColor,
  32285. opacity: data.getItemVisual(idx, 'opacity')
  32286. });
  32287. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  32288. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  32289. var smooth = labelLineModel.get('smooth');
  32290. if (smooth && smooth === true) {
  32291. smooth = 0.4;
  32292. }
  32293. labelLine.setShape({
  32294. smooth: smooth
  32295. });
  32296. };
  32297. inherits(PiePiece, Group);
  32298. // Pie view
  32299. var PieView = Chart.extend({
  32300. type: 'pie',
  32301. init: function () {
  32302. var sectorGroup = new Group();
  32303. this._sectorGroup = sectorGroup;
  32304. },
  32305. render: function (seriesModel, ecModel, api, payload) {
  32306. if (payload && (payload.from === this.uid)) {
  32307. return;
  32308. }
  32309. var data = seriesModel.getData();
  32310. var oldData = this._data;
  32311. var group = this.group;
  32312. var hasAnimation = ecModel.get('animation');
  32313. var isFirstRender = !oldData;
  32314. var animationType = seriesModel.get('animationType');
  32315. var onSectorClick = curry(
  32316. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  32317. );
  32318. var selectedMode = seriesModel.get('selectedMode');
  32319. data.diff(oldData)
  32320. .add(function (idx) {
  32321. var piePiece = new PiePiece(data, idx);
  32322. // Default expansion animation
  32323. if (isFirstRender && animationType !== 'scale') {
  32324. piePiece.eachChild(function (child) {
  32325. child.stopAnimation(true);
  32326. });
  32327. }
  32328. selectedMode && piePiece.on('click', onSectorClick);
  32329. data.setItemGraphicEl(idx, piePiece);
  32330. group.add(piePiece);
  32331. })
  32332. .update(function (newIdx, oldIdx) {
  32333. var piePiece = oldData.getItemGraphicEl(oldIdx);
  32334. piePiece.updateData(data, newIdx);
  32335. piePiece.off('click');
  32336. selectedMode && piePiece.on('click', onSectorClick);
  32337. group.add(piePiece);
  32338. data.setItemGraphicEl(newIdx, piePiece);
  32339. })
  32340. .remove(function (idx) {
  32341. var piePiece = oldData.getItemGraphicEl(idx);
  32342. group.remove(piePiece);
  32343. })
  32344. .execute();
  32345. if (
  32346. hasAnimation && isFirstRender && data.count() > 0
  32347. // Default expansion animation
  32348. && animationType !== 'scale'
  32349. ) {
  32350. var shape = data.getItemLayout(0);
  32351. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  32352. var removeClipPath = bind(group.removeClipPath, group);
  32353. group.setClipPath(this._createClipPath(
  32354. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel
  32355. ));
  32356. }
  32357. this._data = data;
  32358. },
  32359. dispose: function () {},
  32360. _createClipPath: function (
  32361. cx, cy, r, startAngle, clockwise, cb, seriesModel
  32362. ) {
  32363. var clipPath = new Sector({
  32364. shape: {
  32365. cx: cx,
  32366. cy: cy,
  32367. r0: 0,
  32368. r: r,
  32369. startAngle: startAngle,
  32370. endAngle: startAngle,
  32371. clockwise: clockwise
  32372. }
  32373. });
  32374. initProps(clipPath, {
  32375. shape: {
  32376. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  32377. }
  32378. }, seriesModel, cb);
  32379. return clipPath;
  32380. },
  32381. /**
  32382. * @implement
  32383. */
  32384. containPoint: function (point, seriesModel) {
  32385. var data = seriesModel.getData();
  32386. var itemLayout = data.getItemLayout(0);
  32387. if (itemLayout) {
  32388. var dx = point[0] - itemLayout.cx;
  32389. var dy = point[1] - itemLayout.cy;
  32390. var radius = Math.sqrt(dx * dx + dy * dy);
  32391. return radius <= itemLayout.r && radius >= itemLayout.r0;
  32392. }
  32393. }
  32394. });
  32395. var createDataSelectAction = function (seriesType, actionInfos) {
  32396. each$1(actionInfos, function (actionInfo) {
  32397. actionInfo.update = 'updateView';
  32398. /**
  32399. * @payload
  32400. * @property {string} seriesName
  32401. * @property {string} name
  32402. */
  32403. registerAction(actionInfo, function (payload, ecModel) {
  32404. var selected = {};
  32405. ecModel.eachComponent(
  32406. {mainType: 'series', subType: seriesType, query: payload},
  32407. function (seriesModel) {
  32408. if (seriesModel[actionInfo.method]) {
  32409. seriesModel[actionInfo.method](
  32410. payload.name,
  32411. payload.dataIndex
  32412. );
  32413. }
  32414. var data = seriesModel.getData();
  32415. // Create selected map
  32416. data.each(function (idx) {
  32417. var name = data.getName(idx);
  32418. selected[name] = seriesModel.isSelected(name)
  32419. || false;
  32420. });
  32421. }
  32422. );
  32423. return {
  32424. name: payload.name,
  32425. selected: selected
  32426. };
  32427. });
  32428. });
  32429. };
  32430. // Pick color from palette for each data item.
  32431. // Applicable for charts that require applying color palette
  32432. // in data level (like pie, funnel, chord).
  32433. var dataColor = function (seriesType) {
  32434. return {
  32435. getTargetSeries: function (ecModel) {
  32436. // Pie and funnel may use diferrent scope
  32437. var paletteScope = {};
  32438. var seiresModelMap = createHashMap();
  32439. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  32440. seriesModel.__paletteScope = paletteScope;
  32441. seiresModelMap.set(seriesModel.uid, seriesModel);
  32442. });
  32443. return seiresModelMap;
  32444. },
  32445. reset: function (seriesModel, ecModel) {
  32446. var dataAll = seriesModel.getRawData();
  32447. var idxMap = {};
  32448. var data = seriesModel.getData();
  32449. data.each(function (idx) {
  32450. var rawIdx = data.getRawIndex(idx);
  32451. idxMap[rawIdx] = idx;
  32452. });
  32453. dataAll.each(function (rawIdx) {
  32454. var filteredIdx = idxMap[rawIdx];
  32455. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  32456. var singleDataColor = filteredIdx != null
  32457. && data.getItemVisual(filteredIdx, 'color', true);
  32458. if (!singleDataColor) {
  32459. // FIXME Performance
  32460. var itemModel = dataAll.getItemModel(rawIdx);
  32461. var color = itemModel.get('itemStyle.color')
  32462. || seriesModel.getColorFromPalette(
  32463. dataAll.getName(rawIdx) || (rawIdx + ''), seriesModel.__paletteScope,
  32464. dataAll.count()
  32465. );
  32466. // Legend may use the visual info in data before processed
  32467. dataAll.setItemVisual(rawIdx, 'color', color);
  32468. // Data is not filtered
  32469. if (filteredIdx != null) {
  32470. data.setItemVisual(filteredIdx, 'color', color);
  32471. }
  32472. }
  32473. else {
  32474. // Set data all color for legend
  32475. dataAll.setItemVisual(rawIdx, 'color', singleDataColor);
  32476. }
  32477. });
  32478. }
  32479. };
  32480. };
  32481. // FIXME emphasis label position is not same with normal label position
  32482. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight) {
  32483. list.sort(function (a, b) {
  32484. return a.y - b.y;
  32485. });
  32486. // 压
  32487. function shiftDown(start, end, delta, dir) {
  32488. for (var j = start; j < end; j++) {
  32489. list[j].y += delta;
  32490. if (j > start
  32491. && j + 1 < end
  32492. && list[j + 1].y > list[j].y + list[j].height
  32493. ) {
  32494. shiftUp(j, delta / 2);
  32495. return;
  32496. }
  32497. }
  32498. shiftUp(end - 1, delta / 2);
  32499. }
  32500. // 弹
  32501. function shiftUp(end, delta) {
  32502. for (var j = end; j >= 0; j--) {
  32503. list[j].y -= delta;
  32504. if (j > 0
  32505. && list[j].y > list[j - 1].y + list[j - 1].height
  32506. ) {
  32507. break;
  32508. }
  32509. }
  32510. }
  32511. function changeX(list, isDownList, cx, cy, r, dir) {
  32512. var lastDeltaX = dir > 0
  32513. ? isDownList // 右侧
  32514. ? Number.MAX_VALUE // 下
  32515. : 0 // 上
  32516. : isDownList // 左侧
  32517. ? Number.MAX_VALUE // 下
  32518. : 0; // 上
  32519. for (var i = 0, l = list.length; i < l; i++) {
  32520. // Not change x for center label
  32521. if (list[i].position === 'center') {
  32522. continue;
  32523. }
  32524. var deltaY = Math.abs(list[i].y - cy);
  32525. var length = list[i].len;
  32526. var length2 = list[i].len2;
  32527. var deltaX = (deltaY < r + length)
  32528. ? Math.sqrt(
  32529. (r + length + length2) * (r + length + length2)
  32530. - deltaY * deltaY
  32531. )
  32532. : Math.abs(list[i].x - cx);
  32533. if (isDownList && deltaX >= lastDeltaX) {
  32534. // 右下,左下
  32535. deltaX = lastDeltaX - 10;
  32536. }
  32537. if (!isDownList && deltaX <= lastDeltaX) {
  32538. // 右上,左上
  32539. deltaX = lastDeltaX + 10;
  32540. }
  32541. list[i].x = cx + deltaX * dir;
  32542. lastDeltaX = deltaX;
  32543. }
  32544. }
  32545. var lastY = 0;
  32546. var delta;
  32547. var len = list.length;
  32548. var upList = [];
  32549. var downList = [];
  32550. for (var i = 0; i < len; i++) {
  32551. delta = list[i].y - lastY;
  32552. if (delta < 0) {
  32553. shiftDown(i, len, -delta, dir);
  32554. }
  32555. lastY = list[i].y + list[i].height;
  32556. }
  32557. if (viewHeight - lastY < 0) {
  32558. shiftUp(len - 1, lastY - viewHeight);
  32559. }
  32560. for (var i = 0; i < len; i++) {
  32561. if (list[i].y >= cy) {
  32562. downList.push(list[i]);
  32563. }
  32564. else {
  32565. upList.push(list[i]);
  32566. }
  32567. }
  32568. changeX(upList, false, cx, cy, r, dir);
  32569. changeX(downList, true, cx, cy, r, dir);
  32570. }
  32571. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight) {
  32572. var leftList = [];
  32573. var rightList = [];
  32574. for (var i = 0; i < labelLayoutList.length; i++) {
  32575. if (labelLayoutList[i].x < cx) {
  32576. leftList.push(labelLayoutList[i]);
  32577. }
  32578. else {
  32579. rightList.push(labelLayoutList[i]);
  32580. }
  32581. }
  32582. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight);
  32583. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight);
  32584. for (var i = 0; i < labelLayoutList.length; i++) {
  32585. var linePoints = labelLayoutList[i].linePoints;
  32586. if (linePoints) {
  32587. var dist = linePoints[1][0] - linePoints[2][0];
  32588. if (labelLayoutList[i].x < cx) {
  32589. linePoints[2][0] = labelLayoutList[i].x + 3;
  32590. }
  32591. else {
  32592. linePoints[2][0] = labelLayoutList[i].x - 3;
  32593. }
  32594. linePoints[1][1] = linePoints[2][1] = labelLayoutList[i].y;
  32595. linePoints[1][0] = linePoints[2][0] + dist;
  32596. }
  32597. }
  32598. }
  32599. var labelLayout = function (seriesModel, r, viewWidth, viewHeight) {
  32600. var data = seriesModel.getData();
  32601. var labelLayoutList = [];
  32602. var cx;
  32603. var cy;
  32604. var hasLabelRotate = false;
  32605. data.each(function (idx) {
  32606. var layout = data.getItemLayout(idx);
  32607. var itemModel = data.getItemModel(idx);
  32608. var labelModel = itemModel.getModel('label');
  32609. // Use position in normal or emphasis
  32610. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  32611. var labelLineModel = itemModel.getModel('labelLine');
  32612. var labelLineLen = labelLineModel.get('length');
  32613. var labelLineLen2 = labelLineModel.get('length2');
  32614. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  32615. var dx = Math.cos(midAngle);
  32616. var dy = Math.sin(midAngle);
  32617. var textX;
  32618. var textY;
  32619. var linePoints;
  32620. var textAlign;
  32621. cx = layout.cx;
  32622. cy = layout.cy;
  32623. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  32624. if (labelPosition === 'center') {
  32625. textX = layout.cx;
  32626. textY = layout.cy;
  32627. textAlign = 'center';
  32628. }
  32629. else {
  32630. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  32631. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  32632. textX = x1 + dx * 3;
  32633. textY = y1 + dy * 3;
  32634. if (!isLabelInside) {
  32635. // For roseType
  32636. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  32637. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  32638. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  32639. var y3 = y2;
  32640. textX = x3 + (dx < 0 ? -5 : 5);
  32641. textY = y3;
  32642. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  32643. }
  32644. textAlign = isLabelInside ? 'center' : (dx > 0 ? 'left' : 'right');
  32645. }
  32646. var font = labelModel.getFont();
  32647. var labelRotate = labelModel.get('rotate')
  32648. ? (dx < 0 ? -midAngle + Math.PI : -midAngle) : 0;
  32649. var text = seriesModel.getFormattedLabel(idx, 'normal')
  32650. || data.getName(idx);
  32651. var textRect = getBoundingRect(
  32652. text, font, textAlign, 'top'
  32653. );
  32654. hasLabelRotate = !!labelRotate;
  32655. layout.label = {
  32656. x: textX,
  32657. y: textY,
  32658. position: labelPosition,
  32659. height: textRect.height,
  32660. len: labelLineLen,
  32661. len2: labelLineLen2,
  32662. linePoints: linePoints,
  32663. textAlign: textAlign,
  32664. verticalAlign: 'middle',
  32665. rotation: labelRotate,
  32666. inside: isLabelInside
  32667. };
  32668. // Not layout the inside label
  32669. if (!isLabelInside) {
  32670. labelLayoutList.push(layout.label);
  32671. }
  32672. });
  32673. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  32674. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight);
  32675. }
  32676. };
  32677. var PI2$4 = Math.PI * 2;
  32678. var RADIAN = Math.PI / 180;
  32679. var pieLayout = function (seriesType, ecModel, api, payload) {
  32680. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  32681. var data = seriesModel.getData();
  32682. var valueDim = data.mapDimension('value');
  32683. var center = seriesModel.get('center');
  32684. var radius = seriesModel.get('radius');
  32685. if (!isArray(radius)) {
  32686. radius = [0, radius];
  32687. }
  32688. if (!isArray(center)) {
  32689. center = [center, center];
  32690. }
  32691. var width = api.getWidth();
  32692. var height = api.getHeight();
  32693. var size = Math.min(width, height);
  32694. var cx = parsePercent$1(center[0], width);
  32695. var cy = parsePercent$1(center[1], height);
  32696. var r0 = parsePercent$1(radius[0], size / 2);
  32697. var r = parsePercent$1(radius[1], size / 2);
  32698. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  32699. var minAngle = seriesModel.get('minAngle') * RADIAN;
  32700. var validDataCount = 0;
  32701. data.each(valueDim, function (value) {
  32702. !isNaN(value) && validDataCount++;
  32703. });
  32704. var sum = data.getSum(valueDim);
  32705. // Sum may be 0
  32706. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  32707. var clockwise = seriesModel.get('clockwise');
  32708. var roseType = seriesModel.get('roseType');
  32709. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  32710. // [0...max]
  32711. var extent = data.getDataExtent(valueDim);
  32712. extent[0] = 0;
  32713. // In the case some sector angle is smaller than minAngle
  32714. var restAngle = PI2$4;
  32715. var valueSumLargerThanMinAngle = 0;
  32716. var currentAngle = startAngle;
  32717. var dir = clockwise ? 1 : -1;
  32718. data.each(valueDim, function (value, idx) {
  32719. var angle;
  32720. if (isNaN(value)) {
  32721. data.setItemLayout(idx, {
  32722. angle: NaN,
  32723. startAngle: NaN,
  32724. endAngle: NaN,
  32725. clockwise: clockwise,
  32726. cx: cx,
  32727. cy: cy,
  32728. r0: r0,
  32729. r: roseType
  32730. ? NaN
  32731. : r
  32732. });
  32733. return;
  32734. }
  32735. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  32736. if (roseType !== 'area') {
  32737. angle = (sum === 0 && stillShowZeroSum)
  32738. ? unitRadian : (value * unitRadian);
  32739. }
  32740. else {
  32741. angle = PI2$4 / validDataCount;
  32742. }
  32743. if (angle < minAngle) {
  32744. angle = minAngle;
  32745. restAngle -= minAngle;
  32746. }
  32747. else {
  32748. valueSumLargerThanMinAngle += value;
  32749. }
  32750. var endAngle = currentAngle + dir * angle;
  32751. data.setItemLayout(idx, {
  32752. angle: angle,
  32753. startAngle: currentAngle,
  32754. endAngle: endAngle,
  32755. clockwise: clockwise,
  32756. cx: cx,
  32757. cy: cy,
  32758. r0: r0,
  32759. r: roseType
  32760. ? linearMap(value, extent, [r0, r])
  32761. : r
  32762. });
  32763. currentAngle = endAngle;
  32764. });
  32765. // Some sector is constrained by minAngle
  32766. // Rest sectors needs recalculate angle
  32767. if (restAngle < PI2$4 && validDataCount) {
  32768. // Average the angle if rest angle is not enough after all angles is
  32769. // Constrained by minAngle
  32770. if (restAngle <= 1e-3) {
  32771. var angle = PI2$4 / validDataCount;
  32772. data.each(valueDim, function (value, idx) {
  32773. if (!isNaN(value)) {
  32774. var layout = data.getItemLayout(idx);
  32775. layout.angle = angle;
  32776. layout.startAngle = startAngle + dir * idx * angle;
  32777. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  32778. }
  32779. });
  32780. }
  32781. else {
  32782. unitRadian = restAngle / valueSumLargerThanMinAngle;
  32783. currentAngle = startAngle;
  32784. data.each(valueDim, function (value, idx) {
  32785. if (!isNaN(value)) {
  32786. var layout = data.getItemLayout(idx);
  32787. var angle = layout.angle === minAngle
  32788. ? minAngle : value * unitRadian;
  32789. layout.startAngle = currentAngle;
  32790. layout.endAngle = currentAngle + dir * angle;
  32791. currentAngle += dir * angle;
  32792. }
  32793. });
  32794. }
  32795. }
  32796. labelLayout(seriesModel, r, width, height);
  32797. });
  32798. };
  32799. var dataFilter = function (seriesType) {
  32800. return {
  32801. seriesType: seriesType,
  32802. reset: function (seriesModel, ecModel) {
  32803. var legendModels = ecModel.findComponents({
  32804. mainType: 'legend'
  32805. });
  32806. if (!legendModels || !legendModels.length) {
  32807. return;
  32808. }
  32809. var data = seriesModel.getData();
  32810. data.filterSelf(function (idx) {
  32811. var name = data.getName(idx);
  32812. // If in any legend component the status is not selected.
  32813. for (var i = 0; i < legendModels.length; i++) {
  32814. if (!legendModels[i].isSelected(name)) {
  32815. return false;
  32816. }
  32817. }
  32818. return true;
  32819. });
  32820. }
  32821. };
  32822. };
  32823. createDataSelectAction('pie', [{
  32824. type: 'pieToggleSelect',
  32825. event: 'pieselectchanged',
  32826. method: 'toggleSelected'
  32827. }, {
  32828. type: 'pieSelect',
  32829. event: 'pieselected',
  32830. method: 'select'
  32831. }, {
  32832. type: 'pieUnSelect',
  32833. event: 'pieunselected',
  32834. method: 'unSelect'
  32835. }]);
  32836. registerVisual(dataColor('pie'));
  32837. registerLayout(curry(pieLayout, 'pie'));
  32838. registerProcessor(dataFilter('pie'));
  32839. SeriesModel.extend({
  32840. type: 'series.scatter',
  32841. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  32842. getInitialData: function (option, ecModel) {
  32843. return createListFromArray(this.getSource(), this);
  32844. },
  32845. brushSelector: 'point',
  32846. getProgressive: function () {
  32847. var progressive = this.option.progressive;
  32848. if (progressive == null) {
  32849. // PENDING
  32850. return this.option.large ? 5e3 : this.get('progressive');
  32851. }
  32852. return progressive;
  32853. },
  32854. getProgressiveThreshold: function () {
  32855. var progressiveThreshold = this.option.progressiveThreshold;
  32856. if (progressiveThreshold == null) {
  32857. // PENDING
  32858. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  32859. }
  32860. return progressiveThreshold;
  32861. },
  32862. defaultOption: {
  32863. coordinateSystem: 'cartesian2d',
  32864. zlevel: 0,
  32865. z: 2,
  32866. legendHoverLink: true,
  32867. hoverAnimation: true,
  32868. // Cartesian coordinate system
  32869. // xAxisIndex: 0,
  32870. // yAxisIndex: 0,
  32871. // Polar coordinate system
  32872. // polarIndex: 0,
  32873. // Geo coordinate system
  32874. // geoIndex: 0,
  32875. // symbol: null, // 图形类型
  32876. symbolSize: 10, // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  32877. // symbolRotate: null, // 图形旋转控制
  32878. large: false,
  32879. // Available when large is true
  32880. largeThreshold: 2000,
  32881. // cursor: null,
  32882. // label: {
  32883. // show: false
  32884. // distance: 5,
  32885. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  32886. // position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
  32887. // 'inside'|'left'|'right'|'top'|'bottom'
  32888. // 默认使用全局文本样式,详见TEXTSTYLE
  32889. // },
  32890. itemStyle: {
  32891. opacity: 0.8
  32892. // color: 各异
  32893. },
  32894. progressive: null
  32895. }
  32896. });
  32897. // TODO Batch by color
  32898. var BOOST_SIZE_THRESHOLD = 4;
  32899. var LargeSymbolPath = extendShape({
  32900. shape: {
  32901. points: null
  32902. },
  32903. symbolProxy: null,
  32904. buildPath: function (path, shape) {
  32905. var points = shape.points;
  32906. var size = shape.size;
  32907. var symbolProxy = this.symbolProxy;
  32908. var symbolProxyShape = symbolProxy.shape;
  32909. var ctx = path.getContext ? path.getContext() : path;
  32910. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  32911. // Do draw in afterBrush.
  32912. if (canBoost) {
  32913. return;
  32914. }
  32915. for (var i = 0; i < points.length;) {
  32916. var x = points[i++];
  32917. var y = points[i++];
  32918. if (isNaN(x) || isNaN(y)) {
  32919. continue;
  32920. }
  32921. symbolProxyShape.x = x - size[0] / 2;
  32922. symbolProxyShape.y = y - size[1] / 2;
  32923. symbolProxyShape.width = size[0];
  32924. symbolProxyShape.height = size[1];
  32925. symbolProxy.buildPath(path, symbolProxyShape, true);
  32926. }
  32927. },
  32928. afterBrush: function (ctx) {
  32929. var shape = this.shape;
  32930. var points = shape.points;
  32931. var size = shape.size;
  32932. var canBoost = size[0] < BOOST_SIZE_THRESHOLD;
  32933. if (!canBoost) {
  32934. return;
  32935. }
  32936. this.setTransform(ctx);
  32937. // PENDING If style or other canvas status changed?
  32938. for (var i = 0; i < points.length;) {
  32939. var x = points[i++];
  32940. var y = points[i++];
  32941. if (isNaN(x) || isNaN(y)) {
  32942. continue;
  32943. }
  32944. // fillRect is faster than building a rect path and draw.
  32945. // And it support light globalCompositeOperation.
  32946. ctx.fillRect(
  32947. x - size[0] / 2, y - size[1] / 2,
  32948. size[0], size[1]
  32949. );
  32950. }
  32951. this.restoreTransform(ctx);
  32952. },
  32953. findDataIndex: function (x, y) {
  32954. // TODO ???
  32955. // Consider transform
  32956. var shape = this.shape;
  32957. var points = shape.points;
  32958. var size = shape.size;
  32959. var w = Math.max(size[0], 4);
  32960. var h = Math.max(size[1], 4);
  32961. // Not consider transform
  32962. // Treat each element as a rect
  32963. // top down traverse
  32964. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  32965. var i = idx * 2;
  32966. var x0 = points[i] - w / 2;
  32967. var y0 = points[i + 1] - h / 2;
  32968. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  32969. return idx;
  32970. }
  32971. }
  32972. return -1;
  32973. }
  32974. });
  32975. function LargeSymbolDraw() {
  32976. this.group = new Group();
  32977. }
  32978. var largeSymbolProto = LargeSymbolDraw.prototype;
  32979. largeSymbolProto.isPersistent = function () {
  32980. return !this._incremental;
  32981. };
  32982. /**
  32983. * Update symbols draw by new data
  32984. * @param {module:echarts/data/List} data
  32985. */
  32986. largeSymbolProto.updateData = function (data) {
  32987. this.group.removeAll();
  32988. var symbolEl = new LargeSymbolPath({
  32989. rectHover: true,
  32990. cursor: 'default'
  32991. });
  32992. symbolEl.setShape({
  32993. points: data.getLayout('symbolPoints')
  32994. });
  32995. this._setCommon(symbolEl, data);
  32996. this.group.add(symbolEl);
  32997. this._incremental = null;
  32998. };
  32999. largeSymbolProto.updateLayout = function (data) {
  33000. if (this._incremental) {
  33001. return;
  33002. }
  33003. var points = data.getLayout('symbolPoints');
  33004. this.group.eachChild(function (child) {
  33005. if (child.startIndex != null) {
  33006. var len = (child.endIndex - child.startIndex) * 2;
  33007. var byteOffset = child.startIndex * 4 * 2;
  33008. points = new Float32Array(points.buffer, byteOffset, len);
  33009. }
  33010. child.setShape('points', points);
  33011. });
  33012. };
  33013. largeSymbolProto.incrementalPrepareUpdate = function (data) {
  33014. this.group.removeAll();
  33015. this._clearIncremental();
  33016. // Only use incremental displayables when data amount is larger than 2 million.
  33017. // PENDING Incremental data?
  33018. if (data.count() > 2e6) {
  33019. if (!this._incremental) {
  33020. this._incremental = new IncrementalDisplayble({
  33021. silent: true
  33022. });
  33023. }
  33024. this.group.add(this._incremental);
  33025. }
  33026. else {
  33027. this._incremental = null;
  33028. }
  33029. };
  33030. largeSymbolProto.incrementalUpdate = function (taskParams, data) {
  33031. var symbolEl;
  33032. if (this._incremental) {
  33033. symbolEl = new LargeSymbolPath();
  33034. this._incremental.addDisplayable(symbolEl, true);
  33035. }
  33036. else {
  33037. symbolEl = new LargeSymbolPath({
  33038. rectHover: true,
  33039. cursor: 'default',
  33040. startIndex: taskParams.start,
  33041. endIndex: taskParams.end
  33042. });
  33043. symbolEl.incremental = true;
  33044. this.group.add(symbolEl);
  33045. }
  33046. symbolEl.setShape({
  33047. points: data.getLayout('symbolPoints')
  33048. });
  33049. this._setCommon(symbolEl, data, !!this._incremental);
  33050. };
  33051. largeSymbolProto._setCommon = function (symbolEl, data, isIncremental) {
  33052. var hostModel = data.hostModel;
  33053. // TODO
  33054. // if (data.hasItemVisual.symbolSize) {
  33055. // // TODO typed array?
  33056. // symbolEl.setShape('sizes', data.mapArray(
  33057. // function (idx) {
  33058. // var size = data.getItemVisual(idx, 'symbolSize');
  33059. // return (size instanceof Array) ? size : [size, size];
  33060. // }
  33061. // ));
  33062. // }
  33063. // else {
  33064. var size = data.getVisual('symbolSize');
  33065. symbolEl.setShape('size', (size instanceof Array) ? size : [size, size]);
  33066. // }
  33067. // Create symbolProxy to build path for each data
  33068. symbolEl.symbolProxy = createSymbol(
  33069. data.getVisual('symbol'), 0, 0, 0, 0
  33070. );
  33071. // Use symbolProxy setColor method
  33072. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  33073. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  33074. symbolEl.useStyle(
  33075. // Draw shadow when doing fillRect is extremely slow.
  33076. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color'])
  33077. );
  33078. var visualColor = data.getVisual('color');
  33079. if (visualColor) {
  33080. symbolEl.setColor(visualColor);
  33081. }
  33082. if (!isIncremental) {
  33083. // Enable tooltip
  33084. // PENDING May have performance issue when path is extremely large
  33085. symbolEl.seriesIndex = hostModel.seriesIndex;
  33086. symbolEl.on('mousemove', function (e) {
  33087. symbolEl.dataIndex = null;
  33088. var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY);
  33089. if (dataIndex >= 0) {
  33090. // Provide dataIndex for tooltip
  33091. symbolEl.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  33092. }
  33093. });
  33094. }
  33095. };
  33096. largeSymbolProto.remove = function () {
  33097. this._clearIncremental();
  33098. this._incremental = null;
  33099. this.group.removeAll();
  33100. };
  33101. largeSymbolProto._clearIncremental = function () {
  33102. var incremental = this._incremental;
  33103. if (incremental) {
  33104. incremental.clearDisplaybles();
  33105. }
  33106. };
  33107. extendChartView({
  33108. type: 'scatter',
  33109. render: function (seriesModel, ecModel, api) {
  33110. var data = seriesModel.getData();
  33111. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  33112. symbolDraw.updateData(data);
  33113. this._finished = true;
  33114. },
  33115. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  33116. var data = seriesModel.getData();
  33117. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  33118. symbolDraw.incrementalPrepareUpdate(data);
  33119. this._finished = false;
  33120. },
  33121. incrementalRender: function (taskParams, seriesModel, ecModel) {
  33122. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData());
  33123. this._finished = taskParams.end === seriesModel.getData().count();
  33124. },
  33125. updateTransform: function (seriesModel, ecModel, api) {
  33126. var data = seriesModel.getData();
  33127. // Must mark group dirty and make sure the incremental layer will be cleared
  33128. // PENDING
  33129. this.group.dirty();
  33130. if (!this._finished || data.count() > 1e4 || !this._symbolDraw.isPersistent()) {
  33131. return {
  33132. update: true
  33133. };
  33134. }
  33135. else {
  33136. var res = pointsLayout().reset(seriesModel);
  33137. if (res.progress) {
  33138. res.progress({ start: 0, end: data.count() }, data);
  33139. }
  33140. this._symbolDraw.updateLayout(data);
  33141. }
  33142. },
  33143. _updateSymbolDraw: function (data, seriesModel) {
  33144. var symbolDraw = this._symbolDraw;
  33145. var pipelineContext = seriesModel.pipelineContext;
  33146. var isLargeDraw = pipelineContext.large;
  33147. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  33148. symbolDraw && symbolDraw.remove();
  33149. symbolDraw = this._symbolDraw = isLargeDraw
  33150. ? new LargeSymbolDraw()
  33151. : new SymbolDraw();
  33152. this._isLargeDraw = isLargeDraw;
  33153. this.group.removeAll();
  33154. }
  33155. this.group.add(symbolDraw.group);
  33156. return symbolDraw;
  33157. },
  33158. remove: function (ecModel, api) {
  33159. this._symbolDraw && this._symbolDraw.remove(true);
  33160. this._symbolDraw = null;
  33161. },
  33162. dispose: function () {}
  33163. });
  33164. // import * as zrUtil from 'zrender/src/core/util';
  33165. // In case developer forget to include grid component
  33166. registerVisual(visualSymbol('scatter', 'circle'));
  33167. registerLayout(pointsLayout('scatter'));
  33168. // echarts.registerProcessor(function (ecModel, api) {
  33169. // ecModel.eachSeriesByType('scatter', function (seriesModel) {
  33170. // var data = seriesModel.getData();
  33171. // var coordSys = seriesModel.coordinateSystem;
  33172. // if (coordSys.type !== 'geo') {
  33173. // return;
  33174. // }
  33175. // var startPt = coordSys.pointToData([0, 0]);
  33176. // var endPt = coordSys.pointToData([api.getWidth(), api.getHeight()]);
  33177. // var dims = zrUtil.map(coordSys.dimensions, function (dim) {
  33178. // return data.mapDimension(dim);
  33179. // });
  33180. // var range = {};
  33181. // range[dims[0]] = [Math.min(startPt[0], endPt[0]), Math.max(startPt[0], endPt[0])];
  33182. // range[dims[1]] = [Math.min(startPt[1], endPt[1]), Math.max(startPt[1], endPt[1])];
  33183. // data.selectRange(range);
  33184. // });
  33185. // });
  33186. // -------------
  33187. // Preprocessor
  33188. // -------------
  33189. registerPreprocessor(function (option) {
  33190. var graphicOption = option.graphic;
  33191. // Convert
  33192. // {graphic: [{left: 10, type: 'circle'}, ...]}
  33193. // or
  33194. // {graphic: {left: 10, type: 'circle'}}
  33195. // to
  33196. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  33197. if (isArray(graphicOption)) {
  33198. if (!graphicOption[0] || !graphicOption[0].elements) {
  33199. option.graphic = [{elements: graphicOption}];
  33200. }
  33201. else {
  33202. // Only one graphic instance can be instantiated. (We dont
  33203. // want that too many views are created in echarts._viewMap)
  33204. option.graphic = [option.graphic[0]];
  33205. }
  33206. }
  33207. else if (graphicOption && !graphicOption.elements) {
  33208. option.graphic = [{elements: [graphicOption]}];
  33209. }
  33210. });
  33211. // ------
  33212. // Model
  33213. // ------
  33214. var GraphicModel = extendComponentModel({
  33215. type: 'graphic',
  33216. defaultOption: {
  33217. // Extra properties for each elements:
  33218. //
  33219. // left/right/top/bottom: (like 12, '22%', 'center', default undefined)
  33220. // If left/rigth is set, shape.x/shape.cx/position will not be used.
  33221. // If top/bottom is set, shape.y/shape.cy/position will not be used.
  33222. // This mechanism is useful when you want to position a group/element
  33223. // against the right side or the center of this container.
  33224. //
  33225. // width/height: (can only be pixel value, default 0)
  33226. // Only be used to specify contianer(group) size, if needed. And
  33227. // can not be percentage value (like '33%'). See the reason in the
  33228. // layout algorithm below.
  33229. //
  33230. // bounding: (enum: 'all' (default) | 'raw')
  33231. // Specify how to calculate boundingRect when locating.
  33232. // 'all': Get uioned and transformed boundingRect
  33233. // from both itself and its descendants.
  33234. // This mode simplies confining a group of elements in the bounding
  33235. // of their ancester container (e.g., using 'right: 0').
  33236. // 'raw': Only use the boundingRect of itself and before transformed.
  33237. // This mode is similar to css behavior, which is useful when you
  33238. // want an element to be able to overflow its container. (Consider
  33239. // a rotated circle needs to be located in a corner.)
  33240. // Note: elements is always behind its ancestors in this elements array.
  33241. elements: [],
  33242. parentId: null
  33243. },
  33244. /**
  33245. * Save el options for the sake of the performance (only update modified graphics).
  33246. * The order is the same as those in option. (ancesters -> descendants)
  33247. *
  33248. * @private
  33249. * @type {Array.<Object>}
  33250. */
  33251. _elOptionsToUpdate: null,
  33252. /**
  33253. * @override
  33254. */
  33255. mergeOption: function (option) {
  33256. // Prevent default merge to elements
  33257. var elements = this.option.elements;
  33258. this.option.elements = null;
  33259. GraphicModel.superApply(this, 'mergeOption', arguments);
  33260. this.option.elements = elements;
  33261. },
  33262. /**
  33263. * @override
  33264. */
  33265. optionUpdated: function (newOption, isInit) {
  33266. var thisOption = this.option;
  33267. var newList = (isInit ? thisOption : newOption).elements;
  33268. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  33269. var flattenedList = [];
  33270. this._flatten(newList, flattenedList);
  33271. var mappingResult = mappingToExists(existList, flattenedList);
  33272. makeIdAndName(mappingResult);
  33273. // Clear elOptionsToUpdate
  33274. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  33275. each$1(mappingResult, function (resultItem, index) {
  33276. var newElOption = resultItem.option;
  33277. if (__DEV__) {
  33278. assert$1(
  33279. isObject$1(newElOption) || resultItem.exist,
  33280. 'Empty graphic option definition'
  33281. );
  33282. }
  33283. if (!newElOption) {
  33284. return;
  33285. }
  33286. elOptionsToUpdate.push(newElOption);
  33287. setKeyInfoToNewElOption(resultItem, newElOption);
  33288. mergeNewElOptionToExist(existList, index, newElOption);
  33289. setLayoutInfoToExist(existList[index], newElOption);
  33290. }, this);
  33291. // Clean
  33292. for (var i = existList.length - 1; i >= 0; i--) {
  33293. if (existList[i] == null) {
  33294. existList.splice(i, 1);
  33295. }
  33296. else {
  33297. // $action should be volatile, otherwise option gotten from
  33298. // `getOption` will contain unexpected $action.
  33299. delete existList[i].$action;
  33300. }
  33301. }
  33302. },
  33303. /**
  33304. * Convert
  33305. * [{
  33306. * type: 'group',
  33307. * id: 'xx',
  33308. * children: [{type: 'circle'}, {type: 'polygon'}]
  33309. * }]
  33310. * to
  33311. * [
  33312. * {type: 'group', id: 'xx'},
  33313. * {type: 'circle', parentId: 'xx'},
  33314. * {type: 'polygon', parentId: 'xx'}
  33315. * ]
  33316. *
  33317. * @private
  33318. * @param {Array.<Object>} optionList option list
  33319. * @param {Array.<Object>} result result of flatten
  33320. * @param {Object} parentOption parent option
  33321. */
  33322. _flatten: function (optionList, result, parentOption) {
  33323. each$1(optionList, function (option) {
  33324. if (!option) {
  33325. return;
  33326. }
  33327. if (parentOption) {
  33328. option.parentOption = parentOption;
  33329. }
  33330. result.push(option);
  33331. var children = option.children;
  33332. if (option.type === 'group' && children) {
  33333. this._flatten(children, result, option);
  33334. }
  33335. // Deleting for JSON output, and for not affecting group creation.
  33336. delete option.children;
  33337. }, this);
  33338. },
  33339. // FIXME
  33340. // Pass to view using payload? setOption has a payload?
  33341. useElOptionsToUpdate: function () {
  33342. var els = this._elOptionsToUpdate;
  33343. // Clear to avoid render duplicately when zooming.
  33344. this._elOptionsToUpdate = null;
  33345. return els;
  33346. }
  33347. });
  33348. // -----
  33349. // View
  33350. // -----
  33351. extendComponentView({
  33352. type: 'graphic',
  33353. /**
  33354. * @override
  33355. */
  33356. init: function (ecModel, api) {
  33357. /**
  33358. * @private
  33359. * @type {module:zrender/core/util.HashMap}
  33360. */
  33361. this._elMap = createHashMap();
  33362. /**
  33363. * @private
  33364. * @type {module:echarts/graphic/GraphicModel}
  33365. */
  33366. this._lastGraphicModel;
  33367. },
  33368. /**
  33369. * @override
  33370. */
  33371. render: function (graphicModel, ecModel, api) {
  33372. // Having leveraged between use cases and algorithm complexity, a very
  33373. // simple layout mechanism is used:
  33374. // The size(width/height) can be determined by itself or its parent (not
  33375. // implemented yet), but can not by its children. (Top-down travel)
  33376. // The location(x/y) can be determined by the bounding rect of itself
  33377. // (can including its descendants or not) and the size of its parent.
  33378. // (Bottom-up travel)
  33379. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  33380. // view will be reused.
  33381. if (graphicModel !== this._lastGraphicModel) {
  33382. this._clear();
  33383. }
  33384. this._lastGraphicModel = graphicModel;
  33385. this._updateElements(graphicModel, api);
  33386. this._relocate(graphicModel, api);
  33387. },
  33388. /**
  33389. * Update graphic elements.
  33390. *
  33391. * @private
  33392. * @param {Object} graphicModel graphic model
  33393. * @param {module:echarts/ExtensionAPI} api extension API
  33394. */
  33395. _updateElements: function (graphicModel, api) {
  33396. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  33397. if (!elOptionsToUpdate) {
  33398. return;
  33399. }
  33400. var elMap = this._elMap;
  33401. var rootGroup = this.group;
  33402. // Top-down tranverse to assign graphic settings to each elements.
  33403. each$1(elOptionsToUpdate, function (elOption) {
  33404. var $action = elOption.$action;
  33405. var id = elOption.id;
  33406. var existEl = elMap.get(id);
  33407. var parentId = elOption.parentId;
  33408. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  33409. if (elOption.type === 'text') {
  33410. var elOptionStyle = elOption.style;
  33411. // In top/bottom mode, textVerticalAlign should not be used, which cause
  33412. // inaccurately locating.
  33413. if (elOption.hv && elOption.hv[1]) {
  33414. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = null;
  33415. }
  33416. // Compatible with previous setting: both support fill and textFill,
  33417. // stroke and textStroke.
  33418. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  33419. elOptionStyle.textFill = elOptionStyle.fill
  33420. );
  33421. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  33422. elOptionStyle.textStroke = elOptionStyle.stroke
  33423. );
  33424. }
  33425. // Remove unnecessary props to avoid potential problems.
  33426. var elOptionCleaned = getCleanedElOption(elOption);
  33427. // For simple, do not support parent change, otherwise reorder is needed.
  33428. if (__DEV__) {
  33429. existEl && assert$1(
  33430. targetElParent === existEl.parent,
  33431. 'Changing parent is not supported.'
  33432. );
  33433. }
  33434. if (!$action || $action === 'merge') {
  33435. existEl
  33436. ? existEl.attr(elOptionCleaned)
  33437. : createEl(id, targetElParent, elOptionCleaned, elMap);
  33438. }
  33439. else if ($action === 'replace') {
  33440. removeEl(existEl, elMap);
  33441. createEl(id, targetElParent, elOptionCleaned, elMap);
  33442. }
  33443. else if ($action === 'remove') {
  33444. removeEl(existEl, elMap);
  33445. }
  33446. var el = elMap.get(id);
  33447. if (el) {
  33448. el.__ecGraphicWidth = elOption.width;
  33449. el.__ecGraphicHeight = elOption.height;
  33450. }
  33451. });
  33452. },
  33453. /**
  33454. * Locate graphic elements.
  33455. *
  33456. * @private
  33457. * @param {Object} graphicModel graphic model
  33458. * @param {module:echarts/ExtensionAPI} api extension API
  33459. */
  33460. _relocate: function (graphicModel, api) {
  33461. var elOptions = graphicModel.option.elements;
  33462. var rootGroup = this.group;
  33463. var elMap = this._elMap;
  33464. // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  33465. for (var i = elOptions.length - 1; i >= 0; i--) {
  33466. var elOption = elOptions[i];
  33467. var el = elMap.get(elOption.id);
  33468. if (!el) {
  33469. continue;
  33470. }
  33471. var parentEl = el.parent;
  33472. var containerInfo = parentEl === rootGroup
  33473. ? {
  33474. width: api.getWidth(),
  33475. height: api.getHeight()
  33476. }
  33477. : { // Like 'position:absolut' in css, default 0.
  33478. width: parentEl.__ecGraphicWidth || 0,
  33479. height: parentEl.__ecGraphicHeight || 0
  33480. };
  33481. positionElement(
  33482. el, elOption, containerInfo, null,
  33483. {hv: elOption.hv, boundingMode: elOption.bounding}
  33484. );
  33485. }
  33486. },
  33487. /**
  33488. * Clear all elements.
  33489. *
  33490. * @private
  33491. */
  33492. _clear: function () {
  33493. var elMap = this._elMap;
  33494. elMap.each(function (el) {
  33495. removeEl(el, elMap);
  33496. });
  33497. this._elMap = createHashMap();
  33498. },
  33499. /**
  33500. * @override
  33501. */
  33502. dispose: function () {
  33503. this._clear();
  33504. }
  33505. });
  33506. function createEl(id, targetElParent, elOption, elMap) {
  33507. var graphicType = elOption.type;
  33508. if (__DEV__) {
  33509. assert$1(graphicType, 'graphic type MUST be set');
  33510. }
  33511. var Clz = graphic[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];
  33512. if (__DEV__) {
  33513. assert$1(Clz, 'graphic type can not be found');
  33514. }
  33515. var el = new Clz(elOption);
  33516. targetElParent.add(el);
  33517. elMap.set(id, el);
  33518. el.__ecGraphicId = id;
  33519. }
  33520. function removeEl(existEl, elMap) {
  33521. var existElParent = existEl && existEl.parent;
  33522. if (existElParent) {
  33523. existEl.type === 'group' && existEl.traverse(function (el) {
  33524. removeEl(el, elMap);
  33525. });
  33526. elMap.removeKey(existEl.__ecGraphicId);
  33527. existElParent.remove(existEl);
  33528. }
  33529. }
  33530. // Remove unnecessary props to avoid potential problems.
  33531. function getCleanedElOption(elOption) {
  33532. elOption = extend({}, elOption);
  33533. each$1(
  33534. ['id', 'parentId', '$action', 'hv', 'bounding'].concat(LOCATION_PARAMS),
  33535. function (name) {
  33536. delete elOption[name];
  33537. }
  33538. );
  33539. return elOption;
  33540. }
  33541. function isSetLoc(obj, props) {
  33542. var isSet;
  33543. each$1(props, function (prop) {
  33544. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  33545. });
  33546. return isSet;
  33547. }
  33548. function setKeyInfoToNewElOption(resultItem, newElOption) {
  33549. var existElOption = resultItem.exist;
  33550. // Set id and type after id assigned.
  33551. newElOption.id = resultItem.keyInfo.id;
  33552. !newElOption.type && existElOption && (newElOption.type = existElOption.type);
  33553. // Set parent id if not specified
  33554. if (newElOption.parentId == null) {
  33555. var newElParentOption = newElOption.parentOption;
  33556. if (newElParentOption) {
  33557. newElOption.parentId = newElParentOption.id;
  33558. }
  33559. else if (existElOption) {
  33560. newElOption.parentId = existElOption.parentId;
  33561. }
  33562. }
  33563. // Clear
  33564. newElOption.parentOption = null;
  33565. }
  33566. function mergeNewElOptionToExist(existList, index, newElOption) {
  33567. // Update existing options, for `getOption` feature.
  33568. var newElOptCopy = extend({}, newElOption);
  33569. var existElOption = existList[index];
  33570. var $action = newElOption.$action || 'merge';
  33571. if ($action === 'merge') {
  33572. if (existElOption) {
  33573. if (__DEV__) {
  33574. var newType = newElOption.type;
  33575. assert$1(
  33576. !newType || existElOption.type === newType,
  33577. 'Please set $action: "replace" to change `type`'
  33578. );
  33579. }
  33580. // We can ensure that newElOptCopy and existElOption are not
  33581. // the same object, so `merge` will not change newElOptCopy.
  33582. merge(existElOption, newElOptCopy, true);
  33583. // Rigid body, use ignoreSize.
  33584. mergeLayoutParam(existElOption, newElOptCopy, {ignoreSize: true});
  33585. // Will be used in render.
  33586. copyLayoutParams(newElOption, existElOption);
  33587. }
  33588. else {
  33589. existList[index] = newElOptCopy;
  33590. }
  33591. }
  33592. else if ($action === 'replace') {
  33593. existList[index] = newElOptCopy;
  33594. }
  33595. else if ($action === 'remove') {
  33596. // null will be cleaned later.
  33597. existElOption && (existList[index] = null);
  33598. }
  33599. }
  33600. function setLayoutInfoToExist(existItem, newElOption) {
  33601. if (!existItem) {
  33602. return;
  33603. }
  33604. existItem.hv = newElOption.hv = [
  33605. // Rigid body, dont care `width`.
  33606. isSetLoc(newElOption, ['left', 'right']),
  33607. // Rigid body, dont care `height`.
  33608. isSetLoc(newElOption, ['top', 'bottom'])
  33609. ];
  33610. // Give default group size. Otherwise layout error may occur.
  33611. if (existItem.type === 'group') {
  33612. existItem.width == null && (existItem.width = newElOption.width = 0);
  33613. existItem.height == null && (existItem.height = newElOption.height = 0);
  33614. }
  33615. }
  33616. /**
  33617. * @param {Object} finder contains {seriesIndex, dataIndex, dataIndexInside}
  33618. * @param {module:echarts/model/Global} ecModel
  33619. * @return {Object} {point: [x, y], el: ...} point Will not be null.
  33620. */
  33621. var findPointFromSeries = function (finder, ecModel) {
  33622. var point = [];
  33623. var seriesIndex = finder.seriesIndex;
  33624. var seriesModel;
  33625. if (seriesIndex == null || !(
  33626. seriesModel = ecModel.getSeriesByIndex(seriesIndex)
  33627. )) {
  33628. return {point: []};
  33629. }
  33630. var data = seriesModel.getData();
  33631. var dataIndex = queryDataIndex(data, finder);
  33632. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  33633. return {point: []};
  33634. }
  33635. var el = data.getItemGraphicEl(dataIndex);
  33636. var coordSys = seriesModel.coordinateSystem;
  33637. if (seriesModel.getTooltipPosition) {
  33638. point = seriesModel.getTooltipPosition(dataIndex) || [];
  33639. }
  33640. else if (coordSys && coordSys.dataToPoint) {
  33641. point = coordSys.dataToPoint(
  33642. data.getValues(
  33643. map(coordSys.dimensions, function (dim) {
  33644. return data.mapDimension(dim);
  33645. }), dataIndex, true
  33646. )
  33647. ) || [];
  33648. }
  33649. else if (el) {
  33650. // Use graphic bounding rect
  33651. var rect = el.getBoundingRect().clone();
  33652. rect.applyTransform(el.transform);
  33653. point = [
  33654. rect.x + rect.width / 2,
  33655. rect.y + rect.height / 2
  33656. ];
  33657. }
  33658. return {point: point, el: el};
  33659. };
  33660. var each$8 = each$1;
  33661. var curry$2 = curry;
  33662. var inner$6 = makeInner();
  33663. /**
  33664. * Basic logic: check all axis, if they do not demand show/highlight,
  33665. * then hide/downplay them.
  33666. *
  33667. * @param {Object} coordSysAxesInfo
  33668. * @param {Object} payload
  33669. * @param {string} [payload.currTrigger] 'click' | 'mousemove' | 'leave'
  33670. * @param {Array.<number>} [payload.x] x and y, which are mandatory, specify a point to
  33671. * trigger axisPointer and tooltip.
  33672. * @param {Array.<number>} [payload.y] x and y, which are mandatory, specify a point to
  33673. * trigger axisPointer and tooltip.
  33674. * @param {Object} [payload.seriesIndex] finder, optional, restrict target axes.
  33675. * @param {Object} [payload.dataIndex] finder, restrict target axes.
  33676. * @param {Object} [payload.axesInfo] finder, restrict target axes.
  33677. * [{
  33678. * axisDim: 'x'|'y'|'angle'|...,
  33679. * axisIndex: ...,
  33680. * value: ...
  33681. * }, ...]
  33682. * @param {Function} [payload.dispatchAction]
  33683. * @param {Object} [payload.tooltipOption]
  33684. * @param {Object|Array.<number>|Function} [payload.position] Tooltip position,
  33685. * which can be specified in dispatchAction
  33686. * @param {module:echarts/model/Global} ecModel
  33687. * @param {module:echarts/ExtensionAPI} api
  33688. * @return {Object} content of event obj for echarts.connect.
  33689. */
  33690. var axisTrigger = function (payload, ecModel, api) {
  33691. var currTrigger = payload.currTrigger;
  33692. var point = [payload.x, payload.y];
  33693. var finder = payload;
  33694. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  33695. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  33696. // Pending
  33697. // See #6121. But we are not able to reproduce it yet.
  33698. if (!coordSysAxesInfo) {
  33699. return;
  33700. }
  33701. if (illegalPoint(point)) {
  33702. // Used in the default behavior of `connection`: use the sample seriesIndex
  33703. // and dataIndex. And also used in the tooltipView trigger.
  33704. point = findPointFromSeries({
  33705. seriesIndex: finder.seriesIndex,
  33706. // Do not use dataIndexInside from other ec instance.
  33707. // FIXME: auto detect it?
  33708. dataIndex: finder.dataIndex
  33709. }, ecModel).point;
  33710. }
  33711. var isIllegalPoint = illegalPoint(point);
  33712. // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  33713. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  33714. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  33715. // and dataIndex.
  33716. var inputAxesInfo = finder.axesInfo;
  33717. var axesInfo = coordSysAxesInfo.axesInfo;
  33718. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  33719. var outputFinder = {};
  33720. var showValueMap = {};
  33721. var dataByCoordSys = {list: [], map: {}};
  33722. var updaters = {
  33723. showPointer: curry$2(showPointer, showValueMap),
  33724. showTooltip: curry$2(showTooltip, dataByCoordSys)
  33725. };
  33726. // Process for triggered axes.
  33727. each$8(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  33728. // If a point given, it must be contained by the coordinate system.
  33729. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  33730. each$8(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  33731. var axis = axisInfo.axis;
  33732. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo);
  33733. // If no inputAxesInfo, no axis is restricted.
  33734. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  33735. var val = inputAxisInfo && inputAxisInfo.value;
  33736. if (val == null && !isIllegalPoint) {
  33737. val = axis.pointToData(point);
  33738. }
  33739. val != null && processOnAxis(axisInfo, val, updaters, false, outputFinder);
  33740. }
  33741. });
  33742. });
  33743. // Process for linked axes.
  33744. var linkTriggers = {};
  33745. each$8(axesInfo, function (tarAxisInfo, tarKey) {
  33746. var linkGroup = tarAxisInfo.linkGroup;
  33747. // If axis has been triggered in the previous stage, it should not be triggered by link.
  33748. if (linkGroup && !showValueMap[tarKey]) {
  33749. each$8(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  33750. var srcValItem = showValueMap[srcKey];
  33751. // If srcValItem exist, source axis is triggered, so link to target axis.
  33752. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  33753. var val = srcValItem.value;
  33754. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(
  33755. val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo)
  33756. )));
  33757. linkTriggers[tarAxisInfo.key] = val;
  33758. }
  33759. });
  33760. }
  33761. });
  33762. each$8(linkTriggers, function (val, tarKey) {
  33763. processOnAxis(axesInfo[tarKey], val, updaters, true, outputFinder);
  33764. });
  33765. updateModelActually(showValueMap, axesInfo, outputFinder);
  33766. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  33767. dispatchHighDownActually(axesInfo, dispatchAction, api);
  33768. return outputFinder;
  33769. };
  33770. function processOnAxis(axisInfo, newValue, updaters, dontSnap, outputFinder) {
  33771. var axis = axisInfo.axis;
  33772. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  33773. return;
  33774. }
  33775. if (!axisInfo.involveSeries) {
  33776. updaters.showPointer(axisInfo, newValue);
  33777. return;
  33778. }
  33779. // Heavy calculation. So put it after axis.containData checking.
  33780. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  33781. var payloadBatch = payloadInfo.payloadBatch;
  33782. var snapToValue = payloadInfo.snapToValue;
  33783. // Fill content of event obj for echarts.connect.
  33784. // By defualt use the first involved series data as a sample to connect.
  33785. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  33786. extend(outputFinder, payloadBatch[0]);
  33787. }
  33788. // If no linkSource input, this process is for collecting link
  33789. // target, where snap should not be accepted.
  33790. if (!dontSnap && axisInfo.snap) {
  33791. if (axis.containData(snapToValue) && snapToValue != null) {
  33792. newValue = snapToValue;
  33793. }
  33794. }
  33795. updaters.showPointer(axisInfo, newValue, payloadBatch, outputFinder);
  33796. // Tooltip should always be snapToValue, otherwise there will be
  33797. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  33798. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  33799. }
  33800. function buildPayloadsBySeries(value, axisInfo) {
  33801. var axis = axisInfo.axis;
  33802. var dim = axis.dim;
  33803. var snapToValue = value;
  33804. var payloadBatch = [];
  33805. var minDist = Number.MAX_VALUE;
  33806. var minDiff = -1;
  33807. each$8(axisInfo.seriesModels, function (series, idx) {
  33808. var dataDim = series.getData().mapDimension(dim, true);
  33809. var seriesNestestValue;
  33810. var dataIndices;
  33811. if (series.getAxisTooltipData) {
  33812. var result = series.getAxisTooltipData(dataDim, value, axis);
  33813. dataIndices = result.dataIndices;
  33814. seriesNestestValue = result.nestestValue;
  33815. }
  33816. else {
  33817. dataIndices = series.getData().indicesOfNearest(
  33818. dataDim[0],
  33819. value,
  33820. // Add a threshold to avoid find the wrong dataIndex
  33821. // when data length is not same.
  33822. // false,
  33823. axis.type === 'category' ? 0.5 : null
  33824. );
  33825. if (!dataIndices.length) {
  33826. return;
  33827. }
  33828. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  33829. }
  33830. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  33831. return;
  33832. }
  33833. var diff = value - seriesNestestValue;
  33834. var dist = Math.abs(diff);
  33835. // Consider category case
  33836. if (dist <= minDist) {
  33837. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  33838. minDist = dist;
  33839. minDiff = diff;
  33840. snapToValue = seriesNestestValue;
  33841. payloadBatch.length = 0;
  33842. }
  33843. each$8(dataIndices, function (dataIndex) {
  33844. payloadBatch.push({
  33845. seriesIndex: series.seriesIndex,
  33846. dataIndexInside: dataIndex,
  33847. dataIndex: series.getData().getRawIndex(dataIndex)
  33848. });
  33849. });
  33850. }
  33851. });
  33852. return {
  33853. payloadBatch: payloadBatch,
  33854. snapToValue: snapToValue
  33855. };
  33856. }
  33857. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  33858. showValueMap[axisInfo.key] = {value: value, payloadBatch: payloadBatch};
  33859. }
  33860. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  33861. var payloadBatch = payloadInfo.payloadBatch;
  33862. var axis = axisInfo.axis;
  33863. var axisModel = axis.model;
  33864. var axisPointerModel = axisInfo.axisPointerModel;
  33865. // If no data, do not create anything in dataByCoordSys,
  33866. // whose length will be used to judge whether dispatch action.
  33867. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  33868. return;
  33869. }
  33870. var coordSysModel = axisInfo.coordSys.model;
  33871. var coordSysKey = makeKey(coordSysModel);
  33872. var coordSysItem = dataByCoordSys.map[coordSysKey];
  33873. if (!coordSysItem) {
  33874. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  33875. coordSysId: coordSysModel.id,
  33876. coordSysIndex: coordSysModel.componentIndex,
  33877. coordSysType: coordSysModel.type,
  33878. coordSysMainType: coordSysModel.mainType,
  33879. dataByAxis: []
  33880. };
  33881. dataByCoordSys.list.push(coordSysItem);
  33882. }
  33883. coordSysItem.dataByAxis.push({
  33884. axisDim: axis.dim,
  33885. axisIndex: axisModel.componentIndex,
  33886. axisType: axisModel.type,
  33887. axisId: axisModel.id,
  33888. value: value,
  33889. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  33890. // depends that all models have been updated. So it should not be performed
  33891. // here. Considering axisPointerModel used here is volatile, which is hard
  33892. // to be retrieve in TooltipView, we prepare parameters here.
  33893. valueLabelOpt: {
  33894. precision: axisPointerModel.get('label.precision'),
  33895. formatter: axisPointerModel.get('label.formatter')
  33896. },
  33897. seriesDataIndices: payloadBatch.slice()
  33898. });
  33899. }
  33900. function updateModelActually(showValueMap, axesInfo, outputFinder) {
  33901. var outputAxesInfo = outputFinder.axesInfo = [];
  33902. // Basic logic: If no 'show' required, 'hide' this axisPointer.
  33903. each$8(axesInfo, function (axisInfo, key) {
  33904. var option = axisInfo.axisPointerModel.option;
  33905. var valItem = showValueMap[key];
  33906. if (valItem) {
  33907. !axisInfo.useHandle && (option.status = 'show');
  33908. option.value = valItem.value;
  33909. // For label formatter param and highlight.
  33910. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  33911. }
  33912. // When always show (e.g., handle used), remain
  33913. // original value and status.
  33914. else {
  33915. // If hide, value still need to be set, consider
  33916. // click legend to toggle axis blank.
  33917. !axisInfo.useHandle && (option.status = 'hide');
  33918. }
  33919. // If status is 'hide', should be no info in payload.
  33920. option.status === 'show' && outputAxesInfo.push({
  33921. axisDim: axisInfo.axis.dim,
  33922. axisIndex: axisInfo.axis.model.componentIndex,
  33923. value: option.value
  33924. });
  33925. });
  33926. }
  33927. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  33928. // Basic logic: If no showTip required, hideTip will be dispatched.
  33929. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  33930. dispatchAction({type: 'hideTip'});
  33931. return;
  33932. }
  33933. // In most case only one axis (or event one series is used). It is
  33934. // convinient to fetch payload.seriesIndex and payload.dataIndex
  33935. // dirtectly. So put the first seriesIndex and dataIndex of the first
  33936. // axis on the payload.
  33937. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  33938. dispatchAction({
  33939. type: 'showTip',
  33940. escapeConnect: true,
  33941. x: point[0],
  33942. y: point[1],
  33943. tooltipOption: payload.tooltipOption,
  33944. position: payload.position,
  33945. dataIndexInside: sampleItem.dataIndexInside,
  33946. dataIndex: sampleItem.dataIndex,
  33947. seriesIndex: sampleItem.seriesIndex,
  33948. dataByCoordSys: dataByCoordSys.list
  33949. });
  33950. }
  33951. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  33952. // FIXME
  33953. // highlight status modification shoule be a stage of main process?
  33954. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  33955. var zr = api.getZr();
  33956. var highDownKey = 'axisPointerLastHighlights';
  33957. var lastHighlights = inner$6(zr)[highDownKey] || {};
  33958. var newHighlights = inner$6(zr)[highDownKey] = {};
  33959. // Update highlight/downplay status according to axisPointer model.
  33960. // Build hash map and remove duplicate incidentally.
  33961. each$8(axesInfo, function (axisInfo, key) {
  33962. var option = axisInfo.axisPointerModel.option;
  33963. option.status === 'show' && each$8(option.seriesDataIndices, function (batchItem) {
  33964. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  33965. newHighlights[key] = batchItem;
  33966. });
  33967. });
  33968. // Diff.
  33969. var toHighlight = [];
  33970. var toDownplay = [];
  33971. each$1(lastHighlights, function (batchItem, key) {
  33972. !newHighlights[key] && toDownplay.push(batchItem);
  33973. });
  33974. each$1(newHighlights, function (batchItem, key) {
  33975. !lastHighlights[key] && toHighlight.push(batchItem);
  33976. });
  33977. toDownplay.length && api.dispatchAction({
  33978. type: 'downplay', escapeConnect: true, batch: toDownplay
  33979. });
  33980. toHighlight.length && api.dispatchAction({
  33981. type: 'highlight', escapeConnect: true, batch: toHighlight
  33982. });
  33983. }
  33984. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  33985. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  33986. var inputAxisInfo = inputAxesInfo[i];
  33987. if (axisInfo.axis.dim === inputAxisInfo.axisDim
  33988. && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex
  33989. ) {
  33990. return inputAxisInfo;
  33991. }
  33992. }
  33993. }
  33994. function makeMapperParam(axisInfo) {
  33995. var axisModel = axisInfo.axis.model;
  33996. var item = {};
  33997. var dim = item.axisDim = axisInfo.axis.dim;
  33998. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  33999. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  34000. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  34001. return item;
  34002. }
  34003. function illegalPoint(point) {
  34004. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  34005. }
  34006. var AxisPointerModel = extendComponentModel({
  34007. type: 'axisPointer',
  34008. coordSysAxesInfo: null,
  34009. defaultOption: {
  34010. // 'auto' means that show when triggered by tooltip or handle.
  34011. show: 'auto',
  34012. // 'click' | 'mousemove' | 'none'
  34013. triggerOn: null, // set default in AxisPonterView.js
  34014. zlevel: 0,
  34015. z: 50,
  34016. type: 'line',
  34017. // axispointer triggered by tootip determine snap automatically,
  34018. // see `modelHelper`.
  34019. snap: false,
  34020. triggerTooltip: true,
  34021. value: null,
  34022. status: null, // Init value depends on whether handle is used.
  34023. // [group0, group1, ...]
  34024. // Each group can be: {
  34025. // mapper: function () {},
  34026. // singleTooltip: 'multiple', // 'multiple' or 'single'
  34027. // xAxisId: ...,
  34028. // yAxisName: ...,
  34029. // angleAxisIndex: ...
  34030. // }
  34031. // mapper: can be ignored.
  34032. // input: {axisInfo, value}
  34033. // output: {axisInfo, value}
  34034. link: [],
  34035. // Do not set 'auto' here, otherwise global animation: false
  34036. // will not effect at this axispointer.
  34037. animation: null,
  34038. animationDurationUpdate: 200,
  34039. lineStyle: {
  34040. color: '#aaa',
  34041. width: 1,
  34042. type: 'solid'
  34043. },
  34044. shadowStyle: {
  34045. color: 'rgba(150,150,150,0.3)'
  34046. },
  34047. label: {
  34048. show: true,
  34049. formatter: null, // string | Function
  34050. precision: 'auto', // Or a number like 0, 1, 2 ...
  34051. margin: 3,
  34052. color: '#fff',
  34053. padding: [5, 7, 5, 7],
  34054. backgroundColor: 'auto', // default: axis line color
  34055. borderColor: null,
  34056. borderWidth: 0,
  34057. shadowBlur: 3,
  34058. shadowColor: '#aaa'
  34059. // Considering applicability, common style should
  34060. // better not have shadowOffset.
  34061. // shadowOffsetX: 0,
  34062. // shadowOffsetY: 2
  34063. },
  34064. handle: {
  34065. show: false,
  34066. icon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7v-1.2h6.6z M13.3,22H6.7v-1.2h6.6z M13.3,19.6H6.7v-1.2h6.6z', // jshint ignore:line
  34067. size: 45,
  34068. // handle margin is from symbol center to axis, which is stable when circular move.
  34069. margin: 50,
  34070. // color: '#1b8bbd'
  34071. // color: '#2f4554'
  34072. color: '#333',
  34073. shadowBlur: 3,
  34074. shadowColor: '#aaa',
  34075. shadowOffsetX: 0,
  34076. shadowOffsetY: 2,
  34077. // For mobile performance
  34078. throttle: 40
  34079. }
  34080. }
  34081. });
  34082. var inner$7 = makeInner();
  34083. var each$9 = each$1;
  34084. /**
  34085. * @param {string} key
  34086. * @param {module:echarts/ExtensionAPI} api
  34087. * @param {Function} handler
  34088. * param: {string} currTrigger
  34089. * param: {Array.<number>} point
  34090. */
  34091. function register(key, api, handler) {
  34092. if (env$1.node) {
  34093. return;
  34094. }
  34095. var zr = api.getZr();
  34096. inner$7(zr).records || (inner$7(zr).records = {});
  34097. initGlobalListeners(zr, api);
  34098. var record = inner$7(zr).records[key] || (inner$7(zr).records[key] = {});
  34099. record.handler = handler;
  34100. }
  34101. function initGlobalListeners(zr, api) {
  34102. if (inner$7(zr).initialized) {
  34103. return;
  34104. }
  34105. inner$7(zr).initialized = true;
  34106. useHandler('click', curry(doEnter, 'click'));
  34107. useHandler('mousemove', curry(doEnter, 'mousemove'));
  34108. // useHandler('mouseout', onLeave);
  34109. useHandler('globalout', onLeave);
  34110. function useHandler(eventType, cb) {
  34111. zr.on(eventType, function (e) {
  34112. var dis = makeDispatchAction(api);
  34113. each$9(inner$7(zr).records, function (record) {
  34114. record && cb(record, e, dis.dispatchAction);
  34115. });
  34116. dispatchTooltipFinally(dis.pendings, api);
  34117. });
  34118. }
  34119. }
  34120. function dispatchTooltipFinally(pendings, api) {
  34121. var showLen = pendings.showTip.length;
  34122. var hideLen = pendings.hideTip.length;
  34123. var actuallyPayload;
  34124. if (showLen) {
  34125. actuallyPayload = pendings.showTip[showLen - 1];
  34126. }
  34127. else if (hideLen) {
  34128. actuallyPayload = pendings.hideTip[hideLen - 1];
  34129. }
  34130. if (actuallyPayload) {
  34131. actuallyPayload.dispatchAction = null;
  34132. api.dispatchAction(actuallyPayload);
  34133. }
  34134. }
  34135. function onLeave(record, e, dispatchAction) {
  34136. record.handler('leave', null, dispatchAction);
  34137. }
  34138. function doEnter(currTrigger, record, e, dispatchAction) {
  34139. record.handler(currTrigger, e, dispatchAction);
  34140. }
  34141. function makeDispatchAction(api) {
  34142. var pendings = {
  34143. showTip: [],
  34144. hideTip: []
  34145. };
  34146. // FIXME
  34147. // better approach?
  34148. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  34149. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  34150. // So we have to add "final stage" to merge those dispatched actions.
  34151. var dispatchAction = function (payload) {
  34152. var pendingList = pendings[payload.type];
  34153. if (pendingList) {
  34154. pendingList.push(payload);
  34155. }
  34156. else {
  34157. payload.dispatchAction = dispatchAction;
  34158. api.dispatchAction(payload);
  34159. }
  34160. };
  34161. return {
  34162. dispatchAction: dispatchAction,
  34163. pendings: pendings
  34164. };
  34165. }
  34166. /**
  34167. * @param {string} key
  34168. * @param {module:echarts/ExtensionAPI} api
  34169. */
  34170. function unregister(key, api) {
  34171. if (env$1.node) {
  34172. return;
  34173. }
  34174. var zr = api.getZr();
  34175. var record = (inner$7(zr).records || {})[key];
  34176. if (record) {
  34177. inner$7(zr).records[key] = null;
  34178. }
  34179. }
  34180. var AxisPointerView = extendComponentView({
  34181. type: 'axisPointer',
  34182. render: function (globalAxisPointerModel, ecModel, api) {
  34183. var globalTooltipModel = ecModel.getComponent('tooltip');
  34184. var triggerOn = globalAxisPointerModel.get('triggerOn')
  34185. || (globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click');
  34186. // Register global listener in AxisPointerView to enable
  34187. // AxisPointerView to be independent to Tooltip.
  34188. register(
  34189. 'axisPointer',
  34190. api,
  34191. function (currTrigger, e, dispatchAction) {
  34192. // If 'none', it is not controlled by mouse totally.
  34193. if (triggerOn !== 'none'
  34194. && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)
  34195. ) {
  34196. dispatchAction({
  34197. type: 'updateAxisPointer',
  34198. currTrigger: currTrigger,
  34199. x: e && e.offsetX,
  34200. y: e && e.offsetY
  34201. });
  34202. }
  34203. }
  34204. );
  34205. },
  34206. /**
  34207. * @override
  34208. */
  34209. remove: function (ecModel, api) {
  34210. unregister(api.getZr(), 'axisPointer');
  34211. AxisPointerView.superApply(this._model, 'remove', arguments);
  34212. },
  34213. /**
  34214. * @override
  34215. */
  34216. dispose: function (ecModel, api) {
  34217. unregister('axisPointer', api);
  34218. AxisPointerView.superApply(this._model, 'dispose', arguments);
  34219. }
  34220. });
  34221. var inner$8 = makeInner();
  34222. var clone$4 = clone;
  34223. var bind$1 = bind;
  34224. /**
  34225. * Base axis pointer class in 2D.
  34226. * Implemenents {module:echarts/component/axis/IAxisPointer}.
  34227. */
  34228. function BaseAxisPointer () {
  34229. }
  34230. BaseAxisPointer.prototype = {
  34231. /**
  34232. * @private
  34233. */
  34234. _group: null,
  34235. /**
  34236. * @private
  34237. */
  34238. _lastGraphicKey: null,
  34239. /**
  34240. * @private
  34241. */
  34242. _handle: null,
  34243. /**
  34244. * @private
  34245. */
  34246. _dragging: false,
  34247. /**
  34248. * @private
  34249. */
  34250. _lastValue: null,
  34251. /**
  34252. * @private
  34253. */
  34254. _lastStatus: null,
  34255. /**
  34256. * @private
  34257. */
  34258. _payloadInfo: null,
  34259. /**
  34260. * In px, arbitrary value. Do not set too small,
  34261. * no animation is ok for most cases.
  34262. * @protected
  34263. */
  34264. animationThreshold: 15,
  34265. /**
  34266. * @implement
  34267. */
  34268. render: function (axisModel, axisPointerModel, api, forceRender) {
  34269. var value = axisPointerModel.get('value');
  34270. var status = axisPointerModel.get('status');
  34271. // Bind them to `this`, not in closure, otherwise they will not
  34272. // be replaced when user calling setOption in not merge mode.
  34273. this._axisModel = axisModel;
  34274. this._axisPointerModel = axisPointerModel;
  34275. this._api = api;
  34276. // Optimize: `render` will be called repeatly during mouse move.
  34277. // So it is power consuming if performing `render` each time,
  34278. // especially on mobile device.
  34279. if (!forceRender
  34280. && this._lastValue === value
  34281. && this._lastStatus === status
  34282. ) {
  34283. return;
  34284. }
  34285. this._lastValue = value;
  34286. this._lastStatus = status;
  34287. var group = this._group;
  34288. var handle = this._handle;
  34289. if (!status || status === 'hide') {
  34290. // Do not clear here, for animation better.
  34291. group && group.hide();
  34292. handle && handle.hide();
  34293. return;
  34294. }
  34295. group && group.show();
  34296. handle && handle.show();
  34297. // Otherwise status is 'show'
  34298. var elOption = {};
  34299. this.makeElOption(elOption, value, axisModel, axisPointerModel, api);
  34300. // Enable change axis pointer type.
  34301. var graphicKey = elOption.graphicKey;
  34302. if (graphicKey !== this._lastGraphicKey) {
  34303. this.clear(api);
  34304. }
  34305. this._lastGraphicKey = graphicKey;
  34306. var moveAnimation = this._moveAnimation =
  34307. this.determineAnimation(axisModel, axisPointerModel);
  34308. if (!group) {
  34309. group = this._group = new Group();
  34310. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  34311. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  34312. api.getZr().add(group);
  34313. }
  34314. else {
  34315. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  34316. this.updatePointerEl(group, elOption, doUpdateProps, axisPointerModel);
  34317. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  34318. }
  34319. updateMandatoryProps(group, axisPointerModel, true);
  34320. this._renderHandle(value);
  34321. },
  34322. /**
  34323. * @implement
  34324. */
  34325. remove: function (api) {
  34326. this.clear(api);
  34327. },
  34328. /**
  34329. * @implement
  34330. */
  34331. dispose: function (api) {
  34332. this.clear(api);
  34333. },
  34334. /**
  34335. * @protected
  34336. */
  34337. determineAnimation: function (axisModel, axisPointerModel) {
  34338. var animation = axisPointerModel.get('animation');
  34339. var axis = axisModel.axis;
  34340. var isCategoryAxis = axis.type === 'category';
  34341. var useSnap = axisPointerModel.get('snap');
  34342. // Value axis without snap always do not snap.
  34343. if (!useSnap && !isCategoryAxis) {
  34344. return false;
  34345. }
  34346. if (animation === 'auto' || animation == null) {
  34347. var animationThreshold = this.animationThreshold;
  34348. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  34349. return true;
  34350. }
  34351. // It is important to auto animation when snap used. Consider if there is
  34352. // a dataZoom, animation will be disabled when too many points exist, while
  34353. // it will be enabled for better visual effect when little points exist.
  34354. if (useSnap) {
  34355. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  34356. var axisExtent = axis.getExtent();
  34357. // Approximate band width
  34358. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  34359. }
  34360. return false;
  34361. }
  34362. return animation === true;
  34363. },
  34364. /**
  34365. * add {pointer, label, graphicKey} to elOption
  34366. * @protected
  34367. */
  34368. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  34369. // Shoule be implemenented by sub-class.
  34370. },
  34371. /**
  34372. * @protected
  34373. */
  34374. createPointerEl: function (group, elOption, axisModel, axisPointerModel) {
  34375. var pointerOption = elOption.pointer;
  34376. if (pointerOption) {
  34377. var pointerEl = inner$8(group).pointerEl = new graphic[pointerOption.type](
  34378. clone$4(elOption.pointer)
  34379. );
  34380. group.add(pointerEl);
  34381. }
  34382. },
  34383. /**
  34384. * @protected
  34385. */
  34386. createLabelEl: function (group, elOption, axisModel, axisPointerModel) {
  34387. if (elOption.label) {
  34388. var labelEl = inner$8(group).labelEl = new Rect(
  34389. clone$4(elOption.label)
  34390. );
  34391. group.add(labelEl);
  34392. updateLabelShowHide(labelEl, axisPointerModel);
  34393. }
  34394. },
  34395. /**
  34396. * @protected
  34397. */
  34398. updatePointerEl: function (group, elOption, updateProps$$1) {
  34399. var pointerEl = inner$8(group).pointerEl;
  34400. if (pointerEl) {
  34401. pointerEl.setStyle(elOption.pointer.style);
  34402. updateProps$$1(pointerEl, {shape: elOption.pointer.shape});
  34403. }
  34404. },
  34405. /**
  34406. * @protected
  34407. */
  34408. updateLabelEl: function (group, elOption, updateProps$$1, axisPointerModel) {
  34409. var labelEl = inner$8(group).labelEl;
  34410. if (labelEl) {
  34411. labelEl.setStyle(elOption.label.style);
  34412. updateProps$$1(labelEl, {
  34413. // Consider text length change in vertical axis, animation should
  34414. // be used on shape, otherwise the effect will be weird.
  34415. shape: elOption.label.shape,
  34416. position: elOption.label.position
  34417. });
  34418. updateLabelShowHide(labelEl, axisPointerModel);
  34419. }
  34420. },
  34421. /**
  34422. * @private
  34423. */
  34424. _renderHandle: function (value) {
  34425. if (this._dragging || !this.updateHandleTransform) {
  34426. return;
  34427. }
  34428. var axisPointerModel = this._axisPointerModel;
  34429. var zr = this._api.getZr();
  34430. var handle = this._handle;
  34431. var handleModel = axisPointerModel.getModel('handle');
  34432. var status = axisPointerModel.get('status');
  34433. if (!handleModel.get('show') || !status || status === 'hide') {
  34434. handle && zr.remove(handle);
  34435. this._handle = null;
  34436. return;
  34437. }
  34438. var isInit;
  34439. if (!this._handle) {
  34440. isInit = true;
  34441. handle = this._handle = createIcon(
  34442. handleModel.get('icon'),
  34443. {
  34444. cursor: 'move',
  34445. draggable: true,
  34446. onmousemove: function (e) {
  34447. // Fot mobile devicem, prevent screen slider on the button.
  34448. stop(e.event);
  34449. },
  34450. onmousedown: bind$1(this._onHandleDragMove, this, 0, 0),
  34451. drift: bind$1(this._onHandleDragMove, this),
  34452. ondragend: bind$1(this._onHandleDragEnd, this)
  34453. }
  34454. );
  34455. zr.add(handle);
  34456. }
  34457. updateMandatoryProps(handle, axisPointerModel, false);
  34458. // update style
  34459. var includeStyles = [
  34460. 'color', 'borderColor', 'borderWidth', 'opacity',
  34461. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'
  34462. ];
  34463. handle.setStyle(handleModel.getItemStyle(null, includeStyles));
  34464. // update position
  34465. var handleSize = handleModel.get('size');
  34466. if (!isArray(handleSize)) {
  34467. handleSize = [handleSize, handleSize];
  34468. }
  34469. handle.attr('scale', [handleSize[0] / 2, handleSize[1] / 2]);
  34470. createOrUpdate(
  34471. this,
  34472. '_doDispatchAxisPointer',
  34473. handleModel.get('throttle') || 0,
  34474. 'fixRate'
  34475. );
  34476. this._moveHandleToValue(value, isInit);
  34477. },
  34478. /**
  34479. * @private
  34480. */
  34481. _moveHandleToValue: function (value, isInit) {
  34482. updateProps$1(
  34483. this._axisPointerModel,
  34484. !isInit && this._moveAnimation,
  34485. this._handle,
  34486. getHandleTransProps(this.getHandleTransform(
  34487. value, this._axisModel, this._axisPointerModel
  34488. ))
  34489. );
  34490. },
  34491. /**
  34492. * @private
  34493. */
  34494. _onHandleDragMove: function (dx, dy) {
  34495. var handle = this._handle;
  34496. if (!handle) {
  34497. return;
  34498. }
  34499. this._dragging = true;
  34500. // Persistent for throttle.
  34501. var trans = this.updateHandleTransform(
  34502. getHandleTransProps(handle),
  34503. [dx, dy],
  34504. this._axisModel,
  34505. this._axisPointerModel
  34506. );
  34507. this._payloadInfo = trans;
  34508. handle.stopAnimation();
  34509. handle.attr(getHandleTransProps(trans));
  34510. inner$8(handle).lastProp = null;
  34511. this._doDispatchAxisPointer();
  34512. },
  34513. /**
  34514. * Throttled method.
  34515. * @private
  34516. */
  34517. _doDispatchAxisPointer: function () {
  34518. var handle = this._handle;
  34519. if (!handle) {
  34520. return;
  34521. }
  34522. var payloadInfo = this._payloadInfo;
  34523. var axisModel = this._axisModel;
  34524. this._api.dispatchAction({
  34525. type: 'updateAxisPointer',
  34526. x: payloadInfo.cursorPoint[0],
  34527. y: payloadInfo.cursorPoint[1],
  34528. tooltipOption: payloadInfo.tooltipOption,
  34529. axesInfo: [{
  34530. axisDim: axisModel.axis.dim,
  34531. axisIndex: axisModel.componentIndex
  34532. }]
  34533. });
  34534. },
  34535. /**
  34536. * @private
  34537. */
  34538. _onHandleDragEnd: function (moveAnimation) {
  34539. this._dragging = false;
  34540. var handle = this._handle;
  34541. if (!handle) {
  34542. return;
  34543. }
  34544. var value = this._axisPointerModel.get('value');
  34545. // Consider snap or categroy axis, handle may be not consistent with
  34546. // axisPointer. So move handle to align the exact value position when
  34547. // drag ended.
  34548. this._moveHandleToValue(value);
  34549. // For the effect: tooltip will be shown when finger holding on handle
  34550. // button, and will be hidden after finger left handle button.
  34551. this._api.dispatchAction({
  34552. type: 'hideTip'
  34553. });
  34554. },
  34555. /**
  34556. * Should be implemenented by sub-class if support `handle`.
  34557. * @protected
  34558. * @param {number} value
  34559. * @param {module:echarts/model/Model} axisModel
  34560. * @param {module:echarts/model/Model} axisPointerModel
  34561. * @return {Object} {position: [x, y], rotation: 0}
  34562. */
  34563. getHandleTransform: null,
  34564. /**
  34565. * * Should be implemenented by sub-class if support `handle`.
  34566. * @protected
  34567. * @param {Object} transform {position, rotation}
  34568. * @param {Array.<number>} delta [dx, dy]
  34569. * @param {module:echarts/model/Model} axisModel
  34570. * @param {module:echarts/model/Model} axisPointerModel
  34571. * @return {Object} {position: [x, y], rotation: 0, cursorPoint: [x, y]}
  34572. */
  34573. updateHandleTransform: null,
  34574. /**
  34575. * @private
  34576. */
  34577. clear: function (api) {
  34578. this._lastValue = null;
  34579. this._lastStatus = null;
  34580. var zr = api.getZr();
  34581. var group = this._group;
  34582. var handle = this._handle;
  34583. if (zr && group) {
  34584. this._lastGraphicKey = null;
  34585. group && zr.remove(group);
  34586. handle && zr.remove(handle);
  34587. this._group = null;
  34588. this._handle = null;
  34589. this._payloadInfo = null;
  34590. }
  34591. },
  34592. /**
  34593. * @protected
  34594. */
  34595. doClear: function () {
  34596. // Implemented by sub-class if necessary.
  34597. },
  34598. /**
  34599. * @protected
  34600. * @param {Array.<number>} xy
  34601. * @param {Array.<number>} wh
  34602. * @param {number} [xDimIndex=0] or 1
  34603. */
  34604. buildLabel: function (xy, wh, xDimIndex) {
  34605. xDimIndex = xDimIndex || 0;
  34606. return {
  34607. x: xy[xDimIndex],
  34608. y: xy[1 - xDimIndex],
  34609. width: wh[xDimIndex],
  34610. height: wh[1 - xDimIndex]
  34611. };
  34612. }
  34613. };
  34614. BaseAxisPointer.prototype.constructor = BaseAxisPointer;
  34615. function updateProps$1(animationModel, moveAnimation, el, props) {
  34616. // Animation optimize.
  34617. if (!propsEqual(inner$8(el).lastProp, props)) {
  34618. inner$8(el).lastProp = props;
  34619. moveAnimation
  34620. ? updateProps(el, props, animationModel)
  34621. : (el.stopAnimation(), el.attr(props));
  34622. }
  34623. }
  34624. function propsEqual(lastProps, newProps) {
  34625. if (isObject$1(lastProps) && isObject$1(newProps)) {
  34626. var equals = true;
  34627. each$1(newProps, function (item, key) {
  34628. equals = equals && propsEqual(lastProps[key], item);
  34629. });
  34630. return !!equals;
  34631. }
  34632. else {
  34633. return lastProps === newProps;
  34634. }
  34635. }
  34636. function updateLabelShowHide(labelEl, axisPointerModel) {
  34637. labelEl[axisPointerModel.get('label.show') ? 'show' : 'hide']();
  34638. }
  34639. function getHandleTransProps(trans) {
  34640. return {
  34641. position: trans.position.slice(),
  34642. rotation: trans.rotation || 0
  34643. };
  34644. }
  34645. function updateMandatoryProps(group, axisPointerModel, silent) {
  34646. var z = axisPointerModel.get('z');
  34647. var zlevel = axisPointerModel.get('zlevel');
  34648. group && group.traverse(function (el) {
  34649. if (el.type !== 'group') {
  34650. z != null && (el.z = z);
  34651. zlevel != null && (el.zlevel = zlevel);
  34652. el.silent = silent;
  34653. }
  34654. });
  34655. }
  34656. enableClassExtend(BaseAxisPointer);
  34657. /**
  34658. * @param {module:echarts/model/Model} axisPointerModel
  34659. */
  34660. function buildElStyle(axisPointerModel) {
  34661. var axisPointerType = axisPointerModel.get('type');
  34662. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  34663. var style;
  34664. if (axisPointerType === 'line') {
  34665. style = styleModel.getLineStyle();
  34666. style.fill = null;
  34667. }
  34668. else if (axisPointerType === 'shadow') {
  34669. style = styleModel.getAreaStyle();
  34670. style.stroke = null;
  34671. }
  34672. return style;
  34673. }
  34674. /**
  34675. * @param {Function} labelPos {align, verticalAlign, position}
  34676. */
  34677. function buildLabelElOption(
  34678. elOption, axisModel, axisPointerModel, api, labelPos
  34679. ) {
  34680. var value = axisPointerModel.get('value');
  34681. var text = getValueLabel(
  34682. value, axisModel.axis, axisModel.ecModel,
  34683. axisPointerModel.get('seriesDataIndices'),
  34684. {
  34685. precision: axisPointerModel.get('label.precision'),
  34686. formatter: axisPointerModel.get('label.formatter')
  34687. }
  34688. );
  34689. var labelModel = axisPointerModel.getModel('label');
  34690. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  34691. var font = labelModel.getFont();
  34692. var textRect = getBoundingRect(text, font);
  34693. var position = labelPos.position;
  34694. var width = textRect.width + paddings[1] + paddings[3];
  34695. var height = textRect.height + paddings[0] + paddings[2];
  34696. // Adjust by align.
  34697. var align = labelPos.align;
  34698. align === 'right' && (position[0] -= width);
  34699. align === 'center' && (position[0] -= width / 2);
  34700. var verticalAlign = labelPos.verticalAlign;
  34701. verticalAlign === 'bottom' && (position[1] -= height);
  34702. verticalAlign === 'middle' && (position[1] -= height / 2);
  34703. // Not overflow ec container
  34704. confineInContainer(position, width, height, api);
  34705. var bgColor = labelModel.get('backgroundColor');
  34706. if (!bgColor || bgColor === 'auto') {
  34707. bgColor = axisModel.get('axisLine.lineStyle.color');
  34708. }
  34709. elOption.label = {
  34710. shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  34711. position: position.slice(),
  34712. // TODO: rich
  34713. style: {
  34714. text: text,
  34715. textFont: font,
  34716. textFill: labelModel.getTextColor(),
  34717. textPosition: 'inside',
  34718. fill: bgColor,
  34719. stroke: labelModel.get('borderColor') || 'transparent',
  34720. lineWidth: labelModel.get('borderWidth') || 0,
  34721. shadowBlur: labelModel.get('shadowBlur'),
  34722. shadowColor: labelModel.get('shadowColor'),
  34723. shadowOffsetX: labelModel.get('shadowOffsetX'),
  34724. shadowOffsetY: labelModel.get('shadowOffsetY')
  34725. },
  34726. // Lable should be over axisPointer.
  34727. z2: 10
  34728. };
  34729. }
  34730. // Do not overflow ec container
  34731. function confineInContainer(position, width, height, api) {
  34732. var viewWidth = api.getWidth();
  34733. var viewHeight = api.getHeight();
  34734. position[0] = Math.min(position[0] + width, viewWidth) - width;
  34735. position[1] = Math.min(position[1] + height, viewHeight) - height;
  34736. position[0] = Math.max(position[0], 0);
  34737. position[1] = Math.max(position[1], 0);
  34738. }
  34739. /**
  34740. * @param {number} value
  34741. * @param {module:echarts/coord/Axis} axis
  34742. * @param {module:echarts/model/Global} ecModel
  34743. * @param {Object} opt
  34744. * @param {Array.<Object>} seriesDataIndices
  34745. * @param {number|string} opt.precision 'auto' or a number
  34746. * @param {string|Function} opt.formatter label formatter
  34747. */
  34748. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  34749. var text = axis.scale.getLabel(
  34750. // If `precision` is set, width can be fixed (like '12.00500'), which
  34751. // helps to debounce when when moving label.
  34752. value, {precision: opt.precision}
  34753. );
  34754. var formatter = opt.formatter;
  34755. if (formatter) {
  34756. var params = {
  34757. value: getAxisRawValue(axis, value),
  34758. seriesData: []
  34759. };
  34760. each$1(seriesDataIndices, function (idxItem) {
  34761. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  34762. var dataIndex = idxItem.dataIndexInside;
  34763. var dataParams = series && series.getDataParams(dataIndex);
  34764. dataParams && params.seriesData.push(dataParams);
  34765. });
  34766. if (isString(formatter)) {
  34767. text = formatter.replace('{value}', text);
  34768. }
  34769. else if (isFunction$1(formatter)) {
  34770. text = formatter(params);
  34771. }
  34772. }
  34773. return text;
  34774. }
  34775. /**
  34776. * @param {module:echarts/coord/Axis} axis
  34777. * @param {number} value
  34778. * @param {Object} layoutInfo {
  34779. * rotation, position, labelOffset, labelDirection, labelMargin
  34780. * }
  34781. */
  34782. function getTransformedPosition (axis, value, layoutInfo) {
  34783. var transform = create$1();
  34784. rotate(transform, transform, layoutInfo.rotation);
  34785. translate(transform, transform, layoutInfo.position);
  34786. return applyTransform$1([
  34787. axis.dataToCoord(value),
  34788. (layoutInfo.labelOffset || 0)
  34789. + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)
  34790. ], transform);
  34791. }
  34792. function buildCartesianSingleLabelElOption(
  34793. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  34794. ) {
  34795. var textLayout = AxisBuilder.innerTextLayout(
  34796. layoutInfo.rotation, 0, layoutInfo.labelDirection
  34797. );
  34798. layoutInfo.labelMargin = axisPointerModel.get('label.margin');
  34799. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  34800. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  34801. align: textLayout.textAlign,
  34802. verticalAlign: textLayout.textVerticalAlign
  34803. });
  34804. }
  34805. /**
  34806. * @param {Array.<number>} p1
  34807. * @param {Array.<number>} p2
  34808. * @param {number} [xDimIndex=0] or 1
  34809. */
  34810. function makeLineShape(p1, p2, xDimIndex) {
  34811. xDimIndex = xDimIndex || 0;
  34812. return {
  34813. x1: p1[xDimIndex],
  34814. y1: p1[1 - xDimIndex],
  34815. x2: p2[xDimIndex],
  34816. y2: p2[1 - xDimIndex]
  34817. };
  34818. }
  34819. /**
  34820. * @param {Array.<number>} xy
  34821. * @param {Array.<number>} wh
  34822. * @param {number} [xDimIndex=0] or 1
  34823. */
  34824. function makeRectShape(xy, wh, xDimIndex) {
  34825. xDimIndex = xDimIndex || 0;
  34826. return {
  34827. x: xy[xDimIndex],
  34828. y: xy[1 - xDimIndex],
  34829. width: wh[xDimIndex],
  34830. height: wh[1 - xDimIndex]
  34831. };
  34832. }
  34833. var CartesianAxisPointer = BaseAxisPointer.extend({
  34834. /**
  34835. * @override
  34836. */
  34837. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  34838. var axis = axisModel.axis;
  34839. var grid = axis.grid;
  34840. var axisPointerType = axisPointerModel.get('type');
  34841. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  34842. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  34843. if (axisPointerType && axisPointerType !== 'none') {
  34844. var elStyle = buildElStyle(axisPointerModel);
  34845. var pointerOption = pointerShapeBuilder[axisPointerType](
  34846. axis, pixelValue, otherExtent, elStyle
  34847. );
  34848. pointerOption.style = elStyle;
  34849. elOption.graphicKey = pointerOption.type;
  34850. elOption.pointer = pointerOption;
  34851. }
  34852. var layoutInfo = layout$1(grid.model, axisModel);
  34853. buildCartesianSingleLabelElOption(
  34854. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  34855. );
  34856. },
  34857. /**
  34858. * @override
  34859. */
  34860. getHandleTransform: function (value, axisModel, axisPointerModel) {
  34861. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  34862. labelInside: false
  34863. });
  34864. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  34865. return {
  34866. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  34867. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  34868. };
  34869. },
  34870. /**
  34871. * @override
  34872. */
  34873. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  34874. var axis = axisModel.axis;
  34875. var grid = axis.grid;
  34876. var axisExtent = axis.getGlobalExtent(true);
  34877. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  34878. var dimIndex = axis.dim === 'x' ? 0 : 1;
  34879. var currPosition = transform.position;
  34880. currPosition[dimIndex] += delta[dimIndex];
  34881. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  34882. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  34883. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  34884. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  34885. cursorPoint[dimIndex] = currPosition[dimIndex];
  34886. // Make tooltip do not overlap axisPointer and in the middle of the grid.
  34887. var tooltipOptions = [{verticalAlign: 'middle'}, {align: 'center'}];
  34888. return {
  34889. position: currPosition,
  34890. rotation: transform.rotation,
  34891. cursorPoint: cursorPoint,
  34892. tooltipOption: tooltipOptions[dimIndex]
  34893. };
  34894. }
  34895. });
  34896. function getCartesian(grid, axis) {
  34897. var opt = {};
  34898. opt[axis.dim + 'AxisIndex'] = axis.index;
  34899. return grid.getCartesian(opt);
  34900. }
  34901. var pointerShapeBuilder = {
  34902. line: function (axis, pixelValue, otherExtent, elStyle) {
  34903. var targetShape = makeLineShape(
  34904. [pixelValue, otherExtent[0]],
  34905. [pixelValue, otherExtent[1]],
  34906. getAxisDimIndex(axis)
  34907. );
  34908. subPixelOptimizeLine({
  34909. shape: targetShape,
  34910. style: elStyle
  34911. });
  34912. return {
  34913. type: 'Line',
  34914. shape: targetShape
  34915. };
  34916. },
  34917. shadow: function (axis, pixelValue, otherExtent, elStyle) {
  34918. var bandWidth = axis.getBandWidth();
  34919. var span = otherExtent[1] - otherExtent[0];
  34920. return {
  34921. type: 'Rect',
  34922. shape: makeRectShape(
  34923. [pixelValue - bandWidth / 2, otherExtent[0]],
  34924. [bandWidth, span],
  34925. getAxisDimIndex(axis)
  34926. )
  34927. };
  34928. }
  34929. };
  34930. function getAxisDimIndex(axis) {
  34931. return axis.dim === 'x' ? 0 : 1;
  34932. }
  34933. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  34934. // CartesianAxisPointer is not supposed to be required here. But consider
  34935. // echarts.simple.js and online build tooltip, which only require gridSimple,
  34936. // CartesianAxisPointer should be able to required somewhere.
  34937. registerPreprocessor(function (option) {
  34938. // Always has a global axisPointerModel for default setting.
  34939. if (option) {
  34940. (!option.axisPointer || option.axisPointer.length === 0)
  34941. && (option.axisPointer = {});
  34942. var link = option.axisPointer.link;
  34943. // Normalize to array to avoid object mergin. But if link
  34944. // is not set, remain null/undefined, otherwise it will
  34945. // override existent link setting.
  34946. if (link && !isArray(link)) {
  34947. option.axisPointer.link = [link];
  34948. }
  34949. }
  34950. });
  34951. // This process should proformed after coordinate systems created
  34952. // and series data processed. So put it on statistic processing stage.
  34953. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  34954. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  34955. // allAxesInfo should be updated when setOption performed.
  34956. ecModel.getComponent('axisPointer').coordSysAxesInfo
  34957. = collect(ecModel, api);
  34958. });
  34959. // Broadcast to all views.
  34960. registerAction({
  34961. type: 'updateAxisPointer',
  34962. event: 'updateAxisPointer',
  34963. update: ':updateAxisPointer'
  34964. }, axisTrigger);
  34965. extendComponentModel({
  34966. type: 'tooltip',
  34967. dependencies: ['axisPointer'],
  34968. defaultOption: {
  34969. zlevel: 0,
  34970. z: 8,
  34971. show: true,
  34972. // tooltip主体内容
  34973. showContent: true,
  34974. // 'trigger' only works on coordinate system.
  34975. // 'item' | 'axis' | 'none'
  34976. trigger: 'item',
  34977. // 'click' | 'mousemove' | 'none'
  34978. triggerOn: 'mousemove|click',
  34979. alwaysShowContent: false,
  34980. displayMode: 'single', // 'single' | 'multipleByCoordSys'
  34981. // 位置 {Array} | {Function}
  34982. // position: null
  34983. // Consider triggered from axisPointer handle, verticalAlign should be 'middle'
  34984. // align: null,
  34985. // verticalAlign: null,
  34986. // 是否约束 content 在 viewRect 中。默认 false 是为了兼容以前版本。
  34987. confine: false,
  34988. // 内容格式器:{string}(Template) ¦ {Function}
  34989. // formatter: null
  34990. showDelay: 0,
  34991. // 隐藏延迟,单位ms
  34992. hideDelay: 100,
  34993. // 动画变换时间,单位s
  34994. transitionDuration: 0.4,
  34995. enterable: false,
  34996. // 提示背景颜色,默认为透明度为0.7的黑色
  34997. backgroundColor: 'rgba(50,50,50,0.7)',
  34998. // 提示边框颜色
  34999. borderColor: '#333',
  35000. // 提示边框圆角,单位px,默认为4
  35001. borderRadius: 4,
  35002. // 提示边框线宽,单位px,默认为0(无边框)
  35003. borderWidth: 0,
  35004. // 提示内边距,单位px,默认各方向内边距为5,
  35005. // 接受数组分别设定上右下左边距,同css
  35006. padding: 5,
  35007. // Extra css text
  35008. extraCssText: '',
  35009. // 坐标轴指示器,坐标轴触发有效
  35010. axisPointer: {
  35011. // 默认为直线
  35012. // 可选为:'line' | 'shadow' | 'cross'
  35013. type: 'line',
  35014. // type 为 line 的时候有效,指定 tooltip line 所在的轴,可选
  35015. // 可选 'x' | 'y' | 'angle' | 'radius' | 'auto'
  35016. // 默认 'auto',会选择类型为 category 的轴,对于双数值轴,笛卡尔坐标系会默认选择 x 轴
  35017. // 极坐标系会默认选择 angle 轴
  35018. axis: 'auto',
  35019. animation: 'auto',
  35020. animationDurationUpdate: 200,
  35021. animationEasingUpdate: 'exponentialOut',
  35022. crossStyle: {
  35023. color: '#999',
  35024. width: 1,
  35025. type: 'dashed',
  35026. // TODO formatter
  35027. textStyle: {}
  35028. }
  35029. // lineStyle and shadowStyle should not be specified here,
  35030. // otherwise it will always override those styles on option.axisPointer.
  35031. },
  35032. textStyle: {
  35033. color: '#fff',
  35034. fontSize: 14
  35035. }
  35036. }
  35037. });
  35038. var each$11 = each$1;
  35039. var toCamelCase$1 = toCamelCase;
  35040. var vendors = ['', '-webkit-', '-moz-', '-o-'];
  35041. var gCssText = 'position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;';
  35042. /**
  35043. * @param {number} duration
  35044. * @return {string}
  35045. * @inner
  35046. */
  35047. function assembleTransition(duration) {
  35048. var transitionCurve = 'cubic-bezier(0.23, 1, 0.32, 1)';
  35049. var transitionText = 'left ' + duration + 's ' + transitionCurve + ','
  35050. + 'top ' + duration + 's ' + transitionCurve;
  35051. return map(vendors, function (vendorPrefix) {
  35052. return vendorPrefix + 'transition:' + transitionText;
  35053. }).join(';');
  35054. }
  35055. /**
  35056. * @param {Object} textStyle
  35057. * @return {string}
  35058. * @inner
  35059. */
  35060. function assembleFont(textStyleModel) {
  35061. var cssText = [];
  35062. var fontSize = textStyleModel.get('fontSize');
  35063. var color = textStyleModel.getTextColor();
  35064. color && cssText.push('color:' + color);
  35065. cssText.push('font:' + textStyleModel.getFont());
  35066. fontSize &&
  35067. cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  35068. each$11(['decoration', 'align'], function (name) {
  35069. var val = textStyleModel.get(name);
  35070. val && cssText.push('text-' + name + ':' + val);
  35071. });
  35072. return cssText.join(';');
  35073. }
  35074. /**
  35075. * @param {Object} tooltipModel
  35076. * @return {string}
  35077. * @inner
  35078. */
  35079. function assembleCssText(tooltipModel) {
  35080. var cssText = [];
  35081. var transitionDuration = tooltipModel.get('transitionDuration');
  35082. var backgroundColor = tooltipModel.get('backgroundColor');
  35083. var textStyleModel = tooltipModel.getModel('textStyle');
  35084. var padding = tooltipModel.get('padding');
  35085. // Animation transition. Do not animate when transitionDuration is 0.
  35086. transitionDuration &&
  35087. cssText.push(assembleTransition(transitionDuration));
  35088. if (backgroundColor) {
  35089. if (env$1.canvasSupported) {
  35090. cssText.push('background-Color:' + backgroundColor);
  35091. }
  35092. else {
  35093. // for ie
  35094. cssText.push(
  35095. 'background-Color:#' + toHex(backgroundColor)
  35096. );
  35097. cssText.push('filter:alpha(opacity=70)');
  35098. }
  35099. }
  35100. // Border style
  35101. each$11(['width', 'color', 'radius'], function (name) {
  35102. var borderName = 'border-' + name;
  35103. var camelCase = toCamelCase$1(borderName);
  35104. var val = tooltipModel.get(camelCase);
  35105. val != null &&
  35106. cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  35107. });
  35108. // Text style
  35109. cssText.push(assembleFont(textStyleModel));
  35110. // Padding
  35111. if (padding != null) {
  35112. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  35113. }
  35114. return cssText.join(';') + ';';
  35115. }
  35116. /**
  35117. * @alias module:echarts/component/tooltip/TooltipContent
  35118. * @constructor
  35119. */
  35120. function TooltipContent(container, api) {
  35121. if (env$1.wxa) {
  35122. return null;
  35123. }
  35124. var el = document.createElement('div');
  35125. var zr = this._zr = api.getZr();
  35126. this.el = el;
  35127. this._x = api.getWidth() / 2;
  35128. this._y = api.getHeight() / 2;
  35129. container.appendChild(el);
  35130. this._container = container;
  35131. this._show = false;
  35132. /**
  35133. * @private
  35134. */
  35135. this._hideTimeout;
  35136. var self = this;
  35137. el.onmouseenter = function () {
  35138. // clear the timeout in hideLater and keep showing tooltip
  35139. if (self._enterable) {
  35140. clearTimeout(self._hideTimeout);
  35141. self._show = true;
  35142. }
  35143. self._inContent = true;
  35144. };
  35145. el.onmousemove = function (e) {
  35146. e = e || window.event;
  35147. if (!self._enterable) {
  35148. // Try trigger zrender event to avoid mouse
  35149. // in and out shape too frequently
  35150. var handler = zr.handler;
  35151. normalizeEvent(container, e, true);
  35152. handler.dispatch('mousemove', e);
  35153. }
  35154. };
  35155. el.onmouseleave = function () {
  35156. if (self._enterable) {
  35157. if (self._show) {
  35158. self.hideLater(self._hideDelay);
  35159. }
  35160. }
  35161. self._inContent = false;
  35162. };
  35163. }
  35164. TooltipContent.prototype = {
  35165. constructor: TooltipContent,
  35166. /**
  35167. * @private
  35168. * @type {boolean}
  35169. */
  35170. _enterable: true,
  35171. /**
  35172. * Update when tooltip is rendered
  35173. */
  35174. update: function () {
  35175. // FIXME
  35176. // Move this logic to ec main?
  35177. var container = this._container;
  35178. var stl = container.currentStyle
  35179. || document.defaultView.getComputedStyle(container);
  35180. var domStyle = container.style;
  35181. if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
  35182. domStyle.position = 'relative';
  35183. }
  35184. // Hide the tooltip
  35185. // PENDING
  35186. // this.hide();
  35187. },
  35188. show: function (tooltipModel) {
  35189. clearTimeout(this._hideTimeout);
  35190. var el = this.el;
  35191. el.style.cssText = gCssText + assembleCssText(tooltipModel)
  35192. // http://stackoverflow.com/questions/21125587/css3-transition-not-working-in-chrome-anymore
  35193. + ';left:' + this._x + 'px;top:' + this._y + 'px;'
  35194. + (tooltipModel.get('extraCssText') || '');
  35195. el.style.display = el.innerHTML ? 'block' : 'none';
  35196. this._show = true;
  35197. },
  35198. setContent: function (content) {
  35199. this.el.innerHTML = content == null ? '' : content;
  35200. },
  35201. setEnterable: function (enterable) {
  35202. this._enterable = enterable;
  35203. },
  35204. getSize: function () {
  35205. var el = this.el;
  35206. return [el.clientWidth, el.clientHeight];
  35207. },
  35208. moveTo: function (x, y) {
  35209. // xy should be based on canvas root. But tooltipContent is
  35210. // the sibling of canvas root. So padding of ec container
  35211. // should be considered here.
  35212. var zr = this._zr;
  35213. var viewportRootOffset;
  35214. if (zr && zr.painter && (viewportRootOffset = zr.painter.getViewportRootOffset())) {
  35215. x += viewportRootOffset.offsetLeft;
  35216. y += viewportRootOffset.offsetTop;
  35217. }
  35218. var style = this.el.style;
  35219. style.left = x + 'px';
  35220. style.top = y + 'px';
  35221. this._x = x;
  35222. this._y = y;
  35223. },
  35224. hide: function () {
  35225. this.el.style.display = 'none';
  35226. this._show = false;
  35227. },
  35228. hideLater: function (time) {
  35229. if (this._show && !(this._inContent && this._enterable)) {
  35230. if (time) {
  35231. this._hideDelay = time;
  35232. // Set show false to avoid invoke hideLater mutiple times
  35233. this._show = false;
  35234. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  35235. }
  35236. else {
  35237. this.hide();
  35238. }
  35239. }
  35240. },
  35241. isShow: function () {
  35242. return this._show;
  35243. }
  35244. };
  35245. var bind$2 = bind;
  35246. var each$10 = each$1;
  35247. var parsePercent$2 = parsePercent$1;
  35248. var proxyRect = new Rect({
  35249. shape: {x: -1, y: -1, width: 2, height: 2}
  35250. });
  35251. extendComponentView({
  35252. type: 'tooltip',
  35253. init: function (ecModel, api) {
  35254. if (env$1.node) {
  35255. return;
  35256. }
  35257. var tooltipContent = new TooltipContent(api.getDom(), api);
  35258. this._tooltipContent = tooltipContent;
  35259. },
  35260. render: function (tooltipModel, ecModel, api) {
  35261. if (env$1.node || env$1.wxa) {
  35262. return;
  35263. }
  35264. // Reset
  35265. this.group.removeAll();
  35266. /**
  35267. * @private
  35268. * @type {module:echarts/component/tooltip/TooltipModel}
  35269. */
  35270. this._tooltipModel = tooltipModel;
  35271. /**
  35272. * @private
  35273. * @type {module:echarts/model/Global}
  35274. */
  35275. this._ecModel = ecModel;
  35276. /**
  35277. * @private
  35278. * @type {module:echarts/ExtensionAPI}
  35279. */
  35280. this._api = api;
  35281. /**
  35282. * Should be cleaned when render.
  35283. * @private
  35284. * @type {Array.<Array.<Object>>}
  35285. */
  35286. this._lastDataByCoordSys = null;
  35287. /**
  35288. * @private
  35289. * @type {boolean}
  35290. */
  35291. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  35292. var tooltipContent = this._tooltipContent;
  35293. tooltipContent.update();
  35294. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  35295. this._initGlobalListener();
  35296. this._keepShow();
  35297. },
  35298. _initGlobalListener: function () {
  35299. var tooltipModel = this._tooltipModel;
  35300. var triggerOn = tooltipModel.get('triggerOn');
  35301. register(
  35302. 'itemTooltip',
  35303. this._api,
  35304. bind$2(function (currTrigger, e, dispatchAction) {
  35305. // If 'none', it is not controlled by mouse totally.
  35306. if (triggerOn !== 'none') {
  35307. if (triggerOn.indexOf(currTrigger) >= 0) {
  35308. this._tryShow(e, dispatchAction);
  35309. }
  35310. else if (currTrigger === 'leave') {
  35311. this._hide(dispatchAction);
  35312. }
  35313. }
  35314. }, this)
  35315. );
  35316. },
  35317. _keepShow: function () {
  35318. var tooltipModel = this._tooltipModel;
  35319. var ecModel = this._ecModel;
  35320. var api = this._api;
  35321. // Try to keep the tooltip show when refreshing
  35322. if (this._lastX != null
  35323. && this._lastY != null
  35324. // When user is willing to control tooltip totally using API,
  35325. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  35326. // which is not expected.
  35327. && tooltipModel.get('triggerOn') !== 'none'
  35328. ) {
  35329. var self = this;
  35330. clearTimeout(this._refreshUpdateTimeout);
  35331. this._refreshUpdateTimeout = setTimeout(function () {
  35332. // Show tip next tick after other charts are rendered
  35333. // In case highlight action has wrong result
  35334. // FIXME
  35335. self.manuallyShowTip(tooltipModel, ecModel, api, {
  35336. x: self._lastX,
  35337. y: self._lastY
  35338. });
  35339. });
  35340. }
  35341. },
  35342. /**
  35343. * Show tip manually by
  35344. * dispatchAction({
  35345. * type: 'showTip',
  35346. * x: 10,
  35347. * y: 10
  35348. * });
  35349. * Or
  35350. * dispatchAction({
  35351. * type: 'showTip',
  35352. * seriesIndex: 0,
  35353. * dataIndex or dataIndexInside or name
  35354. * });
  35355. *
  35356. * TODO Batch
  35357. */
  35358. manuallyShowTip: function (tooltipModel, ecModel, api, payload) {
  35359. if (payload.from === this.uid || env$1.node) {
  35360. return;
  35361. }
  35362. var dispatchAction = makeDispatchAction$1(payload, api);
  35363. // Reset ticket
  35364. this._ticket = '';
  35365. // When triggered from axisPointer.
  35366. var dataByCoordSys = payload.dataByCoordSys;
  35367. if (payload.tooltip && payload.x != null && payload.y != null) {
  35368. var el = proxyRect;
  35369. el.position = [payload.x, payload.y];
  35370. el.update();
  35371. el.tooltip = payload.tooltip;
  35372. // Manually show tooltip while view is not using zrender elements.
  35373. this._tryShow({
  35374. offsetX: payload.x,
  35375. offsetY: payload.y,
  35376. target: el
  35377. }, dispatchAction);
  35378. }
  35379. else if (dataByCoordSys) {
  35380. this._tryShow({
  35381. offsetX: payload.x,
  35382. offsetY: payload.y,
  35383. position: payload.position,
  35384. event: {},
  35385. dataByCoordSys: payload.dataByCoordSys,
  35386. tooltipOption: payload.tooltipOption
  35387. }, dispatchAction);
  35388. }
  35389. else if (payload.seriesIndex != null) {
  35390. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  35391. return;
  35392. }
  35393. var pointInfo = findPointFromSeries(payload, ecModel);
  35394. var cx = pointInfo.point[0];
  35395. var cy = pointInfo.point[1];
  35396. if (cx != null && cy != null) {
  35397. this._tryShow({
  35398. offsetX: cx,
  35399. offsetY: cy,
  35400. position: payload.position,
  35401. target: pointInfo.el,
  35402. event: {}
  35403. }, dispatchAction);
  35404. }
  35405. }
  35406. else if (payload.x != null && payload.y != null) {
  35407. // FIXME
  35408. // should wrap dispatchAction like `axisPointer/globalListener` ?
  35409. api.dispatchAction({
  35410. type: 'updateAxisPointer',
  35411. x: payload.x,
  35412. y: payload.y
  35413. });
  35414. this._tryShow({
  35415. offsetX: payload.x,
  35416. offsetY: payload.y,
  35417. position: payload.position,
  35418. target: api.getZr().findHover(payload.x, payload.y).target,
  35419. event: {}
  35420. }, dispatchAction);
  35421. }
  35422. },
  35423. manuallyHideTip: function (tooltipModel, ecModel, api, payload) {
  35424. var tooltipContent = this._tooltipContent;
  35425. if (!this._alwaysShowContent && this._tooltipModel) {
  35426. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  35427. }
  35428. this._lastX = this._lastY = null;
  35429. if (payload.from !== this.uid) {
  35430. this._hide(makeDispatchAction$1(payload, api));
  35431. }
  35432. },
  35433. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  35434. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  35435. // and tooltip.
  35436. _manuallyAxisShowTip: function (tooltipModel, ecModel, api, payload) {
  35437. var seriesIndex = payload.seriesIndex;
  35438. var dataIndex = payload.dataIndex;
  35439. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  35440. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  35441. return;
  35442. }
  35443. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  35444. if (!seriesModel) {
  35445. return;
  35446. }
  35447. var data = seriesModel.getData();
  35448. var tooltipModel = buildTooltipModel([
  35449. data.getItemModel(dataIndex),
  35450. seriesModel,
  35451. (seriesModel.coordinateSystem || {}).model,
  35452. tooltipModel
  35453. ]);
  35454. if (tooltipModel.get('trigger') !== 'axis') {
  35455. return;
  35456. }
  35457. api.dispatchAction({
  35458. type: 'updateAxisPointer',
  35459. seriesIndex: seriesIndex,
  35460. dataIndex: dataIndex,
  35461. position: payload.position
  35462. });
  35463. return true;
  35464. },
  35465. _tryShow: function (e, dispatchAction) {
  35466. var el = e.target;
  35467. var tooltipModel = this._tooltipModel;
  35468. if (!tooltipModel) {
  35469. return;
  35470. }
  35471. // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  35472. this._lastX = e.offsetX;
  35473. this._lastY = e.offsetY;
  35474. var dataByCoordSys = e.dataByCoordSys;
  35475. if (dataByCoordSys && dataByCoordSys.length) {
  35476. this._showAxisTooltip(dataByCoordSys, e);
  35477. }
  35478. // Always show item tooltip if mouse is on the element with dataIndex
  35479. else if (el && el.dataIndex != null) {
  35480. this._lastDataByCoordSys = null;
  35481. this._showSeriesItemTooltip(e, el, dispatchAction);
  35482. }
  35483. // Tooltip provided directly. Like legend.
  35484. else if (el && el.tooltip) {
  35485. this._lastDataByCoordSys = null;
  35486. this._showComponentItemTooltip(e, el, dispatchAction);
  35487. }
  35488. else {
  35489. this._lastDataByCoordSys = null;
  35490. this._hide(dispatchAction);
  35491. }
  35492. },
  35493. _showOrMove: function (tooltipModel, cb) {
  35494. // showDelay is used in this case: tooltip.enterable is set
  35495. // as true. User intent to move mouse into tooltip and click
  35496. // something. `showDelay` makes it easyer to enter the content
  35497. // but tooltip do not move immediately.
  35498. var delay = tooltipModel.get('showDelay');
  35499. cb = bind(cb, this);
  35500. clearTimeout(this._showTimout);
  35501. delay > 0
  35502. ? (this._showTimout = setTimeout(cb, delay))
  35503. : cb();
  35504. },
  35505. _showAxisTooltip: function (dataByCoordSys, e) {
  35506. var ecModel = this._ecModel;
  35507. var globalTooltipModel = this._tooltipModel;
  35508. var point = [e.offsetX, e.offsetY];
  35509. var singleDefaultHTML = [];
  35510. var singleParamsList = [];
  35511. var singleTooltipModel = buildTooltipModel([
  35512. e.tooltipOption,
  35513. globalTooltipModel
  35514. ]);
  35515. each$10(dataByCoordSys, function (itemCoordSys) {
  35516. // var coordParamList = [];
  35517. // var coordDefaultHTML = [];
  35518. // var coordTooltipModel = buildTooltipModel([
  35519. // e.tooltipOption,
  35520. // itemCoordSys.tooltipOption,
  35521. // ecModel.getComponent(itemCoordSys.coordSysMainType, itemCoordSys.coordSysIndex),
  35522. // globalTooltipModel
  35523. // ]);
  35524. // var displayMode = coordTooltipModel.get('displayMode');
  35525. // var paramsList = displayMode === 'single' ? singleParamsList : [];
  35526. each$10(itemCoordSys.dataByAxis, function (item) {
  35527. var axisModel = ecModel.getComponent(item.axisDim + 'Axis', item.axisIndex);
  35528. var axisValue = item.value;
  35529. var seriesDefaultHTML = [];
  35530. if (!axisModel || axisValue == null) {
  35531. return;
  35532. }
  35533. var valueLabel = getValueLabel(
  35534. axisValue, axisModel.axis, ecModel,
  35535. item.seriesDataIndices,
  35536. item.valueLabelOpt
  35537. );
  35538. each$1(item.seriesDataIndices, function (idxItem) {
  35539. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  35540. var dataIndex = idxItem.dataIndexInside;
  35541. var dataParams = series && series.getDataParams(dataIndex);
  35542. dataParams.axisDim = item.axisDim;
  35543. dataParams.axisIndex = item.axisIndex;
  35544. dataParams.axisType = item.axisType;
  35545. dataParams.axisId = item.axisId;
  35546. dataParams.axisValue = getAxisRawValue(axisModel.axis, axisValue);
  35547. dataParams.axisValueLabel = valueLabel;
  35548. if (dataParams) {
  35549. singleParamsList.push(dataParams);
  35550. seriesDefaultHTML.push(series.formatTooltip(dataIndex, true));
  35551. }
  35552. });
  35553. // Default tooltip content
  35554. // FIXME
  35555. // (1) shold be the first data which has name?
  35556. // (2) themeRiver, firstDataIndex is array, and first line is unnecessary.
  35557. var firstLine = valueLabel;
  35558. singleDefaultHTML.push(
  35559. (firstLine ? encodeHTML(firstLine) + '<br />' : '')
  35560. + seriesDefaultHTML.join('<br />')
  35561. );
  35562. });
  35563. }, this);
  35564. // In most case, the second axis is shown upper than the first one.
  35565. singleDefaultHTML.reverse();
  35566. singleDefaultHTML = singleDefaultHTML.join('<br /><br />');
  35567. var positionExpr = e.position;
  35568. this._showOrMove(singleTooltipModel, function () {
  35569. if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
  35570. this._updatePosition(
  35571. singleTooltipModel,
  35572. positionExpr,
  35573. point[0], point[1],
  35574. this._tooltipContent,
  35575. singleParamsList
  35576. );
  35577. }
  35578. else {
  35579. this._showTooltipContent(
  35580. singleTooltipModel, singleDefaultHTML, singleParamsList, Math.random(),
  35581. point[0], point[1], positionExpr
  35582. );
  35583. }
  35584. });
  35585. // Do not trigger events here, because this branch only be entered
  35586. // from dispatchAction.
  35587. },
  35588. _showSeriesItemTooltip: function (e, el, dispatchAction) {
  35589. var ecModel = this._ecModel;
  35590. // Use dataModel in element if possible
  35591. // Used when mouseover on a element like markPoint or edge
  35592. // In which case, the data is not main data in series.
  35593. var seriesIndex = el.seriesIndex;
  35594. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  35595. // For example, graph link.
  35596. var dataModel = el.dataModel || seriesModel;
  35597. var dataIndex = el.dataIndex;
  35598. var dataType = el.dataType;
  35599. var data = dataModel.getData();
  35600. var tooltipModel = buildTooltipModel([
  35601. data.getItemModel(dataIndex),
  35602. dataModel,
  35603. seriesModel && (seriesModel.coordinateSystem || {}).model,
  35604. this._tooltipModel
  35605. ]);
  35606. var tooltipTrigger = tooltipModel.get('trigger');
  35607. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  35608. return;
  35609. }
  35610. var params = dataModel.getDataParams(dataIndex, dataType);
  35611. var defaultHtml = dataModel.formatTooltip(dataIndex, false, dataType);
  35612. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  35613. this._showOrMove(tooltipModel, function () {
  35614. this._showTooltipContent(
  35615. tooltipModel, defaultHtml, params, asyncTicket,
  35616. e.offsetX, e.offsetY, e.position, e.target
  35617. );
  35618. });
  35619. // FIXME
  35620. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  35621. dispatchAction({
  35622. type: 'showTip',
  35623. dataIndexInside: dataIndex,
  35624. dataIndex: data.getRawIndex(dataIndex),
  35625. seriesIndex: seriesIndex,
  35626. from: this.uid
  35627. });
  35628. },
  35629. _showComponentItemTooltip: function (e, el, dispatchAction) {
  35630. var tooltipOpt = el.tooltip;
  35631. if (typeof tooltipOpt === 'string') {
  35632. var content = tooltipOpt;
  35633. tooltipOpt = {
  35634. content: content,
  35635. // Fixed formatter
  35636. formatter: content
  35637. };
  35638. }
  35639. var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
  35640. var defaultHtml = subTooltipModel.get('content');
  35641. var asyncTicket = Math.random();
  35642. // Do not check whether `trigger` is 'none' here, because `trigger`
  35643. // only works on cooridinate system. In fact, we have not found case
  35644. // that requires setting `trigger` nothing on component yet.
  35645. this._showOrMove(subTooltipModel, function () {
  35646. this._showTooltipContent(
  35647. subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {},
  35648. asyncTicket, e.offsetX, e.offsetY, e.position, el
  35649. );
  35650. });
  35651. // If not dispatch showTip, tip may be hide triggered by axis.
  35652. dispatchAction({
  35653. type: 'showTip',
  35654. from: this.uid
  35655. });
  35656. },
  35657. _showTooltipContent: function (
  35658. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el
  35659. ) {
  35660. // Reset ticket
  35661. this._ticket = '';
  35662. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  35663. return;
  35664. }
  35665. var tooltipContent = this._tooltipContent;
  35666. var formatter = tooltipModel.get('formatter');
  35667. positionExpr = positionExpr || tooltipModel.get('position');
  35668. var html = defaultHtml;
  35669. if (formatter && typeof formatter === 'string') {
  35670. html = formatTpl(formatter, params, true);
  35671. }
  35672. else if (typeof formatter === 'function') {
  35673. var callback = bind$2(function (cbTicket, html) {
  35674. if (cbTicket === this._ticket) {
  35675. tooltipContent.setContent(html);
  35676. this._updatePosition(
  35677. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  35678. );
  35679. }
  35680. }, this);
  35681. this._ticket = asyncTicket;
  35682. html = formatter(params, asyncTicket, callback);
  35683. }
  35684. tooltipContent.setContent(html);
  35685. tooltipContent.show(tooltipModel);
  35686. this._updatePosition(
  35687. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  35688. );
  35689. },
  35690. /**
  35691. * @param {string|Function|Array.<number>|Object} positionExpr
  35692. * @param {number} x Mouse x
  35693. * @param {number} y Mouse y
  35694. * @param {boolean} confine Whether confine tooltip content in view rect.
  35695. * @param {Object|<Array.<Object>} params
  35696. * @param {module:zrender/Element} el target element
  35697. * @param {module:echarts/ExtensionAPI} api
  35698. * @return {Array.<number>}
  35699. */
  35700. _updatePosition: function (tooltipModel, positionExpr, x, y, content, params, el) {
  35701. var viewWidth = this._api.getWidth();
  35702. var viewHeight = this._api.getHeight();
  35703. positionExpr = positionExpr || tooltipModel.get('position');
  35704. var contentSize = content.getSize();
  35705. var align = tooltipModel.get('align');
  35706. var vAlign = tooltipModel.get('verticalAlign');
  35707. var rect = el && el.getBoundingRect().clone();
  35708. el && rect.applyTransform(el.transform);
  35709. if (typeof positionExpr === 'function') {
  35710. // Callback of position can be an array or a string specify the position
  35711. positionExpr = positionExpr([x, y], params, content.el, rect, {
  35712. viewSize: [viewWidth, viewHeight],
  35713. contentSize: contentSize.slice()
  35714. });
  35715. }
  35716. if (isArray(positionExpr)) {
  35717. x = parsePercent$2(positionExpr[0], viewWidth);
  35718. y = parsePercent$2(positionExpr[1], viewHeight);
  35719. }
  35720. else if (isObject$1(positionExpr)) {
  35721. positionExpr.width = contentSize[0];
  35722. positionExpr.height = contentSize[1];
  35723. var layoutRect = getLayoutRect(
  35724. positionExpr, {width: viewWidth, height: viewHeight}
  35725. );
  35726. x = layoutRect.x;
  35727. y = layoutRect.y;
  35728. align = null;
  35729. // When positionExpr is left/top/right/bottom,
  35730. // align and verticalAlign will not work.
  35731. vAlign = null;
  35732. }
  35733. // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  35734. else if (typeof positionExpr === 'string' && el) {
  35735. var pos = calcTooltipPosition(
  35736. positionExpr, rect, contentSize
  35737. );
  35738. x = pos[0];
  35739. y = pos[1];
  35740. }
  35741. else {
  35742. var pos = refixTooltipPosition(
  35743. x, y, content.el, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20
  35744. );
  35745. x = pos[0];
  35746. y = pos[1];
  35747. }
  35748. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  35749. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  35750. if (tooltipModel.get('confine')) {
  35751. var pos = confineTooltipPosition(
  35752. x, y, content.el, viewWidth, viewHeight
  35753. );
  35754. x = pos[0];
  35755. y = pos[1];
  35756. }
  35757. content.moveTo(x, y);
  35758. },
  35759. // FIXME
  35760. // Should we remove this but leave this to user?
  35761. _updateContentNotChangedOnAxis: function (dataByCoordSys) {
  35762. var lastCoordSys = this._lastDataByCoordSys;
  35763. var contentNotChanged = !!lastCoordSys
  35764. && lastCoordSys.length === dataByCoordSys.length;
  35765. contentNotChanged && each$10(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  35766. var lastDataByAxis = lastItemCoordSys.dataByAxis || {};
  35767. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  35768. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  35769. contentNotChanged &= lastDataByAxis.length === thisDataByAxis.length;
  35770. contentNotChanged && each$10(lastDataByAxis, function (lastItem, indexAxis) {
  35771. var thisItem = thisDataByAxis[indexAxis] || {};
  35772. var lastIndices = lastItem.seriesDataIndices || [];
  35773. var newIndices = thisItem.seriesDataIndices || [];
  35774. contentNotChanged &=
  35775. lastItem.value === thisItem.value
  35776. && lastItem.axisType === thisItem.axisType
  35777. && lastItem.axisId === thisItem.axisId
  35778. && lastIndices.length === newIndices.length;
  35779. contentNotChanged && each$10(lastIndices, function (lastIdxItem, j) {
  35780. var newIdxItem = newIndices[j];
  35781. contentNotChanged &=
  35782. lastIdxItem.seriesIndex === newIdxItem.seriesIndex
  35783. && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  35784. });
  35785. });
  35786. });
  35787. this._lastDataByCoordSys = dataByCoordSys;
  35788. return !!contentNotChanged;
  35789. },
  35790. _hide: function (dispatchAction) {
  35791. // Do not directly hideLater here, because this behavior may be prevented
  35792. // in dispatchAction when showTip is dispatched.
  35793. // FIXME
  35794. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  35795. this._lastDataByCoordSys = null;
  35796. dispatchAction({
  35797. type: 'hideTip',
  35798. from: this.uid
  35799. });
  35800. },
  35801. dispose: function (ecModel, api) {
  35802. if (env$1.node) {
  35803. return;
  35804. }
  35805. this._tooltipContent.hide();
  35806. unregister('itemTooltip', api);
  35807. }
  35808. });
  35809. /**
  35810. * @param {Array.<Object|module:echarts/model/Model>} modelCascade
  35811. * From top to bottom. (the last one should be globalTooltipModel);
  35812. */
  35813. function buildTooltipModel(modelCascade) {
  35814. var resultModel = modelCascade.pop();
  35815. while (modelCascade.length) {
  35816. var tooltipOpt = modelCascade.pop();
  35817. if (tooltipOpt) {
  35818. if (Model.isInstance(tooltipOpt)) {
  35819. tooltipOpt = tooltipOpt.get('tooltip', true);
  35820. }
  35821. // In each data item tooltip can be simply write:
  35822. // {
  35823. // value: 10,
  35824. // tooltip: 'Something you need to know'
  35825. // }
  35826. if (typeof tooltipOpt === 'string') {
  35827. tooltipOpt = {formatter: tooltipOpt};
  35828. }
  35829. resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
  35830. }
  35831. }
  35832. return resultModel;
  35833. }
  35834. function makeDispatchAction$1(payload, api) {
  35835. return payload.dispatchAction || bind(api.dispatchAction, api);
  35836. }
  35837. function refixTooltipPosition(x, y, el, viewWidth, viewHeight, gapH, gapV) {
  35838. var size = getOuterSize(el);
  35839. var width = size.width;
  35840. var height = size.height;
  35841. if (gapH != null) {
  35842. if (x + width + gapH > viewWidth) {
  35843. x -= width + gapH;
  35844. }
  35845. else {
  35846. x += gapH;
  35847. }
  35848. }
  35849. if (gapV != null) {
  35850. if (y + height + gapV > viewHeight) {
  35851. y -= height + gapV;
  35852. }
  35853. else {
  35854. y += gapV;
  35855. }
  35856. }
  35857. return [x, y];
  35858. }
  35859. function confineTooltipPosition(x, y, el, viewWidth, viewHeight) {
  35860. var size = getOuterSize(el);
  35861. var width = size.width;
  35862. var height = size.height;
  35863. x = Math.min(x + width, viewWidth) - width;
  35864. y = Math.min(y + height, viewHeight) - height;
  35865. x = Math.max(x, 0);
  35866. y = Math.max(y, 0);
  35867. return [x, y];
  35868. }
  35869. function getOuterSize(el) {
  35870. var width = el.clientWidth;
  35871. var height = el.clientHeight;
  35872. // Consider browser compatibility.
  35873. // IE8 does not support getComputedStyle.
  35874. if (document.defaultView && document.defaultView.getComputedStyle) {
  35875. var stl = document.defaultView.getComputedStyle(el);
  35876. if (stl) {
  35877. width += parseInt(stl.paddingLeft, 10) + parseInt(stl.paddingRight, 10)
  35878. + parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10);
  35879. height += parseInt(stl.paddingTop, 10) + parseInt(stl.paddingBottom, 10)
  35880. + parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10);
  35881. }
  35882. }
  35883. return {width: width, height: height};
  35884. }
  35885. function calcTooltipPosition(position, rect, contentSize) {
  35886. var domWidth = contentSize[0];
  35887. var domHeight = contentSize[1];
  35888. var gap = 5;
  35889. var x = 0;
  35890. var y = 0;
  35891. var rectWidth = rect.width;
  35892. var rectHeight = rect.height;
  35893. switch (position) {
  35894. case 'inside':
  35895. x = rect.x + rectWidth / 2 - domWidth / 2;
  35896. y = rect.y + rectHeight / 2 - domHeight / 2;
  35897. break;
  35898. case 'top':
  35899. x = rect.x + rectWidth / 2 - domWidth / 2;
  35900. y = rect.y - domHeight - gap;
  35901. break;
  35902. case 'bottom':
  35903. x = rect.x + rectWidth / 2 - domWidth / 2;
  35904. y = rect.y + rectHeight + gap;
  35905. break;
  35906. case 'left':
  35907. x = rect.x - domWidth - gap;
  35908. y = rect.y + rectHeight / 2 - domHeight / 2;
  35909. break;
  35910. case 'right':
  35911. x = rect.x + rectWidth + gap;
  35912. y = rect.y + rectHeight / 2 - domHeight / 2;
  35913. }
  35914. return [x, y];
  35915. }
  35916. function isCenterAlign(align) {
  35917. return align === 'center' || align === 'middle';
  35918. }
  35919. // FIXME Better way to pack data in graphic element
  35920. /**
  35921. * @action
  35922. * @property {string} type
  35923. * @property {number} seriesIndex
  35924. * @property {number} dataIndex
  35925. * @property {number} [x]
  35926. * @property {number} [y]
  35927. */
  35928. registerAction(
  35929. {
  35930. type: 'showTip',
  35931. event: 'showTip',
  35932. update: 'tooltip:manuallyShowTip'
  35933. },
  35934. // noop
  35935. function () {}
  35936. );
  35937. registerAction(
  35938. {
  35939. type: 'hideTip',
  35940. event: 'hideTip',
  35941. update: 'tooltip:manuallyHideTip'
  35942. },
  35943. // noop
  35944. function () {}
  35945. );
  35946. var LegendModel = extendComponentModel({
  35947. type: 'legend.plain',
  35948. dependencies: ['series'],
  35949. layoutMode: {
  35950. type: 'box',
  35951. // legend.width/height are maxWidth/maxHeight actually,
  35952. // whereas realy width/height is calculated by its content.
  35953. // (Setting {left: 10, right: 10} does not make sense).
  35954. // So consider the case:
  35955. // `setOption({legend: {left: 10});`
  35956. // then `setOption({legend: {right: 10});`
  35957. // The previous `left` should be cleared by setting `ignoreSize`.
  35958. ignoreSize: true
  35959. },
  35960. init: function (option, parentModel, ecModel) {
  35961. this.mergeDefaultAndTheme(option, ecModel);
  35962. option.selected = option.selected || {};
  35963. },
  35964. mergeOption: function (option) {
  35965. LegendModel.superCall(this, 'mergeOption', option);
  35966. },
  35967. optionUpdated: function () {
  35968. this._updateData(this.ecModel);
  35969. var legendData = this._data;
  35970. // If selectedMode is single, try to select one
  35971. if (legendData[0] && this.get('selectedMode') === 'single') {
  35972. var hasSelected = false;
  35973. // If has any selected in option.selected
  35974. for (var i = 0; i < legendData.length; i++) {
  35975. var name = legendData[i].get('name');
  35976. if (this.isSelected(name)) {
  35977. // Force to unselect others
  35978. this.select(name);
  35979. hasSelected = true;
  35980. break;
  35981. }
  35982. }
  35983. // Try select the first if selectedMode is single
  35984. !hasSelected && this.select(legendData[0].get('name'));
  35985. }
  35986. },
  35987. _updateData: function (ecModel) {
  35988. var potentialData = [];
  35989. var availableNames = [];
  35990. ecModel.eachRawSeries(function (seriesModel) {
  35991. var seriesName = seriesModel.name;
  35992. availableNames.push(seriesName);
  35993. var isPotential;
  35994. if (seriesModel.legendDataProvider) {
  35995. var data = seriesModel.legendDataProvider();
  35996. var names = data.mapArray(data.getName);
  35997. if (!ecModel.isSeriesFiltered(seriesModel)) {
  35998. availableNames = availableNames.concat(names);
  35999. }
  36000. if (names.length) {
  36001. potentialData = potentialData.concat(names);
  36002. }
  36003. else {
  36004. isPotential = true;
  36005. }
  36006. }
  36007. else {
  36008. isPotential = true;
  36009. }
  36010. if (isPotential && isNameSpecified(seriesModel)) {
  36011. potentialData.push(seriesModel.name);
  36012. }
  36013. });
  36014. /**
  36015. * @type {Array.<string>}
  36016. * @private
  36017. */
  36018. this._availableNames = availableNames;
  36019. // If legend.data not specified in option, use availableNames as data,
  36020. // which is convinient for user preparing option.
  36021. var rawData = this.get('data') || potentialData;
  36022. var legendData = map(rawData, function (dataItem) {
  36023. // Can be string or number
  36024. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  36025. dataItem = {
  36026. name: dataItem
  36027. };
  36028. }
  36029. return new Model(dataItem, this, this.ecModel);
  36030. }, this);
  36031. /**
  36032. * @type {Array.<module:echarts/model/Model>}
  36033. * @private
  36034. */
  36035. this._data = legendData;
  36036. },
  36037. /**
  36038. * @return {Array.<module:echarts/model/Model>}
  36039. */
  36040. getData: function () {
  36041. return this._data;
  36042. },
  36043. /**
  36044. * @param {string} name
  36045. */
  36046. select: function (name) {
  36047. var selected = this.option.selected;
  36048. var selectedMode = this.get('selectedMode');
  36049. if (selectedMode === 'single') {
  36050. var data = this._data;
  36051. each$1(data, function (dataItem) {
  36052. selected[dataItem.get('name')] = false;
  36053. });
  36054. }
  36055. selected[name] = true;
  36056. },
  36057. /**
  36058. * @param {string} name
  36059. */
  36060. unSelect: function (name) {
  36061. if (this.get('selectedMode') !== 'single') {
  36062. this.option.selected[name] = false;
  36063. }
  36064. },
  36065. /**
  36066. * @param {string} name
  36067. */
  36068. toggleSelected: function (name) {
  36069. var selected = this.option.selected;
  36070. // Default is true
  36071. if (!selected.hasOwnProperty(name)) {
  36072. selected[name] = true;
  36073. }
  36074. this[selected[name] ? 'unSelect' : 'select'](name);
  36075. },
  36076. /**
  36077. * @param {string} name
  36078. */
  36079. isSelected: function (name) {
  36080. var selected = this.option.selected;
  36081. return !(selected.hasOwnProperty(name) && !selected[name])
  36082. && indexOf(this._availableNames, name) >= 0;
  36083. },
  36084. defaultOption: {
  36085. // 一级层叠
  36086. zlevel: 0,
  36087. // 二级层叠
  36088. z: 4,
  36089. show: true,
  36090. // 布局方式,默认为水平布局,可选为:
  36091. // 'horizontal' | 'vertical'
  36092. orient: 'horizontal',
  36093. left: 'center',
  36094. // right: 'center',
  36095. top: 0,
  36096. // bottom: null,
  36097. // 水平对齐
  36098. // 'auto' | 'left' | 'right'
  36099. // 默认为 'auto', 根据 x 的位置判断是左对齐还是右对齐
  36100. align: 'auto',
  36101. backgroundColor: 'rgba(0,0,0,0)',
  36102. // 图例边框颜色
  36103. borderColor: '#ccc',
  36104. borderRadius: 0,
  36105. // 图例边框线宽,单位px,默认为0(无边框)
  36106. borderWidth: 0,
  36107. // 图例内边距,单位px,默认各方向内边距为5,
  36108. // 接受数组分别设定上右下左边距,同css
  36109. padding: 5,
  36110. // 各个item之间的间隔,单位px,默认为10,
  36111. // 横向布局时为水平间隔,纵向布局时为纵向间隔
  36112. itemGap: 10,
  36113. // 图例图形宽度
  36114. itemWidth: 25,
  36115. // 图例图形高度
  36116. itemHeight: 14,
  36117. // 图例关闭时候的颜色
  36118. inactiveColor: '#ccc',
  36119. textStyle: {
  36120. // 图例文字颜色
  36121. color: '#333'
  36122. },
  36123. // formatter: '',
  36124. // 选择模式,默认开启图例开关
  36125. selectedMode: true,
  36126. // 配置默认选中状态,可配合LEGEND.SELECTED事件做动态数据载入
  36127. // selected: null,
  36128. // 图例内容(详见legend.data,数组中每一项代表一个item
  36129. // data: [],
  36130. // Tooltip 相关配置
  36131. tooltip: {
  36132. show: false
  36133. }
  36134. }
  36135. });
  36136. function legendSelectActionHandler(methodName, payload, ecModel) {
  36137. var selectedMap = {};
  36138. var isToggleSelect = methodName === 'toggleSelected';
  36139. var isSelected;
  36140. // Update all legend components
  36141. ecModel.eachComponent('legend', function (legendModel) {
  36142. if (isToggleSelect && isSelected != null) {
  36143. // Force other legend has same selected status
  36144. // Or the first is toggled to true and other are toggled to false
  36145. // In the case one legend has some item unSelected in option. And if other legend
  36146. // doesn't has the item, they will assume it is selected.
  36147. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  36148. }
  36149. else {
  36150. legendModel[methodName](payload.name);
  36151. isSelected = legendModel.isSelected(payload.name);
  36152. }
  36153. var legendData = legendModel.getData();
  36154. each$1(legendData, function (model) {
  36155. var name = model.get('name');
  36156. // Wrap element
  36157. if (name === '\n' || name === '') {
  36158. return;
  36159. }
  36160. var isItemSelected = legendModel.isSelected(name);
  36161. if (selectedMap.hasOwnProperty(name)) {
  36162. // Unselected if any legend is unselected
  36163. selectedMap[name] = selectedMap[name] && isItemSelected;
  36164. }
  36165. else {
  36166. selectedMap[name] = isItemSelected;
  36167. }
  36168. });
  36169. });
  36170. // Return the event explicitly
  36171. return {
  36172. name: payload.name,
  36173. selected: selectedMap
  36174. };
  36175. }
  36176. /**
  36177. * @event legendToggleSelect
  36178. * @type {Object}
  36179. * @property {string} type 'legendToggleSelect'
  36180. * @property {string} [from]
  36181. * @property {string} name Series name or data item name
  36182. */
  36183. registerAction(
  36184. 'legendToggleSelect', 'legendselectchanged',
  36185. curry(legendSelectActionHandler, 'toggleSelected')
  36186. );
  36187. /**
  36188. * @event legendSelect
  36189. * @type {Object}
  36190. * @property {string} type 'legendSelect'
  36191. * @property {string} name Series name or data item name
  36192. */
  36193. registerAction(
  36194. 'legendSelect', 'legendselected',
  36195. curry(legendSelectActionHandler, 'select')
  36196. );
  36197. /**
  36198. * @event legendUnSelect
  36199. * @type {Object}
  36200. * @property {string} type 'legendUnSelect'
  36201. * @property {string} name Series name or data item name
  36202. */
  36203. registerAction(
  36204. 'legendUnSelect', 'legendunselected',
  36205. curry(legendSelectActionHandler, 'unSelect')
  36206. );
  36207. /**
  36208. * Layout list like component.
  36209. * It will box layout each items in group of component and then position the whole group in the viewport
  36210. * @param {module:zrender/group/Group} group
  36211. * @param {module:echarts/model/Component} componentModel
  36212. * @param {module:echarts/ExtensionAPI}
  36213. */
  36214. function layout$2(group, componentModel, api) {
  36215. var boxLayoutParams = componentModel.getBoxLayoutParams();
  36216. var padding = componentModel.get('padding');
  36217. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  36218. var rect = getLayoutRect(
  36219. boxLayoutParams,
  36220. viewportSize,
  36221. padding
  36222. );
  36223. box(
  36224. componentModel.get('orient'),
  36225. group,
  36226. componentModel.get('itemGap'),
  36227. rect.width,
  36228. rect.height
  36229. );
  36230. positionElement(
  36231. group,
  36232. boxLayoutParams,
  36233. viewportSize,
  36234. padding
  36235. );
  36236. }
  36237. function makeBackground(rect, componentModel) {
  36238. var padding = normalizeCssArray$1(
  36239. componentModel.get('padding')
  36240. );
  36241. var style = componentModel.getItemStyle(['color', 'opacity']);
  36242. style.fill = componentModel.get('backgroundColor');
  36243. var rect = new Rect({
  36244. shape: {
  36245. x: rect.x - padding[3],
  36246. y: rect.y - padding[0],
  36247. width: rect.width + padding[1] + padding[3],
  36248. height: rect.height + padding[0] + padding[2],
  36249. r: componentModel.get('borderRadius')
  36250. },
  36251. style: style,
  36252. silent: true,
  36253. z2: -1
  36254. });
  36255. // FIXME
  36256. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  36257. // and background rect when setting like `left: 0`, `top: 0`.
  36258. // graphic.subPixelOptimizeRect(rect);
  36259. return rect;
  36260. }
  36261. var curry$3 = curry;
  36262. var each$12 = each$1;
  36263. var Group$2 = Group;
  36264. var LegendView = extendComponentView({
  36265. type: 'legend.plain',
  36266. newlineDisabled: false,
  36267. /**
  36268. * @override
  36269. */
  36270. init: function () {
  36271. /**
  36272. * @private
  36273. * @type {module:zrender/container/Group}
  36274. */
  36275. this.group.add(this._contentGroup = new Group$2());
  36276. /**
  36277. * @private
  36278. * @type {module:zrender/Element}
  36279. */
  36280. this._backgroundEl;
  36281. },
  36282. /**
  36283. * @protected
  36284. */
  36285. getContentGroup: function () {
  36286. return this._contentGroup;
  36287. },
  36288. /**
  36289. * @override
  36290. */
  36291. render: function (legendModel, ecModel, api) {
  36292. this.resetInner();
  36293. if (!legendModel.get('show', true)) {
  36294. return;
  36295. }
  36296. var itemAlign = legendModel.get('align');
  36297. if (!itemAlign || itemAlign === 'auto') {
  36298. itemAlign = (
  36299. legendModel.get('left') === 'right'
  36300. && legendModel.get('orient') === 'vertical'
  36301. ) ? 'right' : 'left';
  36302. }
  36303. this.renderInner(itemAlign, legendModel, ecModel, api);
  36304. // Perform layout.
  36305. var positionInfo = legendModel.getBoxLayoutParams();
  36306. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  36307. var padding = legendModel.get('padding');
  36308. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  36309. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize);
  36310. // Place mainGroup, based on the calculated `mainRect`.
  36311. var layoutRect = getLayoutRect(
  36312. defaults({width: mainRect.width, height: mainRect.height}, positionInfo),
  36313. viewportSize,
  36314. padding
  36315. );
  36316. this.group.attr('position', [layoutRect.x - mainRect.x, layoutRect.y - mainRect.y]);
  36317. // Render background after group is layout.
  36318. this.group.add(
  36319. this._backgroundEl = makeBackground(mainRect, legendModel)
  36320. );
  36321. },
  36322. /**
  36323. * @protected
  36324. */
  36325. resetInner: function () {
  36326. this.getContentGroup().removeAll();
  36327. this._backgroundEl && this.group.remove(this._backgroundEl);
  36328. },
  36329. /**
  36330. * @protected
  36331. */
  36332. renderInner: function (itemAlign, legendModel, ecModel, api) {
  36333. var contentGroup = this.getContentGroup();
  36334. var legendDrawnMap = createHashMap();
  36335. var selectMode = legendModel.get('selectedMode');
  36336. each$12(legendModel.getData(), function (itemModel, dataIndex) {
  36337. var name = itemModel.get('name');
  36338. // Use empty string or \n as a newline string
  36339. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  36340. contentGroup.add(new Group$2({
  36341. newline: true
  36342. }));
  36343. return;
  36344. }
  36345. var seriesModel = ecModel.getSeriesByName(name)[0];
  36346. if (legendDrawnMap.get(name)) {
  36347. // Have been drawed
  36348. return;
  36349. }
  36350. // Series legend
  36351. if (seriesModel) {
  36352. var data = seriesModel.getData();
  36353. var color = data.getVisual('color');
  36354. // If color is a callback function
  36355. if (typeof color === 'function') {
  36356. // Use the first data
  36357. color = color(seriesModel.getDataParams(0));
  36358. }
  36359. // Using rect symbol defaultly
  36360. var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
  36361. var symbolType = data.getVisual('symbol');
  36362. var itemGroup = this._createItem(
  36363. name, dataIndex, itemModel, legendModel,
  36364. legendSymbolType, symbolType,
  36365. itemAlign, color,
  36366. selectMode
  36367. );
  36368. itemGroup.on('click', curry$3(dispatchSelectAction, name, api))
  36369. .on('mouseover', curry$3(dispatchHighlightAction, seriesModel, null, api))
  36370. .on('mouseout', curry$3(dispatchDownplayAction, seriesModel, null, api));
  36371. legendDrawnMap.set(name, true);
  36372. }
  36373. else {
  36374. // Data legend of pie, funnel
  36375. ecModel.eachRawSeries(function (seriesModel) {
  36376. // In case multiple series has same data name
  36377. if (legendDrawnMap.get(name)) {
  36378. return;
  36379. }
  36380. if (seriesModel.legendDataProvider) {
  36381. var data = seriesModel.legendDataProvider();
  36382. var idx = data.indexOfName(name);
  36383. if (idx < 0) {
  36384. return;
  36385. }
  36386. var color = data.getItemVisual(idx, 'color');
  36387. var legendSymbolType = 'roundRect';
  36388. var itemGroup = this._createItem(
  36389. name, dataIndex, itemModel, legendModel,
  36390. legendSymbolType, null,
  36391. itemAlign, color,
  36392. selectMode
  36393. );
  36394. itemGroup.on('click', curry$3(dispatchSelectAction, name, api))
  36395. // FIXME Should not specify the series name
  36396. .on('mouseover', curry$3(dispatchHighlightAction, seriesModel, name, api))
  36397. .on('mouseout', curry$3(dispatchDownplayAction, seriesModel, name, api));
  36398. legendDrawnMap.set(name, true);
  36399. }
  36400. }, this);
  36401. }
  36402. if (__DEV__) {
  36403. if (!legendDrawnMap.get(name)) {
  36404. console.warn(name + ' series not exists. Legend data should be same with series name or data name.');
  36405. }
  36406. }
  36407. }, this);
  36408. },
  36409. _createItem: function (
  36410. name, dataIndex, itemModel, legendModel,
  36411. legendSymbolType, symbolType,
  36412. itemAlign, color, selectMode
  36413. ) {
  36414. var itemWidth = legendModel.get('itemWidth');
  36415. var itemHeight = legendModel.get('itemHeight');
  36416. var inactiveColor = legendModel.get('inactiveColor');
  36417. var isSelected = legendModel.isSelected(name);
  36418. var itemGroup = new Group$2();
  36419. var textStyleModel = itemModel.getModel('textStyle');
  36420. var itemIcon = itemModel.get('icon');
  36421. var tooltipModel = itemModel.getModel('tooltip');
  36422. var legendGlobalTooltipModel = tooltipModel.parentModel;
  36423. // Use user given icon first
  36424. legendSymbolType = itemIcon || legendSymbolType;
  36425. itemGroup.add(createSymbol(
  36426. legendSymbolType,
  36427. 0,
  36428. 0,
  36429. itemWidth,
  36430. itemHeight,
  36431. isSelected ? color : inactiveColor,
  36432. true
  36433. ));
  36434. // Compose symbols
  36435. // PENDING
  36436. if (!itemIcon && symbolType
  36437. // At least show one symbol, can't be all none
  36438. && ((symbolType !== legendSymbolType) || symbolType == 'none')
  36439. ) {
  36440. var size = itemHeight * 0.8;
  36441. if (symbolType === 'none') {
  36442. symbolType = 'circle';
  36443. }
  36444. // Put symbol in the center
  36445. itemGroup.add(createSymbol(
  36446. symbolType, (itemWidth - size) / 2, (itemHeight - size) / 2, size, size,
  36447. isSelected ? color : inactiveColor
  36448. ));
  36449. }
  36450. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  36451. var textAlign = itemAlign;
  36452. var formatter = legendModel.get('formatter');
  36453. var content = name;
  36454. if (typeof formatter === 'string' && formatter) {
  36455. content = formatter.replace('{name}', name != null ? name : '');
  36456. }
  36457. else if (typeof formatter === 'function') {
  36458. content = formatter(name);
  36459. }
  36460. itemGroup.add(new Text({
  36461. style: setTextStyle({}, textStyleModel, {
  36462. text: content,
  36463. x: textX,
  36464. y: itemHeight / 2,
  36465. textFill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  36466. textAlign: textAlign,
  36467. textVerticalAlign: 'middle'
  36468. })
  36469. }));
  36470. // Add a invisible rect to increase the area of mouse hover
  36471. var hitRect = new Rect({
  36472. shape: itemGroup.getBoundingRect(),
  36473. invisible: true,
  36474. tooltip: tooltipModel.get('show') ? extend({
  36475. content: name,
  36476. // Defaul formatter
  36477. formatter: legendGlobalTooltipModel.get('formatter', true) || function () {
  36478. return name;
  36479. },
  36480. formatterParams: {
  36481. componentType: 'legend',
  36482. legendIndex: legendModel.componentIndex,
  36483. name: name,
  36484. $vars: ['name']
  36485. }
  36486. }, tooltipModel.option) : null
  36487. });
  36488. itemGroup.add(hitRect);
  36489. itemGroup.eachChild(function (child) {
  36490. child.silent = true;
  36491. });
  36492. hitRect.silent = !selectMode;
  36493. this.getContentGroup().add(itemGroup);
  36494. setHoverStyle(itemGroup);
  36495. itemGroup.__legendDataIndex = dataIndex;
  36496. return itemGroup;
  36497. },
  36498. /**
  36499. * @protected
  36500. */
  36501. layoutInner: function (legendModel, itemAlign, maxSize) {
  36502. var contentGroup = this.getContentGroup();
  36503. // Place items in contentGroup.
  36504. box(
  36505. legendModel.get('orient'),
  36506. contentGroup,
  36507. legendModel.get('itemGap'),
  36508. maxSize.width,
  36509. maxSize.height
  36510. );
  36511. var contentRect = contentGroup.getBoundingRect();
  36512. contentGroup.attr('position', [-contentRect.x, -contentRect.y]);
  36513. return this.group.getBoundingRect();
  36514. }
  36515. });
  36516. function dispatchSelectAction(name, api) {
  36517. api.dispatchAction({
  36518. type: 'legendToggleSelect',
  36519. name: name
  36520. });
  36521. }
  36522. function dispatchHighlightAction(seriesModel, dataName, api) {
  36523. // If element hover will move to a hoverLayer.
  36524. var el = api.getZr().storage.getDisplayList()[0];
  36525. if (!(el && el.useHoverLayer)) {
  36526. seriesModel.get('legendHoverLink') && api.dispatchAction({
  36527. type: 'highlight',
  36528. seriesName: seriesModel.name,
  36529. name: dataName
  36530. });
  36531. }
  36532. }
  36533. function dispatchDownplayAction(seriesModel, dataName, api) {
  36534. // If element hover will move to a hoverLayer.
  36535. var el = api.getZr().storage.getDisplayList()[0];
  36536. if (!(el && el.useHoverLayer)) {
  36537. seriesModel.get('legendHoverLink') && api.dispatchAction({
  36538. type: 'downplay',
  36539. seriesName: seriesModel.name,
  36540. name: dataName
  36541. });
  36542. }
  36543. }
  36544. var legendFilter = function (ecModel) {
  36545. var legendModels = ecModel.findComponents({
  36546. mainType: 'legend'
  36547. });
  36548. if (legendModels && legendModels.length) {
  36549. ecModel.filterSeries(function (series) {
  36550. // If in any legend component the status is not selected.
  36551. // Because in legend series is assumed selected when it is not in the legend data.
  36552. for (var i = 0; i < legendModels.length; i++) {
  36553. if (!legendModels[i].isSelected(series.name)) {
  36554. return false;
  36555. }
  36556. }
  36557. return true;
  36558. });
  36559. }
  36560. };
  36561. // Do not contain scrollable legend, for sake of file size.
  36562. // Series Filter
  36563. registerProcessor(legendFilter);
  36564. ComponentModel.registerSubTypeDefaulter('legend', function () {
  36565. // Default 'plain' when no type specified.
  36566. return 'plain';
  36567. });
  36568. var ScrollableLegendModel = LegendModel.extend({
  36569. type: 'legend.scroll',
  36570. /**
  36571. * @param {number} scrollDataIndex
  36572. */
  36573. setScrollDataIndex: function (scrollDataIndex) {
  36574. this.option.scrollDataIndex = scrollDataIndex;
  36575. },
  36576. defaultOption: {
  36577. scrollDataIndex: 0,
  36578. pageButtonItemGap: 5,
  36579. pageButtonGap: null,
  36580. pageButtonPosition: 'end', // 'start' or 'end'
  36581. pageFormatter: '{current}/{total}', // If null/undefined, do not show page.
  36582. pageIcons: {
  36583. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  36584. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  36585. },
  36586. pageIconColor: '#2f4554',
  36587. pageIconInactiveColor: '#aaa',
  36588. pageIconSize: 15, // Can be [10, 3], which represents [width, height]
  36589. pageTextStyle: {
  36590. color: '#333'
  36591. },
  36592. animationDurationUpdate: 800
  36593. },
  36594. /**
  36595. * @override
  36596. */
  36597. init: function (option, parentModel, ecModel, extraOpt) {
  36598. var inputPositionParams = getLayoutParams(option);
  36599. ScrollableLegendModel.superCall(this, 'init', option, parentModel, ecModel, extraOpt);
  36600. mergeAndNormalizeLayoutParams(this, option, inputPositionParams);
  36601. },
  36602. /**
  36603. * @override
  36604. */
  36605. mergeOption: function (option, extraOpt) {
  36606. ScrollableLegendModel.superCall(this, 'mergeOption', option, extraOpt);
  36607. mergeAndNormalizeLayoutParams(this, this.option, option);
  36608. },
  36609. getOrient: function () {
  36610. return this.get('orient') === 'vertical'
  36611. ? {index: 1, name: 'vertical'}
  36612. : {index: 0, name: 'horizontal'};
  36613. }
  36614. });
  36615. // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  36616. function mergeAndNormalizeLayoutParams(legendModel, target, raw) {
  36617. var orient = legendModel.getOrient();
  36618. var ignoreSize = [1, 1];
  36619. ignoreSize[orient.index] = 0;
  36620. mergeLayoutParam(target, raw, {
  36621. type: 'box', ignoreSize: ignoreSize
  36622. });
  36623. }
  36624. /**
  36625. * Separate legend and scrollable legend to reduce package size.
  36626. */
  36627. var Group$3 = Group;
  36628. var WH = ['width', 'height'];
  36629. var XY = ['x', 'y'];
  36630. var ScrollableLegendView = LegendView.extend({
  36631. type: 'legend.scroll',
  36632. newlineDisabled: true,
  36633. init: function () {
  36634. ScrollableLegendView.superCall(this, 'init');
  36635. /**
  36636. * @private
  36637. * @type {number} For `scroll`.
  36638. */
  36639. this._currentIndex = 0;
  36640. /**
  36641. * @private
  36642. * @type {module:zrender/container/Group}
  36643. */
  36644. this.group.add(this._containerGroup = new Group$3());
  36645. this._containerGroup.add(this.getContentGroup());
  36646. /**
  36647. * @private
  36648. * @type {module:zrender/container/Group}
  36649. */
  36650. this.group.add(this._controllerGroup = new Group$3());
  36651. /**
  36652. *
  36653. * @private
  36654. */
  36655. this._showController;
  36656. },
  36657. /**
  36658. * @override
  36659. */
  36660. resetInner: function () {
  36661. ScrollableLegendView.superCall(this, 'resetInner');
  36662. this._controllerGroup.removeAll();
  36663. this._containerGroup.removeClipPath();
  36664. this._containerGroup.__rectSize = null;
  36665. },
  36666. /**
  36667. * @override
  36668. */
  36669. renderInner: function (itemAlign, legendModel, ecModel, api) {
  36670. var me = this;
  36671. // Render content items.
  36672. ScrollableLegendView.superCall(this, 'renderInner', itemAlign, legendModel, ecModel, api);
  36673. var controllerGroup = this._controllerGroup;
  36674. var pageIconSize = legendModel.get('pageIconSize', true);
  36675. if (!isArray(pageIconSize)) {
  36676. pageIconSize = [pageIconSize, pageIconSize];
  36677. }
  36678. createPageButton('pagePrev', 0);
  36679. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  36680. controllerGroup.add(new Text({
  36681. name: 'pageText',
  36682. style: {
  36683. textFill: pageTextStyleModel.getTextColor(),
  36684. font: pageTextStyleModel.getFont(),
  36685. textVerticalAlign: 'middle',
  36686. textAlign: 'center'
  36687. },
  36688. silent: true
  36689. }));
  36690. createPageButton('pageNext', 1);
  36691. function createPageButton(name, iconIdx) {
  36692. var pageDataIndexName = name + 'DataIndex';
  36693. var icon = createIcon(
  36694. legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx],
  36695. {
  36696. // Buttons will be created in each render, so we do not need
  36697. // to worry about avoiding using legendModel kept in scope.
  36698. onclick: bind(
  36699. me._pageGo, me, pageDataIndexName, legendModel, api
  36700. )
  36701. },
  36702. {
  36703. x: -pageIconSize[0] / 2,
  36704. y: -pageIconSize[1] / 2,
  36705. width: pageIconSize[0],
  36706. height: pageIconSize[1]
  36707. }
  36708. );
  36709. icon.name = name;
  36710. controllerGroup.add(icon);
  36711. }
  36712. },
  36713. /**
  36714. * @override
  36715. */
  36716. layoutInner: function (legendModel, itemAlign, maxSize) {
  36717. var contentGroup = this.getContentGroup();
  36718. var containerGroup = this._containerGroup;
  36719. var controllerGroup = this._controllerGroup;
  36720. var orientIdx = legendModel.getOrient().index;
  36721. var wh = WH[orientIdx];
  36722. var hw = WH[1 - orientIdx];
  36723. var yx = XY[1 - orientIdx];
  36724. // Place items in contentGroup.
  36725. box(
  36726. legendModel.get('orient'),
  36727. contentGroup,
  36728. legendModel.get('itemGap'),
  36729. !orientIdx ? null : maxSize.width,
  36730. orientIdx ? null : maxSize.height
  36731. );
  36732. box(
  36733. // Buttons in controller are layout always horizontally.
  36734. 'horizontal',
  36735. controllerGroup,
  36736. legendModel.get('pageButtonItemGap', true)
  36737. );
  36738. var contentRect = contentGroup.getBoundingRect();
  36739. var controllerRect = controllerGroup.getBoundingRect();
  36740. var showController = this._showController = contentRect[wh] > maxSize[wh];
  36741. var contentPos = [-contentRect.x, -contentRect.y];
  36742. // Remain contentPos when scroll animation perfroming.
  36743. contentPos[orientIdx] = contentGroup.position[orientIdx];
  36744. // Layout container group based on 0.
  36745. var containerPos = [0, 0];
  36746. var controllerPos = [-controllerRect.x, -controllerRect.y];
  36747. var pageButtonGap = retrieve2(
  36748. legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)
  36749. );
  36750. // Place containerGroup and controllerGroup and contentGroup.
  36751. if (showController) {
  36752. var pageButtonPosition = legendModel.get('pageButtonPosition', true);
  36753. // controller is on the right / bottom.
  36754. if (pageButtonPosition === 'end') {
  36755. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  36756. }
  36757. // controller is on the left / top.
  36758. else {
  36759. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  36760. }
  36761. }
  36762. // Always align controller to content as 'middle'.
  36763. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  36764. contentGroup.attr('position', contentPos);
  36765. containerGroup.attr('position', containerPos);
  36766. controllerGroup.attr('position', controllerPos);
  36767. // Calculate `mainRect` and set `clipPath`.
  36768. // mainRect should not be calculated by `this.group.getBoundingRect()`
  36769. // for sake of the overflow.
  36770. var mainRect = this.group.getBoundingRect();
  36771. var mainRect = {x: 0, y: 0};
  36772. // Consider content may be overflow (should be clipped).
  36773. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  36774. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]);
  36775. // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  36776. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  36777. containerGroup.__rectSize = maxSize[wh];
  36778. if (showController) {
  36779. var clipShape = {x: 0, y: 0};
  36780. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  36781. clipShape[hw] = mainRect[hw];
  36782. containerGroup.setClipPath(new Rect({shape: clipShape}));
  36783. // Consider content may be larger than container, container rect
  36784. // can not be obtained from `containerGroup.getBoundingRect()`.
  36785. containerGroup.__rectSize = clipShape[wh];
  36786. }
  36787. else {
  36788. // Do not remove or ignore controller. Keep them set as place holders.
  36789. controllerGroup.eachChild(function (child) {
  36790. child.attr({invisible: true, silent: true});
  36791. });
  36792. }
  36793. // Content translate animation.
  36794. var pageInfo = this._getPageInfo(legendModel);
  36795. pageInfo.pageIndex != null && updateProps(
  36796. contentGroup,
  36797. {position: pageInfo.contentPosition},
  36798. // When switch from "show controller" to "not show controller", view should be
  36799. // updated immediately without animation, otherwise causes weird efffect.
  36800. showController ? legendModel : false
  36801. );
  36802. this._updatePageInfoView(legendModel, pageInfo);
  36803. return mainRect;
  36804. },
  36805. _pageGo: function (to, legendModel, api) {
  36806. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  36807. scrollDataIndex != null && api.dispatchAction({
  36808. type: 'legendScroll',
  36809. scrollDataIndex: scrollDataIndex,
  36810. legendId: legendModel.id
  36811. });
  36812. },
  36813. _updatePageInfoView: function (legendModel, pageInfo) {
  36814. var controllerGroup = this._controllerGroup;
  36815. each$1(['pagePrev', 'pageNext'], function (name) {
  36816. var canJump = pageInfo[name + 'DataIndex'] != null;
  36817. var icon = controllerGroup.childOfName(name);
  36818. if (icon) {
  36819. icon.setStyle(
  36820. 'fill',
  36821. canJump
  36822. ? legendModel.get('pageIconColor', true)
  36823. : legendModel.get('pageIconInactiveColor', true)
  36824. );
  36825. icon.cursor = canJump ? 'pointer' : 'default';
  36826. }
  36827. });
  36828. var pageText = controllerGroup.childOfName('pageText');
  36829. var pageFormatter = legendModel.get('pageFormatter');
  36830. var pageIndex = pageInfo.pageIndex;
  36831. var current = pageIndex != null ? pageIndex + 1 : 0;
  36832. var total = pageInfo.pageCount;
  36833. pageText && pageFormatter && pageText.setStyle(
  36834. 'text',
  36835. isString(pageFormatter)
  36836. ? pageFormatter.replace('{current}', current).replace('{total}', total)
  36837. : pageFormatter({current: current, total: total})
  36838. );
  36839. },
  36840. /**
  36841. * @param {module:echarts/model/Model} legendModel
  36842. * @return {Object} {
  36843. * contentPosition: Array.<number>, null when data item not found.
  36844. * pageIndex: number, null when data item not found.
  36845. * pageCount: number, always be a number, can be 0.
  36846. * pagePrevDataIndex: number, null when no next page.
  36847. * pageNextDataIndex: number, null when no previous page.
  36848. * }
  36849. */
  36850. _getPageInfo: function (legendModel) {
  36851. // Align left or top by the current dataIndex.
  36852. var currDataIndex = legendModel.get('scrollDataIndex', true);
  36853. var contentGroup = this.getContentGroup();
  36854. var contentRect = contentGroup.getBoundingRect();
  36855. var containerRectSize = this._containerGroup.__rectSize;
  36856. var orientIdx = legendModel.getOrient().index;
  36857. var wh = WH[orientIdx];
  36858. var hw = WH[1 - orientIdx];
  36859. var xy = XY[orientIdx];
  36860. var contentPos = contentGroup.position.slice();
  36861. var pageIndex;
  36862. var pagePrevDataIndex;
  36863. var pageNextDataIndex;
  36864. var targetItemGroup;
  36865. if (this._showController) {
  36866. contentGroup.eachChild(function (child) {
  36867. if (child.__legendDataIndex === currDataIndex) {
  36868. targetItemGroup = child;
  36869. }
  36870. });
  36871. }
  36872. else {
  36873. targetItemGroup = contentGroup.childAt(0);
  36874. }
  36875. var pageCount = containerRectSize ? Math.ceil(contentRect[wh] / containerRectSize) : 0;
  36876. if (targetItemGroup) {
  36877. var itemRect = targetItemGroup.getBoundingRect();
  36878. var itemLoc = targetItemGroup.position[orientIdx] + itemRect[xy];
  36879. contentPos[orientIdx] = -itemLoc - contentRect[xy];
  36880. pageIndex = Math.floor(
  36881. pageCount * (itemLoc + itemRect[xy] + containerRectSize / 2) / contentRect[wh]
  36882. );
  36883. pageIndex = (contentRect[wh] && pageCount)
  36884. ? Math.max(0, Math.min(pageCount - 1, pageIndex))
  36885. : -1;
  36886. var winRect = {x: 0, y: 0};
  36887. winRect[wh] = containerRectSize;
  36888. winRect[hw] = contentRect[hw];
  36889. winRect[xy] = -contentPos[orientIdx] - contentRect[xy];
  36890. var startIdx;
  36891. var children = contentGroup.children();
  36892. contentGroup.eachChild(function (child, index) {
  36893. var itemRect = getItemRect(child);
  36894. if (itemRect.intersect(winRect)) {
  36895. startIdx == null && (startIdx = index);
  36896. // It is user-friendly that the last item shown in the
  36897. // current window is shown at the begining of next window.
  36898. pageNextDataIndex = child.__legendDataIndex;
  36899. }
  36900. // If the last item is shown entirely, no next page.
  36901. if (index === children.length - 1
  36902. && itemRect[xy] + itemRect[wh] <= winRect[xy] + winRect[wh]
  36903. ) {
  36904. pageNextDataIndex = null;
  36905. }
  36906. });
  36907. // Always align based on the left/top most item, so the left/top most
  36908. // item in the previous window is needed to be found here.
  36909. if (startIdx != null) {
  36910. var startItem = children[startIdx];
  36911. var startRect = getItemRect(startItem);
  36912. winRect[xy] = startRect[xy] + startRect[wh] - winRect[wh];
  36913. // If the first item is shown entirely, no previous page.
  36914. if (startIdx <= 0 && startRect[xy] >= winRect[xy]) {
  36915. pagePrevDataIndex = null;
  36916. }
  36917. else {
  36918. while (startIdx > 0 && getItemRect(children[startIdx - 1]).intersect(winRect)) {
  36919. startIdx--;
  36920. }
  36921. pagePrevDataIndex = children[startIdx].__legendDataIndex;
  36922. }
  36923. }
  36924. }
  36925. return {
  36926. contentPosition: contentPos,
  36927. pageIndex: pageIndex,
  36928. pageCount: pageCount,
  36929. pagePrevDataIndex: pagePrevDataIndex,
  36930. pageNextDataIndex: pageNextDataIndex
  36931. };
  36932. function getItemRect(el) {
  36933. var itemRect = el.getBoundingRect().clone();
  36934. itemRect[xy] += el.position[orientIdx];
  36935. return itemRect;
  36936. }
  36937. }
  36938. });
  36939. /**
  36940. * @event legendScroll
  36941. * @type {Object}
  36942. * @property {string} type 'legendScroll'
  36943. * @property {string} scrollDataIndex
  36944. */
  36945. registerAction(
  36946. 'legendScroll', 'legendscroll',
  36947. function (payload, ecModel) {
  36948. var scrollDataIndex = payload.scrollDataIndex;
  36949. scrollDataIndex != null && ecModel.eachComponent(
  36950. {mainType: 'legend', subType: 'scroll', query: payload},
  36951. function (legendModel) {
  36952. legendModel.setScrollDataIndex(scrollDataIndex);
  36953. }
  36954. );
  36955. }
  36956. );
  36957. /**
  36958. * Legend component entry file8
  36959. */
  36960. // Model
  36961. extendComponentModel({
  36962. type: 'title',
  36963. layoutMode: {type: 'box', ignoreSize: true},
  36964. defaultOption: {
  36965. // 一级层叠
  36966. zlevel: 0,
  36967. // 二级层叠
  36968. z: 6,
  36969. show: true,
  36970. text: '',
  36971. // 超链接跳转
  36972. // link: null,
  36973. // 仅支持self | blank
  36974. target: 'blank',
  36975. subtext: '',
  36976. // 超链接跳转
  36977. // sublink: null,
  36978. // 仅支持self | blank
  36979. subtarget: 'blank',
  36980. // 'center' ¦ 'left' ¦ 'right'
  36981. // ¦ {number}(x坐标,单位px)
  36982. left: 0,
  36983. // 'top' ¦ 'bottom' ¦ 'center'
  36984. // ¦ {number}(y坐标,单位px)
  36985. top: 0,
  36986. // 水平对齐
  36987. // 'auto' | 'left' | 'right' | 'center'
  36988. // 默认根据 left 的位置判断是左对齐还是右对齐
  36989. // textAlign: null
  36990. //
  36991. // 垂直对齐
  36992. // 'auto' | 'top' | 'bottom' | 'middle'
  36993. // 默认根据 top 位置判断是上对齐还是下对齐
  36994. // textBaseline: null
  36995. backgroundColor: 'rgba(0,0,0,0)',
  36996. // 标题边框颜色
  36997. borderColor: '#ccc',
  36998. // 标题边框线宽,单位px,默认为0(无边框)
  36999. borderWidth: 0,
  37000. // 标题内边距,单位px,默认各方向内边距为5,
  37001. // 接受数组分别设定上右下左边距,同css
  37002. padding: 5,
  37003. // 主副标题纵向间隔,单位px,默认为10,
  37004. itemGap: 10,
  37005. textStyle: {
  37006. fontSize: 18,
  37007. fontWeight: 'bolder',
  37008. color: '#333'
  37009. },
  37010. subtextStyle: {
  37011. color: '#aaa'
  37012. }
  37013. }
  37014. });
  37015. // View
  37016. extendComponentView({
  37017. type: 'title',
  37018. render: function (titleModel, ecModel, api) {
  37019. this.group.removeAll();
  37020. if (!titleModel.get('show')) {
  37021. return;
  37022. }
  37023. var group = this.group;
  37024. var textStyleModel = titleModel.getModel('textStyle');
  37025. var subtextStyleModel = titleModel.getModel('subtextStyle');
  37026. var textAlign = titleModel.get('textAlign');
  37027. var textBaseline = titleModel.get('textBaseline');
  37028. var textEl = new Text({
  37029. style: setTextStyle({}, textStyleModel, {
  37030. text: titleModel.get('text'),
  37031. textFill: textStyleModel.getTextColor()
  37032. }, {disableBox: true}),
  37033. z2: 10
  37034. });
  37035. var textRect = textEl.getBoundingRect();
  37036. var subText = titleModel.get('subtext');
  37037. var subTextEl = new Text({
  37038. style: setTextStyle({}, subtextStyleModel, {
  37039. text: subText,
  37040. textFill: subtextStyleModel.getTextColor(),
  37041. y: textRect.height + titleModel.get('itemGap'),
  37042. textVerticalAlign: 'top'
  37043. }, {disableBox: true}),
  37044. z2: 10
  37045. });
  37046. var link = titleModel.get('link');
  37047. var sublink = titleModel.get('sublink');
  37048. textEl.silent = !link;
  37049. subTextEl.silent = !sublink;
  37050. if (link) {
  37051. textEl.on('click', function () {
  37052. window.open(link, '_' + titleModel.get('target'));
  37053. });
  37054. }
  37055. if (sublink) {
  37056. subTextEl.on('click', function () {
  37057. window.open(sublink, '_' + titleModel.get('subtarget'));
  37058. });
  37059. }
  37060. group.add(textEl);
  37061. subText && group.add(subTextEl);
  37062. // If no subText, but add subTextEl, there will be an empty line.
  37063. var groupRect = group.getBoundingRect();
  37064. var layoutOption = titleModel.getBoxLayoutParams();
  37065. layoutOption.width = groupRect.width;
  37066. layoutOption.height = groupRect.height;
  37067. var layoutRect = getLayoutRect(
  37068. layoutOption, {
  37069. width: api.getWidth(),
  37070. height: api.getHeight()
  37071. }, titleModel.get('padding')
  37072. );
  37073. // Adjust text align based on position
  37074. if (!textAlign) {
  37075. // Align left if title is on the left. center and right is same
  37076. textAlign = titleModel.get('left') || titleModel.get('right');
  37077. if (textAlign === 'middle') {
  37078. textAlign = 'center';
  37079. }
  37080. // Adjust layout by text align
  37081. if (textAlign === 'right') {
  37082. layoutRect.x += layoutRect.width;
  37083. }
  37084. else if (textAlign === 'center') {
  37085. layoutRect.x += layoutRect.width / 2;
  37086. }
  37087. }
  37088. if (!textBaseline) {
  37089. textBaseline = titleModel.get('top') || titleModel.get('bottom');
  37090. if (textBaseline === 'center') {
  37091. textBaseline = 'middle';
  37092. }
  37093. if (textBaseline === 'bottom') {
  37094. layoutRect.y += layoutRect.height;
  37095. }
  37096. else if (textBaseline === 'middle') {
  37097. layoutRect.y += layoutRect.height / 2;
  37098. }
  37099. textBaseline = textBaseline || 'top';
  37100. }
  37101. group.attr('position', [layoutRect.x, layoutRect.y]);
  37102. var alignStyle = {
  37103. textAlign: textAlign,
  37104. textVerticalAlign: textBaseline
  37105. };
  37106. textEl.setStyle(alignStyle);
  37107. subTextEl.setStyle(alignStyle);
  37108. // Render background
  37109. // Get groupRect again because textAlign has been changed
  37110. groupRect = group.getBoundingRect();
  37111. var padding = layoutRect.margin;
  37112. var style = titleModel.getItemStyle(['color', 'opacity']);
  37113. style.fill = titleModel.get('backgroundColor');
  37114. var rect = new Rect({
  37115. shape: {
  37116. x: groupRect.x - padding[3],
  37117. y: groupRect.y - padding[0],
  37118. width: groupRect.width + padding[1] + padding[3],
  37119. height: groupRect.height + padding[0] + padding[2],
  37120. r: titleModel.get('borderRadius')
  37121. },
  37122. style: style,
  37123. silent: true
  37124. });
  37125. subPixelOptimizeRect(rect);
  37126. group.add(rect);
  37127. }
  37128. });
  37129. var addCommas$1 = addCommas;
  37130. var encodeHTML$1 = encodeHTML;
  37131. function fillLabel(opt) {
  37132. defaultEmphasis(opt, 'label', ['show']);
  37133. }
  37134. var MarkerModel = extendComponentModel({
  37135. type: 'marker',
  37136. dependencies: ['series', 'grid', 'polar', 'geo'],
  37137. /**
  37138. * @overrite
  37139. */
  37140. init: function (option, parentModel, ecModel, extraOpt) {
  37141. if (__DEV__) {
  37142. if (this.type === 'marker') {
  37143. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  37144. }
  37145. }
  37146. this.mergeDefaultAndTheme(option, ecModel);
  37147. this.mergeOption(option, ecModel, extraOpt.createdBySelf, true);
  37148. },
  37149. /**
  37150. * @return {boolean}
  37151. */
  37152. isAnimationEnabled: function () {
  37153. if (env$1.node) {
  37154. return false;
  37155. }
  37156. var hostSeries = this.__hostSeries;
  37157. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  37158. },
  37159. mergeOption: function (newOpt, ecModel, createdBySelf, isInit) {
  37160. var MarkerModel = this.constructor;
  37161. var modelPropName = this.mainType + 'Model';
  37162. if (!createdBySelf) {
  37163. ecModel.eachSeries(function (seriesModel) {
  37164. var markerOpt = seriesModel.get(this.mainType);
  37165. var markerModel = seriesModel[modelPropName];
  37166. if (!markerOpt || !markerOpt.data) {
  37167. seriesModel[modelPropName] = null;
  37168. return;
  37169. }
  37170. if (!markerModel) {
  37171. if (isInit) {
  37172. // Default label emphasis `position` and `show`
  37173. fillLabel(markerOpt);
  37174. }
  37175. each$1(markerOpt.data, function (item) {
  37176. // FIXME Overwrite fillLabel method ?
  37177. if (item instanceof Array) {
  37178. fillLabel(item[0]);
  37179. fillLabel(item[1]);
  37180. }
  37181. else {
  37182. fillLabel(item);
  37183. }
  37184. });
  37185. markerModel = new MarkerModel(
  37186. markerOpt, this, ecModel
  37187. );
  37188. extend(markerModel, {
  37189. mainType: this.mainType,
  37190. // Use the same series index and name
  37191. seriesIndex: seriesModel.seriesIndex,
  37192. name: seriesModel.name,
  37193. createdBySelf: true
  37194. });
  37195. markerModel.__hostSeries = seriesModel;
  37196. }
  37197. else {
  37198. markerModel.mergeOption(markerOpt, ecModel, true);
  37199. }
  37200. seriesModel[modelPropName] = markerModel;
  37201. }, this);
  37202. }
  37203. },
  37204. formatTooltip: function (dataIndex) {
  37205. var data = this.getData();
  37206. var value = this.getRawValue(dataIndex);
  37207. var formattedValue = isArray(value)
  37208. ? map(value, addCommas$1).join(', ') : addCommas$1(value);
  37209. var name = data.getName(dataIndex);
  37210. var html = encodeHTML$1(this.name);
  37211. if (value != null || name) {
  37212. html += '<br />';
  37213. }
  37214. if (name) {
  37215. html += encodeHTML$1(name);
  37216. if (value != null) {
  37217. html += ' : ';
  37218. }
  37219. }
  37220. if (value != null) {
  37221. html += encodeHTML$1(formattedValue);
  37222. }
  37223. return html;
  37224. },
  37225. getData: function () {
  37226. return this._data;
  37227. },
  37228. setData: function (data) {
  37229. this._data = data;
  37230. }
  37231. });
  37232. mixin(MarkerModel, dataFormatMixin);
  37233. MarkerModel.extend({
  37234. type: 'markPoint',
  37235. defaultOption: {
  37236. zlevel: 0,
  37237. z: 5,
  37238. symbol: 'pin',
  37239. symbolSize: 50,
  37240. //symbolRotate: 0,
  37241. //symbolOffset: [0, 0]
  37242. tooltip: {
  37243. trigger: 'item'
  37244. },
  37245. label: {
  37246. show: true,
  37247. position: 'inside'
  37248. },
  37249. itemStyle: {
  37250. borderWidth: 2
  37251. },
  37252. emphasis: {
  37253. label: {
  37254. show: true
  37255. }
  37256. }
  37257. }
  37258. });
  37259. var indexOf$1 = indexOf;
  37260. function hasXOrY(item) {
  37261. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  37262. }
  37263. function hasXAndY(item) {
  37264. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  37265. }
  37266. // Make it simple, do not visit all stacked value to count precision.
  37267. // function getPrecision(data, valueAxisDim, dataIndex) {
  37268. // var precision = -1;
  37269. // var stackedDim = data.mapDimension(valueAxisDim);
  37270. // do {
  37271. // precision = Math.max(
  37272. // numberUtil.getPrecision(data.get(stackedDim, dataIndex)),
  37273. // precision
  37274. // );
  37275. // var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  37276. // if (stackedOnSeries) {
  37277. // var byValue = data.get(data.getCalculationInfo('stackedByDimension'), dataIndex);
  37278. // data = stackedOnSeries.getData();
  37279. // dataIndex = data.indexOf(data.getCalculationInfo('stackedByDimension'), byValue);
  37280. // stackedDim = data.getCalculationInfo('stackedDimension');
  37281. // }
  37282. // else {
  37283. // data = null;
  37284. // }
  37285. // } while (data);
  37286. // return precision;
  37287. // }
  37288. function markerTypeCalculatorWithExtent(
  37289. mlType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex
  37290. ) {
  37291. var coordArr = [];
  37292. var stacked = isDimensionStacked(data, targetDataDim, otherDataDim);
  37293. var calcDataDim = stacked
  37294. ? data.getCalculationInfo('stackResultDimension')
  37295. : targetDataDim;
  37296. var value = numCalculate(data, calcDataDim, mlType);
  37297. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  37298. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  37299. coordArr[targetCoordIndex] = data.get(targetDataDim, dataIndex);
  37300. // Make it simple, do not visit all stacked value to count precision.
  37301. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  37302. precision = Math.min(precision, 20);
  37303. if (precision >= 0) {
  37304. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  37305. }
  37306. return coordArr;
  37307. }
  37308. var curry$4 = curry;
  37309. // TODO Specified percent
  37310. var markerTypeCalculator = {
  37311. /**
  37312. * @method
  37313. * @param {module:echarts/data/List} data
  37314. * @param {string} baseAxisDim
  37315. * @param {string} valueAxisDim
  37316. */
  37317. min: curry$4(markerTypeCalculatorWithExtent, 'min'),
  37318. /**
  37319. * @method
  37320. * @param {module:echarts/data/List} data
  37321. * @param {string} baseAxisDim
  37322. * @param {string} valueAxisDim
  37323. */
  37324. max: curry$4(markerTypeCalculatorWithExtent, 'max'),
  37325. /**
  37326. * @method
  37327. * @param {module:echarts/data/List} data
  37328. * @param {string} baseAxisDim
  37329. * @param {string} valueAxisDim
  37330. */
  37331. average: curry$4(markerTypeCalculatorWithExtent, 'average')
  37332. };
  37333. /**
  37334. * Transform markPoint data item to format used in List by do the following
  37335. * 1. Calculate statistic like `max`, `min`, `average`
  37336. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  37337. * @param {module:echarts/model/Series} seriesModel
  37338. * @param {module:echarts/coord/*} [coordSys]
  37339. * @param {Object} item
  37340. * @return {Object}
  37341. */
  37342. function dataTransform(seriesModel, item) {
  37343. var data = seriesModel.getData();
  37344. var coordSys = seriesModel.coordinateSystem;
  37345. // 1. If not specify the position with pixel directly
  37346. // 2. If `coord` is not a data array. Which uses `xAxis`,
  37347. // `yAxis` to specify the coord on each dimension
  37348. // parseFloat first because item.x and item.y can be percent string like '20%'
  37349. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  37350. var dims = coordSys.dimensions;
  37351. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  37352. // Clone the option
  37353. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  37354. item = clone(item);
  37355. if (item.type
  37356. && markerTypeCalculator[item.type]
  37357. && axisInfo.baseAxis && axisInfo.valueAxis
  37358. ) {
  37359. var otherCoordIndex = indexOf$1(dims, axisInfo.baseAxis.dim);
  37360. var targetCoordIndex = indexOf$1(dims, axisInfo.valueAxis.dim);
  37361. item.coord = markerTypeCalculator[item.type](
  37362. data, axisInfo.baseDataDim, axisInfo.valueDataDim,
  37363. otherCoordIndex, targetCoordIndex
  37364. );
  37365. // Force to use the value of calculated value.
  37366. item.value = item.coord[targetCoordIndex];
  37367. }
  37368. else {
  37369. // FIXME Only has one of xAxis and yAxis.
  37370. var coord = [
  37371. item.xAxis != null ? item.xAxis : item.radiusAxis,
  37372. item.yAxis != null ? item.yAxis : item.angleAxis
  37373. ];
  37374. // Each coord support max, min, average
  37375. for (var i = 0; i < 2; i++) {
  37376. if (markerTypeCalculator[coord[i]]) {
  37377. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  37378. }
  37379. }
  37380. item.coord = coord;
  37381. }
  37382. }
  37383. return item;
  37384. }
  37385. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  37386. var ret = {};
  37387. if (item.valueIndex != null || item.valueDim != null) {
  37388. ret.valueDataDim = item.valueIndex != null
  37389. ? data.getDimension(item.valueIndex) : item.valueDim;
  37390. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  37391. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  37392. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  37393. }
  37394. else {
  37395. ret.baseAxis = seriesModel.getBaseAxis();
  37396. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  37397. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  37398. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  37399. }
  37400. return ret;
  37401. }
  37402. function dataDimToCoordDim(seriesModel, dataDim) {
  37403. var data = seriesModel.getData();
  37404. var dimensions = data.dimensions;
  37405. dataDim = data.getDimension(dataDim);
  37406. for (var i = 0; i < dimensions.length; i++) {
  37407. var dimItem = data.getDimensionInfo(dimensions[i]);
  37408. if (dimItem.name === dataDim) {
  37409. return dimItem.coordDim;
  37410. }
  37411. }
  37412. }
  37413. /**
  37414. * Filter data which is out of coordinateSystem range
  37415. * [dataFilter description]
  37416. * @param {module:echarts/coord/*} [coordSys]
  37417. * @param {Object} item
  37418. * @return {boolean}
  37419. */
  37420. function dataFilter$1(coordSys, item) {
  37421. // Alwalys return true if there is no coordSys
  37422. return (coordSys && coordSys.containData && item.coord && !hasXOrY(item))
  37423. ? coordSys.containData(item.coord) : true;
  37424. }
  37425. function dimValueGetter(item, dimName, dataIndex, dimIndex) {
  37426. // x, y, radius, angle
  37427. if (dimIndex < 2) {
  37428. return item.coord && item.coord[dimIndex];
  37429. }
  37430. return item.value;
  37431. }
  37432. function numCalculate(data, valueDataDim, type) {
  37433. if (type === 'average') {
  37434. var sum = 0;
  37435. var count = 0;
  37436. data.each(valueDataDim, function (val, idx) {
  37437. if (!isNaN(val)) {
  37438. sum += val;
  37439. count++;
  37440. }
  37441. });
  37442. return sum / count;
  37443. }
  37444. else {
  37445. return data.getDataExtent(valueDataDim, true)[type === 'max' ? 1 : 0];
  37446. }
  37447. }
  37448. var MarkerView = extendComponentView({
  37449. type: 'marker',
  37450. init: function () {
  37451. /**
  37452. * Markline grouped by series
  37453. * @private
  37454. * @type {module:zrender/core/util.HashMap}
  37455. */
  37456. this.markerGroupMap = createHashMap();
  37457. },
  37458. render: function (markerModel, ecModel, api) {
  37459. var markerGroupMap = this.markerGroupMap;
  37460. markerGroupMap.each(function (item) {
  37461. item.__keep = false;
  37462. });
  37463. var markerModelKey = this.type + 'Model';
  37464. ecModel.eachSeries(function (seriesModel) {
  37465. var markerModel = seriesModel[markerModelKey];
  37466. markerModel && this.renderSeries(seriesModel, markerModel, ecModel, api);
  37467. }, this);
  37468. markerGroupMap.each(function (item) {
  37469. !item.__keep && this.group.remove(item.group);
  37470. }, this);
  37471. },
  37472. renderSeries: function () {}
  37473. });
  37474. function updateMarkerLayout(mpData, seriesModel, api) {
  37475. var coordSys = seriesModel.coordinateSystem;
  37476. mpData.each(function (idx) {
  37477. var itemModel = mpData.getItemModel(idx);
  37478. var point;
  37479. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  37480. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  37481. if (!isNaN(xPx) && !isNaN(yPx)) {
  37482. point = [xPx, yPx];
  37483. }
  37484. // Chart like bar may have there own marker positioning logic
  37485. else if (seriesModel.getMarkerPosition) {
  37486. // Use the getMarkerPoisition
  37487. point = seriesModel.getMarkerPosition(
  37488. mpData.getValues(mpData.dimensions, idx)
  37489. );
  37490. }
  37491. else if (coordSys) {
  37492. var x = mpData.get(coordSys.dimensions[0], idx);
  37493. var y = mpData.get(coordSys.dimensions[1], idx);
  37494. point = coordSys.dataToPoint([x, y]);
  37495. }
  37496. // Use x, y if has any
  37497. if (!isNaN(xPx)) {
  37498. point[0] = xPx;
  37499. }
  37500. if (!isNaN(yPx)) {
  37501. point[1] = yPx;
  37502. }
  37503. mpData.setItemLayout(idx, point);
  37504. });
  37505. }
  37506. MarkerView.extend({
  37507. type: 'markPoint',
  37508. // updateLayout: function (markPointModel, ecModel, api) {
  37509. // ecModel.eachSeries(function (seriesModel) {
  37510. // var mpModel = seriesModel.markPointModel;
  37511. // if (mpModel) {
  37512. // updateMarkerLayout(mpModel.getData(), seriesModel, api);
  37513. // this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  37514. // }
  37515. // }, this);
  37516. // },
  37517. updateTransform: function (markPointModel, ecModel, api) {
  37518. ecModel.eachSeries(function (seriesModel) {
  37519. var mpModel = seriesModel.markPointModel;
  37520. if (mpModel) {
  37521. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  37522. this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  37523. }
  37524. }, this);
  37525. },
  37526. renderSeries: function (seriesModel, mpModel, ecModel, api) {
  37527. var coordSys = seriesModel.coordinateSystem;
  37528. var seriesId = seriesModel.id;
  37529. var seriesData = seriesModel.getData();
  37530. var symbolDrawMap = this.markerGroupMap;
  37531. var symbolDraw = symbolDrawMap.get(seriesId)
  37532. || symbolDrawMap.set(seriesId, new SymbolDraw());
  37533. var mpData = createList$1(coordSys, seriesModel, mpModel);
  37534. // FIXME
  37535. mpModel.setData(mpData);
  37536. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  37537. mpData.each(function (idx) {
  37538. var itemModel = mpData.getItemModel(idx);
  37539. var symbolSize = itemModel.getShallow('symbolSize');
  37540. if (typeof symbolSize === 'function') {
  37541. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  37542. symbolSize = symbolSize(
  37543. mpModel.getRawValue(idx), mpModel.getDataParams(idx)
  37544. );
  37545. }
  37546. mpData.setItemVisual(idx, {
  37547. symbolSize: symbolSize,
  37548. color: itemModel.get('itemStyle.color')
  37549. || seriesData.getVisual('color'),
  37550. symbol: itemModel.getShallow('symbol')
  37551. });
  37552. });
  37553. // TODO Text are wrong
  37554. symbolDraw.updateData(mpData);
  37555. this.group.add(symbolDraw.group);
  37556. // Set host model for tooltip
  37557. // FIXME
  37558. mpData.eachItemGraphicEl(function (el) {
  37559. el.traverse(function (child) {
  37560. child.dataModel = mpModel;
  37561. });
  37562. });
  37563. symbolDraw.__keep = true;
  37564. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  37565. }
  37566. });
  37567. /**
  37568. * @inner
  37569. * @param {module:echarts/coord/*} [coordSys]
  37570. * @param {module:echarts/model/Series} seriesModel
  37571. * @param {module:echarts/model/Model} mpModel
  37572. */
  37573. function createList$1(coordSys, seriesModel, mpModel) {
  37574. var coordDimsInfos;
  37575. if (coordSys) {
  37576. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  37577. var info = seriesModel.getData().getDimensionInfo(
  37578. seriesModel.getData().mapDimension(coordDim)
  37579. ) || {};
  37580. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  37581. return defaults({name: coordDim}, info);
  37582. });
  37583. }
  37584. else {
  37585. coordDimsInfos =[{
  37586. name: 'value',
  37587. type: 'float'
  37588. }];
  37589. }
  37590. var mpData = new List(coordDimsInfos, mpModel);
  37591. var dataOpt = map(mpModel.get('data'), curry(
  37592. dataTransform, seriesModel
  37593. ));
  37594. if (coordSys) {
  37595. dataOpt = filter(
  37596. dataOpt, curry(dataFilter$1, coordSys)
  37597. );
  37598. }
  37599. mpData.initData(dataOpt, null,
  37600. coordSys ? dimValueGetter : function (item) {
  37601. return item.value;
  37602. }
  37603. );
  37604. return mpData;
  37605. }
  37606. // HINT Markpoint can't be used too much
  37607. registerPreprocessor(function (opt) {
  37608. // Make sure markPoint component is enabled
  37609. opt.markPoint = opt.markPoint || {};
  37610. });
  37611. MarkerModel.extend({
  37612. type: 'markLine',
  37613. defaultOption: {
  37614. zlevel: 0,
  37615. z: 5,
  37616. symbol: ['circle', 'arrow'],
  37617. symbolSize: [8, 16],
  37618. //symbolRotate: 0,
  37619. precision: 2,
  37620. tooltip: {
  37621. trigger: 'item'
  37622. },
  37623. label: {
  37624. show: true,
  37625. position: 'end'
  37626. },
  37627. lineStyle: {
  37628. type: 'dashed'
  37629. },
  37630. emphasis: {
  37631. label: {
  37632. show: true
  37633. },
  37634. lineStyle: {
  37635. width: 3
  37636. }
  37637. },
  37638. animationEasing: 'linear'
  37639. }
  37640. });
  37641. /**
  37642. * Line path for bezier and straight line draw
  37643. */
  37644. var straightLineProto = Line.prototype;
  37645. var bezierCurveProto = BezierCurve.prototype;
  37646. function isLine(shape) {
  37647. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  37648. }
  37649. var LinePath = extendShape({
  37650. type: 'ec-line',
  37651. style: {
  37652. stroke: '#000',
  37653. fill: null
  37654. },
  37655. shape: {
  37656. x1: 0,
  37657. y1: 0,
  37658. x2: 0,
  37659. y2: 0,
  37660. percent: 1,
  37661. cpx1: null,
  37662. cpy1: null
  37663. },
  37664. buildPath: function (ctx, shape) {
  37665. (isLine(shape) ? straightLineProto : bezierCurveProto).buildPath(ctx, shape);
  37666. },
  37667. pointAt: function (t) {
  37668. return isLine(this.shape)
  37669. ? straightLineProto.pointAt.call(this, t)
  37670. : bezierCurveProto.pointAt.call(this, t);
  37671. },
  37672. tangentAt: function (t) {
  37673. var shape = this.shape;
  37674. var p = isLine(shape)
  37675. ? [shape.x2 - shape.x1, shape.y2 - shape.y1]
  37676. : bezierCurveProto.tangentAt.call(this, t);
  37677. return normalize(p, p);
  37678. }
  37679. });
  37680. /**
  37681. * @module echarts/chart/helper/Line
  37682. */
  37683. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  37684. function makeSymbolTypeKey(symbolCategory) {
  37685. return '_' + symbolCategory + 'Type';
  37686. }
  37687. /**
  37688. * @inner
  37689. */
  37690. function createSymbol$1(name, lineData, idx) {
  37691. var color = lineData.getItemVisual(idx, 'color');
  37692. var symbolType = lineData.getItemVisual(idx, name);
  37693. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  37694. if (!symbolType || symbolType === 'none') {
  37695. return;
  37696. }
  37697. if (!isArray(symbolSize)) {
  37698. symbolSize = [symbolSize, symbolSize];
  37699. }
  37700. var symbolPath = createSymbol(
  37701. symbolType, -symbolSize[0] / 2, -symbolSize[1] / 2,
  37702. symbolSize[0], symbolSize[1], color
  37703. );
  37704. symbolPath.name = name;
  37705. return symbolPath;
  37706. }
  37707. function createLine(points) {
  37708. var line = new LinePath({
  37709. name: 'line'
  37710. });
  37711. setLinePoints(line.shape, points);
  37712. return line;
  37713. }
  37714. function setLinePoints(targetShape, points) {
  37715. var p1 = points[0];
  37716. var p2 = points[1];
  37717. var cp1 = points[2];
  37718. targetShape.x1 = p1[0];
  37719. targetShape.y1 = p1[1];
  37720. targetShape.x2 = p2[0];
  37721. targetShape.y2 = p2[1];
  37722. targetShape.percent = 1;
  37723. if (cp1) {
  37724. targetShape.cpx1 = cp1[0];
  37725. targetShape.cpy1 = cp1[1];
  37726. }
  37727. else {
  37728. targetShape.cpx1 = NaN;
  37729. targetShape.cpy1 = NaN;
  37730. }
  37731. }
  37732. function updateSymbolAndLabelBeforeLineUpdate () {
  37733. var lineGroup = this;
  37734. var symbolFrom = lineGroup.childOfName('fromSymbol');
  37735. var symbolTo = lineGroup.childOfName('toSymbol');
  37736. var label = lineGroup.childOfName('label');
  37737. // Quick reject
  37738. if (!symbolFrom && !symbolTo && label.ignore) {
  37739. return;
  37740. }
  37741. var invScale = 1;
  37742. var parentNode = this.parent;
  37743. while (parentNode) {
  37744. if (parentNode.scale) {
  37745. invScale /= parentNode.scale[0];
  37746. }
  37747. parentNode = parentNode.parent;
  37748. }
  37749. var line = lineGroup.childOfName('line');
  37750. // If line not changed
  37751. // FIXME Parent scale changed
  37752. if (!this.__dirty && !line.__dirty) {
  37753. return;
  37754. }
  37755. var percent = line.shape.percent;
  37756. var fromPos = line.pointAt(0);
  37757. var toPos = line.pointAt(percent);
  37758. var d = sub([], toPos, fromPos);
  37759. normalize(d, d);
  37760. if (symbolFrom) {
  37761. symbolFrom.attr('position', fromPos);
  37762. var tangent = line.tangentAt(0);
  37763. symbolFrom.attr('rotation', Math.PI / 2 - Math.atan2(
  37764. tangent[1], tangent[0]
  37765. ));
  37766. symbolFrom.attr('scale', [invScale * percent, invScale * percent]);
  37767. }
  37768. if (symbolTo) {
  37769. symbolTo.attr('position', toPos);
  37770. var tangent = line.tangentAt(1);
  37771. symbolTo.attr('rotation', -Math.PI / 2 - Math.atan2(
  37772. tangent[1], tangent[0]
  37773. ));
  37774. symbolTo.attr('scale', [invScale * percent, invScale * percent]);
  37775. }
  37776. if (!label.ignore) {
  37777. label.attr('position', toPos);
  37778. var textPosition;
  37779. var textAlign;
  37780. var textVerticalAlign;
  37781. var distance$$1 = 5 * invScale;
  37782. // End
  37783. if (label.__position === 'end') {
  37784. textPosition = [d[0] * distance$$1 + toPos[0], d[1] * distance$$1 + toPos[1]];
  37785. textAlign = d[0] > 0.8 ? 'left' : (d[0] < -0.8 ? 'right' : 'center');
  37786. textVerticalAlign = d[1] > 0.8 ? 'top' : (d[1] < -0.8 ? 'bottom' : 'middle');
  37787. }
  37788. // Middle
  37789. else if (label.__position === 'middle') {
  37790. var halfPercent = percent / 2;
  37791. var tangent = line.tangentAt(halfPercent);
  37792. var n = [tangent[1], -tangent[0]];
  37793. var cp = line.pointAt(halfPercent);
  37794. if (n[1] > 0) {
  37795. n[0] = -n[0];
  37796. n[1] = -n[1];
  37797. }
  37798. textPosition = [cp[0] + n[0] * distance$$1, cp[1] + n[1] * distance$$1];
  37799. textAlign = 'center';
  37800. textVerticalAlign = 'bottom';
  37801. var rotation = -Math.atan2(tangent[1], tangent[0]);
  37802. if (toPos[0] < fromPos[0]) {
  37803. rotation = Math.PI + rotation;
  37804. }
  37805. label.attr('rotation', rotation);
  37806. }
  37807. // Start
  37808. else {
  37809. textPosition = [-d[0] * distance$$1 + fromPos[0], -d[1] * distance$$1 + fromPos[1]];
  37810. textAlign = d[0] > 0.8 ? 'right' : (d[0] < -0.8 ? 'left' : 'center');
  37811. textVerticalAlign = d[1] > 0.8 ? 'bottom' : (d[1] < -0.8 ? 'top' : 'middle');
  37812. }
  37813. label.attr({
  37814. style: {
  37815. // Use the user specified text align and baseline first
  37816. textVerticalAlign: label.__verticalAlign || textVerticalAlign,
  37817. textAlign: label.__textAlign || textAlign
  37818. },
  37819. position: textPosition,
  37820. scale: [invScale, invScale]
  37821. });
  37822. }
  37823. }
  37824. /**
  37825. * @constructor
  37826. * @extends {module:zrender/graphic/Group}
  37827. * @alias {module:echarts/chart/helper/Line}
  37828. */
  37829. function Line$1(lineData, idx, seriesScope) {
  37830. Group.call(this);
  37831. this._createLine(lineData, idx, seriesScope);
  37832. }
  37833. var lineProto = Line$1.prototype;
  37834. // Update symbol position and rotation
  37835. lineProto.beforeUpdate = updateSymbolAndLabelBeforeLineUpdate;
  37836. lineProto._createLine = function (lineData, idx, seriesScope) {
  37837. var seriesModel = lineData.hostModel;
  37838. var linePoints = lineData.getItemLayout(idx);
  37839. var line = createLine(linePoints);
  37840. line.shape.percent = 0;
  37841. initProps(line, {
  37842. shape: {
  37843. percent: 1
  37844. }
  37845. }, seriesModel, idx);
  37846. this.add(line);
  37847. var label = new Text({
  37848. name: 'label'
  37849. });
  37850. this.add(label);
  37851. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  37852. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  37853. // symbols must added after line to make sure
  37854. // it will be updated after line#update.
  37855. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  37856. this.add(symbol);
  37857. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  37858. }, this);
  37859. this._updateCommonStl(lineData, idx, seriesScope);
  37860. };
  37861. lineProto.updateData = function (lineData, idx, seriesScope) {
  37862. var seriesModel = lineData.hostModel;
  37863. var line = this.childOfName('line');
  37864. var linePoints = lineData.getItemLayout(idx);
  37865. var target = {
  37866. shape: {}
  37867. };
  37868. setLinePoints(target.shape, linePoints);
  37869. updateProps(line, target, seriesModel, idx);
  37870. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  37871. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  37872. var key = makeSymbolTypeKey(symbolCategory);
  37873. // Symbol changed
  37874. if (this[key] !== symbolType) {
  37875. this.remove(this.childOfName(symbolCategory));
  37876. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  37877. this.add(symbol);
  37878. }
  37879. this[key] = symbolType;
  37880. }, this);
  37881. this._updateCommonStl(lineData, idx, seriesScope);
  37882. };
  37883. lineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  37884. var seriesModel = lineData.hostModel;
  37885. var line = this.childOfName('line');
  37886. var lineStyle = seriesScope && seriesScope.lineStyle;
  37887. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  37888. var labelModel = seriesScope && seriesScope.labelModel;
  37889. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  37890. // Optimization for large dataset
  37891. if (!seriesScope || lineData.hasItemOption) {
  37892. var itemModel = lineData.getItemModel(idx);
  37893. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  37894. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  37895. labelModel = itemModel.getModel('label');
  37896. hoverLabelModel = itemModel.getModel('emphasis.label');
  37897. }
  37898. var visualColor = lineData.getItemVisual(idx, 'color');
  37899. var visualOpacity = retrieve3(
  37900. lineData.getItemVisual(idx, 'opacity'),
  37901. lineStyle.opacity,
  37902. 1
  37903. );
  37904. line.useStyle(defaults(
  37905. {
  37906. strokeNoScale: true,
  37907. fill: 'none',
  37908. stroke: visualColor,
  37909. opacity: visualOpacity
  37910. },
  37911. lineStyle
  37912. ));
  37913. line.hoverStyle = hoverLineStyle;
  37914. // Update symbol
  37915. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  37916. var symbol = this.childOfName(symbolCategory);
  37917. if (symbol) {
  37918. symbol.setColor(visualColor);
  37919. symbol.setStyle({
  37920. opacity: visualOpacity
  37921. });
  37922. }
  37923. }, this);
  37924. var showLabel = labelModel.getShallow('show');
  37925. var hoverShowLabel = hoverLabelModel.getShallow('show');
  37926. var label = this.childOfName('label');
  37927. var defaultLabelColor;
  37928. var normalText;
  37929. var emphasisText;
  37930. if (showLabel || hoverShowLabel) {
  37931. defaultLabelColor = visualColor || '#000';
  37932. normalText = seriesModel.getFormattedLabel(idx, 'normal', lineData.dataType);
  37933. if (normalText == null) {
  37934. var rawVal = seriesModel.getRawValue(idx);
  37935. normalText = rawVal == null
  37936. ? lineData.getName(idx)
  37937. : isFinite(rawVal)
  37938. ? round$1(rawVal)
  37939. : rawVal;
  37940. }
  37941. emphasisText = retrieve2(
  37942. seriesModel.getFormattedLabel(idx, 'emphasis', lineData.dataType),
  37943. normalText
  37944. );
  37945. }
  37946. // label.afterUpdate = lineAfterUpdate;
  37947. if (showLabel) {
  37948. var labelStyle = setTextStyle(label.style, labelModel, {
  37949. text: normalText
  37950. }, {
  37951. autoColor: defaultLabelColor
  37952. });
  37953. label.__textAlign = labelStyle.textAlign;
  37954. label.__verticalAlign = labelStyle.textVerticalAlign;
  37955. // 'start', 'middle', 'end'
  37956. label.__position = labelModel.get('position') || 'middle';
  37957. }
  37958. else {
  37959. label.setStyle('text', null);
  37960. }
  37961. if (hoverShowLabel) {
  37962. // Only these properties supported in this emphasis style here.
  37963. label.hoverStyle = {
  37964. text: emphasisText,
  37965. textFill: hoverLabelModel.getTextColor(true),
  37966. // For merging hover style to normal style, do not use
  37967. // `hoverLabelModel.getFont()` here.
  37968. fontStyle: hoverLabelModel.getShallow('fontStyle'),
  37969. fontWeight: hoverLabelModel.getShallow('fontWeight'),
  37970. fontSize: hoverLabelModel.getShallow('fontSize'),
  37971. fontFamily: hoverLabelModel.getShallow('fontFamily')
  37972. };
  37973. }
  37974. else {
  37975. label.hoverStyle = {
  37976. text: null
  37977. };
  37978. }
  37979. label.ignore = !showLabel && !hoverShowLabel;
  37980. setHoverStyle(this);
  37981. };
  37982. lineProto.highlight = function () {
  37983. this.trigger('emphasis');
  37984. };
  37985. lineProto.downplay = function () {
  37986. this.trigger('normal');
  37987. };
  37988. lineProto.updateLayout = function (lineData, idx) {
  37989. this.setLinePoints(lineData.getItemLayout(idx));
  37990. };
  37991. lineProto.setLinePoints = function (points) {
  37992. var linePath = this.childOfName('line');
  37993. setLinePoints(linePath.shape, points);
  37994. linePath.dirty();
  37995. };
  37996. inherits(Line$1, Group);
  37997. /**
  37998. * @module echarts/chart/helper/LineDraw
  37999. */
  38000. // import IncrementalDisplayable from 'zrender/src/graphic/IncrementalDisplayable';
  38001. /**
  38002. * @alias module:echarts/component/marker/LineDraw
  38003. * @constructor
  38004. */
  38005. function LineDraw(ctor) {
  38006. this._ctor = ctor || Line$1;
  38007. this.group = new Group();
  38008. }
  38009. var lineDrawProto = LineDraw.prototype;
  38010. lineDrawProto.isPersistent = function () {
  38011. return true;
  38012. };
  38013. /**
  38014. * @param {module:echarts/data/List} lineData
  38015. */
  38016. lineDrawProto.updateData = function (lineData) {
  38017. var lineDraw = this;
  38018. var group = lineDraw.group;
  38019. var oldLineData = lineDraw._lineData;
  38020. lineDraw._lineData = lineData;
  38021. // There is no oldLineData only when first rendering or switching from
  38022. // stream mode to normal mode, where previous elements should be removed.
  38023. if (!oldLineData) {
  38024. group.removeAll();
  38025. }
  38026. var seriesScope = makeSeriesScope$1(lineData);
  38027. lineData.diff(oldLineData)
  38028. .add(function (idx) {
  38029. doAdd(lineDraw, lineData, idx, seriesScope);
  38030. })
  38031. .update(function (newIdx, oldIdx) {
  38032. doUpdate(lineDraw, oldLineData, lineData, oldIdx, newIdx, seriesScope);
  38033. })
  38034. .remove(function (idx) {
  38035. group.remove(oldLineData.getItemGraphicEl(idx));
  38036. })
  38037. .execute();
  38038. };
  38039. function doAdd(lineDraw, lineData, idx, seriesScope) {
  38040. var itemLayout = lineData.getItemLayout(idx);
  38041. if (!lineNeedsDraw(itemLayout)) {
  38042. return;
  38043. }
  38044. var el = new lineDraw._ctor(lineData, idx, seriesScope);
  38045. lineData.setItemGraphicEl(idx, el);
  38046. lineDraw.group.add(el);
  38047. }
  38048. function doUpdate(lineDraw, oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  38049. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  38050. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  38051. lineDraw.group.remove(itemEl);
  38052. return;
  38053. }
  38054. if (!itemEl) {
  38055. itemEl = new lineDraw._ctor(newLineData, newIdx, seriesScope);
  38056. }
  38057. else {
  38058. itemEl.updateData(newLineData, newIdx, seriesScope);
  38059. }
  38060. newLineData.setItemGraphicEl(newIdx, itemEl);
  38061. lineDraw.group.add(itemEl);
  38062. }
  38063. lineDrawProto.updateLayout = function () {
  38064. var lineData = this._lineData;
  38065. lineData.eachItemGraphicEl(function (el, idx) {
  38066. el.updateLayout(lineData, idx);
  38067. }, this);
  38068. };
  38069. lineDrawProto.incrementalPrepareUpdate = function (lineData) {
  38070. this._seriesScope = makeSeriesScope$1(lineData);
  38071. this._lineData = null;
  38072. this.group.removeAll();
  38073. };
  38074. lineDrawProto.incrementalUpdate = function (taskParams, lineData) {
  38075. function updateIncrementalAndHover(el) {
  38076. if (!el.isGroup) {
  38077. el.incremental = el.useHoverLayer = true;
  38078. }
  38079. }
  38080. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  38081. var itemLayout = lineData.getItemLayout(idx);
  38082. if (lineNeedsDraw(itemLayout)) {
  38083. var el = new this._ctor(lineData, idx, this._seriesScope);
  38084. el.traverse(updateIncrementalAndHover);
  38085. this.group.add(el);
  38086. }
  38087. }
  38088. };
  38089. function makeSeriesScope$1(lineData) {
  38090. var hostModel = lineData.hostModel;
  38091. return {
  38092. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  38093. hoverLineStyle: hostModel.getModel('emphasis.lineStyle').getLineStyle(),
  38094. labelModel: hostModel.getModel('label'),
  38095. hoverLabelModel: hostModel.getModel('emphasis.label')
  38096. };
  38097. }
  38098. lineDrawProto.remove = function () {
  38099. this._clearIncremental();
  38100. this._incremental = null;
  38101. this.group.removeAll();
  38102. };
  38103. lineDrawProto._clearIncremental = function () {
  38104. var incremental = this._incremental;
  38105. if (incremental) {
  38106. incremental.clearDisplaybles();
  38107. }
  38108. };
  38109. function isPointNaN(pt) {
  38110. return isNaN(pt[0]) || isNaN(pt[1]);
  38111. }
  38112. function lineNeedsDraw(pts) {
  38113. return !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  38114. }
  38115. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  38116. var data = seriesModel.getData();
  38117. // Special type markLine like 'min', 'max', 'average'
  38118. var mlType = item.type;
  38119. if (!isArray(item)
  38120. && (
  38121. mlType === 'min' || mlType === 'max' || mlType === 'average'
  38122. // In case
  38123. // data: [{
  38124. // yAxis: 10
  38125. // }]
  38126. || (item.xAxis != null || item.yAxis != null)
  38127. )
  38128. ) {
  38129. var valueAxis;
  38130. var valueDataDim;
  38131. var value;
  38132. if (item.yAxis != null || item.xAxis != null) {
  38133. valueDataDim = item.yAxis != null ? 'y' : 'x';
  38134. valueAxis = coordSys.getAxis(valueDataDim);
  38135. value = retrieve(item.yAxis, item.xAxis);
  38136. }
  38137. else {
  38138. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  38139. valueDataDim = axisInfo.valueDataDim;
  38140. valueAxis = axisInfo.valueAxis;
  38141. value = numCalculate(data, valueDataDim, mlType);
  38142. }
  38143. var valueIndex = valueDataDim === 'x' ? 0 : 1;
  38144. var baseIndex = 1 - valueIndex;
  38145. var mlFrom = clone(item);
  38146. var mlTo = {};
  38147. mlFrom.type = null;
  38148. mlFrom.coord = [];
  38149. mlTo.coord = [];
  38150. mlFrom.coord[baseIndex] = -Infinity;
  38151. mlTo.coord[baseIndex] = Infinity;
  38152. var precision = mlModel.get('precision');
  38153. if (precision >= 0 && typeof value === 'number') {
  38154. value = +value.toFixed(Math.min(precision, 20));
  38155. }
  38156. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  38157. item = [mlFrom, mlTo, { // Extra option for tooltip and label
  38158. type: mlType,
  38159. valueIndex: item.valueIndex,
  38160. // Force to use the value of calculated value.
  38161. value: value
  38162. }];
  38163. }
  38164. item = [
  38165. dataTransform(seriesModel, item[0]),
  38166. dataTransform(seriesModel, item[1]),
  38167. extend({}, item[2])
  38168. ];
  38169. // Avoid line data type is extended by from(to) data type
  38170. item[2].type = item[2].type || '';
  38171. // Merge from option and to option into line option
  38172. merge(item[2], item[0]);
  38173. merge(item[2], item[1]);
  38174. return item;
  38175. };
  38176. function isInifinity(val) {
  38177. return !isNaN(val) && !isFinite(val);
  38178. }
  38179. // If a markLine has one dim
  38180. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  38181. var otherDimIndex = 1 - dimIndex;
  38182. var dimName = coordSys.dimensions[dimIndex];
  38183. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex])
  38184. && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  38185. }
  38186. function markLineFilter(coordSys, item) {
  38187. if (coordSys.type === 'cartesian2d') {
  38188. var fromCoord = item[0].coord;
  38189. var toCoord = item[1].coord;
  38190. // In case
  38191. // {
  38192. // markLine: {
  38193. // data: [{ yAxis: 2 }]
  38194. // }
  38195. // }
  38196. if (
  38197. fromCoord && toCoord &&
  38198. (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys)
  38199. || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))
  38200. ) {
  38201. return true;
  38202. }
  38203. }
  38204. return dataFilter$1(coordSys, item[0])
  38205. && dataFilter$1(coordSys, item[1]);
  38206. }
  38207. function updateSingleMarkerEndLayout(
  38208. data, idx, isFrom, seriesModel, api
  38209. ) {
  38210. var coordSys = seriesModel.coordinateSystem;
  38211. var itemModel = data.getItemModel(idx);
  38212. var point;
  38213. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  38214. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  38215. if (!isNaN(xPx) && !isNaN(yPx)) {
  38216. point = [xPx, yPx];
  38217. }
  38218. else {
  38219. // Chart like bar may have there own marker positioning logic
  38220. if (seriesModel.getMarkerPosition) {
  38221. // Use the getMarkerPoisition
  38222. point = seriesModel.getMarkerPosition(
  38223. data.getValues(data.dimensions, idx)
  38224. );
  38225. }
  38226. else {
  38227. var dims = coordSys.dimensions;
  38228. var x = data.get(dims[0], idx);
  38229. var y = data.get(dims[1], idx);
  38230. point = coordSys.dataToPoint([x, y]);
  38231. }
  38232. // Expand line to the edge of grid if value on one axis is Inifnity
  38233. // In case
  38234. // markLine: {
  38235. // data: [{
  38236. // yAxis: 2
  38237. // // or
  38238. // type: 'average'
  38239. // }]
  38240. // }
  38241. if (coordSys.type === 'cartesian2d') {
  38242. var xAxis = coordSys.getAxis('x');
  38243. var yAxis = coordSys.getAxis('y');
  38244. var dims = coordSys.dimensions;
  38245. if (isInifinity(data.get(dims[0], idx))) {
  38246. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  38247. }
  38248. else if (isInifinity(data.get(dims[1], idx))) {
  38249. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  38250. }
  38251. }
  38252. // Use x, y if has any
  38253. if (!isNaN(xPx)) {
  38254. point[0] = xPx;
  38255. }
  38256. if (!isNaN(yPx)) {
  38257. point[1] = yPx;
  38258. }
  38259. }
  38260. data.setItemLayout(idx, point);
  38261. }
  38262. MarkerView.extend({
  38263. type: 'markLine',
  38264. // updateLayout: function (markLineModel, ecModel, api) {
  38265. // ecModel.eachSeries(function (seriesModel) {
  38266. // var mlModel = seriesModel.markLineModel;
  38267. // if (mlModel) {
  38268. // var mlData = mlModel.getData();
  38269. // var fromData = mlModel.__from;
  38270. // var toData = mlModel.__to;
  38271. // // Update visual and layout of from symbol and to symbol
  38272. // fromData.each(function (idx) {
  38273. // updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  38274. // updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  38275. // });
  38276. // // Update layout of line
  38277. // mlData.each(function (idx) {
  38278. // mlData.setItemLayout(idx, [
  38279. // fromData.getItemLayout(idx),
  38280. // toData.getItemLayout(idx)
  38281. // ]);
  38282. // });
  38283. // this.markerGroupMap.get(seriesModel.id).updateLayout();
  38284. // }
  38285. // }, this);
  38286. // },
  38287. updateTransform: function (markLineModel, ecModel, api) {
  38288. ecModel.eachSeries(function (seriesModel) {
  38289. var mlModel = seriesModel.markLineModel;
  38290. if (mlModel) {
  38291. var mlData = mlModel.getData();
  38292. var fromData = mlModel.__from;
  38293. var toData = mlModel.__to;
  38294. // Update visual and layout of from symbol and to symbol
  38295. fromData.each(function (idx) {
  38296. updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  38297. updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  38298. });
  38299. // Update layout of line
  38300. mlData.each(function (idx) {
  38301. mlData.setItemLayout(idx, [
  38302. fromData.getItemLayout(idx),
  38303. toData.getItemLayout(idx)
  38304. ]);
  38305. });
  38306. this.markerGroupMap.get(seriesModel.id).updateLayout();
  38307. }
  38308. }, this);
  38309. },
  38310. renderSeries: function (seriesModel, mlModel, ecModel, api) {
  38311. var coordSys = seriesModel.coordinateSystem;
  38312. var seriesId = seriesModel.id;
  38313. var seriesData = seriesModel.getData();
  38314. var lineDrawMap = this.markerGroupMap;
  38315. var lineDraw = lineDrawMap.get(seriesId)
  38316. || lineDrawMap.set(seriesId, new LineDraw());
  38317. this.group.add(lineDraw.group);
  38318. var mlData = createList$2(coordSys, seriesModel, mlModel);
  38319. var fromData = mlData.from;
  38320. var toData = mlData.to;
  38321. var lineData = mlData.line;
  38322. mlModel.__from = fromData;
  38323. mlModel.__to = toData;
  38324. // Line data for tooltip and formatter
  38325. mlModel.setData(lineData);
  38326. var symbolType = mlModel.get('symbol');
  38327. var symbolSize = mlModel.get('symbolSize');
  38328. if (!isArray(symbolType)) {
  38329. symbolType = [symbolType, symbolType];
  38330. }
  38331. if (typeof symbolSize === 'number') {
  38332. symbolSize = [symbolSize, symbolSize];
  38333. }
  38334. // Update visual and layout of from symbol and to symbol
  38335. mlData.from.each(function (idx) {
  38336. updateDataVisualAndLayout(fromData, idx, true);
  38337. updateDataVisualAndLayout(toData, idx, false);
  38338. });
  38339. // Update visual and layout of line
  38340. lineData.each(function (idx) {
  38341. var lineColor = lineData.getItemModel(idx).get('lineStyle.color');
  38342. lineData.setItemVisual(idx, {
  38343. color: lineColor || fromData.getItemVisual(idx, 'color')
  38344. });
  38345. lineData.setItemLayout(idx, [
  38346. fromData.getItemLayout(idx),
  38347. toData.getItemLayout(idx)
  38348. ]);
  38349. lineData.setItemVisual(idx, {
  38350. 'fromSymbolSize': fromData.getItemVisual(idx, 'symbolSize'),
  38351. 'fromSymbol': fromData.getItemVisual(idx, 'symbol'),
  38352. 'toSymbolSize': toData.getItemVisual(idx, 'symbolSize'),
  38353. 'toSymbol': toData.getItemVisual(idx, 'symbol')
  38354. });
  38355. });
  38356. lineDraw.updateData(lineData);
  38357. // Set host model for tooltip
  38358. // FIXME
  38359. mlData.line.eachItemGraphicEl(function (el, idx) {
  38360. el.traverse(function (child) {
  38361. child.dataModel = mlModel;
  38362. });
  38363. });
  38364. function updateDataVisualAndLayout(data, idx, isFrom) {
  38365. var itemModel = data.getItemModel(idx);
  38366. updateSingleMarkerEndLayout(
  38367. data, idx, isFrom, seriesModel, api
  38368. );
  38369. data.setItemVisual(idx, {
  38370. symbolSize: itemModel.get('symbolSize') || symbolSize[isFrom ? 0 : 1],
  38371. symbol: itemModel.get('symbol', true) || symbolType[isFrom ? 0 : 1],
  38372. color: itemModel.get('itemStyle.color') || seriesData.getVisual('color')
  38373. });
  38374. }
  38375. lineDraw.__keep = true;
  38376. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  38377. }
  38378. });
  38379. /**
  38380. * @inner
  38381. * @param {module:echarts/coord/*} coordSys
  38382. * @param {module:echarts/model/Series} seriesModel
  38383. * @param {module:echarts/model/Model} mpModel
  38384. */
  38385. function createList$2(coordSys, seriesModel, mlModel) {
  38386. var coordDimsInfos;
  38387. if (coordSys) {
  38388. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  38389. var info = seriesModel.getData().getDimensionInfo(
  38390. seriesModel.getData().mapDimension(coordDim)
  38391. ) || {};
  38392. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  38393. return defaults({name: coordDim}, info);
  38394. });
  38395. }
  38396. else {
  38397. coordDimsInfos =[{
  38398. name: 'value',
  38399. type: 'float'
  38400. }];
  38401. }
  38402. var fromData = new List(coordDimsInfos, mlModel);
  38403. var toData = new List(coordDimsInfos, mlModel);
  38404. // No dimensions
  38405. var lineData = new List([], mlModel);
  38406. var optData = map(mlModel.get('data'), curry(
  38407. markLineTransform, seriesModel, coordSys, mlModel
  38408. ));
  38409. if (coordSys) {
  38410. optData = filter(
  38411. optData, curry(markLineFilter, coordSys)
  38412. );
  38413. }
  38414. var dimValueGetter$$1 = coordSys ? dimValueGetter : function (item) {
  38415. return item.value;
  38416. };
  38417. fromData.initData(
  38418. map(optData, function (item) { return item[0]; }),
  38419. null, dimValueGetter$$1
  38420. );
  38421. toData.initData(
  38422. map(optData, function (item) { return item[1]; }),
  38423. null, dimValueGetter$$1
  38424. );
  38425. lineData.initData(
  38426. map(optData, function (item) { return item[2]; })
  38427. );
  38428. lineData.hasItemOption = true;
  38429. return {
  38430. from: fromData,
  38431. to: toData,
  38432. line: lineData
  38433. };
  38434. }
  38435. registerPreprocessor(function (opt) {
  38436. // Make sure markLine component is enabled
  38437. opt.markLine = opt.markLine || {};
  38438. });
  38439. MarkerModel.extend({
  38440. type: 'markArea',
  38441. defaultOption: {
  38442. zlevel: 0,
  38443. // PENDING
  38444. z: 1,
  38445. tooltip: {
  38446. trigger: 'item'
  38447. },
  38448. // markArea should fixed on the coordinate system
  38449. animation: false,
  38450. label: {
  38451. show: true,
  38452. position: 'top'
  38453. },
  38454. itemStyle: {
  38455. // color and borderColor default to use color from series
  38456. // color: 'auto'
  38457. // borderColor: 'auto'
  38458. borderWidth: 0
  38459. },
  38460. emphasis: {
  38461. label: {
  38462. show: true,
  38463. position: 'top'
  38464. }
  38465. }
  38466. }
  38467. });
  38468. // TODO Better on polar
  38469. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  38470. var lt = dataTransform(seriesModel, item[0]);
  38471. var rb = dataTransform(seriesModel, item[1]);
  38472. var retrieve$$1 = retrieve;
  38473. // FIXME make sure lt is less than rb
  38474. var ltCoord = lt.coord;
  38475. var rbCoord = rb.coord;
  38476. ltCoord[0] = retrieve$$1(ltCoord[0], -Infinity);
  38477. ltCoord[1] = retrieve$$1(ltCoord[1], -Infinity);
  38478. rbCoord[0] = retrieve$$1(rbCoord[0], Infinity);
  38479. rbCoord[1] = retrieve$$1(rbCoord[1], Infinity);
  38480. // Merge option into one
  38481. var result = mergeAll([{}, lt, rb]);
  38482. result.coord = [
  38483. lt.coord, rb.coord
  38484. ];
  38485. result.x0 = lt.x;
  38486. result.y0 = lt.y;
  38487. result.x1 = rb.x;
  38488. result.y1 = rb.y;
  38489. return result;
  38490. };
  38491. function isInifinity$1(val) {
  38492. return !isNaN(val) && !isFinite(val);
  38493. }
  38494. // If a markArea has one dim
  38495. function ifMarkLineHasOnlyDim$1(dimIndex, fromCoord, toCoord, coordSys) {
  38496. var otherDimIndex = 1 - dimIndex;
  38497. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  38498. }
  38499. function markAreaFilter(coordSys, item) {
  38500. var fromCoord = item.coord[0];
  38501. var toCoord = item.coord[1];
  38502. if (coordSys.type === 'cartesian2d') {
  38503. // In case
  38504. // {
  38505. // markArea: {
  38506. // data: [{ yAxis: 2 }]
  38507. // }
  38508. // }
  38509. if (
  38510. fromCoord && toCoord &&
  38511. (ifMarkLineHasOnlyDim$1(1, fromCoord, toCoord, coordSys)
  38512. || ifMarkLineHasOnlyDim$1(0, fromCoord, toCoord, coordSys))
  38513. ) {
  38514. return true;
  38515. }
  38516. }
  38517. return dataFilter$1(coordSys, {
  38518. coord: fromCoord,
  38519. x: item.x0,
  38520. y: item.y0
  38521. })
  38522. || dataFilter$1(coordSys, {
  38523. coord: toCoord,
  38524. x: item.x1,
  38525. y: item.y1
  38526. });
  38527. }
  38528. // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  38529. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  38530. var coordSys = seriesModel.coordinateSystem;
  38531. var itemModel = data.getItemModel(idx);
  38532. var point;
  38533. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  38534. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  38535. if (!isNaN(xPx) && !isNaN(yPx)) {
  38536. point = [xPx, yPx];
  38537. }
  38538. else {
  38539. // Chart like bar may have there own marker positioning logic
  38540. if (seriesModel.getMarkerPosition) {
  38541. // Use the getMarkerPoisition
  38542. point = seriesModel.getMarkerPosition(
  38543. data.getValues(dims, idx)
  38544. );
  38545. }
  38546. else {
  38547. var x = data.get(dims[0], idx);
  38548. var y = data.get(dims[1], idx);
  38549. var pt = [x, y];
  38550. coordSys.clampData && coordSys.clampData(pt, pt);
  38551. point = coordSys.dataToPoint(pt, true);
  38552. }
  38553. if (coordSys.type === 'cartesian2d') {
  38554. var xAxis = coordSys.getAxis('x');
  38555. var yAxis = coordSys.getAxis('y');
  38556. var x = data.get(dims[0], idx);
  38557. var y = data.get(dims[1], idx);
  38558. if (isInifinity$1(x)) {
  38559. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  38560. }
  38561. else if (isInifinity$1(y)) {
  38562. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  38563. }
  38564. }
  38565. // Use x, y if has any
  38566. if (!isNaN(xPx)) {
  38567. point[0] = xPx;
  38568. }
  38569. if (!isNaN(yPx)) {
  38570. point[1] = yPx;
  38571. }
  38572. }
  38573. return point;
  38574. }
  38575. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  38576. MarkerView.extend({
  38577. type: 'markArea',
  38578. // updateLayout: function (markAreaModel, ecModel, api) {
  38579. // ecModel.eachSeries(function (seriesModel) {
  38580. // var maModel = seriesModel.markAreaModel;
  38581. // if (maModel) {
  38582. // var areaData = maModel.getData();
  38583. // areaData.each(function (idx) {
  38584. // var points = zrUtil.map(dimPermutations, function (dim) {
  38585. // return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  38586. // });
  38587. // // Layout
  38588. // areaData.setItemLayout(idx, points);
  38589. // var el = areaData.getItemGraphicEl(idx);
  38590. // el.setShape('points', points);
  38591. // });
  38592. // }
  38593. // }, this);
  38594. // },
  38595. updateTransform: function (markAreaModel, ecModel, api) {
  38596. ecModel.eachSeries(function (seriesModel) {
  38597. var maModel = seriesModel.markAreaModel;
  38598. if (maModel) {
  38599. var areaData = maModel.getData();
  38600. areaData.each(function (idx) {
  38601. var points = map(dimPermutations, function (dim) {
  38602. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  38603. });
  38604. // Layout
  38605. areaData.setItemLayout(idx, points);
  38606. var el = areaData.getItemGraphicEl(idx);
  38607. el.setShape('points', points);
  38608. });
  38609. }
  38610. }, this);
  38611. },
  38612. renderSeries: function (seriesModel, maModel, ecModel, api) {
  38613. var coordSys = seriesModel.coordinateSystem;
  38614. var seriesName = seriesModel.name;
  38615. var seriesData = seriesModel.getData();
  38616. var areaGroupMap = this.markerGroupMap;
  38617. var polygonGroup = areaGroupMap.get(seriesName)
  38618. || areaGroupMap.set(seriesName, {group: new Group()});
  38619. this.group.add(polygonGroup.group);
  38620. polygonGroup.__keep = true;
  38621. var areaData = createList$3(coordSys, seriesModel, maModel);
  38622. // Line data for tooltip and formatter
  38623. maModel.setData(areaData);
  38624. // Update visual and layout of line
  38625. areaData.each(function (idx) {
  38626. // Layout
  38627. areaData.setItemLayout(idx, map(dimPermutations, function (dim) {
  38628. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  38629. }));
  38630. // Visual
  38631. areaData.setItemVisual(idx, {
  38632. color: seriesData.getVisual('color')
  38633. });
  38634. });
  38635. areaData.diff(polygonGroup.__data)
  38636. .add(function (idx) {
  38637. var polygon = new Polygon({
  38638. shape: {
  38639. points: areaData.getItemLayout(idx)
  38640. }
  38641. });
  38642. areaData.setItemGraphicEl(idx, polygon);
  38643. polygonGroup.group.add(polygon);
  38644. })
  38645. .update(function (newIdx, oldIdx) {
  38646. var polygon = polygonGroup.__data.getItemGraphicEl(oldIdx);
  38647. updateProps(polygon, {
  38648. shape: {
  38649. points: areaData.getItemLayout(newIdx)
  38650. }
  38651. }, maModel, newIdx);
  38652. polygonGroup.group.add(polygon);
  38653. areaData.setItemGraphicEl(newIdx, polygon);
  38654. })
  38655. .remove(function (idx) {
  38656. var polygon = polygonGroup.__data.getItemGraphicEl(idx);
  38657. polygonGroup.group.remove(polygon);
  38658. })
  38659. .execute();
  38660. areaData.eachItemGraphicEl(function (polygon, idx) {
  38661. var itemModel = areaData.getItemModel(idx);
  38662. var labelModel = itemModel.getModel('label');
  38663. var labelHoverModel = itemModel.getModel('emphasis.label');
  38664. var color = areaData.getItemVisual(idx, 'color');
  38665. polygon.useStyle(
  38666. defaults(
  38667. itemModel.getModel('itemStyle').getItemStyle(),
  38668. {
  38669. fill: modifyAlpha(color, 0.4),
  38670. stroke: color
  38671. }
  38672. )
  38673. );
  38674. polygon.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  38675. setLabelStyle(
  38676. polygon.style, polygon.hoverStyle, labelModel, labelHoverModel,
  38677. {
  38678. labelFetcher: maModel,
  38679. labelDataIndex: idx,
  38680. defaultText: areaData.getName(idx) || '',
  38681. isRectText: true,
  38682. autoColor: color
  38683. }
  38684. );
  38685. setHoverStyle(polygon, {});
  38686. polygon.dataModel = maModel;
  38687. });
  38688. polygonGroup.__data = areaData;
  38689. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  38690. }
  38691. });
  38692. /**
  38693. * @inner
  38694. * @param {module:echarts/coord/*} coordSys
  38695. * @param {module:echarts/model/Series} seriesModel
  38696. * @param {module:echarts/model/Model} mpModel
  38697. */
  38698. function createList$3(coordSys, seriesModel, maModel) {
  38699. var coordDimsInfos;
  38700. var areaData;
  38701. var dims = ['x0', 'y0', 'x1', 'y1'];
  38702. if (coordSys) {
  38703. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  38704. var data = seriesModel.getData();
  38705. var info = data.getDimensionInfo(
  38706. data.mapDimension(coordDim)
  38707. ) || {};
  38708. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  38709. return defaults({name: coordDim}, info);
  38710. });
  38711. areaData = new List(map(dims, function (dim, idx) {
  38712. return {
  38713. name: dim,
  38714. type: coordDimsInfos[idx % 2].type
  38715. };
  38716. }), maModel);
  38717. }
  38718. else {
  38719. coordDimsInfos =[{
  38720. name: 'value',
  38721. type: 'float'
  38722. }];
  38723. areaData = new List(coordDimsInfos, maModel);
  38724. }
  38725. var optData = map(maModel.get('data'), curry(
  38726. markAreaTransform, seriesModel, coordSys, maModel
  38727. ));
  38728. if (coordSys) {
  38729. optData = filter(
  38730. optData, curry(markAreaFilter, coordSys)
  38731. );
  38732. }
  38733. var dimValueGetter$$1 = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  38734. return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  38735. } : function (item) {
  38736. return item.value;
  38737. };
  38738. areaData.initData(optData, null, dimValueGetter$$1);
  38739. areaData.hasItemOption = true;
  38740. return areaData;
  38741. }
  38742. registerPreprocessor(function (opt) {
  38743. // Make sure markArea component is enabled
  38744. opt.markArea = opt.markArea || {};
  38745. });
  38746. ComponentModel.registerSubTypeDefaulter('dataZoom', function () {
  38747. // Default 'slider' when no type specified.
  38748. return 'slider';
  38749. });
  38750. var AXIS_DIMS = ['x', 'y', 'z', 'radius', 'angle', 'single'];
  38751. // Supported coords.
  38752. var COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  38753. /**
  38754. * @param {string} coordType
  38755. * @return {boolean}
  38756. */
  38757. function isCoordSupported(coordType) {
  38758. return indexOf(COORDS, coordType) >= 0;
  38759. }
  38760. /**
  38761. * Create "each" method to iterate names.
  38762. *
  38763. * @pubilc
  38764. * @param {Array.<string>} names
  38765. * @param {Array.<string>=} attrs
  38766. * @return {Function}
  38767. */
  38768. function createNameEach(names, attrs) {
  38769. names = names.slice();
  38770. var capitalNames = map(names, capitalFirst);
  38771. attrs = (attrs || []).slice();
  38772. var capitalAttrs = map(attrs, capitalFirst);
  38773. return function (callback, context) {
  38774. each$1(names, function (name, index) {
  38775. var nameObj = {name: name, capital: capitalNames[index]};
  38776. for (var j = 0; j < attrs.length; j++) {
  38777. nameObj[attrs[j]] = name + capitalAttrs[j];
  38778. }
  38779. callback.call(context, nameObj);
  38780. });
  38781. };
  38782. }
  38783. /**
  38784. * Iterate each dimension name.
  38785. *
  38786. * @public
  38787. * @param {Function} callback The parameter is like:
  38788. * {
  38789. * name: 'angle',
  38790. * capital: 'Angle',
  38791. * axis: 'angleAxis',
  38792. * axisIndex: 'angleAixs',
  38793. * index: 'angleIndex'
  38794. * }
  38795. * @param {Object} context
  38796. */
  38797. var eachAxisDim$1 = createNameEach(AXIS_DIMS, ['axisIndex', 'axis', 'index', 'id']);
  38798. /**
  38799. * If tow dataZoomModels has the same axis controlled, we say that they are 'linked'.
  38800. * dataZoomModels and 'links' make up one or more graphics.
  38801. * This function finds the graphic where the source dataZoomModel is in.
  38802. *
  38803. * @public
  38804. * @param {Function} forEachNode Node iterator.
  38805. * @param {Function} forEachEdgeType edgeType iterator
  38806. * @param {Function} edgeIdGetter Giving node and edgeType, return an array of edge id.
  38807. * @return {Function} Input: sourceNode, Output: Like {nodes: [], dims: {}}
  38808. */
  38809. function createLinkedNodesFinder(forEachNode, forEachEdgeType, edgeIdGetter) {
  38810. return function (sourceNode) {
  38811. var result = {
  38812. nodes: [],
  38813. records: {} // key: edgeType.name, value: Object (key: edge id, value: boolean).
  38814. };
  38815. forEachEdgeType(function (edgeType) {
  38816. result.records[edgeType.name] = {};
  38817. });
  38818. if (!sourceNode) {
  38819. return result;
  38820. }
  38821. absorb(sourceNode, result);
  38822. var existsLink;
  38823. do {
  38824. existsLink = false;
  38825. forEachNode(processSingleNode);
  38826. }
  38827. while (existsLink);
  38828. function processSingleNode(node) {
  38829. if (!isNodeAbsorded(node, result) && isLinked(node, result)) {
  38830. absorb(node, result);
  38831. existsLink = true;
  38832. }
  38833. }
  38834. return result;
  38835. };
  38836. function isNodeAbsorded(node, result) {
  38837. return indexOf(result.nodes, node) >= 0;
  38838. }
  38839. function isLinked(node, result) {
  38840. var hasLink = false;
  38841. forEachEdgeType(function (edgeType) {
  38842. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  38843. result.records[edgeType.name][edgeId] && (hasLink = true);
  38844. });
  38845. });
  38846. return hasLink;
  38847. }
  38848. function absorb(node, result) {
  38849. result.nodes.push(node);
  38850. forEachEdgeType(function (edgeType) {
  38851. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  38852. result.records[edgeType.name][edgeId] = true;
  38853. });
  38854. });
  38855. }
  38856. }
  38857. var each$14 = each$1;
  38858. var asc$1 = asc;
  38859. /**
  38860. * Operate single axis.
  38861. * One axis can only operated by one axis operator.
  38862. * Different dataZoomModels may be defined to operate the same axis.
  38863. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  38864. * So dataZoomModels share one axisProxy in that case.
  38865. *
  38866. * @class
  38867. */
  38868. var AxisProxy = function (dimName, axisIndex, dataZoomModel, ecModel) {
  38869. /**
  38870. * @private
  38871. * @type {string}
  38872. */
  38873. this._dimName = dimName;
  38874. /**
  38875. * @private
  38876. */
  38877. this._axisIndex = axisIndex;
  38878. /**
  38879. * @private
  38880. * @type {Array.<number>}
  38881. */
  38882. this._valueWindow;
  38883. /**
  38884. * @private
  38885. * @type {Array.<number>}
  38886. */
  38887. this._percentWindow;
  38888. /**
  38889. * @private
  38890. * @type {Array.<number>}
  38891. */
  38892. this._dataExtent;
  38893. /**
  38894. * {minSpan, maxSpan, minValueSpan, maxValueSpan}
  38895. * @private
  38896. * @type {Object}
  38897. */
  38898. this._minMaxSpan;
  38899. /**
  38900. * @readOnly
  38901. * @type {module: echarts/model/Global}
  38902. */
  38903. this.ecModel = ecModel;
  38904. /**
  38905. * @private
  38906. * @type {module: echarts/component/dataZoom/DataZoomModel}
  38907. */
  38908. this._dataZoomModel = dataZoomModel;
  38909. // /**
  38910. // * @readOnly
  38911. // * @private
  38912. // */
  38913. // this.hasSeriesStacked;
  38914. };
  38915. AxisProxy.prototype = {
  38916. constructor: AxisProxy,
  38917. /**
  38918. * Whether the axisProxy is hosted by dataZoomModel.
  38919. *
  38920. * @public
  38921. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  38922. * @return {boolean}
  38923. */
  38924. hostedBy: function (dataZoomModel) {
  38925. return this._dataZoomModel === dataZoomModel;
  38926. },
  38927. /**
  38928. * @return {Array.<number>} Value can only be NaN or finite value.
  38929. */
  38930. getDataValueWindow: function () {
  38931. return this._valueWindow.slice();
  38932. },
  38933. /**
  38934. * @return {Array.<number>}
  38935. */
  38936. getDataPercentWindow: function () {
  38937. return this._percentWindow.slice();
  38938. },
  38939. /**
  38940. * @public
  38941. * @param {number} axisIndex
  38942. * @return {Array} seriesModels
  38943. */
  38944. getTargetSeriesModels: function () {
  38945. var seriesModels = [];
  38946. var ecModel = this.ecModel;
  38947. ecModel.eachSeries(function (seriesModel) {
  38948. if (isCoordSupported(seriesModel.get('coordinateSystem'))) {
  38949. var dimName = this._dimName;
  38950. var axisModel = ecModel.queryComponents({
  38951. mainType: dimName + 'Axis',
  38952. index: seriesModel.get(dimName + 'AxisIndex'),
  38953. id: seriesModel.get(dimName + 'AxisId')
  38954. })[0];
  38955. if (this._axisIndex === (axisModel && axisModel.componentIndex)) {
  38956. seriesModels.push(seriesModel);
  38957. }
  38958. }
  38959. }, this);
  38960. return seriesModels;
  38961. },
  38962. getAxisModel: function () {
  38963. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  38964. },
  38965. getOtherAxisModel: function () {
  38966. var axisDim = this._dimName;
  38967. var ecModel = this.ecModel;
  38968. var axisModel = this.getAxisModel();
  38969. var isCartesian = axisDim === 'x' || axisDim === 'y';
  38970. var otherAxisDim;
  38971. var coordSysIndexName;
  38972. if (isCartesian) {
  38973. coordSysIndexName = 'gridIndex';
  38974. otherAxisDim = axisDim === 'x' ? 'y' : 'x';
  38975. }
  38976. else {
  38977. coordSysIndexName = 'polarIndex';
  38978. otherAxisDim = axisDim === 'angle' ? 'radius' : 'angle';
  38979. }
  38980. var foundOtherAxisModel;
  38981. ecModel.eachComponent(otherAxisDim + 'Axis', function (otherAxisModel) {
  38982. if ((otherAxisModel.get(coordSysIndexName) || 0)
  38983. === (axisModel.get(coordSysIndexName) || 0)
  38984. ) {
  38985. foundOtherAxisModel = otherAxisModel;
  38986. }
  38987. });
  38988. return foundOtherAxisModel;
  38989. },
  38990. getMinMaxSpan: function () {
  38991. return clone(this._minMaxSpan);
  38992. },
  38993. /**
  38994. * Only calculate by given range and this._dataExtent, do not change anything.
  38995. *
  38996. * @param {Object} opt
  38997. * @param {number} [opt.start]
  38998. * @param {number} [opt.end]
  38999. * @param {number} [opt.startValue]
  39000. * @param {number} [opt.endValue]
  39001. */
  39002. calculateDataWindow: function (opt) {
  39003. var dataExtent = this._dataExtent;
  39004. var axisModel = this.getAxisModel();
  39005. var scale = axisModel.axis.scale;
  39006. var rangePropMode = this._dataZoomModel.getRangePropMode();
  39007. var percentExtent = [0, 100];
  39008. var percentWindow = [
  39009. opt.start,
  39010. opt.end
  39011. ];
  39012. var valueWindow = [];
  39013. each$14(['startValue', 'endValue'], function (prop) {
  39014. valueWindow.push(opt[prop] != null ? scale.parse(opt[prop]) : null);
  39015. });
  39016. // Normalize bound.
  39017. each$14([0, 1], function (idx) {
  39018. var boundValue = valueWindow[idx];
  39019. var boundPercent = percentWindow[idx];
  39020. // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  39021. // on `valueProp` ('startValue', 'endValue'). The former one is suitable
  39022. // for cases that a dataZoom component controls multiple axes with different
  39023. // unit or extent, and the latter one is suitable for accurate zoom by pixel
  39024. // (e.g., in dataZoomSelect). `valueProp` can be calculated from `percentProp`,
  39025. // but it is awkward that `percentProp` can not be obtained from `valueProp`
  39026. // accurately (because all of values that are overflow the `dataExtent` will
  39027. // be calculated to percent '100%'). So we have to use
  39028. // `dataZoom.getRangePropMode()` to mark which prop is used.
  39029. // `rangePropMode` is updated only when setOption or dispatchAction, otherwise
  39030. // it remains its original value.
  39031. if (rangePropMode[idx] === 'percent') {
  39032. if (boundPercent == null) {
  39033. boundPercent = percentExtent[idx];
  39034. }
  39035. // Use scale.parse to math round for category or time axis.
  39036. boundValue = scale.parse(linearMap(
  39037. boundPercent, percentExtent, dataExtent, true
  39038. ));
  39039. }
  39040. else {
  39041. // Calculating `percent` from `value` may be not accurate, because
  39042. // This calculation can not be inversed, because all of values that
  39043. // are overflow the `dataExtent` will be calculated to percent '100%'
  39044. boundPercent = linearMap(
  39045. boundValue, dataExtent, percentExtent, true
  39046. );
  39047. }
  39048. // valueWindow[idx] = round(boundValue);
  39049. // percentWindow[idx] = round(boundPercent);
  39050. valueWindow[idx] = boundValue;
  39051. percentWindow[idx] = boundPercent;
  39052. });
  39053. return {
  39054. valueWindow: asc$1(valueWindow),
  39055. percentWindow: asc$1(percentWindow)
  39056. };
  39057. },
  39058. /**
  39059. * Notice: reset should not be called before series.restoreData() called,
  39060. * so it is recommanded to be called in "process stage" but not "model init
  39061. * stage".
  39062. *
  39063. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  39064. */
  39065. reset: function (dataZoomModel) {
  39066. if (dataZoomModel !== this._dataZoomModel) {
  39067. return;
  39068. }
  39069. var targetSeries = this.getTargetSeriesModels();
  39070. // Culculate data window and data extent, and record them.
  39071. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries);
  39072. // this.hasSeriesStacked = false;
  39073. // each(targetSeries, function (series) {
  39074. // var data = series.getData();
  39075. // var dataDim = data.mapDimension(this._dimName);
  39076. // var stackedDimension = data.getCalculationInfo('stackedDimension');
  39077. // if (stackedDimension && stackedDimension === dataDim) {
  39078. // this.hasSeriesStacked = true;
  39079. // }
  39080. // }, this);
  39081. var dataWindow = this.calculateDataWindow(dataZoomModel.option);
  39082. this._valueWindow = dataWindow.valueWindow;
  39083. this._percentWindow = dataWindow.percentWindow;
  39084. setMinMaxSpan(this);
  39085. // Update axis setting then.
  39086. setAxisModel(this);
  39087. },
  39088. /**
  39089. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  39090. */
  39091. restore: function (dataZoomModel) {
  39092. if (dataZoomModel !== this._dataZoomModel) {
  39093. return;
  39094. }
  39095. this._valueWindow = this._percentWindow = null;
  39096. setAxisModel(this, true);
  39097. },
  39098. /**
  39099. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  39100. */
  39101. filterData: function (dataZoomModel, api) {
  39102. if (dataZoomModel !== this._dataZoomModel) {
  39103. return;
  39104. }
  39105. var axisDim = this._dimName;
  39106. var seriesModels = this.getTargetSeriesModels();
  39107. var filterMode = dataZoomModel.get('filterMode');
  39108. var valueWindow = this._valueWindow;
  39109. if (filterMode === 'none') {
  39110. return;
  39111. }
  39112. // FIXME
  39113. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  39114. // with NaN data, NaN will be filtered and stack will be wrong.
  39115. // So we need to force the mode to be set empty.
  39116. // In fect, it is not a big deal that do not support filterMode-'filter'
  39117. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  39118. // selection" some day, which might need "adapt to data extent on the
  39119. // otherAxis", which is disabled by filterMode-'empty'.
  39120. // But currently, stack has been fixed to based on value but not index,
  39121. // so this is not an issue any more.
  39122. // var otherAxisModel = this.getOtherAxisModel();
  39123. // if (dataZoomModel.get('$fromToolbox')
  39124. // && otherAxisModel
  39125. // && otherAxisModel.hasSeriesStacked
  39126. // ) {
  39127. // filterMode = 'empty';
  39128. // }
  39129. // TODO
  39130. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  39131. // Process series data
  39132. each$14(seriesModels, function (seriesModel) {
  39133. var seriesData = seriesModel.getData();
  39134. var dataDims = seriesData.mapDimension(axisDim, true);
  39135. if (filterMode === 'weakFilter') {
  39136. seriesData.filterSelf(function (dataIndex) {
  39137. var leftOut;
  39138. var rightOut;
  39139. var hasValue;
  39140. for (var i = 0; i < dataDims.length; i++) {
  39141. var value = seriesData.get(dataDims[i], dataIndex);
  39142. var thisHasValue = !isNaN(value);
  39143. var thisLeftOut = value < valueWindow[0];
  39144. var thisRightOut = value > valueWindow[1];
  39145. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  39146. return true;
  39147. }
  39148. thisHasValue && (hasValue = true);
  39149. thisLeftOut && (leftOut = true);
  39150. thisRightOut && (rightOut = true);
  39151. }
  39152. // If both left out and right out, do not filter.
  39153. return hasValue && leftOut && rightOut;
  39154. });
  39155. }
  39156. else {
  39157. each$14(dataDims, function (dim) {
  39158. if (filterMode === 'empty') {
  39159. seriesModel.setData(
  39160. seriesData.map(dim, function (value) {
  39161. return !isInWindow(value) ? NaN : value;
  39162. })
  39163. );
  39164. }
  39165. else {
  39166. var range = {};
  39167. range[dim] = valueWindow;
  39168. // console.time('select');
  39169. seriesData.selectRange(range);
  39170. // console.timeEnd('select');
  39171. }
  39172. });
  39173. }
  39174. each$14(dataDims, function (dim) {
  39175. seriesData.setApproximateExtent(valueWindow, dim);
  39176. });
  39177. });
  39178. function isInWindow(value) {
  39179. return value >= valueWindow[0] && value <= valueWindow[1];
  39180. }
  39181. }
  39182. };
  39183. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  39184. var dataExtent = [Infinity, -Infinity];
  39185. each$14(seriesModels, function (seriesModel) {
  39186. var seriesData = seriesModel.getData();
  39187. if (seriesData) {
  39188. each$14(seriesData.mapDimension(axisDim, true), function (dim) {
  39189. var seriesExtent = seriesData.getApproximateExtent(dim);
  39190. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  39191. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  39192. });
  39193. }
  39194. });
  39195. if (dataExtent[1] < dataExtent[0]) {
  39196. dataExtent = [NaN, NaN];
  39197. }
  39198. // It is important to get "consistent" extent when more then one axes is
  39199. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  39200. // when zooming. But it is difficult to know what is "consistent", considering
  39201. // axes have different type or even different meanings (For example, two
  39202. // time axes are used to compare data of the same date in different years).
  39203. // So basically dataZoom just obtains extent by series.data (in category axis
  39204. // extent can be obtained from axis.data).
  39205. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  39206. // consistent.
  39207. fixExtentByAxis(axisProxy, dataExtent);
  39208. return dataExtent;
  39209. }
  39210. function fixExtentByAxis(axisProxy, dataExtent) {
  39211. var axisModel = axisProxy.getAxisModel();
  39212. var min = axisModel.getMin(true);
  39213. // For category axis, if min/max/scale are not set, extent is determined
  39214. // by axis.data by default.
  39215. var isCategoryAxis = axisModel.get('type') === 'category';
  39216. var axisDataLen = isCategoryAxis && axisModel.getCategories().length;
  39217. if (min != null && min !== 'dataMin' && typeof min !== 'function') {
  39218. dataExtent[0] = min;
  39219. }
  39220. else if (isCategoryAxis) {
  39221. dataExtent[0] = axisDataLen > 0 ? 0 : NaN;
  39222. }
  39223. var max = axisModel.getMax(true);
  39224. if (max != null && max !== 'dataMax' && typeof max !== 'function') {
  39225. dataExtent[1] = max;
  39226. }
  39227. else if (isCategoryAxis) {
  39228. dataExtent[1] = axisDataLen > 0 ? axisDataLen - 1 : NaN;
  39229. }
  39230. if (!axisModel.get('scale', true)) {
  39231. dataExtent[0] > 0 && (dataExtent[0] = 0);
  39232. dataExtent[1] < 0 && (dataExtent[1] = 0);
  39233. }
  39234. // For value axis, if min/max/scale are not set, we just use the extent obtained
  39235. // by series data, which may be a little different from the extent calculated by
  39236. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  39237. // little when zooming. So it will not be fixed until some users require it strongly.
  39238. return dataExtent;
  39239. }
  39240. function setAxisModel(axisProxy, isRestore) {
  39241. var axisModel = axisProxy.getAxisModel();
  39242. var percentWindow = axisProxy._percentWindow;
  39243. var valueWindow = axisProxy._valueWindow;
  39244. if (!percentWindow) {
  39245. return;
  39246. }
  39247. // [0, 500]: arbitrary value, guess axis extent.
  39248. var precision = getPixelPrecision(valueWindow, [0, 500]);
  39249. precision = Math.min(precision, 20);
  39250. // isRestore or isFull
  39251. var useOrigin = isRestore || (percentWindow[0] === 0 && percentWindow[1] === 100);
  39252. axisModel.setRange(
  39253. useOrigin ? null : +valueWindow[0].toFixed(precision),
  39254. useOrigin ? null : +valueWindow[1].toFixed(precision)
  39255. );
  39256. }
  39257. function setMinMaxSpan(axisProxy) {
  39258. var minMaxSpan = axisProxy._minMaxSpan = {};
  39259. var dataZoomModel = axisProxy._dataZoomModel;
  39260. each$14(['min', 'max'], function (minMax) {
  39261. minMaxSpan[minMax + 'Span'] = dataZoomModel.get(minMax + 'Span');
  39262. // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  39263. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  39264. if (valueSpan != null) {
  39265. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  39266. valueSpan = axisProxy.getAxisModel().axis.scale.parse(valueSpan);
  39267. if (valueSpan != null) {
  39268. var dataExtent = axisProxy._dataExtent;
  39269. minMaxSpan[minMax + 'Span'] = linearMap(
  39270. dataExtent[0] + valueSpan, dataExtent, [0, 100], true
  39271. );
  39272. }
  39273. }
  39274. });
  39275. }
  39276. var each$13 = each$1;
  39277. var eachAxisDim = eachAxisDim$1;
  39278. var DataZoomModel = extendComponentModel({
  39279. type: 'dataZoom',
  39280. dependencies: [
  39281. 'xAxis', 'yAxis', 'zAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series'
  39282. ],
  39283. /**
  39284. * @protected
  39285. */
  39286. defaultOption: {
  39287. zlevel: 0,
  39288. z: 4, // Higher than normal component (z: 2).
  39289. orient: null, // Default auto by axisIndex. Possible value: 'horizontal', 'vertical'.
  39290. xAxisIndex: null, // Default the first horizontal category axis.
  39291. yAxisIndex: null, // Default the first vertical category axis.
  39292. filterMode: 'filter', // Possible values: 'filter' or 'empty' or 'weakFilter'.
  39293. // 'filter': data items which are out of window will be removed. This option is
  39294. // applicable when filtering outliers. For each data item, it will be
  39295. // filtered if one of the relevant dimensions is out of the window.
  39296. // 'weakFilter': data items which are out of window will be removed. This option
  39297. // is applicable when filtering outliers. For each data item, it will be
  39298. // filtered only if all of the relevant dimensions are out of the same
  39299. // side of the window.
  39300. // 'empty': data items which are out of window will be set to empty.
  39301. // This option is applicable when user should not neglect
  39302. // that there are some data items out of window.
  39303. // 'none': Do not filter.
  39304. // Taking line chart as an example, line will be broken in
  39305. // the filtered points when filterModel is set to 'empty', but
  39306. // be connected when set to 'filter'.
  39307. throttle: null, // Dispatch action by the fixed rate, avoid frequency.
  39308. // default 100. Do not throttle when use null/undefined.
  39309. // If animation === true and animationDurationUpdate > 0,
  39310. // default value is 100, otherwise 20.
  39311. start: 0, // Start percent. 0 ~ 100
  39312. end: 100, // End percent. 0 ~ 100
  39313. startValue: null, // Start value. If startValue specified, start is ignored.
  39314. endValue: null, // End value. If endValue specified, end is ignored.
  39315. minSpan: null, // 0 ~ 100
  39316. maxSpan: null, // 0 ~ 100
  39317. minValueSpan: null, // The range of dataZoom can not be smaller than that.
  39318. maxValueSpan: null, // The range of dataZoom can not be larger than that.
  39319. rangeMode: null // Array, can be 'value' or 'percent'.
  39320. },
  39321. /**
  39322. * @override
  39323. */
  39324. init: function (option, parentModel, ecModel) {
  39325. /**
  39326. * key like x_0, y_1
  39327. * @private
  39328. * @type {Object}
  39329. */
  39330. this._dataIntervalByAxis = {};
  39331. /**
  39332. * @private
  39333. */
  39334. this._dataInfo = {};
  39335. /**
  39336. * key like x_0, y_1
  39337. * @private
  39338. */
  39339. this._axisProxies = {};
  39340. /**
  39341. * @readOnly
  39342. */
  39343. this.textStyleModel;
  39344. /**
  39345. * @private
  39346. */
  39347. this._autoThrottle = true;
  39348. /**
  39349. * 'percent' or 'value'
  39350. * @private
  39351. */
  39352. this._rangePropMode = ['percent', 'percent'];
  39353. var rawOption = retrieveRaw(option);
  39354. this.mergeDefaultAndTheme(option, ecModel);
  39355. this.doInit(rawOption);
  39356. },
  39357. /**
  39358. * @override
  39359. */
  39360. mergeOption: function (newOption) {
  39361. var rawOption = retrieveRaw(newOption);
  39362. //FIX #2591
  39363. merge(this.option, newOption, true);
  39364. this.doInit(rawOption);
  39365. },
  39366. /**
  39367. * @protected
  39368. */
  39369. doInit: function (rawOption) {
  39370. var thisOption = this.option;
  39371. // Disable realtime view update if canvas is not supported.
  39372. if (!env$1.canvasSupported) {
  39373. thisOption.realtime = false;
  39374. }
  39375. this._setDefaultThrottle(rawOption);
  39376. updateRangeUse(this, rawOption);
  39377. each$13([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  39378. // start/end has higher priority over startValue/endValue if they
  39379. // both set, but we should make chart.setOption({endValue: 1000})
  39380. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  39381. if (this._rangePropMode[index] === 'value') {
  39382. thisOption[names[0]] = null;
  39383. }
  39384. // Otherwise do nothing and use the merge result.
  39385. }, this);
  39386. this.textStyleModel = this.getModel('textStyle');
  39387. this._resetTarget();
  39388. this._giveAxisProxies();
  39389. },
  39390. /**
  39391. * @private
  39392. */
  39393. _giveAxisProxies: function () {
  39394. var axisProxies = this._axisProxies;
  39395. this.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel, ecModel) {
  39396. var axisModel = this.dependentModels[dimNames.axis][axisIndex];
  39397. // If exists, share axisProxy with other dataZoomModels.
  39398. var axisProxy = axisModel.__dzAxisProxy || (
  39399. // Use the first dataZoomModel as the main model of axisProxy.
  39400. axisModel.__dzAxisProxy = new AxisProxy(
  39401. dimNames.name, axisIndex, this, ecModel
  39402. )
  39403. );
  39404. // FIXME
  39405. // dispose __dzAxisProxy
  39406. axisProxies[dimNames.name + '_' + axisIndex] = axisProxy;
  39407. }, this);
  39408. },
  39409. /**
  39410. * @private
  39411. */
  39412. _resetTarget: function () {
  39413. var thisOption = this.option;
  39414. var autoMode = this._judgeAutoMode();
  39415. eachAxisDim(function (dimNames) {
  39416. var axisIndexName = dimNames.axisIndex;
  39417. thisOption[axisIndexName] = normalizeToArray(
  39418. thisOption[axisIndexName]
  39419. );
  39420. }, this);
  39421. if (autoMode === 'axisIndex') {
  39422. this._autoSetAxisIndex();
  39423. }
  39424. else if (autoMode === 'orient') {
  39425. this._autoSetOrient();
  39426. }
  39427. },
  39428. /**
  39429. * @private
  39430. */
  39431. _judgeAutoMode: function () {
  39432. // Auto set only works for setOption at the first time.
  39433. // The following is user's reponsibility. So using merged
  39434. // option is OK.
  39435. var thisOption = this.option;
  39436. var hasIndexSpecified = false;
  39437. eachAxisDim(function (dimNames) {
  39438. // When user set axisIndex as a empty array, we think that user specify axisIndex
  39439. // but do not want use auto mode. Because empty array may be encountered when
  39440. // some error occured.
  39441. if (thisOption[dimNames.axisIndex] != null) {
  39442. hasIndexSpecified = true;
  39443. }
  39444. }, this);
  39445. var orient = thisOption.orient;
  39446. if (orient == null && hasIndexSpecified) {
  39447. return 'orient';
  39448. }
  39449. else if (!hasIndexSpecified) {
  39450. if (orient == null) {
  39451. thisOption.orient = 'horizontal';
  39452. }
  39453. return 'axisIndex';
  39454. }
  39455. },
  39456. /**
  39457. * @private
  39458. */
  39459. _autoSetAxisIndex: function () {
  39460. var autoAxisIndex = true;
  39461. var orient = this.get('orient', true);
  39462. var thisOption = this.option;
  39463. var dependentModels = this.dependentModels;
  39464. if (autoAxisIndex) {
  39465. // Find axis that parallel to dataZoom as default.
  39466. var dimName = orient === 'vertical' ? 'y' : 'x';
  39467. if (dependentModels[dimName + 'Axis'].length) {
  39468. thisOption[dimName + 'AxisIndex'] = [0];
  39469. autoAxisIndex = false;
  39470. }
  39471. else {
  39472. each$13(dependentModels.singleAxis, function (singleAxisModel) {
  39473. if (autoAxisIndex && singleAxisModel.get('orient', true) === orient) {
  39474. thisOption.singleAxisIndex = [singleAxisModel.componentIndex];
  39475. autoAxisIndex = false;
  39476. }
  39477. });
  39478. }
  39479. }
  39480. if (autoAxisIndex) {
  39481. // Find the first category axis as default. (consider polar)
  39482. eachAxisDim(function (dimNames) {
  39483. if (!autoAxisIndex) {
  39484. return;
  39485. }
  39486. var axisIndices = [];
  39487. var axisModels = this.dependentModels[dimNames.axis];
  39488. if (axisModels.length && !axisIndices.length) {
  39489. for (var i = 0, len = axisModels.length; i < len; i++) {
  39490. if (axisModels[i].get('type') === 'category') {
  39491. axisIndices.push(i);
  39492. }
  39493. }
  39494. }
  39495. thisOption[dimNames.axisIndex] = axisIndices;
  39496. if (axisIndices.length) {
  39497. autoAxisIndex = false;
  39498. }
  39499. }, this);
  39500. }
  39501. if (autoAxisIndex) {
  39502. // FIXME
  39503. // 这里是兼容ec2的写法(没指定xAxisIndex和yAxisIndex时把scatter和双数值轴折柱纳入dataZoom控制),
  39504. // 但是实际是否需要Grid.js#getScaleByOption来判断(考虑time,log等axis type)?
  39505. // If both dataZoom.xAxisIndex and dataZoom.yAxisIndex is not specified,
  39506. // dataZoom component auto adopts series that reference to
  39507. // both xAxis and yAxis which type is 'value'.
  39508. this.ecModel.eachSeries(function (seriesModel) {
  39509. if (this._isSeriesHasAllAxesTypeOf(seriesModel, 'value')) {
  39510. eachAxisDim(function (dimNames) {
  39511. var axisIndices = thisOption[dimNames.axisIndex];
  39512. var axisIndex = seriesModel.get(dimNames.axisIndex);
  39513. var axisId = seriesModel.get(dimNames.axisId);
  39514. var axisModel = seriesModel.ecModel.queryComponents({
  39515. mainType: dimNames.axis,
  39516. index: axisIndex,
  39517. id: axisId
  39518. })[0];
  39519. if (__DEV__) {
  39520. if (!axisModel) {
  39521. throw new Error(
  39522. dimNames.axis + ' "' + retrieve(
  39523. axisIndex,
  39524. axisId,
  39525. 0
  39526. ) + '" not found'
  39527. );
  39528. }
  39529. }
  39530. axisIndex = axisModel.componentIndex;
  39531. if (indexOf(axisIndices, axisIndex) < 0) {
  39532. axisIndices.push(axisIndex);
  39533. }
  39534. });
  39535. }
  39536. }, this);
  39537. }
  39538. },
  39539. /**
  39540. * @private
  39541. */
  39542. _autoSetOrient: function () {
  39543. var dim;
  39544. // Find the first axis
  39545. this.eachTargetAxis(function (dimNames) {
  39546. !dim && (dim = dimNames.name);
  39547. }, this);
  39548. this.option.orient = dim === 'y' ? 'vertical' : 'horizontal';
  39549. },
  39550. /**
  39551. * @private
  39552. */
  39553. _isSeriesHasAllAxesTypeOf: function (seriesModel, axisType) {
  39554. // FIXME
  39555. // 需要series的xAxisIndex和yAxisIndex都首先自动设置上。
  39556. // 例如series.type === scatter时。
  39557. var is = true;
  39558. eachAxisDim(function (dimNames) {
  39559. var seriesAxisIndex = seriesModel.get(dimNames.axisIndex);
  39560. var axisModel = this.dependentModels[dimNames.axis][seriesAxisIndex];
  39561. if (!axisModel || axisModel.get('type') !== axisType) {
  39562. is = false;
  39563. }
  39564. }, this);
  39565. return is;
  39566. },
  39567. /**
  39568. * @private
  39569. */
  39570. _setDefaultThrottle: function (rawOption) {
  39571. // When first time user set throttle, auto throttle ends.
  39572. if (rawOption.hasOwnProperty('throttle')) {
  39573. this._autoThrottle = false;
  39574. }
  39575. if (this._autoThrottle) {
  39576. var globalOption = this.ecModel.option;
  39577. this.option.throttle =
  39578. (globalOption.animation && globalOption.animationDurationUpdate > 0)
  39579. ? 100 : 20;
  39580. }
  39581. },
  39582. /**
  39583. * @public
  39584. */
  39585. getFirstTargetAxisModel: function () {
  39586. var firstAxisModel;
  39587. eachAxisDim(function (dimNames) {
  39588. if (firstAxisModel == null) {
  39589. var indices = this.get(dimNames.axisIndex);
  39590. if (indices.length) {
  39591. firstAxisModel = this.dependentModels[dimNames.axis][indices[0]];
  39592. }
  39593. }
  39594. }, this);
  39595. return firstAxisModel;
  39596. },
  39597. /**
  39598. * @public
  39599. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  39600. */
  39601. eachTargetAxis: function (callback, context) {
  39602. var ecModel = this.ecModel;
  39603. eachAxisDim(function (dimNames) {
  39604. each$13(
  39605. this.get(dimNames.axisIndex),
  39606. function (axisIndex) {
  39607. callback.call(context, dimNames, axisIndex, this, ecModel);
  39608. },
  39609. this
  39610. );
  39611. }, this);
  39612. },
  39613. /**
  39614. * @param {string} dimName
  39615. * @param {number} axisIndex
  39616. * @return {module:echarts/component/dataZoom/AxisProxy} If not found, return null/undefined.
  39617. */
  39618. getAxisProxy: function (dimName, axisIndex) {
  39619. return this._axisProxies[dimName + '_' + axisIndex];
  39620. },
  39621. /**
  39622. * @param {string} dimName
  39623. * @param {number} axisIndex
  39624. * @return {module:echarts/model/Model} If not found, return null/undefined.
  39625. */
  39626. getAxisModel: function (dimName, axisIndex) {
  39627. var axisProxy = this.getAxisProxy(dimName, axisIndex);
  39628. return axisProxy && axisProxy.getAxisModel();
  39629. },
  39630. /**
  39631. * If not specified, set to undefined.
  39632. *
  39633. * @public
  39634. * @param {Object} opt
  39635. * @param {number} [opt.start]
  39636. * @param {number} [opt.end]
  39637. * @param {number} [opt.startValue]
  39638. * @param {number} [opt.endValue]
  39639. * @param {boolean} [ignoreUpdateRangeUsg=false]
  39640. */
  39641. setRawRange: function (opt, ignoreUpdateRangeUsg) {
  39642. var option = this.option;
  39643. each$13([['start', 'startValue'], ['end', 'endValue']], function (names) {
  39644. // If only one of 'start' and 'startValue' is not null/undefined, the other
  39645. // should be cleared, which enable clear the option.
  39646. // If both of them are not set, keep option with the original value, which
  39647. // enable use only set start but not set end when calling `dispatchAction`.
  39648. // The same as 'end' and 'endValue'.
  39649. if (opt[names[0]] != null || opt[names[1]] != null) {
  39650. option[names[0]] = opt[names[0]];
  39651. option[names[1]] = opt[names[1]];
  39652. }
  39653. }, this);
  39654. !ignoreUpdateRangeUsg && updateRangeUse(this, opt);
  39655. },
  39656. /**
  39657. * @public
  39658. * @return {Array.<number>} [startPercent, endPercent]
  39659. */
  39660. getPercentRange: function () {
  39661. var axisProxy = this.findRepresentativeAxisProxy();
  39662. if (axisProxy) {
  39663. return axisProxy.getDataPercentWindow();
  39664. }
  39665. },
  39666. /**
  39667. * @public
  39668. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  39669. *
  39670. * @param {string} [axisDimName]
  39671. * @param {number} [axisIndex]
  39672. * @return {Array.<number>} [startValue, endValue] value can only be '-' or finite number.
  39673. */
  39674. getValueRange: function (axisDimName, axisIndex) {
  39675. if (axisDimName == null && axisIndex == null) {
  39676. var axisProxy = this.findRepresentativeAxisProxy();
  39677. if (axisProxy) {
  39678. return axisProxy.getDataValueWindow();
  39679. }
  39680. }
  39681. else {
  39682. return this.getAxisProxy(axisDimName, axisIndex).getDataValueWindow();
  39683. }
  39684. },
  39685. /**
  39686. * @public
  39687. * @param {module:echarts/model/Model} [axisModel] If axisModel given, find axisProxy
  39688. * corresponding to the axisModel
  39689. * @return {module:echarts/component/dataZoom/AxisProxy}
  39690. */
  39691. findRepresentativeAxisProxy: function (axisModel) {
  39692. if (axisModel) {
  39693. return axisModel.__dzAxisProxy;
  39694. }
  39695. // Find the first hosted axisProxy
  39696. var axisProxies = this._axisProxies;
  39697. for (var key in axisProxies) {
  39698. if (axisProxies.hasOwnProperty(key) && axisProxies[key].hostedBy(this)) {
  39699. return axisProxies[key];
  39700. }
  39701. }
  39702. // If no hosted axis find not hosted axisProxy.
  39703. // Consider this case: dataZoomModel1 and dataZoomModel2 control the same axis,
  39704. // and the option.start or option.end settings are different. The percentRange
  39705. // should follow axisProxy.
  39706. // (We encounter this problem in toolbox data zoom.)
  39707. for (var key in axisProxies) {
  39708. if (axisProxies.hasOwnProperty(key) && !axisProxies[key].hostedBy(this)) {
  39709. return axisProxies[key];
  39710. }
  39711. }
  39712. },
  39713. /**
  39714. * @return {Array.<string>}
  39715. */
  39716. getRangePropMode: function () {
  39717. return this._rangePropMode.slice();
  39718. }
  39719. });
  39720. function retrieveRaw(option) {
  39721. var ret = {};
  39722. each$13(
  39723. ['start', 'end', 'startValue', 'endValue', 'throttle'],
  39724. function (name) {
  39725. option.hasOwnProperty(name) && (ret[name] = option[name]);
  39726. }
  39727. );
  39728. return ret;
  39729. }
  39730. function updateRangeUse(dataZoomModel, rawOption) {
  39731. var rangePropMode = dataZoomModel._rangePropMode;
  39732. var rangeModeInOption = dataZoomModel.get('rangeMode');
  39733. each$13([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  39734. var percentSpecified = rawOption[names[0]] != null;
  39735. var valueSpecified = rawOption[names[1]] != null;
  39736. if (percentSpecified && !valueSpecified) {
  39737. rangePropMode[index] = 'percent';
  39738. }
  39739. else if (!percentSpecified && valueSpecified) {
  39740. rangePropMode[index] = 'value';
  39741. }
  39742. else if (rangeModeInOption) {
  39743. rangePropMode[index] = rangeModeInOption[index];
  39744. }
  39745. else if (percentSpecified) { // percentSpecified && valueSpecified
  39746. rangePropMode[index] = 'percent';
  39747. }
  39748. // else remain its original setting.
  39749. });
  39750. }
  39751. var DataZoomView = Component$1.extend({
  39752. type: 'dataZoom',
  39753. render: function (dataZoomModel, ecModel, api, payload) {
  39754. this.dataZoomModel = dataZoomModel;
  39755. this.ecModel = ecModel;
  39756. this.api = api;
  39757. },
  39758. /**
  39759. * Find the first target coordinate system.
  39760. *
  39761. * @protected
  39762. * @return {Object} {
  39763. * grid: [
  39764. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  39765. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  39766. * ...
  39767. * ], // cartesians must not be null/undefined.
  39768. * polar: [
  39769. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  39770. * ...
  39771. * ], // polars must not be null/undefined.
  39772. * singleAxis: [
  39773. * {model: coord0, axisModels: [], coordIndex: 0}
  39774. * ]
  39775. */
  39776. getTargetCoordInfo: function () {
  39777. var dataZoomModel = this.dataZoomModel;
  39778. var ecModel = this.ecModel;
  39779. var coordSysLists = {};
  39780. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  39781. var axisModel = ecModel.getComponent(dimNames.axis, axisIndex);
  39782. if (axisModel) {
  39783. var coordModel = axisModel.getCoordSysModel();
  39784. coordModel && save(
  39785. coordModel,
  39786. axisModel,
  39787. coordSysLists[coordModel.mainType] || (coordSysLists[coordModel.mainType] = []),
  39788. coordModel.componentIndex
  39789. );
  39790. }
  39791. }, this);
  39792. function save(coordModel, axisModel, store, coordIndex) {
  39793. var item;
  39794. for (var i = 0; i < store.length; i++) {
  39795. if (store[i].model === coordModel) {
  39796. item = store[i];
  39797. break;
  39798. }
  39799. }
  39800. if (!item) {
  39801. store.push(item = {
  39802. model: coordModel, axisModels: [], coordIndex: coordIndex
  39803. });
  39804. }
  39805. item.axisModels.push(axisModel);
  39806. }
  39807. return coordSysLists;
  39808. }
  39809. });
  39810. var SliderZoomModel = DataZoomModel.extend({
  39811. type: 'dataZoom.slider',
  39812. layoutMode: 'box',
  39813. /**
  39814. * @protected
  39815. */
  39816. defaultOption: {
  39817. show: true,
  39818. // ph => placeholder. Using placehoder here because
  39819. // deault value can only be drived in view stage.
  39820. right: 'ph', // Default align to grid rect.
  39821. top: 'ph', // Default align to grid rect.
  39822. width: 'ph', // Default align to grid rect.
  39823. height: 'ph', // Default align to grid rect.
  39824. left: null, // Default align to grid rect.
  39825. bottom: null, // Default align to grid rect.
  39826. backgroundColor: 'rgba(47,69,84,0)', // Background of slider zoom component.
  39827. // dataBackgroundColor: '#ddd', // Background coor of data shadow and border of box,
  39828. // highest priority, remain for compatibility of
  39829. // previous version, but not recommended any more.
  39830. dataBackground: {
  39831. lineStyle: {
  39832. color: '#2f4554',
  39833. width: 0.5,
  39834. opacity: 0.3
  39835. },
  39836. areaStyle: {
  39837. color: 'rgba(47,69,84,0.3)',
  39838. opacity: 0.3
  39839. }
  39840. },
  39841. borderColor: '#ddd', // border color of the box. For compatibility,
  39842. // if dataBackgroundColor is set, borderColor
  39843. // is ignored.
  39844. fillerColor: 'rgba(167,183,204,0.4)', // Color of selected area.
  39845. // handleColor: 'rgba(89,170,216,0.95)', // Color of handle.
  39846. // handleIcon: 'path://M4.9,17.8c0-1.4,4.5-10.5,5.5-12.4c0-0.1,0.6-1.1,0.9-1.1c0.4,0,0.9,1,0.9,1.1c1.1,2.2,5.4,11,5.4,12.4v17.8c0,1.5-0.6,2.1-1.3,2.1H6.1c-0.7,0-1.3-0.6-1.3-2.1V17.8z',
  39847. handleIcon: 'M8.2,13.6V3.9H6.3v9.7H3.1v14.9h3.3v9.7h1.8v-9.7h3.3V13.6H8.2z M9.7,24.4H4.8v-1.4h4.9V24.4z M9.7,19.1H4.8v-1.4h4.9V19.1z',
  39848. // Percent of the slider height
  39849. handleSize: '100%',
  39850. handleStyle: {
  39851. color: '#a7b7cc'
  39852. },
  39853. labelPrecision: null,
  39854. labelFormatter: null,
  39855. showDetail: true,
  39856. showDataShadow: 'auto', // Default auto decision.
  39857. realtime: true,
  39858. zoomLock: false, // Whether disable zoom.
  39859. textStyle: {
  39860. color: '#333'
  39861. }
  39862. }
  39863. });
  39864. /**
  39865. * Calculate slider move result.
  39866. * Usage:
  39867. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  39868. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  39869. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  39870. *
  39871. * @param {number} delta Move length.
  39872. * @param {Array.<number>} handleEnds handleEnds[0] can be bigger then handleEnds[1].
  39873. * handleEnds will be modified in this method.
  39874. * @param {Array.<number>} extent handleEnds is restricted by extent.
  39875. * extent[0] should less or equals than extent[1].
  39876. * @param {number|string} handleIndex Can be 'all', means that both move the two handleEnds,
  39877. * where the input minSpan and maxSpan will not work.
  39878. * @param {number} [minSpan] The range of dataZoom can not be smaller than that.
  39879. * If not set, handle0 and cross handle1. If set as a non-negative
  39880. * number (including `0`), handles will push each other when reaching
  39881. * the minSpan.
  39882. * @param {number} [maxSpan] The range of dataZoom can not be larger than that.
  39883. * @return {Array.<number>} The input handleEnds.
  39884. */
  39885. var sliderMove = function (delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  39886. // Normalize firstly.
  39887. handleEnds[0] = restrict(handleEnds[0], extent);
  39888. handleEnds[1] = restrict(handleEnds[1], extent);
  39889. delta = delta || 0;
  39890. var extentSpan = extent[1] - extent[0];
  39891. // Notice maxSpan and minSpan can be null/undefined.
  39892. if (minSpan != null) {
  39893. minSpan = restrict(minSpan, [0, extentSpan]);
  39894. }
  39895. if (maxSpan != null) {
  39896. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  39897. }
  39898. if (handleIndex === 'all') {
  39899. minSpan = maxSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  39900. handleIndex = 0;
  39901. }
  39902. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  39903. handleEnds[handleIndex] += delta;
  39904. // Restrict in extent.
  39905. var extentMinSpan = minSpan || 0;
  39906. var realExtent = extent.slice();
  39907. originalDistSign.sign < 0 ? (realExtent[0] += extentMinSpan) : (realExtent[1] -= extentMinSpan);
  39908. handleEnds[handleIndex] = restrict(handleEnds[handleIndex], realExtent);
  39909. // Expand span.
  39910. var currDistSign = getSpanSign(handleEnds, handleIndex);
  39911. if (minSpan != null && (
  39912. currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan
  39913. )) {
  39914. // If minSpan exists, 'cross' is forbinden.
  39915. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  39916. }
  39917. // Shrink span.
  39918. var currDistSign = getSpanSign(handleEnds, handleIndex);
  39919. if (maxSpan != null && currDistSign.span > maxSpan) {
  39920. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  39921. }
  39922. return handleEnds;
  39923. };
  39924. function getSpanSign(handleEnds, handleIndex) {
  39925. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex];
  39926. // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  39927. // is at left of handleEnds[1] for non-cross case.
  39928. return {span: Math.abs(dist), sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1};
  39929. }
  39930. function restrict(value, extend) {
  39931. return Math.min(extend[1], Math.max(extend[0], value));
  39932. }
  39933. var Rect$1 = Rect;
  39934. var linearMap$2 = linearMap;
  39935. var asc$2 = asc;
  39936. var bind$3 = bind;
  39937. var each$15 = each$1;
  39938. // Constants
  39939. var DEFAULT_LOCATION_EDGE_GAP = 7;
  39940. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  39941. var DEFAULT_FILLER_SIZE = 30;
  39942. var HORIZONTAL = 'horizontal';
  39943. var VERTICAL = 'vertical';
  39944. var LABEL_GAP = 5;
  39945. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  39946. var SliderZoomView = DataZoomView.extend({
  39947. type: 'dataZoom.slider',
  39948. init: function (ecModel, api) {
  39949. /**
  39950. * @private
  39951. * @type {Object}
  39952. */
  39953. this._displayables = {};
  39954. /**
  39955. * @private
  39956. * @type {string}
  39957. */
  39958. this._orient;
  39959. /**
  39960. * [0, 100]
  39961. * @private
  39962. */
  39963. this._range;
  39964. /**
  39965. * [coord of the first handle, coord of the second handle]
  39966. * @private
  39967. */
  39968. this._handleEnds;
  39969. /**
  39970. * [length, thick]
  39971. * @private
  39972. * @type {Array.<number>}
  39973. */
  39974. this._size;
  39975. /**
  39976. * @private
  39977. * @type {number}
  39978. */
  39979. this._handleWidth;
  39980. /**
  39981. * @private
  39982. * @type {number}
  39983. */
  39984. this._handleHeight;
  39985. /**
  39986. * @private
  39987. */
  39988. this._location;
  39989. /**
  39990. * @private
  39991. */
  39992. this._dragging;
  39993. /**
  39994. * @private
  39995. */
  39996. this._dataShadowInfo;
  39997. this.api = api;
  39998. },
  39999. /**
  40000. * @override
  40001. */
  40002. render: function (dataZoomModel, ecModel, api, payload) {
  40003. SliderZoomView.superApply(this, 'render', arguments);
  40004. createOrUpdate(
  40005. this,
  40006. '_dispatchZoomAction',
  40007. this.dataZoomModel.get('throttle'),
  40008. 'fixRate'
  40009. );
  40010. this._orient = dataZoomModel.get('orient');
  40011. if (this.dataZoomModel.get('show') === false) {
  40012. this.group.removeAll();
  40013. return;
  40014. }
  40015. // Notice: this._resetInterval() should not be executed when payload.type
  40016. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  40017. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  40018. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  40019. this._buildView();
  40020. }
  40021. this._updateView();
  40022. },
  40023. /**
  40024. * @override
  40025. */
  40026. remove: function () {
  40027. SliderZoomView.superApply(this, 'remove', arguments);
  40028. clear(this, '_dispatchZoomAction');
  40029. },
  40030. /**
  40031. * @override
  40032. */
  40033. dispose: function () {
  40034. SliderZoomView.superApply(this, 'dispose', arguments);
  40035. clear(this, '_dispatchZoomAction');
  40036. },
  40037. _buildView: function () {
  40038. var thisGroup = this.group;
  40039. thisGroup.removeAll();
  40040. this._resetLocation();
  40041. this._resetInterval();
  40042. var barGroup = this._displayables.barGroup = new Group();
  40043. this._renderBackground();
  40044. this._renderHandle();
  40045. this._renderDataShadow();
  40046. thisGroup.add(barGroup);
  40047. this._positionGroup();
  40048. },
  40049. /**
  40050. * @private
  40051. */
  40052. _resetLocation: function () {
  40053. var dataZoomModel = this.dataZoomModel;
  40054. var api = this.api;
  40055. // If some of x/y/width/height are not specified,
  40056. // auto-adapt according to target grid.
  40057. var coordRect = this._findCoordRect();
  40058. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  40059. // Default align by coordinate system rect.
  40060. var positionInfo = this._orient === HORIZONTAL
  40061. ? {
  40062. // Why using 'right', because right should be used in vertical,
  40063. // and it is better to be consistent for dealing with position param merge.
  40064. right: ecSize.width - coordRect.x - coordRect.width,
  40065. top: (ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP),
  40066. width: coordRect.width,
  40067. height: DEFAULT_FILLER_SIZE
  40068. }
  40069. : { // vertical
  40070. right: DEFAULT_LOCATION_EDGE_GAP,
  40071. top: coordRect.y,
  40072. width: DEFAULT_FILLER_SIZE,
  40073. height: coordRect.height
  40074. };
  40075. // Do not write back to option and replace value 'ph', because
  40076. // the 'ph' value should be recalculated when resize.
  40077. var layoutParams = getLayoutParams(dataZoomModel.option);
  40078. // Replace the placeholder value.
  40079. each$1(['right', 'top', 'width', 'height'], function (name) {
  40080. if (layoutParams[name] === 'ph') {
  40081. layoutParams[name] = positionInfo[name];
  40082. }
  40083. });
  40084. var layoutRect = getLayoutRect(
  40085. layoutParams,
  40086. ecSize,
  40087. dataZoomModel.padding
  40088. );
  40089. this._location = {x: layoutRect.x, y: layoutRect.y};
  40090. this._size = [layoutRect.width, layoutRect.height];
  40091. this._orient === VERTICAL && this._size.reverse();
  40092. },
  40093. /**
  40094. * @private
  40095. */
  40096. _positionGroup: function () {
  40097. var thisGroup = this.group;
  40098. var location = this._location;
  40099. var orient = this._orient;
  40100. // Just use the first axis to determine mapping.
  40101. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  40102. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  40103. var barGroup = this._displayables.barGroup;
  40104. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse;
  40105. // Transform barGroup.
  40106. barGroup.attr(
  40107. (orient === HORIZONTAL && !inverse)
  40108. ? {scale: otherAxisInverse ? [1, 1] : [1, -1]}
  40109. : (orient === HORIZONTAL && inverse)
  40110. ? {scale: otherAxisInverse ? [-1, 1] : [-1, -1]}
  40111. : (orient === VERTICAL && !inverse)
  40112. ? {scale: otherAxisInverse ? [1, -1] : [1, 1], rotation: Math.PI / 2}
  40113. // Dont use Math.PI, considering shadow direction.
  40114. : {scale: otherAxisInverse ? [-1, -1] : [-1, 1], rotation: Math.PI / 2}
  40115. );
  40116. // Position barGroup
  40117. var rect = thisGroup.getBoundingRect([barGroup]);
  40118. thisGroup.attr('position', [location.x - rect.x, location.y - rect.y]);
  40119. },
  40120. /**
  40121. * @private
  40122. */
  40123. _getViewExtent: function () {
  40124. return [0, this._size[0]];
  40125. },
  40126. _renderBackground: function () {
  40127. var dataZoomModel = this.dataZoomModel;
  40128. var size = this._size;
  40129. var barGroup = this._displayables.barGroup;
  40130. barGroup.add(new Rect$1({
  40131. silent: true,
  40132. shape: {
  40133. x: 0, y: 0, width: size[0], height: size[1]
  40134. },
  40135. style: {
  40136. fill: dataZoomModel.get('backgroundColor')
  40137. },
  40138. z2: -40
  40139. }));
  40140. // Click panel, over shadow, below handles.
  40141. barGroup.add(new Rect$1({
  40142. shape: {
  40143. x: 0, y: 0, width: size[0], height: size[1]
  40144. },
  40145. style: {
  40146. fill: 'transparent'
  40147. },
  40148. z2: 0,
  40149. onclick: bind(this._onClickPanelClick, this)
  40150. }));
  40151. },
  40152. _renderDataShadow: function () {
  40153. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  40154. if (!info) {
  40155. return;
  40156. }
  40157. var size = this._size;
  40158. var seriesModel = info.series;
  40159. var data = seriesModel.getRawData();
  40160. var otherDim = seriesModel.getShadowDim
  40161. ? seriesModel.getShadowDim() // @see candlestick
  40162. : info.otherDim;
  40163. if (otherDim == null) {
  40164. return;
  40165. }
  40166. var otherDataExtent = data.getDataExtent(otherDim);
  40167. // Nice extent.
  40168. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
  40169. otherDataExtent = [
  40170. otherDataExtent[0] - otherOffset,
  40171. otherDataExtent[1] + otherOffset
  40172. ];
  40173. var otherShadowExtent = [0, size[1]];
  40174. var thisShadowExtent = [0, size[0]];
  40175. var areaPoints = [[size[0], 0], [0, 0]];
  40176. var linePoints = [];
  40177. var step = thisShadowExtent[1] / (data.count() - 1);
  40178. var thisCoord = 0;
  40179. // Optimize for large data shadow
  40180. var stride = Math.round(data.count() / size[0]);
  40181. var lastIsEmpty;
  40182. data.each([otherDim], function (value, index) {
  40183. if (stride > 0 && (index % stride)) {
  40184. thisCoord += step;
  40185. return;
  40186. }
  40187. // FIXME
  40188. // Should consider axis.min/axis.max when drawing dataShadow.
  40189. // FIXME
  40190. // 应该使用统一的空判断?还是在list里进行空判断?
  40191. var isEmpty = value == null || isNaN(value) || value === '';
  40192. // See #4235.
  40193. var otherCoord = isEmpty
  40194. ? 0 : linearMap$2(value, otherDataExtent, otherShadowExtent, true);
  40195. // Attempt to draw data shadow precisely when there are empty value.
  40196. if (isEmpty && !lastIsEmpty && index) {
  40197. areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
  40198. linePoints.push([linePoints[linePoints.length - 1][0], 0]);
  40199. }
  40200. else if (!isEmpty && lastIsEmpty) {
  40201. areaPoints.push([thisCoord, 0]);
  40202. linePoints.push([thisCoord, 0]);
  40203. }
  40204. areaPoints.push([thisCoord, otherCoord]);
  40205. linePoints.push([thisCoord, otherCoord]);
  40206. thisCoord += step;
  40207. lastIsEmpty = isEmpty;
  40208. });
  40209. var dataZoomModel = this.dataZoomModel;
  40210. // var dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  40211. this._displayables.barGroup.add(new Polygon({
  40212. shape: {points: areaPoints},
  40213. style: defaults(
  40214. {fill: dataZoomModel.get('dataBackgroundColor')},
  40215. dataZoomModel.getModel('dataBackground.areaStyle').getAreaStyle()
  40216. ),
  40217. silent: true,
  40218. z2: -20
  40219. }));
  40220. this._displayables.barGroup.add(new Polyline({
  40221. shape: {points: linePoints},
  40222. style: dataZoomModel.getModel('dataBackground.lineStyle').getLineStyle(),
  40223. silent: true,
  40224. z2: -19
  40225. }));
  40226. },
  40227. _prepareDataShadowInfo: function () {
  40228. var dataZoomModel = this.dataZoomModel;
  40229. var showDataShadow = dataZoomModel.get('showDataShadow');
  40230. if (showDataShadow === false) {
  40231. return;
  40232. }
  40233. // Find a representative series.
  40234. var result;
  40235. var ecModel = this.ecModel;
  40236. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  40237. var seriesModels = dataZoomModel
  40238. .getAxisProxy(dimNames.name, axisIndex)
  40239. .getTargetSeriesModels();
  40240. each$1(seriesModels, function (seriesModel) {
  40241. if (result) {
  40242. return;
  40243. }
  40244. if (showDataShadow !== true && indexOf(
  40245. SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')
  40246. ) < 0
  40247. ) {
  40248. return;
  40249. }
  40250. var thisAxis = ecModel.getComponent(dimNames.axis, axisIndex).axis;
  40251. var otherDim = getOtherDim(dimNames.name);
  40252. var otherAxisInverse;
  40253. var coordSys = seriesModel.coordinateSystem;
  40254. if (otherDim != null && coordSys.getOtherAxis) {
  40255. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  40256. }
  40257. otherDim = seriesModel.getData().mapDimension(otherDim);
  40258. result = {
  40259. thisAxis: thisAxis,
  40260. series: seriesModel,
  40261. thisDim: dimNames.name,
  40262. otherDim: otherDim,
  40263. otherAxisInverse: otherAxisInverse
  40264. };
  40265. }, this);
  40266. }, this);
  40267. return result;
  40268. },
  40269. _renderHandle: function () {
  40270. var displaybles = this._displayables;
  40271. var handles = displaybles.handles = [];
  40272. var handleLabels = displaybles.handleLabels = [];
  40273. var barGroup = this._displayables.barGroup;
  40274. var size = this._size;
  40275. var dataZoomModel = this.dataZoomModel;
  40276. barGroup.add(displaybles.filler = new Rect$1({
  40277. draggable: true,
  40278. cursor: getCursor(this._orient),
  40279. drift: bind$3(this._onDragMove, this, 'all'),
  40280. onmousemove: function (e) {
  40281. // Fot mobile devicem, prevent screen slider on the button.
  40282. stop(e.event);
  40283. },
  40284. ondragstart: bind$3(this._showDataInfo, this, true),
  40285. ondragend: bind$3(this._onDragEnd, this),
  40286. onmouseover: bind$3(this._showDataInfo, this, true),
  40287. onmouseout: bind$3(this._showDataInfo, this, false),
  40288. style: {
  40289. fill: dataZoomModel.get('fillerColor'),
  40290. textPosition : 'inside'
  40291. }
  40292. }));
  40293. // Frame border.
  40294. barGroup.add(new Rect$1(subPixelOptimizeRect({
  40295. silent: true,
  40296. shape: {
  40297. x: 0,
  40298. y: 0,
  40299. width: size[0],
  40300. height: size[1]
  40301. },
  40302. style: {
  40303. stroke: dataZoomModel.get('dataBackgroundColor')
  40304. || dataZoomModel.get('borderColor'),
  40305. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  40306. fill: 'rgba(0,0,0,0)'
  40307. }
  40308. })));
  40309. each$15([0, 1], function (handleIndex) {
  40310. var path = createIcon(
  40311. dataZoomModel.get('handleIcon'),
  40312. {
  40313. cursor: getCursor(this._orient),
  40314. draggable: true,
  40315. drift: bind$3(this._onDragMove, this, handleIndex),
  40316. onmousemove: function (e) {
  40317. // Fot mobile devicem, prevent screen slider on the button.
  40318. stop(e.event);
  40319. },
  40320. ondragend: bind$3(this._onDragEnd, this),
  40321. onmouseover: bind$3(this._showDataInfo, this, true),
  40322. onmouseout: bind$3(this._showDataInfo, this, false)
  40323. },
  40324. {x: -1, y: 0, width: 2, height: 2}
  40325. );
  40326. var bRect = path.getBoundingRect();
  40327. this._handleHeight = parsePercent$1(dataZoomModel.get('handleSize'), this._size[1]);
  40328. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  40329. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  40330. var handleColor = dataZoomModel.get('handleColor');
  40331. // Compatitable with previous version
  40332. if (handleColor != null) {
  40333. path.style.fill = handleColor;
  40334. }
  40335. barGroup.add(handles[handleIndex] = path);
  40336. var textStyleModel = dataZoomModel.textStyleModel;
  40337. this.group.add(
  40338. handleLabels[handleIndex] = new Text({
  40339. silent: true,
  40340. invisible: true,
  40341. style: {
  40342. x: 0, y: 0, text: '',
  40343. textVerticalAlign: 'middle',
  40344. textAlign: 'center',
  40345. textFill: textStyleModel.getTextColor(),
  40346. textFont: textStyleModel.getFont()
  40347. },
  40348. z2: 10
  40349. }));
  40350. }, this);
  40351. },
  40352. /**
  40353. * @private
  40354. */
  40355. _resetInterval: function () {
  40356. var range = this._range = this.dataZoomModel.getPercentRange();
  40357. var viewExtent = this._getViewExtent();
  40358. this._handleEnds = [
  40359. linearMap$2(range[0], [0, 100], viewExtent, true),
  40360. linearMap$2(range[1], [0, 100], viewExtent, true)
  40361. ];
  40362. },
  40363. /**
  40364. * @private
  40365. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  40366. * @param {number} delta
  40367. */
  40368. _updateInterval: function (handleIndex, delta) {
  40369. var dataZoomModel = this.dataZoomModel;
  40370. var handleEnds = this._handleEnds;
  40371. var viewExtend = this._getViewExtent();
  40372. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  40373. var percentExtent = [0, 100];
  40374. sliderMove(
  40375. delta,
  40376. handleEnds,
  40377. viewExtend,
  40378. dataZoomModel.get('zoomLock') ? 'all' : handleIndex,
  40379. minMaxSpan.minSpan != null
  40380. ? linearMap$2(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null,
  40381. minMaxSpan.maxSpan != null
  40382. ? linearMap$2(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null
  40383. );
  40384. this._range = asc$2([
  40385. linearMap$2(handleEnds[0], viewExtend, percentExtent, true),
  40386. linearMap$2(handleEnds[1], viewExtend, percentExtent, true)
  40387. ]);
  40388. },
  40389. /**
  40390. * @private
  40391. */
  40392. _updateView: function (nonRealtime) {
  40393. var displaybles = this._displayables;
  40394. var handleEnds = this._handleEnds;
  40395. var handleInterval = asc$2(handleEnds.slice());
  40396. var size = this._size;
  40397. each$15([0, 1], function (handleIndex) {
  40398. // Handles
  40399. var handle = displaybles.handles[handleIndex];
  40400. var handleHeight = this._handleHeight;
  40401. handle.attr({
  40402. scale: [handleHeight / 2, handleHeight / 2],
  40403. position: [handleEnds[handleIndex], size[1] / 2 - handleHeight / 2]
  40404. });
  40405. }, this);
  40406. // Filler
  40407. displaybles.filler.setShape({
  40408. x: handleInterval[0],
  40409. y: 0,
  40410. width: handleInterval[1] - handleInterval[0],
  40411. height: size[1]
  40412. });
  40413. this._updateDataInfo(nonRealtime);
  40414. },
  40415. /**
  40416. * @private
  40417. */
  40418. _updateDataInfo: function (nonRealtime) {
  40419. var dataZoomModel = this.dataZoomModel;
  40420. var displaybles = this._displayables;
  40421. var handleLabels = displaybles.handleLabels;
  40422. var orient = this._orient;
  40423. var labelTexts = ['', ''];
  40424. // FIXME
  40425. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  40426. if (dataZoomModel.get('showDetail')) {
  40427. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  40428. if (axisProxy) {
  40429. var axis = axisProxy.getAxisModel().axis;
  40430. var range = this._range;
  40431. var dataInterval = nonRealtime
  40432. // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  40433. ? axisProxy.calculateDataWindow({
  40434. start: range[0], end: range[1]
  40435. }).valueWindow
  40436. : axisProxy.getDataValueWindow();
  40437. labelTexts = [
  40438. this._formatLabel(dataInterval[0], axis),
  40439. this._formatLabel(dataInterval[1], axis)
  40440. ];
  40441. }
  40442. }
  40443. var orderedHandleEnds = asc$2(this._handleEnds.slice());
  40444. setLabel.call(this, 0);
  40445. setLabel.call(this, 1);
  40446. function setLabel(handleIndex) {
  40447. // Label
  40448. // Text should not transform by barGroup.
  40449. // Ignore handlers transform
  40450. var barTransform = getTransform(
  40451. displaybles.handles[handleIndex].parent, this.group
  40452. );
  40453. var direction = transformDirection(
  40454. handleIndex === 0 ? 'right' : 'left', barTransform
  40455. );
  40456. var offset = this._handleWidth / 2 + LABEL_GAP;
  40457. var textPoint = applyTransform$1(
  40458. [
  40459. orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset),
  40460. this._size[1] / 2
  40461. ],
  40462. barTransform
  40463. );
  40464. handleLabels[handleIndex].setStyle({
  40465. x: textPoint[0],
  40466. y: textPoint[1],
  40467. textVerticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  40468. textAlign: orient === HORIZONTAL ? direction : 'center',
  40469. text: labelTexts[handleIndex]
  40470. });
  40471. }
  40472. },
  40473. /**
  40474. * @private
  40475. */
  40476. _formatLabel: function (value, axis) {
  40477. var dataZoomModel = this.dataZoomModel;
  40478. var labelFormatter = dataZoomModel.get('labelFormatter');
  40479. var labelPrecision = dataZoomModel.get('labelPrecision');
  40480. if (labelPrecision == null || labelPrecision === 'auto') {
  40481. labelPrecision = axis.getPixelPrecision();
  40482. }
  40483. var valueStr = (value == null || isNaN(value))
  40484. ? ''
  40485. // FIXME Glue code
  40486. : (axis.type === 'category' || axis.type === 'time')
  40487. ? axis.scale.getLabel(Math.round(value))
  40488. // param of toFixed should less then 20.
  40489. : value.toFixed(Math.min(labelPrecision, 20));
  40490. return isFunction$1(labelFormatter)
  40491. ? labelFormatter(value, valueStr)
  40492. : isString(labelFormatter)
  40493. ? labelFormatter.replace('{value}', valueStr)
  40494. : valueStr;
  40495. },
  40496. /**
  40497. * @private
  40498. * @param {boolean} showOrHide true: show, false: hide
  40499. */
  40500. _showDataInfo: function (showOrHide) {
  40501. // Always show when drgging.
  40502. showOrHide = this._dragging || showOrHide;
  40503. var handleLabels = this._displayables.handleLabels;
  40504. handleLabels[0].attr('invisible', !showOrHide);
  40505. handleLabels[1].attr('invisible', !showOrHide);
  40506. },
  40507. _onDragMove: function (handleIndex, dx, dy) {
  40508. this._dragging = true;
  40509. // Transform dx, dy to bar coordination.
  40510. var barTransform = this._displayables.barGroup.getLocalTransform();
  40511. var vertex = applyTransform$1([dx, dy], barTransform, true);
  40512. this._updateInterval(handleIndex, vertex[0]);
  40513. var realtime = this.dataZoomModel.get('realtime');
  40514. this._updateView(!realtime);
  40515. realtime && this._dispatchZoomAction();
  40516. },
  40517. _onDragEnd: function () {
  40518. this._dragging = false;
  40519. this._showDataInfo(false);
  40520. // While in realtime mode and stream mode, dispatch action when
  40521. // drag end will cause the whole view rerender, which is unnecessary.
  40522. var realtime = this.dataZoomModel.get('realtime');
  40523. !realtime && this._dispatchZoomAction();
  40524. },
  40525. _onClickPanelClick: function (e) {
  40526. var size = this._size;
  40527. var localPoint = this._displayables.barGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  40528. if (localPoint[0] < 0 || localPoint[0] > size[0]
  40529. || localPoint[1] < 0 || localPoint[1] > size[1]
  40530. ) {
  40531. return;
  40532. }
  40533. var handleEnds = this._handleEnds;
  40534. var center = (handleEnds[0] + handleEnds[1]) / 2;
  40535. this._updateInterval('all', localPoint[0] - center);
  40536. this._updateView();
  40537. this._dispatchZoomAction();
  40538. },
  40539. /**
  40540. * This action will be throttled.
  40541. * @private
  40542. */
  40543. _dispatchZoomAction: function () {
  40544. var range = this._range;
  40545. this.api.dispatchAction({
  40546. type: 'dataZoom',
  40547. from: this.uid,
  40548. dataZoomId: this.dataZoomModel.id,
  40549. start: range[0],
  40550. end: range[1]
  40551. });
  40552. },
  40553. /**
  40554. * @private
  40555. */
  40556. _findCoordRect: function () {
  40557. // Find the grid coresponding to the first axis referred by dataZoom.
  40558. var rect;
  40559. each$15(this.getTargetCoordInfo(), function (coordInfoList) {
  40560. if (!rect && coordInfoList.length) {
  40561. var coordSys = coordInfoList[0].model.coordinateSystem;
  40562. rect = coordSys.getRect && coordSys.getRect();
  40563. }
  40564. });
  40565. if (!rect) {
  40566. var width = this.api.getWidth();
  40567. var height = this.api.getHeight();
  40568. rect = {
  40569. x: width * 0.2,
  40570. y: height * 0.2,
  40571. width: width * 0.6,
  40572. height: height * 0.6
  40573. };
  40574. }
  40575. return rect;
  40576. }
  40577. });
  40578. function getOtherDim(thisDim) {
  40579. // FIXME
  40580. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  40581. var map$$1 = {x: 'y', y: 'x', radius: 'angle', angle: 'radius'};
  40582. return map$$1[thisDim];
  40583. }
  40584. function getCursor(orient) {
  40585. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  40586. }
  40587. DataZoomModel.extend({
  40588. type: 'dataZoom.inside',
  40589. /**
  40590. * @protected
  40591. */
  40592. defaultOption: {
  40593. disabled: false, // Whether disable this inside zoom.
  40594. zoomLock: false, // Whether disable zoom but only pan.
  40595. zoomOnMouseWheel: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  40596. moveOnMouseMove: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  40597. preventDefaultMouseMove: true
  40598. }
  40599. });
  40600. var ATTR$1 = '\0_ec_interaction_mutex';
  40601. function take(zr, resourceKey, userKey) {
  40602. var store = getStore(zr);
  40603. store[resourceKey] = userKey;
  40604. }
  40605. function release(zr, resourceKey, userKey) {
  40606. var store = getStore(zr);
  40607. var uKey = store[resourceKey];
  40608. if (uKey === userKey) {
  40609. store[resourceKey] = null;
  40610. }
  40611. }
  40612. function isTaken(zr, resourceKey) {
  40613. return !!getStore(zr)[resourceKey];
  40614. }
  40615. function getStore(zr) {
  40616. return zr[ATTR$1] || (zr[ATTR$1] = {});
  40617. }
  40618. /**
  40619. * payload: {
  40620. * type: 'takeGlobalCursor',
  40621. * key: 'dataZoomSelect', or 'brush', or ...,
  40622. * If no userKey, release global cursor.
  40623. * }
  40624. */
  40625. registerAction(
  40626. {type: 'takeGlobalCursor', event: 'globalCursorTaken', update: 'update'},
  40627. function () {}
  40628. );
  40629. /**
  40630. * @alias module:echarts/component/helper/RoamController
  40631. * @constructor
  40632. * @mixin {module:zrender/mixin/Eventful}
  40633. *
  40634. * @param {module:zrender/zrender~ZRender} zr
  40635. */
  40636. function RoamController(zr) {
  40637. /**
  40638. * @type {Function}
  40639. */
  40640. this.pointerChecker;
  40641. /**
  40642. * @type {module:zrender}
  40643. */
  40644. this._zr = zr;
  40645. /**
  40646. * @type {Object}
  40647. */
  40648. this._opt = {};
  40649. // Avoid two roamController bind the same handler
  40650. var bind$$1 = bind;
  40651. var mousedownHandler = bind$$1(mousedown, this);
  40652. var mousemoveHandler = bind$$1(mousemove, this);
  40653. var mouseupHandler = bind$$1(mouseup, this);
  40654. var mousewheelHandler = bind$$1(mousewheel, this);
  40655. var pinchHandler = bind$$1(pinch, this);
  40656. Eventful.call(this);
  40657. /**
  40658. * @param {Function} pointerChecker
  40659. * input: x, y
  40660. * output: boolean
  40661. */
  40662. this.setPointerChecker = function (pointerChecker) {
  40663. this.pointerChecker = pointerChecker;
  40664. };
  40665. /**
  40666. * Notice: only enable needed types. For example, if 'zoom'
  40667. * is not needed, 'zoom' should not be enabled, otherwise
  40668. * default mousewheel behaviour (scroll page) will be disabled.
  40669. *
  40670. * @param {boolean|string} [controlType=true] Specify the control type,
  40671. * which can be null/undefined or true/false
  40672. * or 'pan/move' or 'zoom'/'scale'
  40673. * @param {Object} [opt]
  40674. * @param {Object} [opt.zoomOnMouseWheel=true]
  40675. * @param {Object} [opt.moveOnMouseMove=true]
  40676. * @param {Object} [opt.preventDefaultMouseMove=true] When pan.
  40677. */
  40678. this.enable = function (controlType, opt) {
  40679. // Disable previous first
  40680. this.disable();
  40681. this._opt = defaults(clone(opt) || {}, {
  40682. zoomOnMouseWheel: true,
  40683. moveOnMouseMove: true,
  40684. preventDefaultMouseMove: true
  40685. });
  40686. if (controlType == null) {
  40687. controlType = true;
  40688. }
  40689. if (controlType === true || (controlType === 'move' || controlType === 'pan')) {
  40690. zr.on('mousedown', mousedownHandler);
  40691. zr.on('mousemove', mousemoveHandler);
  40692. zr.on('mouseup', mouseupHandler);
  40693. }
  40694. if (controlType === true || (controlType === 'scale' || controlType === 'zoom')) {
  40695. zr.on('mousewheel', mousewheelHandler);
  40696. zr.on('pinch', pinchHandler);
  40697. }
  40698. };
  40699. this.disable = function () {
  40700. zr.off('mousedown', mousedownHandler);
  40701. zr.off('mousemove', mousemoveHandler);
  40702. zr.off('mouseup', mouseupHandler);
  40703. zr.off('mousewheel', mousewheelHandler);
  40704. zr.off('pinch', pinchHandler);
  40705. };
  40706. this.dispose = this.disable;
  40707. this.isDragging = function () {
  40708. return this._dragging;
  40709. };
  40710. this.isPinching = function () {
  40711. return this._pinching;
  40712. };
  40713. }
  40714. mixin(RoamController, Eventful);
  40715. function mousedown(e) {
  40716. if (notLeftMouse(e)
  40717. || (e.target && e.target.draggable)
  40718. ) {
  40719. return;
  40720. }
  40721. var x = e.offsetX;
  40722. var y = e.offsetY;
  40723. // Only check on mosedown, but not mousemove.
  40724. // Mouse can be out of target when mouse moving.
  40725. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  40726. this._x = x;
  40727. this._y = y;
  40728. this._dragging = true;
  40729. }
  40730. }
  40731. function mousemove(e) {
  40732. if (notLeftMouse(e)
  40733. || !checkKeyBinding(this, 'moveOnMouseMove', e)
  40734. || !this._dragging
  40735. || e.gestureEvent === 'pinch'
  40736. || isTaken(this._zr, 'globalPan')
  40737. ) {
  40738. return;
  40739. }
  40740. var x = e.offsetX;
  40741. var y = e.offsetY;
  40742. var oldX = this._x;
  40743. var oldY = this._y;
  40744. var dx = x - oldX;
  40745. var dy = y - oldY;
  40746. this._x = x;
  40747. this._y = y;
  40748. this._opt.preventDefaultMouseMove && stop(e.event);
  40749. this.trigger('pan', dx, dy, oldX, oldY, x, y);
  40750. }
  40751. function mouseup(e) {
  40752. if (!notLeftMouse(e)) {
  40753. this._dragging = false;
  40754. }
  40755. }
  40756. function mousewheel(e) {
  40757. // wheelDelta maybe -0 in chrome mac.
  40758. if (!checkKeyBinding(this, 'zoomOnMouseWheel', e) || e.wheelDelta === 0) {
  40759. return;
  40760. }
  40761. // Convenience:
  40762. // Mac and VM Windows on Mac: scroll up: zoom out.
  40763. // Windows: scroll up: zoom in.
  40764. var zoomDelta = e.wheelDelta > 0 ? 1.1 : 1 / 1.1;
  40765. zoom.call(this, e, zoomDelta, e.offsetX, e.offsetY);
  40766. }
  40767. function pinch(e) {
  40768. if (isTaken(this._zr, 'globalPan')) {
  40769. return;
  40770. }
  40771. var zoomDelta = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  40772. zoom.call(this, e, zoomDelta, e.pinchX, e.pinchY);
  40773. }
  40774. function zoom(e, zoomDelta, zoomX, zoomY) {
  40775. if (this.pointerChecker && this.pointerChecker(e, zoomX, zoomY)) {
  40776. // When mouse is out of roamController rect,
  40777. // default befavoius should not be be disabled, otherwise
  40778. // page sliding is disabled, contrary to expectation.
  40779. stop(e.event);
  40780. this.trigger('zoom', zoomDelta, zoomX, zoomY);
  40781. }
  40782. }
  40783. function checkKeyBinding(roamController, prop, e) {
  40784. var setting = roamController._opt[prop];
  40785. return setting
  40786. && (!isString(setting) || e.event[setting + 'Key']);
  40787. }
  40788. // Only create one roam controller for each coordinate system.
  40789. // one roam controller might be refered by two inside data zoom
  40790. // components (for example, one for x and one for y). When user
  40791. // pan or zoom, only dispatch one action for those data zoom
  40792. // components.
  40793. var curry$5 = curry;
  40794. var ATTR = '\0_ec_dataZoom_roams';
  40795. /**
  40796. * @public
  40797. * @param {module:echarts/ExtensionAPI} api
  40798. * @param {Object} dataZoomInfo
  40799. * @param {string} dataZoomInfo.coordId
  40800. * @param {Function} dataZoomInfo.containsPoint
  40801. * @param {Array.<string>} dataZoomInfo.allCoordIds
  40802. * @param {string} dataZoomInfo.dataZoomId
  40803. * @param {number} dataZoomInfo.throttleRate
  40804. * @param {Function} dataZoomInfo.panGetRange
  40805. * @param {Function} dataZoomInfo.zoomGetRange
  40806. * @param {boolean} [dataZoomInfo.zoomLock]
  40807. * @param {boolean} [dataZoomInfo.disabled]
  40808. */
  40809. function register$1(api, dataZoomInfo) {
  40810. var store = giveStore(api);
  40811. var theDataZoomId = dataZoomInfo.dataZoomId;
  40812. var theCoordId = dataZoomInfo.coordId;
  40813. // Do clean when a dataZoom changes its target coordnate system.
  40814. // Avoid memory leak, dispose all not-used-registered.
  40815. each$1(store, function (record, coordId) {
  40816. var dataZoomInfos = record.dataZoomInfos;
  40817. if (dataZoomInfos[theDataZoomId]
  40818. && indexOf(dataZoomInfo.allCoordIds, theCoordId) < 0
  40819. ) {
  40820. delete dataZoomInfos[theDataZoomId];
  40821. record.count--;
  40822. }
  40823. });
  40824. cleanStore(store);
  40825. var record = store[theCoordId];
  40826. // Create if needed.
  40827. if (!record) {
  40828. record = store[theCoordId] = {
  40829. coordId: theCoordId,
  40830. dataZoomInfos: {},
  40831. count: 0
  40832. };
  40833. record.controller = createController(api, record);
  40834. record.dispatchAction = curry(dispatchAction, api);
  40835. }
  40836. // Update reference of dataZoom.
  40837. !(record.dataZoomInfos[theDataZoomId]) && record.count++;
  40838. record.dataZoomInfos[theDataZoomId] = dataZoomInfo;
  40839. var controllerParams = mergeControllerParams(record.dataZoomInfos);
  40840. record.controller.enable(controllerParams.controlType, controllerParams.opt);
  40841. // Consider resize, area should be always updated.
  40842. record.controller.setPointerChecker(dataZoomInfo.containsPoint);
  40843. // Update throttle.
  40844. createOrUpdate(
  40845. record,
  40846. 'dispatchAction',
  40847. dataZoomInfo.throttleRate,
  40848. 'fixRate'
  40849. );
  40850. }
  40851. /**
  40852. * @public
  40853. * @param {module:echarts/ExtensionAPI} api
  40854. * @param {string} dataZoomId
  40855. */
  40856. function unregister$1(api, dataZoomId) {
  40857. var store = giveStore(api);
  40858. each$1(store, function (record) {
  40859. record.controller.dispose();
  40860. var dataZoomInfos = record.dataZoomInfos;
  40861. if (dataZoomInfos[dataZoomId]) {
  40862. delete dataZoomInfos[dataZoomId];
  40863. record.count--;
  40864. }
  40865. });
  40866. cleanStore(store);
  40867. }
  40868. /**
  40869. * @public
  40870. */
  40871. function shouldRecordRange(payload, dataZoomId) {
  40872. if (payload && payload.type === 'dataZoom' && payload.batch) {
  40873. for (var i = 0, len = payload.batch.length; i < len; i++) {
  40874. if (payload.batch[i].dataZoomId === dataZoomId) {
  40875. return false;
  40876. }
  40877. }
  40878. }
  40879. return true;
  40880. }
  40881. /**
  40882. * @public
  40883. */
  40884. function generateCoordId(coordModel) {
  40885. return coordModel.type + '\0_' + coordModel.id;
  40886. }
  40887. /**
  40888. * Key: coordId, value: {dataZoomInfos: [], count, controller}
  40889. * @type {Array.<Object>}
  40890. */
  40891. function giveStore(api) {
  40892. // Mount store on zrender instance, so that we do not
  40893. // need to worry about dispose.
  40894. var zr = api.getZr();
  40895. return zr[ATTR] || (zr[ATTR] = {});
  40896. }
  40897. function createController(api, newRecord) {
  40898. var controller = new RoamController(api.getZr());
  40899. controller.on('pan', curry$5(onPan, newRecord));
  40900. controller.on('zoom', curry$5(onZoom, newRecord));
  40901. return controller;
  40902. }
  40903. function cleanStore(store) {
  40904. each$1(store, function (record, coordId) {
  40905. if (!record.count) {
  40906. record.controller.dispose();
  40907. delete store[coordId];
  40908. }
  40909. });
  40910. }
  40911. function onPan(record, dx, dy, oldX, oldY, newX, newY) {
  40912. wrapAndDispatch(record, function (info) {
  40913. return info.panGetRange(record.controller, dx, dy, oldX, oldY, newX, newY);
  40914. });
  40915. }
  40916. function onZoom(record, scale, mouseX, mouseY) {
  40917. wrapAndDispatch(record, function (info) {
  40918. return info.zoomGetRange(record.controller, scale, mouseX, mouseY);
  40919. });
  40920. }
  40921. function wrapAndDispatch(record, getRange) {
  40922. var batch = [];
  40923. each$1(record.dataZoomInfos, function (info) {
  40924. var range = getRange(info);
  40925. !info.disabled && range && batch.push({
  40926. dataZoomId: info.dataZoomId,
  40927. start: range[0],
  40928. end: range[1]
  40929. });
  40930. });
  40931. record.dispatchAction(batch);
  40932. }
  40933. /**
  40934. * This action will be throttled.
  40935. */
  40936. function dispatchAction(api, batch) {
  40937. api.dispatchAction({
  40938. type: 'dataZoom',
  40939. batch: batch
  40940. });
  40941. }
  40942. /**
  40943. * Merge roamController settings when multiple dataZooms share one roamController.
  40944. */
  40945. function mergeControllerParams(dataZoomInfos) {
  40946. var controlType;
  40947. var opt = {};
  40948. // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  40949. // as string, it is probably revert to reserved word by compress tool. See #7411.
  40950. var prefix = 'type_';
  40951. var typePriority = {
  40952. 'type_true': 2,
  40953. 'type_move': 1,
  40954. 'type_false': 0,
  40955. 'type_undefined': -1
  40956. };
  40957. each$1(dataZoomInfos, function (dataZoomInfo) {
  40958. var oneType = dataZoomInfo.disabled ? false : dataZoomInfo.zoomLock ? 'move' : true;
  40959. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  40960. controlType = oneType;
  40961. }
  40962. // Do not support that different 'shift'/'ctrl'/'alt' setting used in one coord sys.
  40963. extend(opt, dataZoomInfo.roamControllerOpt);
  40964. });
  40965. return {
  40966. controlType: controlType,
  40967. opt: opt
  40968. };
  40969. }
  40970. var bind$4 = bind;
  40971. var InsideZoomView = DataZoomView.extend({
  40972. type: 'dataZoom.inside',
  40973. /**
  40974. * @override
  40975. */
  40976. init: function (ecModel, api) {
  40977. /**
  40978. * 'throttle' is used in this.dispatchAction, so we save range
  40979. * to avoid missing some 'pan' info.
  40980. * @private
  40981. * @type {Array.<number>}
  40982. */
  40983. this._range;
  40984. },
  40985. /**
  40986. * @override
  40987. */
  40988. render: function (dataZoomModel, ecModel, api, payload) {
  40989. InsideZoomView.superApply(this, 'render', arguments);
  40990. // Notice: origin this._range should be maintained, and should not be re-fetched
  40991. // from dataZoomModel when payload.type is 'dataZoom', otherwise 'pan' or 'zoom'
  40992. // info will be missed because of 'throttle' of this.dispatchAction.
  40993. if (shouldRecordRange(payload, dataZoomModel.id)) {
  40994. this._range = dataZoomModel.getPercentRange();
  40995. }
  40996. // Reset controllers.
  40997. each$1(this.getTargetCoordInfo(), function (coordInfoList, coordSysName) {
  40998. var allCoordIds = map(coordInfoList, function (coordInfo) {
  40999. return generateCoordId(coordInfo.model);
  41000. });
  41001. each$1(coordInfoList, function (coordInfo) {
  41002. var coordModel = coordInfo.model;
  41003. var dataZoomOption = dataZoomModel.option;
  41004. register$1(
  41005. api,
  41006. {
  41007. coordId: generateCoordId(coordModel),
  41008. allCoordIds: allCoordIds,
  41009. containsPoint: function (e, x, y) {
  41010. return coordModel.coordinateSystem.containPoint([x, y]);
  41011. },
  41012. dataZoomId: dataZoomModel.id,
  41013. throttleRate: dataZoomModel.get('throttle', true),
  41014. panGetRange: bind$4(this._onPan, this, coordInfo, coordSysName),
  41015. zoomGetRange: bind$4(this._onZoom, this, coordInfo, coordSysName),
  41016. zoomLock: dataZoomOption.zoomLock,
  41017. disabled: dataZoomOption.disabled,
  41018. roamControllerOpt: {
  41019. zoomOnMouseWheel: dataZoomOption.zoomOnMouseWheel,
  41020. moveOnMouseMove: dataZoomOption.moveOnMouseMove,
  41021. preventDefaultMouseMove: dataZoomOption.preventDefaultMouseMove
  41022. }
  41023. }
  41024. );
  41025. }, this);
  41026. }, this);
  41027. },
  41028. /**
  41029. * @override
  41030. */
  41031. dispose: function () {
  41032. unregister$1(this.api, this.dataZoomModel.id);
  41033. InsideZoomView.superApply(this, 'dispose', arguments);
  41034. this._range = null;
  41035. },
  41036. /**
  41037. * @private
  41038. */
  41039. _onPan: function (coordInfo, coordSysName, controller, dx, dy, oldX, oldY, newX, newY) {
  41040. var range = this._range.slice();
  41041. // Calculate transform by the first axis.
  41042. var axisModel = coordInfo.axisModels[0];
  41043. if (!axisModel) {
  41044. return;
  41045. }
  41046. var directionInfo = getDirectionInfo[coordSysName](
  41047. [oldX, oldY], [newX, newY], axisModel, controller, coordInfo
  41048. );
  41049. var percentDelta = directionInfo.signal
  41050. * (range[1] - range[0])
  41051. * directionInfo.pixel / directionInfo.pixelLength;
  41052. sliderMove(percentDelta, range, [0, 100], 'all');
  41053. return (this._range = range);
  41054. },
  41055. /**
  41056. * @private
  41057. */
  41058. _onZoom: function (coordInfo, coordSysName, controller, scale, mouseX, mouseY) {
  41059. var range = this._range.slice();
  41060. // Calculate transform by the first axis.
  41061. var axisModel = coordInfo.axisModels[0];
  41062. if (!axisModel) {
  41063. return;
  41064. }
  41065. var directionInfo = getDirectionInfo[coordSysName](
  41066. null, [mouseX, mouseY], axisModel, controller, coordInfo
  41067. );
  41068. var percentPoint = (
  41069. directionInfo.signal > 0
  41070. ? (directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel)
  41071. : (directionInfo.pixel - directionInfo.pixelStart)
  41072. ) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  41073. scale = Math.max(1 / scale, 0);
  41074. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  41075. range[1] = (range[1] - percentPoint) * scale + percentPoint;
  41076. // Restrict range.
  41077. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  41078. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  41079. return (this._range = range);
  41080. }
  41081. });
  41082. var getDirectionInfo = {
  41083. grid: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  41084. var axis = axisModel.axis;
  41085. var ret = {};
  41086. var rect = coordInfo.model.coordinateSystem.getRect();
  41087. oldPoint = oldPoint || [0, 0];
  41088. if (axis.dim === 'x') {
  41089. ret.pixel = newPoint[0] - oldPoint[0];
  41090. ret.pixelLength = rect.width;
  41091. ret.pixelStart = rect.x;
  41092. ret.signal = axis.inverse ? 1 : -1;
  41093. }
  41094. else { // axis.dim === 'y'
  41095. ret.pixel = newPoint[1] - oldPoint[1];
  41096. ret.pixelLength = rect.height;
  41097. ret.pixelStart = rect.y;
  41098. ret.signal = axis.inverse ? -1 : 1;
  41099. }
  41100. return ret;
  41101. },
  41102. polar: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  41103. var axis = axisModel.axis;
  41104. var ret = {};
  41105. var polar = coordInfo.model.coordinateSystem;
  41106. var radiusExtent = polar.getRadiusAxis().getExtent();
  41107. var angleExtent = polar.getAngleAxis().getExtent();
  41108. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  41109. newPoint = polar.pointToCoord(newPoint);
  41110. if (axisModel.mainType === 'radiusAxis') {
  41111. ret.pixel = newPoint[0] - oldPoint[0];
  41112. // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  41113. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  41114. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  41115. ret.pixelStart = radiusExtent[0];
  41116. ret.signal = axis.inverse ? 1 : -1;
  41117. }
  41118. else { // 'angleAxis'
  41119. ret.pixel = newPoint[1] - oldPoint[1];
  41120. // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  41121. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  41122. ret.pixelLength = angleExtent[1] - angleExtent[0];
  41123. ret.pixelStart = angleExtent[0];
  41124. ret.signal = axis.inverse ? -1 : 1;
  41125. }
  41126. return ret;
  41127. },
  41128. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  41129. var axis = axisModel.axis;
  41130. var rect = coordInfo.model.coordinateSystem.getRect();
  41131. var ret = {};
  41132. oldPoint = oldPoint || [0, 0];
  41133. if (axis.orient === 'horizontal') {
  41134. ret.pixel = newPoint[0] - oldPoint[0];
  41135. ret.pixelLength = rect.width;
  41136. ret.pixelStart = rect.x;
  41137. ret.signal = axis.inverse ? 1 : -1;
  41138. }
  41139. else { // 'vertical'
  41140. ret.pixel = newPoint[1] - oldPoint[1];
  41141. ret.pixelLength = rect.height;
  41142. ret.pixelStart = rect.y;
  41143. ret.signal = axis.inverse ? -1 : 1;
  41144. }
  41145. return ret;
  41146. }
  41147. };
  41148. registerProcessor({
  41149. getTargetSeries: function (ecModel) {
  41150. var seriesModelMap = createHashMap();
  41151. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  41152. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  41153. var axisProxy = dataZoomModel.getAxisProxy(dimNames.name, axisIndex);
  41154. each$1(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  41155. seriesModelMap.set(seriesModel.uid, seriesModel);
  41156. });
  41157. });
  41158. });
  41159. return seriesModelMap;
  41160. },
  41161. isOverallFilter: true,
  41162. // Consider appendData, where filter should be performed. Because data process is
  41163. // in block mode currently, it is not need to worry about that the overallProgress
  41164. // execute every frame.
  41165. overallReset: function (ecModel, api) {
  41166. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  41167. // We calculate window and reset axis here but not in model
  41168. // init stage and not after action dispatch handler, because
  41169. // reset should be called after seriesData.restoreData.
  41170. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  41171. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).reset(dataZoomModel, api);
  41172. });
  41173. // Caution: data zoom filtering is order sensitive when using
  41174. // percent range and no min/max/scale set on axis.
  41175. // For example, we have dataZoom definition:
  41176. // [
  41177. // {xAxisIndex: 0, start: 30, end: 70},
  41178. // {yAxisIndex: 0, start: 20, end: 80}
  41179. // ]
  41180. // In this case, [20, 80] of y-dataZoom should be based on data
  41181. // that have filtered by x-dataZoom using range of [30, 70],
  41182. // but should not be based on full raw data. Thus sliding
  41183. // x-dataZoom will change both ranges of xAxis and yAxis,
  41184. // while sliding y-dataZoom will only change the range of yAxis.
  41185. // So we should filter x-axis after reset x-axis immediately,
  41186. // and then reset y-axis and filter y-axis.
  41187. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  41188. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).filterData(dataZoomModel, api);
  41189. });
  41190. });
  41191. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  41192. // Fullfill all of the range props so that user
  41193. // is able to get them from chart.getOption().
  41194. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  41195. var percentRange = axisProxy.getDataPercentWindow();
  41196. var valueRange = axisProxy.getDataValueWindow();
  41197. dataZoomModel.setRawRange({
  41198. start: percentRange[0],
  41199. end: percentRange[1],
  41200. startValue: valueRange[0],
  41201. endValue: valueRange[1]
  41202. }, true);
  41203. });
  41204. }
  41205. });
  41206. registerAction('dataZoom', function (payload, ecModel) {
  41207. var linkedNodesFinder = createLinkedNodesFinder(
  41208. bind(ecModel.eachComponent, ecModel, 'dataZoom'),
  41209. eachAxisDim$1,
  41210. function (model, dimNames) {
  41211. return model.get(dimNames.axisIndex);
  41212. }
  41213. );
  41214. var effectedModels = [];
  41215. ecModel.eachComponent(
  41216. {mainType: 'dataZoom', query: payload},
  41217. function (model, index) {
  41218. effectedModels.push.apply(
  41219. effectedModels, linkedNodesFinder(model).nodes
  41220. );
  41221. }
  41222. );
  41223. each$1(effectedModels, function (dataZoomModel, index) {
  41224. dataZoomModel.setRawRange({
  41225. start: payload.start,
  41226. end: payload.end,
  41227. startValue: payload.startValue,
  41228. endValue: payload.endValue
  41229. });
  41230. });
  41231. });
  41232. /**
  41233. * DataZoom component entry
  41234. */
  41235. var features = {};
  41236. function register$2(name, ctor) {
  41237. features[name] = ctor;
  41238. }
  41239. function get$1(name) {
  41240. return features[name];
  41241. }
  41242. var ToolboxModel = extendComponentModel({
  41243. type: 'toolbox',
  41244. layoutMode: {
  41245. type: 'box',
  41246. ignoreSize: true
  41247. },
  41248. mergeDefaultAndTheme: function (option) {
  41249. ToolboxModel.superApply(this, 'mergeDefaultAndTheme', arguments);
  41250. each$1(this.option.feature, function (featureOpt, featureName) {
  41251. var Feature = get$1(featureName);
  41252. Feature && merge(featureOpt, Feature.defaultOption);
  41253. });
  41254. },
  41255. defaultOption: {
  41256. show: true,
  41257. z: 6,
  41258. zlevel: 0,
  41259. orient: 'horizontal',
  41260. left: 'right',
  41261. top: 'top',
  41262. // right
  41263. // bottom
  41264. backgroundColor: 'transparent',
  41265. borderColor: '#ccc',
  41266. borderRadius: 0,
  41267. borderWidth: 0,
  41268. padding: 5,
  41269. itemSize: 15,
  41270. itemGap: 8,
  41271. showTitle: true,
  41272. iconStyle: {
  41273. borderColor: '#666',
  41274. color: 'none'
  41275. },
  41276. emphasis: {
  41277. iconStyle: {
  41278. borderColor: '#3E98C5'
  41279. }
  41280. }
  41281. // textStyle: {},
  41282. // feature
  41283. }
  41284. });
  41285. extendComponentView({
  41286. type: 'toolbox',
  41287. render: function (toolboxModel, ecModel, api, payload) {
  41288. var group = this.group;
  41289. group.removeAll();
  41290. if (!toolboxModel.get('show')) {
  41291. return;
  41292. }
  41293. var itemSize = +toolboxModel.get('itemSize');
  41294. var featureOpts = toolboxModel.get('feature') || {};
  41295. var features = this._features || (this._features = {});
  41296. var featureNames = [];
  41297. each$1(featureOpts, function (opt, name) {
  41298. featureNames.push(name);
  41299. });
  41300. (new DataDiffer(this._featureNames || [], featureNames))
  41301. .add(processFeature)
  41302. .update(processFeature)
  41303. .remove(curry(processFeature, null))
  41304. .execute();
  41305. // Keep for diff.
  41306. this._featureNames = featureNames;
  41307. function processFeature(newIndex, oldIndex) {
  41308. var featureName = featureNames[newIndex];
  41309. var oldName = featureNames[oldIndex];
  41310. var featureOpt = featureOpts[featureName];
  41311. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  41312. var feature;
  41313. if (featureName && !oldName) { // Create
  41314. if (isUserFeatureName(featureName)) {
  41315. feature = {
  41316. model: featureModel,
  41317. onclick: featureModel.option.onclick,
  41318. featureName: featureName
  41319. };
  41320. }
  41321. else {
  41322. var Feature = get$1(featureName);
  41323. if (!Feature) {
  41324. return;
  41325. }
  41326. feature = new Feature(featureModel, ecModel, api);
  41327. }
  41328. features[featureName] = feature;
  41329. }
  41330. else {
  41331. feature = features[oldName];
  41332. // If feature does not exsit.
  41333. if (!feature) {
  41334. return;
  41335. }
  41336. feature.model = featureModel;
  41337. feature.ecModel = ecModel;
  41338. feature.api = api;
  41339. }
  41340. if (!featureName && oldName) {
  41341. feature.dispose && feature.dispose(ecModel, api);
  41342. return;
  41343. }
  41344. if (!featureModel.get('show') || feature.unusable) {
  41345. feature.remove && feature.remove(ecModel, api);
  41346. return;
  41347. }
  41348. createIconPaths(featureModel, feature, featureName);
  41349. featureModel.setIconStatus = function (iconName, status) {
  41350. var option = this.option;
  41351. var iconPaths = this.iconPaths;
  41352. option.iconStatus = option.iconStatus || {};
  41353. option.iconStatus[iconName] = status;
  41354. // FIXME
  41355. iconPaths[iconName] && iconPaths[iconName].trigger(status);
  41356. };
  41357. if (feature.render) {
  41358. feature.render(featureModel, ecModel, api, payload);
  41359. }
  41360. }
  41361. function createIconPaths(featureModel, feature, featureName) {
  41362. var iconStyleModel = featureModel.getModel('iconStyle');
  41363. var iconStyleEmphasisModel = featureModel.getModel('emphasis.iconStyle');
  41364. // If one feature has mutiple icon. they are orginaized as
  41365. // {
  41366. // icon: {
  41367. // foo: '',
  41368. // bar: ''
  41369. // },
  41370. // title: {
  41371. // foo: '',
  41372. // bar: ''
  41373. // }
  41374. // }
  41375. var icons = feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  41376. var titles = featureModel.get('title') || {};
  41377. if (typeof icons === 'string') {
  41378. var icon = icons;
  41379. var title = titles;
  41380. icons = {};
  41381. titles = {};
  41382. icons[featureName] = icon;
  41383. titles[featureName] = title;
  41384. }
  41385. var iconPaths = featureModel.iconPaths = {};
  41386. each$1(icons, function (iconStr, iconName) {
  41387. var path = createIcon(
  41388. iconStr,
  41389. {},
  41390. {
  41391. x: -itemSize / 2,
  41392. y: -itemSize / 2,
  41393. width: itemSize,
  41394. height: itemSize
  41395. }
  41396. );
  41397. path.setStyle(iconStyleModel.getItemStyle());
  41398. path.hoverStyle = iconStyleEmphasisModel.getItemStyle();
  41399. setHoverStyle(path);
  41400. if (toolboxModel.get('showTitle')) {
  41401. path.__title = titles[iconName];
  41402. path.on('mouseover', function () {
  41403. // Should not reuse above hoverStyle, which might be modified.
  41404. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  41405. path.setStyle({
  41406. text: titles[iconName],
  41407. textPosition: hoverStyle.textPosition || 'bottom',
  41408. textFill: hoverStyle.fill || hoverStyle.stroke || '#000',
  41409. textAlign: hoverStyle.textAlign || 'center'
  41410. });
  41411. })
  41412. .on('mouseout', function () {
  41413. path.setStyle({
  41414. textFill: null
  41415. });
  41416. });
  41417. }
  41418. path.trigger(featureModel.get('iconStatus.' + iconName) || 'normal');
  41419. group.add(path);
  41420. path.on('click', bind(
  41421. feature.onclick, feature, ecModel, api, iconName
  41422. ));
  41423. iconPaths[iconName] = path;
  41424. });
  41425. }
  41426. layout$2(group, toolboxModel, api);
  41427. // Render background after group is layout
  41428. // FIXME
  41429. group.add(makeBackground(group.getBoundingRect(), toolboxModel));
  41430. // Adjust icon title positions to avoid them out of screen
  41431. group.eachChild(function (icon) {
  41432. var titleText = icon.__title;
  41433. var hoverStyle = icon.hoverStyle;
  41434. // May be background element
  41435. if (hoverStyle && titleText) {
  41436. var rect = getBoundingRect(
  41437. titleText, makeFont(hoverStyle)
  41438. );
  41439. var offsetX = icon.position[0] + group.position[0];
  41440. var offsetY = icon.position[1] + group.position[1] + itemSize;
  41441. var needPutOnTop = false;
  41442. if (offsetY + rect.height > api.getHeight()) {
  41443. hoverStyle.textPosition = 'top';
  41444. needPutOnTop = true;
  41445. }
  41446. var topOffset = needPutOnTop ? (-5 - rect.height) : (itemSize + 8);
  41447. if (offsetX + rect.width / 2 > api.getWidth()) {
  41448. hoverStyle.textPosition = ['100%', topOffset];
  41449. hoverStyle.textAlign = 'right';
  41450. }
  41451. else if (offsetX - rect.width / 2 < 0) {
  41452. hoverStyle.textPosition = [0, topOffset];
  41453. hoverStyle.textAlign = 'left';
  41454. }
  41455. }
  41456. });
  41457. },
  41458. updateView: function (toolboxModel, ecModel, api, payload) {
  41459. each$1(this._features, function (feature) {
  41460. feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  41461. });
  41462. },
  41463. // updateLayout: function (toolboxModel, ecModel, api, payload) {
  41464. // zrUtil.each(this._features, function (feature) {
  41465. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  41466. // });
  41467. // },
  41468. remove: function (ecModel, api) {
  41469. each$1(this._features, function (feature) {
  41470. feature.remove && feature.remove(ecModel, api);
  41471. });
  41472. this.group.removeAll();
  41473. },
  41474. dispose: function (ecModel, api) {
  41475. each$1(this._features, function (feature) {
  41476. feature.dispose && feature.dispose(ecModel, api);
  41477. });
  41478. }
  41479. });
  41480. function isUserFeatureName(featureName) {
  41481. return featureName.indexOf('my') === 0;
  41482. }
  41483. var saveAsImageLang = lang.toolbox.saveAsImage;
  41484. function SaveAsImage(model) {
  41485. this.model = model;
  41486. }
  41487. SaveAsImage.defaultOption = {
  41488. show: true,
  41489. icon: 'M4.7,22.9L29.3,45.5L54.7,23.4M4.6,43.6L4.6,58L53.8,58L53.8,43.6M29.2,45.1L29.2,0',
  41490. title: saveAsImageLang.title,
  41491. type: 'png',
  41492. // Default use option.backgroundColor
  41493. // backgroundColor: '#fff',
  41494. name: '',
  41495. excludeComponents: ['toolbox'],
  41496. pixelRatio: 1,
  41497. lang: saveAsImageLang.lang.slice()
  41498. };
  41499. SaveAsImage.prototype.unusable = !env$1.canvasSupported;
  41500. var proto$2 = SaveAsImage.prototype;
  41501. proto$2.onclick = function (ecModel, api) {
  41502. var model = this.model;
  41503. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  41504. var $a = document.createElement('a');
  41505. var type = model.get('type', true) || 'png';
  41506. $a.download = title + '.' + type;
  41507. $a.target = '_blank';
  41508. var url = api.getConnectedDataURL({
  41509. type: type,
  41510. backgroundColor: model.get('backgroundColor', true)
  41511. || ecModel.get('backgroundColor') || '#fff',
  41512. excludeComponents: model.get('excludeComponents'),
  41513. pixelRatio: model.get('pixelRatio')
  41514. });
  41515. $a.href = url;
  41516. // Chrome and Firefox
  41517. if (typeof MouseEvent === 'function' && !env$1.browser.ie && !env$1.browser.edge) {
  41518. var evt = new MouseEvent('click', {
  41519. view: window,
  41520. bubbles: true,
  41521. cancelable: false
  41522. });
  41523. $a.dispatchEvent(evt);
  41524. }
  41525. // IE
  41526. else {
  41527. if (window.navigator.msSaveOrOpenBlob) {
  41528. var bstr = atob(url.split(',')[1]);
  41529. var n = bstr.length;
  41530. var u8arr = new Uint8Array(n);
  41531. while(n--) {
  41532. u8arr[n] = bstr.charCodeAt(n);
  41533. }
  41534. var blob = new Blob([u8arr]);
  41535. window.navigator.msSaveOrOpenBlob(blob, title + '.' + type);
  41536. }
  41537. else {
  41538. var lang$$1 = model.get('lang');
  41539. var html = '' +
  41540. '<body style="margin:0;">' +
  41541. '<img src="' + url + '" style="max-width:100%;" title="' + ((lang$$1 && lang$$1[0]) || '') + '" />' +
  41542. '</body>';
  41543. var tab = window.open();
  41544. tab.document.write(html);
  41545. }
  41546. }
  41547. };
  41548. register$2(
  41549. 'saveAsImage', SaveAsImage
  41550. );
  41551. var magicTypeLang = lang.toolbox.magicType;
  41552. function MagicType(model) {
  41553. this.model = model;
  41554. }
  41555. MagicType.defaultOption = {
  41556. show: true,
  41557. type: [],
  41558. // Icon group
  41559. icon: {
  41560. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  41561. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  41562. stack: 'M8.2,38.4l-8.4,4.1l30.6,15.3L60,42.5l-8.1-4.1l-21.5,11L8.2,38.4z M51.9,30l-8.1,4.2l-13.4,6.9l-13.9-6.9L8.2,30l-8.4,4.2l8.4,4.2l22.2,11l21.5-11l8.1-4.2L51.9,30z M51.9,21.7l-8.1,4.2L35.7,30l-5.3,2.8L24.9,30l-8.4-4.1l-8.3-4.2l-8.4,4.2L8.2,30l8.3,4.2l13.9,6.9l13.4-6.9l8.1-4.2l8.1-4.1L51.9,21.7zM30.4,2.2L-0.2,17.5l8.4,4.1l8.3,4.2l8.4,4.2l5.5,2.7l5.3-2.7l8.1-4.2l8.1-4.2l8.1-4.1L30.4,2.2z', // jshint ignore:line
  41563. tiled: 'M2.3,2.2h22.8V25H2.3V2.2z M35,2.2h22.8V25H35V2.2zM2.3,35h22.8v22.8H2.3V35z M35,35h22.8v22.8H35V35z'
  41564. },
  41565. // `line`, `bar`, `stack`, `tiled`
  41566. title: clone(magicTypeLang.title),
  41567. option: {},
  41568. seriesIndex: {}
  41569. };
  41570. var proto$3 = MagicType.prototype;
  41571. proto$3.getIcons = function () {
  41572. var model = this.model;
  41573. var availableIcons = model.get('icon');
  41574. var icons = {};
  41575. each$1(model.get('type'), function (type) {
  41576. if (availableIcons[type]) {
  41577. icons[type] = availableIcons[type];
  41578. }
  41579. });
  41580. return icons;
  41581. };
  41582. var seriesOptGenreator = {
  41583. 'line': function (seriesType, seriesId, seriesModel, model) {
  41584. if (seriesType === 'bar') {
  41585. return merge({
  41586. id: seriesId,
  41587. type: 'line',
  41588. // Preserve data related option
  41589. data: seriesModel.get('data'),
  41590. stack: seriesModel.get('stack'),
  41591. markPoint: seriesModel.get('markPoint'),
  41592. markLine: seriesModel.get('markLine')
  41593. }, model.get('option.line') || {}, true);
  41594. }
  41595. },
  41596. 'bar': function (seriesType, seriesId, seriesModel, model) {
  41597. if (seriesType === 'line') {
  41598. return merge({
  41599. id: seriesId,
  41600. type: 'bar',
  41601. // Preserve data related option
  41602. data: seriesModel.get('data'),
  41603. stack: seriesModel.get('stack'),
  41604. markPoint: seriesModel.get('markPoint'),
  41605. markLine: seriesModel.get('markLine')
  41606. }, model.get('option.bar') || {}, true);
  41607. }
  41608. },
  41609. 'stack': function (seriesType, seriesId, seriesModel, model) {
  41610. if (seriesType === 'line' || seriesType === 'bar') {
  41611. return merge({
  41612. id: seriesId,
  41613. stack: '__ec_magicType_stack__'
  41614. }, model.get('option.stack') || {}, true);
  41615. }
  41616. },
  41617. 'tiled': function (seriesType, seriesId, seriesModel, model) {
  41618. if (seriesType === 'line' || seriesType === 'bar') {
  41619. return merge({
  41620. id: seriesId,
  41621. stack: ''
  41622. }, model.get('option.tiled') || {}, true);
  41623. }
  41624. }
  41625. };
  41626. var radioTypes = [
  41627. ['line', 'bar'],
  41628. ['stack', 'tiled']
  41629. ];
  41630. proto$3.onclick = function (ecModel, api, type) {
  41631. var model = this.model;
  41632. var seriesIndex = model.get('seriesIndex.' + type);
  41633. // Not supported magicType
  41634. if (!seriesOptGenreator[type]) {
  41635. return;
  41636. }
  41637. var newOption = {
  41638. series: []
  41639. };
  41640. var generateNewSeriesTypes = function (seriesModel) {
  41641. var seriesType = seriesModel.subType;
  41642. var seriesId = seriesModel.id;
  41643. var newSeriesOpt = seriesOptGenreator[type](
  41644. seriesType, seriesId, seriesModel, model
  41645. );
  41646. if (newSeriesOpt) {
  41647. // PENDING If merge original option?
  41648. defaults(newSeriesOpt, seriesModel.option);
  41649. newOption.series.push(newSeriesOpt);
  41650. }
  41651. // Modify boundaryGap
  41652. var coordSys = seriesModel.coordinateSystem;
  41653. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  41654. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  41655. if (categoryAxis) {
  41656. var axisDim = categoryAxis.dim;
  41657. var axisType = axisDim + 'Axis';
  41658. var axisModel = ecModel.queryComponents({
  41659. mainType: axisType,
  41660. index: seriesModel.get(name + 'Index'),
  41661. id: seriesModel.get(name + 'Id')
  41662. })[0];
  41663. var axisIndex = axisModel.componentIndex;
  41664. newOption[axisType] = newOption[axisType] || [];
  41665. for (var i = 0; i <= axisIndex; i++) {
  41666. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  41667. }
  41668. newOption[axisType][axisIndex].boundaryGap = type === 'bar' ? true : false;
  41669. }
  41670. }
  41671. };
  41672. each$1(radioTypes, function (radio) {
  41673. if (indexOf(radio, type) >= 0) {
  41674. each$1(radio, function (item) {
  41675. model.setIconStatus(item, 'normal');
  41676. });
  41677. }
  41678. });
  41679. model.setIconStatus(type, 'emphasis');
  41680. ecModel.eachComponent(
  41681. {
  41682. mainType: 'series',
  41683. query: seriesIndex == null ? null : {
  41684. seriesIndex: seriesIndex
  41685. }
  41686. }, generateNewSeriesTypes
  41687. );
  41688. api.dispatchAction({
  41689. type: 'changeMagicType',
  41690. currentType: type,
  41691. newOption: newOption
  41692. });
  41693. };
  41694. registerAction({
  41695. type: 'changeMagicType',
  41696. event: 'magicTypeChanged',
  41697. update: 'prepareAndUpdate'
  41698. }, function (payload, ecModel) {
  41699. ecModel.mergeOption(payload.newOption);
  41700. });
  41701. register$2('magicType', MagicType);
  41702. var dataViewLang = lang.toolbox.dataView;
  41703. var BLOCK_SPLITER = new Array(60).join('-');
  41704. var ITEM_SPLITER = '\t';
  41705. /**
  41706. * Group series into two types
  41707. * 1. on category axis, like line, bar
  41708. * 2. others, like scatter, pie
  41709. * @param {module:echarts/model/Global} ecModel
  41710. * @return {Object}
  41711. * @inner
  41712. */
  41713. function groupSeries(ecModel) {
  41714. var seriesGroupByCategoryAxis = {};
  41715. var otherSeries = [];
  41716. var meta = [];
  41717. ecModel.eachRawSeries(function (seriesModel) {
  41718. var coordSys = seriesModel.coordinateSystem;
  41719. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  41720. var baseAxis = coordSys.getBaseAxis();
  41721. if (baseAxis.type === 'category') {
  41722. var key = baseAxis.dim + '_' + baseAxis.index;
  41723. if (!seriesGroupByCategoryAxis[key]) {
  41724. seriesGroupByCategoryAxis[key] = {
  41725. categoryAxis: baseAxis,
  41726. valueAxis: coordSys.getOtherAxis(baseAxis),
  41727. series: []
  41728. };
  41729. meta.push({
  41730. axisDim: baseAxis.dim,
  41731. axisIndex: baseAxis.index
  41732. });
  41733. }
  41734. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  41735. }
  41736. else {
  41737. otherSeries.push(seriesModel);
  41738. }
  41739. }
  41740. else {
  41741. otherSeries.push(seriesModel);
  41742. }
  41743. });
  41744. return {
  41745. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  41746. other: otherSeries,
  41747. meta: meta
  41748. };
  41749. }
  41750. /**
  41751. * Assemble content of series on cateogory axis
  41752. * @param {Array.<module:echarts/model/Series>} series
  41753. * @return {string}
  41754. * @inner
  41755. */
  41756. function assembleSeriesWithCategoryAxis(series) {
  41757. var tables = [];
  41758. each$1(series, function (group, key) {
  41759. var categoryAxis = group.categoryAxis;
  41760. var valueAxis = group.valueAxis;
  41761. var valueAxisDim = valueAxis.dim;
  41762. var headers = [' '].concat(map(group.series, function (series) {
  41763. return series.name;
  41764. }));
  41765. var columns = [categoryAxis.model.getCategories()];
  41766. each$1(group.series, function (series) {
  41767. columns.push(series.getRawData().mapArray(valueAxisDim, function (val) {
  41768. return val;
  41769. }));
  41770. });
  41771. // Assemble table content
  41772. var lines = [headers.join(ITEM_SPLITER)];
  41773. for (var i = 0; i < columns[0].length; i++) {
  41774. var items = [];
  41775. for (var j = 0; j < columns.length; j++) {
  41776. items.push(columns[j][i]);
  41777. }
  41778. lines.push(items.join(ITEM_SPLITER));
  41779. }
  41780. tables.push(lines.join('\n'));
  41781. });
  41782. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  41783. }
  41784. /**
  41785. * Assemble content of other series
  41786. * @param {Array.<module:echarts/model/Series>} series
  41787. * @return {string}
  41788. * @inner
  41789. */
  41790. function assembleOtherSeries(series) {
  41791. return map(series, function (series) {
  41792. var data = series.getRawData();
  41793. var lines = [series.name];
  41794. var vals = [];
  41795. data.each(data.dimensions, function () {
  41796. var argLen = arguments.length;
  41797. var dataIndex = arguments[argLen - 1];
  41798. var name = data.getName(dataIndex);
  41799. for (var i = 0; i < argLen - 1; i++) {
  41800. vals[i] = arguments[i];
  41801. }
  41802. lines.push((name ? (name + ITEM_SPLITER) : '') + vals.join(ITEM_SPLITER));
  41803. });
  41804. return lines.join('\n');
  41805. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  41806. }
  41807. /**
  41808. * @param {module:echarts/model/Global}
  41809. * @return {Object}
  41810. * @inner
  41811. */
  41812. function getContentFromModel(ecModel) {
  41813. var result = groupSeries(ecModel);
  41814. return {
  41815. value: filter([
  41816. assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis),
  41817. assembleOtherSeries(result.other)
  41818. ], function (str) {
  41819. return str.replace(/[\n\t\s]/g, '');
  41820. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  41821. meta: result.meta
  41822. };
  41823. }
  41824. function trim$1(str) {
  41825. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  41826. }
  41827. /**
  41828. * If a block is tsv format
  41829. */
  41830. function isTSVFormat(block) {
  41831. // Simple method to find out if a block is tsv format
  41832. var firstLine = block.slice(0, block.indexOf('\n'));
  41833. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  41834. return true;
  41835. }
  41836. }
  41837. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  41838. /**
  41839. * @param {string} tsv
  41840. * @return {Object}
  41841. */
  41842. function parseTSVContents(tsv) {
  41843. var tsvLines = tsv.split(/\n+/g);
  41844. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  41845. var categories = [];
  41846. var series = map(headers, function (header) {
  41847. return {
  41848. name: header,
  41849. data: []
  41850. };
  41851. });
  41852. for (var i = 0; i < tsvLines.length; i++) {
  41853. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  41854. categories.push(items.shift());
  41855. for (var j = 0; j < items.length; j++) {
  41856. series[j] && (series[j].data[i] = items[j]);
  41857. }
  41858. }
  41859. return {
  41860. series: series,
  41861. categories: categories
  41862. };
  41863. }
  41864. /**
  41865. * @param {string} str
  41866. * @return {Array.<Object>}
  41867. * @inner
  41868. */
  41869. function parseListContents(str) {
  41870. var lines = str.split(/\n+/g);
  41871. var seriesName = trim$1(lines.shift());
  41872. var data = [];
  41873. for (var i = 0; i < lines.length; i++) {
  41874. var items = trim$1(lines[i]).split(itemSplitRegex);
  41875. var name = '';
  41876. var value;
  41877. var hasName = false;
  41878. if (isNaN(items[0])) { // First item is name
  41879. hasName = true;
  41880. name = items[0];
  41881. items = items.slice(1);
  41882. data[i] = {
  41883. name: name,
  41884. value: []
  41885. };
  41886. value = data[i].value;
  41887. }
  41888. else {
  41889. value = data[i] = [];
  41890. }
  41891. for (var j = 0; j < items.length; j++) {
  41892. value.push(+items[j]);
  41893. }
  41894. if (value.length === 1) {
  41895. hasName ? (data[i].value = value[0]) : (data[i] = value[0]);
  41896. }
  41897. }
  41898. return {
  41899. name: seriesName,
  41900. data: data
  41901. };
  41902. }
  41903. /**
  41904. * @param {string} str
  41905. * @param {Array.<Object>} blockMetaList
  41906. * @return {Object}
  41907. * @inner
  41908. */
  41909. function parseContents(str, blockMetaList) {
  41910. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  41911. var newOption = {
  41912. series: []
  41913. };
  41914. each$1(blocks, function (block, idx) {
  41915. if (isTSVFormat(block)) {
  41916. var result = parseTSVContents(block);
  41917. var blockMeta = blockMetaList[idx];
  41918. var axisKey = blockMeta.axisDim + 'Axis';
  41919. if (blockMeta) {
  41920. newOption[axisKey] = newOption[axisKey] || [];
  41921. newOption[axisKey][blockMeta.axisIndex] = {
  41922. data: result.categories
  41923. };
  41924. newOption.series = newOption.series.concat(result.series);
  41925. }
  41926. }
  41927. else {
  41928. var result = parseListContents(block);
  41929. newOption.series.push(result);
  41930. }
  41931. });
  41932. return newOption;
  41933. }
  41934. /**
  41935. * @alias {module:echarts/component/toolbox/feature/DataView}
  41936. * @constructor
  41937. * @param {module:echarts/model/Model} model
  41938. */
  41939. function DataView(model) {
  41940. this._dom = null;
  41941. this.model = model;
  41942. }
  41943. DataView.defaultOption = {
  41944. show: true,
  41945. readOnly: false,
  41946. optionToContent: null,
  41947. contentToOption: null,
  41948. icon: 'M17.5,17.3H33 M17.5,17.3H33 M45.4,29.5h-28 M11.5,2v56H51V14.8L38.4,2H11.5z M38.4,2.2v12.7H51 M45.4,41.7h-28',
  41949. title: clone(dataViewLang.title),
  41950. lang: clone(dataViewLang.lang),
  41951. backgroundColor: '#fff',
  41952. textColor: '#000',
  41953. textareaColor: '#fff',
  41954. textareaBorderColor: '#333',
  41955. buttonColor: '#c23531',
  41956. buttonTextColor: '#fff'
  41957. };
  41958. DataView.prototype.onclick = function (ecModel, api) {
  41959. var container = api.getDom();
  41960. var model = this.model;
  41961. if (this._dom) {
  41962. container.removeChild(this._dom);
  41963. }
  41964. var root = document.createElement('div');
  41965. root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;';
  41966. root.style.backgroundColor = model.get('backgroundColor') || '#fff';
  41967. // Create elements
  41968. var header = document.createElement('h4');
  41969. var lang$$1 = model.get('lang') || [];
  41970. header.innerHTML = lang$$1[0] || model.get('title');
  41971. header.style.cssText = 'margin: 10px 20px;';
  41972. header.style.color = model.get('textColor');
  41973. var viewMain = document.createElement('div');
  41974. var textarea = document.createElement('textarea');
  41975. viewMain.style.cssText = 'display:block;width:100%;overflow:auto;';
  41976. var optionToContent = model.get('optionToContent');
  41977. var contentToOption = model.get('contentToOption');
  41978. var result = getContentFromModel(ecModel);
  41979. if (typeof optionToContent === 'function') {
  41980. var htmlOrDom = optionToContent(api.getOption());
  41981. if (typeof htmlOrDom === 'string') {
  41982. viewMain.innerHTML = htmlOrDom;
  41983. }
  41984. else if (isDom(htmlOrDom)) {
  41985. viewMain.appendChild(htmlOrDom);
  41986. }
  41987. }
  41988. else {
  41989. // Use default textarea
  41990. viewMain.appendChild(textarea);
  41991. textarea.readOnly = model.get('readOnly');
  41992. textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;';
  41993. textarea.style.color = model.get('textColor');
  41994. textarea.style.borderColor = model.get('textareaBorderColor');
  41995. textarea.style.backgroundColor = model.get('textareaColor');
  41996. textarea.value = result.value;
  41997. }
  41998. var blockMetaList = result.meta;
  41999. var buttonContainer = document.createElement('div');
  42000. buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;';
  42001. var buttonStyle = 'float:right;margin-right:20px;border:none;'
  42002. + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  42003. var closeButton = document.createElement('div');
  42004. var refreshButton = document.createElement('div');
  42005. buttonStyle += ';background-color:' + model.get('buttonColor');
  42006. buttonStyle += ';color:' + model.get('buttonTextColor');
  42007. var self = this;
  42008. function close() {
  42009. container.removeChild(root);
  42010. self._dom = null;
  42011. }
  42012. addEventListener(closeButton, 'click', close);
  42013. addEventListener(refreshButton, 'click', function () {
  42014. var newOption;
  42015. try {
  42016. if (typeof contentToOption === 'function') {
  42017. newOption = contentToOption(viewMain, api.getOption());
  42018. }
  42019. else {
  42020. newOption = parseContents(textarea.value, blockMetaList);
  42021. }
  42022. }
  42023. catch (e) {
  42024. close();
  42025. throw new Error('Data view format error ' + e);
  42026. }
  42027. if (newOption) {
  42028. api.dispatchAction({
  42029. type: 'changeDataView',
  42030. newOption: newOption
  42031. });
  42032. }
  42033. close();
  42034. });
  42035. closeButton.innerHTML = lang$$1[1];
  42036. refreshButton.innerHTML = lang$$1[2];
  42037. refreshButton.style.cssText = buttonStyle;
  42038. closeButton.style.cssText = buttonStyle;
  42039. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  42040. buttonContainer.appendChild(closeButton);
  42041. // http://stackoverflow.com/questions/6637341/use-tab-to-indent-in-textarea
  42042. addEventListener(textarea, 'keydown', function (e) {
  42043. if ((e.keyCode || e.which) === 9) {
  42044. // get caret position/selection
  42045. var val = this.value;
  42046. var start = this.selectionStart;
  42047. var end = this.selectionEnd;
  42048. // set textarea value to: text before caret + tab + text after caret
  42049. this.value = val.substring(0, start) + ITEM_SPLITER + val.substring(end);
  42050. // put caret at right position again
  42051. this.selectionStart = this.selectionEnd = start + 1;
  42052. // prevent the focus lose
  42053. stop(e);
  42054. }
  42055. });
  42056. root.appendChild(header);
  42057. root.appendChild(viewMain);
  42058. root.appendChild(buttonContainer);
  42059. viewMain.style.height = (container.clientHeight - 80) + 'px';
  42060. container.appendChild(root);
  42061. this._dom = root;
  42062. };
  42063. DataView.prototype.remove = function (ecModel, api) {
  42064. this._dom && api.getDom().removeChild(this._dom);
  42065. };
  42066. DataView.prototype.dispose = function (ecModel, api) {
  42067. this.remove(ecModel, api);
  42068. };
  42069. /**
  42070. * @inner
  42071. */
  42072. function tryMergeDataOption(newData, originalData) {
  42073. return map(newData, function (newVal, idx) {
  42074. var original = originalData && originalData[idx];
  42075. if (isObject$1(original) && !isArray(original)) {
  42076. if (isObject$1(newVal) && !isArray(newVal)) {
  42077. newVal = newVal.value;
  42078. }
  42079. // Original data has option
  42080. return defaults({
  42081. value: newVal
  42082. }, original);
  42083. }
  42084. else {
  42085. return newVal;
  42086. }
  42087. });
  42088. }
  42089. register$2('dataView', DataView);
  42090. registerAction({
  42091. type: 'changeDataView',
  42092. event: 'dataViewChanged',
  42093. update: 'prepareAndUpdate'
  42094. }, function (payload, ecModel) {
  42095. var newSeriesOptList = [];
  42096. each$1(payload.newOption.series, function (seriesOpt) {
  42097. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  42098. if (!seriesModel) {
  42099. // New created series
  42100. // Geuss the series type
  42101. newSeriesOptList.push(extend({
  42102. // Default is scatter
  42103. type: 'scatter'
  42104. }, seriesOpt));
  42105. }
  42106. else {
  42107. var originalData = seriesModel.get('data');
  42108. newSeriesOptList.push({
  42109. name: seriesOpt.name,
  42110. data: tryMergeDataOption(seriesOpt.data, originalData)
  42111. });
  42112. }
  42113. });
  42114. ecModel.mergeOption(defaults({
  42115. series: newSeriesOptList
  42116. }, payload.newOption));
  42117. });
  42118. var curry$6 = curry;
  42119. var each$17 = each$1;
  42120. var map$2 = map;
  42121. var mathMin$4 = Math.min;
  42122. var mathMax$4 = Math.max;
  42123. var mathPow$2 = Math.pow;
  42124. var COVER_Z = 10000;
  42125. var UNSELECT_THRESHOLD = 6;
  42126. var MIN_RESIZE_LINE_WIDTH = 6;
  42127. var MUTEX_RESOURCE_KEY = 'globalPan';
  42128. var DIRECTION_MAP = {
  42129. w: [0, 0],
  42130. e: [0, 1],
  42131. n: [1, 0],
  42132. s: [1, 1]
  42133. };
  42134. var CURSOR_MAP = {
  42135. w: 'ew',
  42136. e: 'ew',
  42137. n: 'ns',
  42138. s: 'ns',
  42139. ne: 'nesw',
  42140. sw: 'nesw',
  42141. nw: 'nwse',
  42142. se: 'nwse'
  42143. };
  42144. var DEFAULT_BRUSH_OPT = {
  42145. brushStyle: {
  42146. lineWidth: 2,
  42147. stroke: 'rgba(0,0,0,0.3)',
  42148. fill: 'rgba(0,0,0,0.1)'
  42149. },
  42150. transformable: true,
  42151. brushMode: 'single',
  42152. removeOnClick: false
  42153. };
  42154. var baseUID = 0;
  42155. /**
  42156. * @alias module:echarts/component/helper/BrushController
  42157. * @constructor
  42158. * @mixin {module:zrender/mixin/Eventful}
  42159. * @event module:echarts/component/helper/BrushController#brush
  42160. * params:
  42161. * areas: Array.<Array>, coord relates to container group,
  42162. * If no container specified, to global.
  42163. * opt {
  42164. * isEnd: boolean,
  42165. * removeOnClick: boolean
  42166. * }
  42167. *
  42168. * @param {module:zrender/zrender~ZRender} zr
  42169. */
  42170. function BrushController(zr) {
  42171. if (__DEV__) {
  42172. assert$1(zr);
  42173. }
  42174. Eventful.call(this);
  42175. /**
  42176. * @type {module:zrender/zrender~ZRender}
  42177. * @private
  42178. */
  42179. this._zr = zr;
  42180. /**
  42181. * @type {module:zrender/container/Group}
  42182. * @readOnly
  42183. */
  42184. this.group = new Group();
  42185. /**
  42186. * Only for drawing (after enabledBrush).
  42187. * 'line', 'rect', 'polygon' or false
  42188. * If passing false/null/undefined, disable brush.
  42189. * If passing 'auto', determined by panel.defaultBrushType
  42190. * @private
  42191. * @type {string}
  42192. */
  42193. this._brushType;
  42194. /**
  42195. * Only for drawing (after enabledBrush).
  42196. *
  42197. * @private
  42198. * @type {Object}
  42199. */
  42200. this._brushOption;
  42201. /**
  42202. * @private
  42203. * @type {Object}
  42204. */
  42205. this._panels;
  42206. /**
  42207. * @private
  42208. * @type {Array.<nubmer>}
  42209. */
  42210. this._track = [];
  42211. /**
  42212. * @private
  42213. * @type {boolean}
  42214. */
  42215. this._dragging;
  42216. /**
  42217. * @private
  42218. * @type {Array}
  42219. */
  42220. this._covers = [];
  42221. /**
  42222. * @private
  42223. * @type {moudule:zrender/container/Group}
  42224. */
  42225. this._creatingCover;
  42226. /**
  42227. * `true` means global panel
  42228. * @private
  42229. * @type {module:zrender/container/Group|boolean}
  42230. */
  42231. this._creatingPanel;
  42232. /**
  42233. * @private
  42234. * @type {boolean}
  42235. */
  42236. this._enableGlobalPan;
  42237. /**
  42238. * @private
  42239. * @type {boolean}
  42240. */
  42241. if (__DEV__) {
  42242. this._mounted;
  42243. }
  42244. /**
  42245. * @private
  42246. * @type {string}
  42247. */
  42248. this._uid = 'brushController_' + baseUID++;
  42249. /**
  42250. * @private
  42251. * @type {Object}
  42252. */
  42253. this._handlers = {};
  42254. each$17(mouseHandlers, function (handler, eventName) {
  42255. this._handlers[eventName] = bind(handler, this);
  42256. }, this);
  42257. }
  42258. BrushController.prototype = {
  42259. constructor: BrushController,
  42260. /**
  42261. * If set to null/undefined/false, select disabled.
  42262. * @param {Object} brushOption
  42263. * @param {string|boolean} brushOption.brushType 'line', 'rect', 'polygon' or false
  42264. * If passing false/null/undefined, disable brush.
  42265. * If passing 'auto', determined by panel.defaultBrushType.
  42266. * ('auto' can not be used in global panel)
  42267. * @param {number} [brushOption.brushMode='single'] 'single' or 'multiple'
  42268. * @param {boolean} [brushOption.transformable=true]
  42269. * @param {boolean} [brushOption.removeOnClick=false]
  42270. * @param {Object} [brushOption.brushStyle]
  42271. * @param {number} [brushOption.brushStyle.width]
  42272. * @param {number} [brushOption.brushStyle.lineWidth]
  42273. * @param {string} [brushOption.brushStyle.stroke]
  42274. * @param {string} [brushOption.brushStyle.fill]
  42275. * @param {number} [brushOption.z]
  42276. */
  42277. enableBrush: function (brushOption) {
  42278. if (__DEV__) {
  42279. assert$1(this._mounted);
  42280. }
  42281. this._brushType && doDisableBrush(this);
  42282. brushOption.brushType && doEnableBrush(this, brushOption);
  42283. return this;
  42284. },
  42285. /**
  42286. * @param {Array.<Object>} panelOpts If not pass, it is global brush.
  42287. * Each items: {
  42288. * panelId, // mandatory.
  42289. * clipPath, // mandatory. function.
  42290. * isTargetByCursor, // mandatory. function.
  42291. * defaultBrushType, // optional, only used when brushType is 'auto'.
  42292. * getLinearBrushOtherExtent, // optional. function.
  42293. * }
  42294. */
  42295. setPanels: function (panelOpts) {
  42296. if (panelOpts && panelOpts.length) {
  42297. var panels = this._panels = {};
  42298. each$1(panelOpts, function (panelOpts) {
  42299. panels[panelOpts.panelId] = clone(panelOpts);
  42300. });
  42301. }
  42302. else {
  42303. this._panels = null;
  42304. }
  42305. return this;
  42306. },
  42307. /**
  42308. * @param {Object} [opt]
  42309. * @return {boolean} [opt.enableGlobalPan=false]
  42310. */
  42311. mount: function (opt) {
  42312. opt = opt || {};
  42313. if (__DEV__) {
  42314. this._mounted = true; // should be at first.
  42315. }
  42316. this._enableGlobalPan = opt.enableGlobalPan;
  42317. var thisGroup = this.group;
  42318. this._zr.add(thisGroup);
  42319. thisGroup.attr({
  42320. position: opt.position || [0, 0],
  42321. rotation: opt.rotation || 0,
  42322. scale: opt.scale || [1, 1]
  42323. });
  42324. this._transform = thisGroup.getLocalTransform();
  42325. return this;
  42326. },
  42327. eachCover: function (cb, context) {
  42328. each$17(this._covers, cb, context);
  42329. },
  42330. /**
  42331. * Update covers.
  42332. * @param {Array.<Object>} brushOptionList Like:
  42333. * [
  42334. * {id: 'xx', brushType: 'line', range: [23, 44], brushStyle, transformable},
  42335. * {id: 'yy', brushType: 'rect', range: [[23, 44], [23, 54]]},
  42336. * ...
  42337. * ]
  42338. * `brushType` is required in each cover info. (can not be 'auto')
  42339. * `id` is not mandatory.
  42340. * `brushStyle`, `transformable` is not mandatory, use DEFAULT_BRUSH_OPT by default.
  42341. * If brushOptionList is null/undefined, all covers removed.
  42342. */
  42343. updateCovers: function (brushOptionList) {
  42344. if (__DEV__) {
  42345. assert$1(this._mounted);
  42346. }
  42347. brushOptionList = map(brushOptionList, function (brushOption) {
  42348. return merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  42349. });
  42350. var tmpIdPrefix = '\0-brush-index-';
  42351. var oldCovers = this._covers;
  42352. var newCovers = this._covers = [];
  42353. var controller = this;
  42354. var creatingCover = this._creatingCover;
  42355. (new DataDiffer(oldCovers, brushOptionList, oldGetKey, getKey))
  42356. .add(addOrUpdate)
  42357. .update(addOrUpdate)
  42358. .remove(remove)
  42359. .execute();
  42360. return this;
  42361. function getKey(brushOption, index) {
  42362. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index)
  42363. + '-' + brushOption.brushType;
  42364. }
  42365. function oldGetKey(cover, index) {
  42366. return getKey(cover.__brushOption, index);
  42367. }
  42368. function addOrUpdate(newIndex, oldIndex) {
  42369. var newBrushOption = brushOptionList[newIndex];
  42370. // Consider setOption in event listener of brushSelect,
  42371. // where updating cover when creating should be forbiden.
  42372. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  42373. newCovers[newIndex] = oldCovers[oldIndex];
  42374. }
  42375. else {
  42376. var cover = newCovers[newIndex] = oldIndex != null
  42377. ? (
  42378. oldCovers[oldIndex].__brushOption = newBrushOption,
  42379. oldCovers[oldIndex]
  42380. )
  42381. : endCreating(controller, createCover(controller, newBrushOption));
  42382. updateCoverAfterCreation(controller, cover);
  42383. }
  42384. }
  42385. function remove(oldIndex) {
  42386. if (oldCovers[oldIndex] !== creatingCover) {
  42387. controller.group.remove(oldCovers[oldIndex]);
  42388. }
  42389. }
  42390. },
  42391. unmount: function () {
  42392. if (__DEV__) {
  42393. if (!this._mounted) {
  42394. return;
  42395. }
  42396. }
  42397. this.enableBrush(false);
  42398. // container may 'removeAll' outside.
  42399. clearCovers(this);
  42400. this._zr.remove(this.group);
  42401. if (__DEV__) {
  42402. this._mounted = false; // should be at last.
  42403. }
  42404. return this;
  42405. },
  42406. dispose: function () {
  42407. this.unmount();
  42408. this.off();
  42409. }
  42410. };
  42411. mixin(BrushController, Eventful);
  42412. function doEnableBrush(controller, brushOption) {
  42413. var zr = controller._zr;
  42414. // Consider roam, which takes globalPan too.
  42415. if (!controller._enableGlobalPan) {
  42416. take(zr, MUTEX_RESOURCE_KEY, controller._uid);
  42417. }
  42418. each$17(controller._handlers, function (handler, eventName) {
  42419. zr.on(eventName, handler);
  42420. });
  42421. controller._brushType = brushOption.brushType;
  42422. controller._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  42423. }
  42424. function doDisableBrush(controller) {
  42425. var zr = controller._zr;
  42426. release(zr, MUTEX_RESOURCE_KEY, controller._uid);
  42427. each$17(controller._handlers, function (handler, eventName) {
  42428. zr.off(eventName, handler);
  42429. });
  42430. controller._brushType = controller._brushOption = null;
  42431. }
  42432. function createCover(controller, brushOption) {
  42433. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  42434. cover.__brushOption = brushOption;
  42435. updateZ$1(cover, brushOption);
  42436. controller.group.add(cover);
  42437. return cover;
  42438. }
  42439. function endCreating(controller, creatingCover) {
  42440. var coverRenderer = getCoverRenderer(creatingCover);
  42441. if (coverRenderer.endCreating) {
  42442. coverRenderer.endCreating(controller, creatingCover);
  42443. updateZ$1(creatingCover, creatingCover.__brushOption);
  42444. }
  42445. return creatingCover;
  42446. }
  42447. function updateCoverShape(controller, cover) {
  42448. var brushOption = cover.__brushOption;
  42449. getCoverRenderer(cover).updateCoverShape(
  42450. controller, cover, brushOption.range, brushOption
  42451. );
  42452. }
  42453. function updateZ$1(cover, brushOption) {
  42454. var z = brushOption.z;
  42455. z == null && (z = COVER_Z);
  42456. cover.traverse(function (el) {
  42457. el.z = z;
  42458. el.z2 = z; // Consider in given container.
  42459. });
  42460. }
  42461. function updateCoverAfterCreation(controller, cover) {
  42462. getCoverRenderer(cover).updateCommon(controller, cover);
  42463. updateCoverShape(controller, cover);
  42464. }
  42465. function getCoverRenderer(cover) {
  42466. return coverRenderers[cover.__brushOption.brushType];
  42467. }
  42468. // return target panel or `true` (means global panel)
  42469. function getPanelByPoint(controller, e, localCursorPoint) {
  42470. var panels = controller._panels;
  42471. if (!panels) {
  42472. return true; // Global panel
  42473. }
  42474. var panel;
  42475. var transform = controller._transform;
  42476. each$17(panels, function (pn) {
  42477. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  42478. });
  42479. return panel;
  42480. }
  42481. // Return a panel or true
  42482. function getPanelByCover(controller, cover) {
  42483. var panels = controller._panels;
  42484. if (!panels) {
  42485. return true; // Global panel
  42486. }
  42487. var panelId = cover.__brushOption.panelId;
  42488. // User may give cover without coord sys info,
  42489. // which is then treated as global panel.
  42490. return panelId != null ? panels[panelId] : true;
  42491. }
  42492. function clearCovers(controller) {
  42493. var covers = controller._covers;
  42494. var originalLength = covers.length;
  42495. each$17(covers, function (cover) {
  42496. controller.group.remove(cover);
  42497. }, controller);
  42498. covers.length = 0;
  42499. return !!originalLength;
  42500. }
  42501. function trigger(controller, opt) {
  42502. var areas = map$2(controller._covers, function (cover) {
  42503. var brushOption = cover.__brushOption;
  42504. var range = clone(brushOption.range);
  42505. return {
  42506. brushType: brushOption.brushType,
  42507. panelId: brushOption.panelId,
  42508. range: range
  42509. };
  42510. });
  42511. controller.trigger('brush', areas, {
  42512. isEnd: !!opt.isEnd,
  42513. removeOnClick: !!opt.removeOnClick
  42514. });
  42515. }
  42516. function shouldShowCover(controller) {
  42517. var track = controller._track;
  42518. if (!track.length) {
  42519. return false;
  42520. }
  42521. var p2 = track[track.length - 1];
  42522. var p1 = track[0];
  42523. var dx = p2[0] - p1[0];
  42524. var dy = p2[1] - p1[1];
  42525. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  42526. return dist > UNSELECT_THRESHOLD;
  42527. }
  42528. function getTrackEnds(track) {
  42529. var tail = track.length - 1;
  42530. tail < 0 && (tail = 0);
  42531. return [track[0], track[tail]];
  42532. }
  42533. function createBaseRectCover(doDrift, controller, brushOption, edgeNames) {
  42534. var cover = new Group();
  42535. cover.add(new Rect({
  42536. name: 'main',
  42537. style: makeStyle(brushOption),
  42538. silent: true,
  42539. draggable: true,
  42540. cursor: 'move',
  42541. drift: curry$6(doDrift, controller, cover, 'nswe'),
  42542. ondragend: curry$6(trigger, controller, {isEnd: true})
  42543. }));
  42544. each$17(
  42545. edgeNames,
  42546. function (name) {
  42547. cover.add(new Rect({
  42548. name: name,
  42549. style: {opacity: 0},
  42550. draggable: true,
  42551. silent: true,
  42552. invisible: true,
  42553. drift: curry$6(doDrift, controller, cover, name),
  42554. ondragend: curry$6(trigger, controller, {isEnd: true})
  42555. }));
  42556. }
  42557. );
  42558. return cover;
  42559. }
  42560. function updateBaseRect(controller, cover, localRange, brushOption) {
  42561. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  42562. var handleSize = mathMax$4(lineWidth, MIN_RESIZE_LINE_WIDTH);
  42563. var x = localRange[0][0];
  42564. var y = localRange[1][0];
  42565. var xa = x - lineWidth / 2;
  42566. var ya = y - lineWidth / 2;
  42567. var x2 = localRange[0][1];
  42568. var y2 = localRange[1][1];
  42569. var x2a = x2 - handleSize + lineWidth / 2;
  42570. var y2a = y2 - handleSize + lineWidth / 2;
  42571. var width = x2 - x;
  42572. var height = y2 - y;
  42573. var widtha = width + lineWidth;
  42574. var heighta = height + lineWidth;
  42575. updateRectShape(controller, cover, 'main', x, y, width, height);
  42576. if (brushOption.transformable) {
  42577. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  42578. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  42579. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  42580. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  42581. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  42582. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  42583. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  42584. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  42585. }
  42586. }
  42587. function updateCommon(controller, cover) {
  42588. var brushOption = cover.__brushOption;
  42589. var transformable = brushOption.transformable;
  42590. var mainEl = cover.childAt(0);
  42591. mainEl.useStyle(makeStyle(brushOption));
  42592. mainEl.attr({
  42593. silent: !transformable,
  42594. cursor: transformable ? 'move' : 'default'
  42595. });
  42596. each$17(
  42597. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw'],
  42598. function (name) {
  42599. var el = cover.childOfName(name);
  42600. var globalDir = getGlobalDirection(controller, name);
  42601. el && el.attr({
  42602. silent: !transformable,
  42603. invisible: !transformable,
  42604. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  42605. });
  42606. }
  42607. );
  42608. }
  42609. function updateRectShape(controller, cover, name, x, y, w, h) {
  42610. var el = cover.childOfName(name);
  42611. el && el.setShape(pointsToRect(
  42612. clipByPanel(controller, cover, [[x, y], [x + w, y + h]])
  42613. ));
  42614. }
  42615. function makeStyle(brushOption) {
  42616. return defaults({strokeNoScale: true}, brushOption.brushStyle);
  42617. }
  42618. function formatRectRange(x, y, x2, y2) {
  42619. var min = [mathMin$4(x, x2), mathMin$4(y, y2)];
  42620. var max = [mathMax$4(x, x2), mathMax$4(y, y2)];
  42621. return [
  42622. [min[0], max[0]], // x range
  42623. [min[1], max[1]] // y range
  42624. ];
  42625. }
  42626. function getTransform$1(controller) {
  42627. return getTransform(controller.group);
  42628. }
  42629. function getGlobalDirection(controller, localDirection) {
  42630. if (localDirection.length > 1) {
  42631. localDirection = localDirection.split('');
  42632. var globalDir = [
  42633. getGlobalDirection(controller, localDirection[0]),
  42634. getGlobalDirection(controller, localDirection[1])
  42635. ];
  42636. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  42637. return globalDir.join('');
  42638. }
  42639. else {
  42640. var map$$1 = {w: 'left', e: 'right', n: 'top', s: 'bottom'};
  42641. var inverseMap = {left: 'w', right: 'e', top: 'n', bottom: 's'};
  42642. var globalDir = transformDirection(
  42643. map$$1[localDirection], getTransform$1(controller)
  42644. );
  42645. return inverseMap[globalDir];
  42646. }
  42647. }
  42648. function driftRect(toRectRange, fromRectRange, controller, cover, name, dx, dy, e) {
  42649. var brushOption = cover.__brushOption;
  42650. var rectRange = toRectRange(brushOption.range);
  42651. var localDelta = toLocalDelta(controller, dx, dy);
  42652. each$17(name.split(''), function (namePart) {
  42653. var ind = DIRECTION_MAP[namePart];
  42654. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  42655. });
  42656. brushOption.range = fromRectRange(formatRectRange(
  42657. rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]
  42658. ));
  42659. updateCoverAfterCreation(controller, cover);
  42660. trigger(controller, {isEnd: false});
  42661. }
  42662. function driftPolygon(controller, cover, dx, dy, e) {
  42663. var range = cover.__brushOption.range;
  42664. var localDelta = toLocalDelta(controller, dx, dy);
  42665. each$17(range, function (point) {
  42666. point[0] += localDelta[0];
  42667. point[1] += localDelta[1];
  42668. });
  42669. updateCoverAfterCreation(controller, cover);
  42670. trigger(controller, {isEnd: false});
  42671. }
  42672. function toLocalDelta(controller, dx, dy) {
  42673. var thisGroup = controller.group;
  42674. var localD = thisGroup.transformCoordToLocal(dx, dy);
  42675. var localZero = thisGroup.transformCoordToLocal(0, 0);
  42676. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  42677. }
  42678. function clipByPanel(controller, cover, data) {
  42679. var panel = getPanelByCover(controller, cover);
  42680. return (panel && panel !== true)
  42681. ? panel.clipPath(data, controller._transform)
  42682. : clone(data);
  42683. }
  42684. function pointsToRect(points) {
  42685. var xmin = mathMin$4(points[0][0], points[1][0]);
  42686. var ymin = mathMin$4(points[0][1], points[1][1]);
  42687. var xmax = mathMax$4(points[0][0], points[1][0]);
  42688. var ymax = mathMax$4(points[0][1], points[1][1]);
  42689. return {
  42690. x: xmin,
  42691. y: ymin,
  42692. width: xmax - xmin,
  42693. height: ymax - ymin
  42694. };
  42695. }
  42696. function resetCursor(controller, e, localCursorPoint) {
  42697. // Check active
  42698. if (!controller._brushType) {
  42699. return;
  42700. }
  42701. var zr = controller._zr;
  42702. var covers = controller._covers;
  42703. var currPanel = getPanelByPoint(controller, e, localCursorPoint);
  42704. // Check whether in covers.
  42705. if (!controller._dragging) {
  42706. for (var i = 0; i < covers.length; i++) {
  42707. var brushOption = covers[i].__brushOption;
  42708. if (currPanel
  42709. && (currPanel === true || brushOption.panelId === currPanel.panelId)
  42710. && coverRenderers[brushOption.brushType].contain(
  42711. covers[i], localCursorPoint[0], localCursorPoint[1]
  42712. )
  42713. ) {
  42714. // Use cursor style set on cover.
  42715. return;
  42716. }
  42717. }
  42718. }
  42719. currPanel && zr.setCursorStyle('crosshair');
  42720. }
  42721. function preventDefault(e) {
  42722. var rawE = e.event;
  42723. rawE.preventDefault && rawE.preventDefault();
  42724. }
  42725. function mainShapeContain(cover, x, y) {
  42726. return cover.childOfName('main').contain(x, y);
  42727. }
  42728. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  42729. var creatingCover = controller._creatingCover;
  42730. var panel = controller._creatingPanel;
  42731. var thisBrushOption = controller._brushOption;
  42732. var eventParams;
  42733. controller._track.push(localCursorPoint.slice());
  42734. if (shouldShowCover(controller) || creatingCover) {
  42735. if (panel && !creatingCover) {
  42736. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  42737. var brushOption = clone(thisBrushOption);
  42738. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  42739. brushOption.panelId = panel === true ? null : panel.panelId;
  42740. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  42741. controller._covers.push(creatingCover);
  42742. }
  42743. if (creatingCover) {
  42744. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  42745. var coverBrushOption = creatingCover.__brushOption;
  42746. coverBrushOption.range = coverRenderer.getCreatingRange(
  42747. clipByPanel(controller, creatingCover, controller._track)
  42748. );
  42749. if (isEnd) {
  42750. endCreating(controller, creatingCover);
  42751. coverRenderer.updateCommon(controller, creatingCover);
  42752. }
  42753. updateCoverShape(controller, creatingCover);
  42754. eventParams = {isEnd: isEnd};
  42755. }
  42756. }
  42757. else if (
  42758. isEnd
  42759. && thisBrushOption.brushMode === 'single'
  42760. && thisBrushOption.removeOnClick
  42761. ) {
  42762. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  42763. // But a single click do not clear covers, because user may have casual
  42764. // clicks (for example, click on other component and do not expect covers
  42765. // disappear).
  42766. // Only some cover removed, trigger action, but not every click trigger action.
  42767. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  42768. eventParams = {isEnd: isEnd, removeOnClick: true};
  42769. }
  42770. }
  42771. return eventParams;
  42772. }
  42773. function determineBrushType(brushType, panel) {
  42774. if (brushType === 'auto') {
  42775. if (__DEV__) {
  42776. assert$1(
  42777. panel && panel.defaultBrushType,
  42778. 'MUST have defaultBrushType when brushType is "atuo"'
  42779. );
  42780. }
  42781. return panel.defaultBrushType;
  42782. }
  42783. return brushType;
  42784. }
  42785. var mouseHandlers = {
  42786. mousedown: function (e) {
  42787. if (this._dragging) {
  42788. // In case some browser do not support globalOut,
  42789. // and release mose out side the browser.
  42790. handleDragEnd.call(this, e);
  42791. }
  42792. else if (!e.target || !e.target.draggable) {
  42793. preventDefault(e);
  42794. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  42795. this._creatingCover = null;
  42796. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  42797. if (panel) {
  42798. this._dragging = true;
  42799. this._track = [localCursorPoint.slice()];
  42800. }
  42801. }
  42802. },
  42803. mousemove: function (e) {
  42804. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  42805. resetCursor(this, e, localCursorPoint);
  42806. if (this._dragging) {
  42807. preventDefault(e);
  42808. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  42809. eventParams && trigger(this, eventParams);
  42810. }
  42811. },
  42812. mouseup: handleDragEnd //,
  42813. // FIXME
  42814. // in tooltip, globalout should not be triggered.
  42815. // globalout: handleDragEnd
  42816. };
  42817. function handleDragEnd(e) {
  42818. if (this._dragging) {
  42819. preventDefault(e);
  42820. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  42821. var eventParams = updateCoverByMouse(this, e, localCursorPoint, true);
  42822. this._dragging = false;
  42823. this._track = [];
  42824. this._creatingCover = null;
  42825. // trigger event shoule be at final, after procedure will be nested.
  42826. eventParams && trigger(this, eventParams);
  42827. }
  42828. }
  42829. /**
  42830. * key: brushType
  42831. * @type {Object}
  42832. */
  42833. var coverRenderers = {
  42834. lineX: getLineRenderer(0),
  42835. lineY: getLineRenderer(1),
  42836. rect: {
  42837. createCover: function (controller, brushOption) {
  42838. return createBaseRectCover(
  42839. curry$6(
  42840. driftRect,
  42841. function (range) {
  42842. return range;
  42843. },
  42844. function (range) {
  42845. return range;
  42846. }
  42847. ),
  42848. controller,
  42849. brushOption,
  42850. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw']
  42851. );
  42852. },
  42853. getCreatingRange: function (localTrack) {
  42854. var ends = getTrackEnds(localTrack);
  42855. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  42856. },
  42857. updateCoverShape: function (controller, cover, localRange, brushOption) {
  42858. updateBaseRect(controller, cover, localRange, brushOption);
  42859. },
  42860. updateCommon: updateCommon,
  42861. contain: mainShapeContain
  42862. },
  42863. polygon: {
  42864. createCover: function (controller, brushOption) {
  42865. var cover = new Group();
  42866. // Do not use graphic.Polygon because graphic.Polyline do not close the
  42867. // border of the shape when drawing, which is a better experience for user.
  42868. cover.add(new Polyline({
  42869. name: 'main',
  42870. style: makeStyle(brushOption),
  42871. silent: true
  42872. }));
  42873. return cover;
  42874. },
  42875. getCreatingRange: function (localTrack) {
  42876. return localTrack;
  42877. },
  42878. endCreating: function (controller, cover) {
  42879. cover.remove(cover.childAt(0));
  42880. // Use graphic.Polygon close the shape.
  42881. cover.add(new Polygon({
  42882. name: 'main',
  42883. draggable: true,
  42884. drift: curry$6(driftPolygon, controller, cover),
  42885. ondragend: curry$6(trigger, controller, {isEnd: true})
  42886. }));
  42887. },
  42888. updateCoverShape: function (controller, cover, localRange, brushOption) {
  42889. cover.childAt(0).setShape({
  42890. points: clipByPanel(controller, cover, localRange)
  42891. });
  42892. },
  42893. updateCommon: updateCommon,
  42894. contain: mainShapeContain
  42895. }
  42896. };
  42897. function getLineRenderer(xyIndex) {
  42898. return {
  42899. createCover: function (controller, brushOption) {
  42900. return createBaseRectCover(
  42901. curry$6(
  42902. driftRect,
  42903. function (range) {
  42904. var rectRange = [range, [0, 100]];
  42905. xyIndex && rectRange.reverse();
  42906. return rectRange;
  42907. },
  42908. function (rectRange) {
  42909. return rectRange[xyIndex];
  42910. }
  42911. ),
  42912. controller,
  42913. brushOption,
  42914. [['w', 'e'], ['n', 's']][xyIndex]
  42915. );
  42916. },
  42917. getCreatingRange: function (localTrack) {
  42918. var ends = getTrackEnds(localTrack);
  42919. var min = mathMin$4(ends[0][xyIndex], ends[1][xyIndex]);
  42920. var max = mathMax$4(ends[0][xyIndex], ends[1][xyIndex]);
  42921. return [min, max];
  42922. },
  42923. updateCoverShape: function (controller, cover, localRange, brushOption) {
  42924. var otherExtent;
  42925. // If brushWidth not specified, fit the panel.
  42926. var panel = getPanelByCover(controller, cover);
  42927. if (panel !== true && panel.getLinearBrushOtherExtent) {
  42928. otherExtent = panel.getLinearBrushOtherExtent(
  42929. xyIndex, controller._transform
  42930. );
  42931. }
  42932. else {
  42933. var zr = controller._zr;
  42934. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  42935. }
  42936. var rectRange = [localRange, otherExtent];
  42937. xyIndex && rectRange.reverse();
  42938. updateBaseRect(controller, cover, rectRange, brushOption);
  42939. },
  42940. updateCommon: updateCommon,
  42941. contain: mainShapeContain
  42942. };
  42943. }
  42944. var IRRELEVANT_EXCLUDES = {'axisPointer': 1, 'tooltip': 1, 'brush': 1};
  42945. /**
  42946. * Avoid that: mouse click on a elements that is over geo or graph,
  42947. * but roam is triggered.
  42948. */
  42949. function onIrrelevantElement(e, api, targetCoordSysModel) {
  42950. var model = api.getComponentByElement(e.topTarget);
  42951. // If model is axisModel, it works only if it is injected with coordinateSystem.
  42952. var coordSys = model && model.coordinateSystem;
  42953. return model
  42954. && model !== targetCoordSysModel
  42955. && !IRRELEVANT_EXCLUDES[model.mainType]
  42956. && (coordSys && coordSys.model !== targetCoordSysModel);
  42957. }
  42958. function makeRectPanelClipPath(rect) {
  42959. rect = normalizeRect(rect);
  42960. return function (localPoints, transform) {
  42961. return clipPointsByRect(localPoints, rect);
  42962. };
  42963. }
  42964. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  42965. rect = normalizeRect(rect);
  42966. return function (xyIndex) {
  42967. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  42968. var brushWidth = idx ? rect.width : rect.height;
  42969. var base = idx ? rect.x : rect.y;
  42970. return [base, base + (brushWidth || 0)];
  42971. };
  42972. }
  42973. function makeRectIsTargetByCursor(rect, api, targetModel) {
  42974. rect = normalizeRect(rect);
  42975. return function (e, localCursorPoint, transform) {
  42976. return rect.contain(localCursorPoint[0], localCursorPoint[1])
  42977. && !onIrrelevantElement(e, api, targetModel);
  42978. };
  42979. }
  42980. // Consider width/height is negative.
  42981. function normalizeRect(rect) {
  42982. return BoundingRect.create(rect);
  42983. }
  42984. var each$18 = each$1;
  42985. var indexOf$2 = indexOf;
  42986. var curry$7 = curry;
  42987. var COORD_CONVERTS = ['dataToPoint', 'pointToData'];
  42988. // FIXME
  42989. // how to genarialize to more coordinate systems.
  42990. var INCLUDE_FINDER_MAIN_TYPES = [
  42991. 'grid', 'xAxis', 'yAxis', 'geo', 'graph',
  42992. 'polar', 'radiusAxis', 'angleAxis', 'bmap'
  42993. ];
  42994. /**
  42995. * [option in constructor]:
  42996. * {
  42997. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  42998. * }
  42999. *
  43000. *
  43001. * [targetInfo]:
  43002. *
  43003. * There can be multiple axes in a single targetInfo. Consider the case
  43004. * of `grid` component, a targetInfo represents a grid which contains one or more
  43005. * cartesian and one or more axes. And consider the case of parallel system,
  43006. * which has multiple axes in a coordinate system.
  43007. * Can be {
  43008. * panelId: ...,
  43009. * coordSys: <a representitive cartesian in grid (first cartesian by default)>,
  43010. * coordSyses: all cartesians.
  43011. * gridModel: <grid component>
  43012. * xAxes: correspond to coordSyses on index
  43013. * yAxes: correspond to coordSyses on index
  43014. * }
  43015. * or {
  43016. * panelId: ...,
  43017. * coordSys: <geo coord sys>
  43018. * coordSyses: [<geo coord sys>]
  43019. * geoModel: <geo component>
  43020. * }
  43021. *
  43022. *
  43023. * [panelOpt]:
  43024. *
  43025. * Make from targetInfo. Input to BrushController.
  43026. * {
  43027. * panelId: ...,
  43028. * rect: ...
  43029. * }
  43030. *
  43031. *
  43032. * [area]:
  43033. *
  43034. * Generated by BrushController or user input.
  43035. * {
  43036. * panelId: Used to locate coordInfo directly. If user inpput, no panelId.
  43037. * brushType: determine how to convert to/from coord('rect' or 'polygon' or 'lineX/Y').
  43038. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  43039. * range: pixel range.
  43040. * coordRange: representitive coord range (the first one of coordRanges).
  43041. * coordRanges: <Array> coord ranges, used in multiple cartesian in one grid.
  43042. * }
  43043. */
  43044. /**
  43045. * @param {Object} option contains Index/Id/Name of xAxis/yAxis/geo/grid
  43046. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  43047. * @param {module:echarts/model/Global} ecModel
  43048. * @param {Object} [opt]
  43049. * @param {Array.<string>} [opt.include] include coordinate system types.
  43050. */
  43051. function BrushTargetManager(option, ecModel, opt) {
  43052. /**
  43053. * @private
  43054. * @type {Array.<Object>}
  43055. */
  43056. var targetInfoList = this._targetInfoList = [];
  43057. var info = {};
  43058. var foundCpts = parseFinder$1(ecModel, option);
  43059. each$18(targetInfoBuilders, function (builder, type) {
  43060. if (!opt || !opt.include || indexOf$2(opt.include, type) >= 0) {
  43061. builder(foundCpts, targetInfoList, info);
  43062. }
  43063. });
  43064. }
  43065. var proto$5 = BrushTargetManager.prototype;
  43066. proto$5.setOutputRanges = function (areas, ecModel) {
  43067. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  43068. (area.coordRanges || (area.coordRanges = [])).push(coordRange);
  43069. // area.coordRange is the first of area.coordRanges
  43070. if (!area.coordRange) {
  43071. area.coordRange = coordRange;
  43072. // In 'category' axis, coord to pixel is not reversible, so we can not
  43073. // rebuild range by coordRange accrately, which may bring trouble when
  43074. // brushing only one item. So we use __rangeOffset to rebuilding range
  43075. // by coordRange. And this it only used in brush component so it is no
  43076. // need to be adapted to coordRanges.
  43077. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  43078. area.__rangeOffset = {
  43079. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  43080. xyMinMax: result.xyMinMax
  43081. };
  43082. }
  43083. });
  43084. };
  43085. proto$5.matchOutputRanges = function (areas, ecModel, cb) {
  43086. each$18(areas, function (area) {
  43087. var targetInfo = this.findTargetInfo(area, ecModel);
  43088. if (targetInfo && targetInfo !== true) {
  43089. each$1(
  43090. targetInfo.coordSyses,
  43091. function (coordSys) {
  43092. var result = coordConvert[area.brushType](1, coordSys, area.range);
  43093. cb(area, result.values, coordSys, ecModel);
  43094. }
  43095. );
  43096. }
  43097. }, this);
  43098. };
  43099. proto$5.setInputRanges = function (areas, ecModel) {
  43100. each$18(areas, function (area) {
  43101. var targetInfo = this.findTargetInfo(area, ecModel);
  43102. if (__DEV__) {
  43103. assert$1(
  43104. !targetInfo || targetInfo === true || area.coordRange,
  43105. 'coordRange must be specified when coord index specified.'
  43106. );
  43107. assert$1(
  43108. !targetInfo || targetInfo !== true || area.range,
  43109. 'range must be specified in global brush.'
  43110. );
  43111. }
  43112. area.range = area.range || [];
  43113. // convert coordRange to global range and set panelId.
  43114. if (targetInfo && targetInfo !== true) {
  43115. area.panelId = targetInfo.panelId;
  43116. // (1) area.range shoule always be calculate from coordRange but does
  43117. // not keep its original value, for the sake of the dataZoom scenario,
  43118. // where area.coordRange remains unchanged but area.range may be changed.
  43119. // (2) Only support converting one coordRange to pixel range in brush
  43120. // component. So do not consider `coordRanges`.
  43121. // (3) About __rangeOffset, see comment above.
  43122. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  43123. var rangeOffset = area.__rangeOffset;
  43124. area.range = rangeOffset
  43125. ? diffProcessor[area.brushType](
  43126. result.values,
  43127. rangeOffset.offset,
  43128. getScales(result.xyMinMax, rangeOffset.xyMinMax)
  43129. )
  43130. : result.values;
  43131. }
  43132. }, this);
  43133. };
  43134. proto$5.makePanelOpts = function (api, getDefaultBrushType) {
  43135. return map(this._targetInfoList, function (targetInfo) {
  43136. var rect = targetInfo.getPanelRect();
  43137. return {
  43138. panelId: targetInfo.panelId,
  43139. defaultBrushType: getDefaultBrushType && getDefaultBrushType(targetInfo),
  43140. clipPath: makeRectPanelClipPath(rect),
  43141. isTargetByCursor: makeRectIsTargetByCursor(
  43142. rect, api, targetInfo.coordSysModel
  43143. ),
  43144. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  43145. };
  43146. });
  43147. };
  43148. proto$5.controlSeries = function (area, seriesModel, ecModel) {
  43149. // Check whether area is bound in coord, and series do not belong to that coord.
  43150. // If do not do this check, some brush (like lineX) will controll all axes.
  43151. var targetInfo = this.findTargetInfo(area, ecModel);
  43152. return targetInfo === true || (
  43153. targetInfo && indexOf$2(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0
  43154. );
  43155. };
  43156. /**
  43157. * If return Object, a coord found.
  43158. * If reutrn true, global found.
  43159. * Otherwise nothing found.
  43160. *
  43161. * @param {Object} area
  43162. * @param {Array} targetInfoList
  43163. * @return {Object|boolean}
  43164. */
  43165. proto$5.findTargetInfo = function (area, ecModel) {
  43166. var targetInfoList = this._targetInfoList;
  43167. var foundCpts = parseFinder$1(ecModel, area);
  43168. for (var i = 0; i < targetInfoList.length; i++) {
  43169. var targetInfo = targetInfoList[i];
  43170. var areaPanelId = area.panelId;
  43171. if (areaPanelId) {
  43172. if (targetInfo.panelId === areaPanelId) {
  43173. return targetInfo;
  43174. }
  43175. }
  43176. else {
  43177. for (var i = 0; i < targetInfoMatchers.length; i++) {
  43178. if (targetInfoMatchers[i](foundCpts, targetInfo)) {
  43179. return targetInfo;
  43180. }
  43181. }
  43182. }
  43183. }
  43184. return true;
  43185. };
  43186. function formatMinMax(minMax) {
  43187. minMax[0] > minMax[1] && minMax.reverse();
  43188. return minMax;
  43189. }
  43190. function parseFinder$1(ecModel, option) {
  43191. return parseFinder(
  43192. ecModel, option, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
  43193. );
  43194. }
  43195. var targetInfoBuilders = {
  43196. grid: function (foundCpts, targetInfoList) {
  43197. var xAxisModels = foundCpts.xAxisModels;
  43198. var yAxisModels = foundCpts.yAxisModels;
  43199. var gridModels = foundCpts.gridModels;
  43200. // Remove duplicated.
  43201. var gridModelMap = createHashMap();
  43202. var xAxesHas = {};
  43203. var yAxesHas = {};
  43204. if (!xAxisModels && !yAxisModels && !gridModels) {
  43205. return;
  43206. }
  43207. each$18(xAxisModels, function (axisModel) {
  43208. var gridModel = axisModel.axis.grid.model;
  43209. gridModelMap.set(gridModel.id, gridModel);
  43210. xAxesHas[gridModel.id] = true;
  43211. });
  43212. each$18(yAxisModels, function (axisModel) {
  43213. var gridModel = axisModel.axis.grid.model;
  43214. gridModelMap.set(gridModel.id, gridModel);
  43215. yAxesHas[gridModel.id] = true;
  43216. });
  43217. each$18(gridModels, function (gridModel) {
  43218. gridModelMap.set(gridModel.id, gridModel);
  43219. xAxesHas[gridModel.id] = true;
  43220. yAxesHas[gridModel.id] = true;
  43221. });
  43222. gridModelMap.each(function (gridModel) {
  43223. var grid = gridModel.coordinateSystem;
  43224. var cartesians = [];
  43225. each$18(grid.getCartesians(), function (cartesian, index) {
  43226. if (indexOf$2(xAxisModels, cartesian.getAxis('x').model) >= 0
  43227. || indexOf$2(yAxisModels, cartesian.getAxis('y').model) >= 0
  43228. ) {
  43229. cartesians.push(cartesian);
  43230. }
  43231. });
  43232. targetInfoList.push({
  43233. panelId: 'grid--' + gridModel.id,
  43234. gridModel: gridModel,
  43235. coordSysModel: gridModel,
  43236. // Use the first one as the representitive coordSys.
  43237. coordSys: cartesians[0],
  43238. coordSyses: cartesians,
  43239. getPanelRect: panelRectBuilder.grid,
  43240. xAxisDeclared: xAxesHas[gridModel.id],
  43241. yAxisDeclared: yAxesHas[gridModel.id]
  43242. });
  43243. });
  43244. },
  43245. geo: function (foundCpts, targetInfoList) {
  43246. each$18(foundCpts.geoModels, function (geoModel) {
  43247. var coordSys = geoModel.coordinateSystem;
  43248. targetInfoList.push({
  43249. panelId: 'geo--' + geoModel.id,
  43250. geoModel: geoModel,
  43251. coordSysModel: geoModel,
  43252. coordSys: coordSys,
  43253. coordSyses: [coordSys],
  43254. getPanelRect: panelRectBuilder.geo
  43255. });
  43256. });
  43257. }
  43258. };
  43259. var targetInfoMatchers = [
  43260. // grid
  43261. function (foundCpts, targetInfo) {
  43262. var xAxisModel = foundCpts.xAxisModel;
  43263. var yAxisModel = foundCpts.yAxisModel;
  43264. var gridModel = foundCpts.gridModel;
  43265. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  43266. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  43267. return gridModel && gridModel === targetInfo.gridModel;
  43268. },
  43269. // geo
  43270. function (foundCpts, targetInfo) {
  43271. var geoModel = foundCpts.geoModel;
  43272. return geoModel && geoModel === targetInfo.geoModel;
  43273. }
  43274. ];
  43275. var panelRectBuilder = {
  43276. grid: function () {
  43277. // grid is not Transformable.
  43278. return this.coordSys.grid.getRect().clone();
  43279. },
  43280. geo: function () {
  43281. var coordSys = this.coordSys;
  43282. var rect = coordSys.getBoundingRect().clone();
  43283. // geo roam and zoom transform
  43284. rect.applyTransform(getTransform(coordSys));
  43285. return rect;
  43286. }
  43287. };
  43288. var coordConvert = {
  43289. lineX: curry$7(axisConvert, 0),
  43290. lineY: curry$7(axisConvert, 1),
  43291. rect: function (to, coordSys, rangeOrCoordRange) {
  43292. var xminymin = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
  43293. var xmaxymax = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
  43294. var values = [
  43295. formatMinMax([xminymin[0], xmaxymax[0]]),
  43296. formatMinMax([xminymin[1], xmaxymax[1]])
  43297. ];
  43298. return {values: values, xyMinMax: values};
  43299. },
  43300. polygon: function (to, coordSys, rangeOrCoordRange) {
  43301. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  43302. var values = map(rangeOrCoordRange, function (item) {
  43303. var p = coordSys[COORD_CONVERTS[to]](item);
  43304. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  43305. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  43306. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  43307. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  43308. return p;
  43309. });
  43310. return {values: values, xyMinMax: xyMinMax};
  43311. }
  43312. };
  43313. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  43314. if (__DEV__) {
  43315. assert$1(
  43316. coordSys.type === 'cartesian2d',
  43317. 'lineX/lineY brush is available only in cartesian2d.'
  43318. );
  43319. }
  43320. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  43321. var values = formatMinMax(map([0, 1], function (i) {
  43322. return to
  43323. ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]))
  43324. : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  43325. }));
  43326. var xyMinMax = [];
  43327. xyMinMax[axisNameIndex] = values;
  43328. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  43329. return {values: values, xyMinMax: xyMinMax};
  43330. }
  43331. var diffProcessor = {
  43332. lineX: curry$7(axisDiffProcessor, 0),
  43333. lineY: curry$7(axisDiffProcessor, 1),
  43334. rect: function (values, refer, scales) {
  43335. return [
  43336. [values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
  43337. [values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
  43338. ];
  43339. },
  43340. polygon: function (values, refer, scales) {
  43341. return map(values, function (item, idx) {
  43342. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  43343. });
  43344. }
  43345. };
  43346. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  43347. return [
  43348. values[0] - scales[axisNameIndex] * refer[0],
  43349. values[1] - scales[axisNameIndex] * refer[1]
  43350. ];
  43351. }
  43352. // We have to process scale caused by dataZoom manually,
  43353. // although it might be not accurate.
  43354. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  43355. var sizeCurr = getSize(xyMinMaxCurr);
  43356. var sizeOrigin = getSize(xyMinMaxOrigin);
  43357. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  43358. isNaN(scales[0]) && (scales[0] = 1);
  43359. isNaN(scales[1]) && (scales[1] = 1);
  43360. return scales;
  43361. }
  43362. function getSize(xyMinMax) {
  43363. return xyMinMax
  43364. ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
  43365. : [NaN, NaN];
  43366. }
  43367. var each$19 = each$1;
  43368. var ATTR$2 = '\0_ec_hist_store';
  43369. /**
  43370. * @param {module:echarts/model/Global} ecModel
  43371. * @param {Object} newSnapshot {dataZoomId, batch: [payloadInfo, ...]}
  43372. */
  43373. function push(ecModel, newSnapshot) {
  43374. var store = giveStore$1(ecModel);
  43375. // If previous dataZoom can not be found,
  43376. // complete an range with current range.
  43377. each$19(newSnapshot, function (batchItem, dataZoomId) {
  43378. var i = store.length - 1;
  43379. for (; i >= 0; i--) {
  43380. var snapshot = store[i];
  43381. if (snapshot[dataZoomId]) {
  43382. break;
  43383. }
  43384. }
  43385. if (i < 0) {
  43386. // No origin range set, create one by current range.
  43387. var dataZoomModel = ecModel.queryComponents(
  43388. {mainType: 'dataZoom', subType: 'select', id: dataZoomId}
  43389. )[0];
  43390. if (dataZoomModel) {
  43391. var percentRange = dataZoomModel.getPercentRange();
  43392. store[0][dataZoomId] = {
  43393. dataZoomId: dataZoomId,
  43394. start: percentRange[0],
  43395. end: percentRange[1]
  43396. };
  43397. }
  43398. }
  43399. });
  43400. store.push(newSnapshot);
  43401. }
  43402. /**
  43403. * @param {module:echarts/model/Global} ecModel
  43404. * @return {Object} snapshot
  43405. */
  43406. function pop(ecModel) {
  43407. var store = giveStore$1(ecModel);
  43408. var head = store[store.length - 1];
  43409. store.length > 1 && store.pop();
  43410. // Find top for all dataZoom.
  43411. var snapshot = {};
  43412. each$19(head, function (batchItem, dataZoomId) {
  43413. for (var i = store.length - 1; i >= 0; i--) {
  43414. var batchItem = store[i][dataZoomId];
  43415. if (batchItem) {
  43416. snapshot[dataZoomId] = batchItem;
  43417. break;
  43418. }
  43419. }
  43420. });
  43421. return snapshot;
  43422. }
  43423. /**
  43424. * @param {module:echarts/model/Global} ecModel
  43425. */
  43426. function clear$1(ecModel) {
  43427. ecModel[ATTR$2] = null;
  43428. }
  43429. /**
  43430. * @param {module:echarts/model/Global} ecModel
  43431. * @return {number} records. always >= 1.
  43432. */
  43433. function count(ecModel) {
  43434. return giveStore$1(ecModel).length;
  43435. }
  43436. /**
  43437. * [{key: dataZoomId, value: {dataZoomId, range}}, ...]
  43438. * History length of each dataZoom may be different.
  43439. * this._history[0] is used to store origin range.
  43440. * @type {Array.<Object>}
  43441. */
  43442. function giveStore$1(ecModel) {
  43443. var store = ecModel[ATTR$2];
  43444. if (!store) {
  43445. store = ecModel[ATTR$2] = [{}];
  43446. }
  43447. return store;
  43448. }
  43449. DataZoomModel.extend({
  43450. type: 'dataZoom.select'
  43451. });
  43452. DataZoomView.extend({
  43453. type: 'dataZoom.select'
  43454. });
  43455. /**
  43456. * DataZoom component entry
  43457. */
  43458. // Use dataZoomSelect
  43459. var dataZoomLang = lang.toolbox.dataZoom;
  43460. var each$16 = each$1;
  43461. // Spectial component id start with \0ec\0, see echarts/model/Global.js~hasInnerId
  43462. var DATA_ZOOM_ID_BASE = '\0_ec_\0toolbox-dataZoom_';
  43463. function DataZoom(model, ecModel, api) {
  43464. /**
  43465. * @private
  43466. * @type {module:echarts/component/helper/BrushController}
  43467. */
  43468. (this._brushController = new BrushController(api.getZr()))
  43469. .on('brush', bind(this._onBrush, this))
  43470. .mount();
  43471. /**
  43472. * @private
  43473. * @type {boolean}
  43474. */
  43475. this._isZoomActive;
  43476. }
  43477. DataZoom.defaultOption = {
  43478. show: true,
  43479. // Icon group
  43480. icon: {
  43481. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  43482. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  43483. },
  43484. // `zoom`, `back`
  43485. title: clone(dataZoomLang.title)
  43486. };
  43487. var proto$4 = DataZoom.prototype;
  43488. proto$4.render = function (featureModel, ecModel, api, payload) {
  43489. this.model = featureModel;
  43490. this.ecModel = ecModel;
  43491. this.api = api;
  43492. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  43493. updateBackBtnStatus(featureModel, ecModel);
  43494. };
  43495. proto$4.onclick = function (ecModel, api, type) {
  43496. handlers[type].call(this);
  43497. };
  43498. proto$4.remove = function (ecModel, api) {
  43499. this._brushController.unmount();
  43500. };
  43501. proto$4.dispose = function (ecModel, api) {
  43502. this._brushController.dispose();
  43503. };
  43504. /**
  43505. * @private
  43506. */
  43507. var handlers = {
  43508. zoom: function () {
  43509. var nextActive = !this._isZoomActive;
  43510. this.api.dispatchAction({
  43511. type: 'takeGlobalCursor',
  43512. key: 'dataZoomSelect',
  43513. dataZoomSelectActive: nextActive
  43514. });
  43515. },
  43516. back: function () {
  43517. this._dispatchZoomAction(pop(this.ecModel));
  43518. }
  43519. };
  43520. /**
  43521. * @private
  43522. */
  43523. proto$4._onBrush = function (areas, opt) {
  43524. if (!opt.isEnd || !areas.length) {
  43525. return;
  43526. }
  43527. var snapshot = {};
  43528. var ecModel = this.ecModel;
  43529. this._brushController.updateCovers([]); // remove cover
  43530. var brushTargetManager = new BrushTargetManager(
  43531. retrieveAxisSetting(this.model.option), ecModel, {include: ['grid']}
  43532. );
  43533. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  43534. if (coordSys.type !== 'cartesian2d') {
  43535. return;
  43536. }
  43537. var brushType = area.brushType;
  43538. if (brushType === 'rect') {
  43539. setBatch('x', coordSys, coordRange[0]);
  43540. setBatch('y', coordSys, coordRange[1]);
  43541. }
  43542. else {
  43543. setBatch(({lineX: 'x', lineY: 'y'})[brushType], coordSys, coordRange);
  43544. }
  43545. });
  43546. push(ecModel, snapshot);
  43547. this._dispatchZoomAction(snapshot);
  43548. function setBatch(dimName, coordSys, minMax) {
  43549. var axis = coordSys.getAxis(dimName);
  43550. var axisModel = axis.model;
  43551. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel);
  43552. // Restrict range.
  43553. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  43554. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  43555. minMax = sliderMove(
  43556. 0, minMax.slice(), axis.scale.getExtent(), 0,
  43557. minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan
  43558. );
  43559. }
  43560. dataZoomModel && (snapshot[dataZoomModel.id] = {
  43561. dataZoomId: dataZoomModel.id,
  43562. startValue: minMax[0],
  43563. endValue: minMax[1]
  43564. });
  43565. }
  43566. function findDataZoom(dimName, axisModel, ecModel) {
  43567. var found;
  43568. ecModel.eachComponent({mainType: 'dataZoom', subType: 'select'}, function (dzModel) {
  43569. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  43570. has && (found = dzModel);
  43571. });
  43572. return found;
  43573. }
  43574. };
  43575. /**
  43576. * @private
  43577. */
  43578. proto$4._dispatchZoomAction = function (snapshot) {
  43579. var batch = [];
  43580. // Convert from hash map to array.
  43581. each$16(snapshot, function (batchItem, dataZoomId) {
  43582. batch.push(clone(batchItem));
  43583. });
  43584. batch.length && this.api.dispatchAction({
  43585. type: 'dataZoom',
  43586. from: this.uid,
  43587. batch: batch
  43588. });
  43589. };
  43590. function retrieveAxisSetting(option) {
  43591. var setting = {};
  43592. // Compatible with previous setting: null => all axis, false => no axis.
  43593. each$1(['xAxisIndex', 'yAxisIndex'], function (name) {
  43594. setting[name] = option[name];
  43595. setting[name] == null && (setting[name] = 'all');
  43596. (setting[name] === false || setting[name] === 'none') && (setting[name] = []);
  43597. });
  43598. return setting;
  43599. }
  43600. function updateBackBtnStatus(featureModel, ecModel) {
  43601. featureModel.setIconStatus(
  43602. 'back',
  43603. count(ecModel) > 1 ? 'emphasis' : 'normal'
  43604. );
  43605. }
  43606. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  43607. var zoomActive = view._isZoomActive;
  43608. if (payload && payload.type === 'takeGlobalCursor') {
  43609. zoomActive = payload.key === 'dataZoomSelect'
  43610. ? payload.dataZoomSelectActive : false;
  43611. }
  43612. view._isZoomActive = zoomActive;
  43613. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  43614. var brushTargetManager = new BrushTargetManager(
  43615. retrieveAxisSetting(featureModel.option), ecModel, {include: ['grid']}
  43616. );
  43617. view._brushController
  43618. .setPanels(brushTargetManager.makePanelOpts(api, function (targetInfo) {
  43619. return (targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared)
  43620. ? 'lineX'
  43621. : (!targetInfo.xAxisDeclared && targetInfo.yAxisDeclared)
  43622. ? 'lineY'
  43623. : 'rect';
  43624. }))
  43625. .enableBrush(
  43626. zoomActive
  43627. ? {
  43628. brushType: 'auto',
  43629. brushStyle: {
  43630. // FIXME user customized?
  43631. lineWidth: 0,
  43632. fill: 'rgba(0,0,0,0.2)'
  43633. }
  43634. }
  43635. : false
  43636. );
  43637. }
  43638. register$2('dataZoom', DataZoom);
  43639. // Create special dataZoom option for select
  43640. registerPreprocessor(function (option) {
  43641. if (!option) {
  43642. return;
  43643. }
  43644. var dataZoomOpts = option.dataZoom || (option.dataZoom = []);
  43645. if (!isArray(dataZoomOpts)) {
  43646. option.dataZoom = dataZoomOpts = [dataZoomOpts];
  43647. }
  43648. var toolboxOpt = option.toolbox;
  43649. if (toolboxOpt) {
  43650. // Assume there is only one toolbox
  43651. if (isArray(toolboxOpt)) {
  43652. toolboxOpt = toolboxOpt[0];
  43653. }
  43654. if (toolboxOpt && toolboxOpt.feature) {
  43655. var dataZoomOpt = toolboxOpt.feature.dataZoom;
  43656. addForAxis('xAxis', dataZoomOpt);
  43657. addForAxis('yAxis', dataZoomOpt);
  43658. }
  43659. }
  43660. function addForAxis(axisName, dataZoomOpt) {
  43661. if (!dataZoomOpt) {
  43662. return;
  43663. }
  43664. // Try not to modify model, because it is not merged yet.
  43665. var axisIndicesName = axisName + 'Index';
  43666. var givenAxisIndices = dataZoomOpt[axisIndicesName];
  43667. if (givenAxisIndices != null
  43668. && givenAxisIndices != 'all'
  43669. && !isArray(givenAxisIndices)
  43670. ) {
  43671. givenAxisIndices = (givenAxisIndices === false || givenAxisIndices === 'none') ? [] : [givenAxisIndices];
  43672. }
  43673. forEachComponent(axisName, function (axisOpt, axisIndex) {
  43674. if (givenAxisIndices != null
  43675. && givenAxisIndices != 'all'
  43676. && indexOf(givenAxisIndices, axisIndex) === -1
  43677. ) {
  43678. return;
  43679. }
  43680. var newOpt = {
  43681. type: 'select',
  43682. $fromToolbox: true,
  43683. // Id for merge mapping.
  43684. id: DATA_ZOOM_ID_BASE + axisName + axisIndex
  43685. };
  43686. // FIXME
  43687. // Only support one axis now.
  43688. newOpt[axisIndicesName] = axisIndex;
  43689. dataZoomOpts.push(newOpt);
  43690. });
  43691. }
  43692. function forEachComponent(mainType, cb) {
  43693. var opts = option[mainType];
  43694. if (!isArray(opts)) {
  43695. opts = opts ? [opts] : [];
  43696. }
  43697. each$16(opts, cb);
  43698. }
  43699. });
  43700. var restoreLang = lang.toolbox.restore;
  43701. function Restore(model) {
  43702. this.model = model;
  43703. }
  43704. Restore.defaultOption = {
  43705. show: true,
  43706. icon: 'M3.8,33.4 M47,18.9h9.8V8.7 M56.3,20.1 C52.1,9,40.5,0.6,26.8,2.1C12.6,3.7,1.6,16.2,2.1,30.6 M13,41.1H3.1v10.2 M3.7,39.9c4.2,11.1,15.8,19.5,29.5,18 c14.2-1.6,25.2-14.1,24.7-28.5',
  43707. title: restoreLang.title
  43708. };
  43709. var proto$6 = Restore.prototype;
  43710. proto$6.onclick = function (ecModel, api, type) {
  43711. clear$1(ecModel);
  43712. api.dispatchAction({
  43713. type: 'restore',
  43714. from: this.uid
  43715. });
  43716. };
  43717. register$2('restore', Restore);
  43718. registerAction(
  43719. {type: 'restore', event: 'restore', update: 'prepareAndUpdate'},
  43720. function (payload, ecModel) {
  43721. ecModel.resetOption('recreate');
  43722. }
  43723. );
  43724. var urn = 'urn:schemas-microsoft-com:vml';
  43725. var win = typeof window === 'undefined' ? null : window;
  43726. var vmlInited = false;
  43727. var doc = win && win.document;
  43728. function createNode(tagName) {
  43729. return doCreateNode(tagName);
  43730. }
  43731. // Avoid assign to an exported variable, for transforming to cjs.
  43732. var doCreateNode;
  43733. if (doc && !env$1.canvasSupported) {
  43734. try {
  43735. !doc.namespaces.zrvml && doc.namespaces.add('zrvml', urn);
  43736. doCreateNode = function (tagName) {
  43737. return doc.createElement('<zrvml:' + tagName + ' class="zrvml">');
  43738. };
  43739. }
  43740. catch (e) {
  43741. doCreateNode = function (tagName) {
  43742. return doc.createElement('<' + tagName + ' xmlns="' + urn + '" class="zrvml">');
  43743. };
  43744. }
  43745. }
  43746. // From raphael
  43747. function initVML() {
  43748. if (vmlInited || !doc) {
  43749. return;
  43750. }
  43751. vmlInited = true;
  43752. var styleSheets = doc.styleSheets;
  43753. if (styleSheets.length < 31) {
  43754. doc.createStyleSheet().addRule('.zrvml', 'behavior:url(#default#VML)');
  43755. }
  43756. else {
  43757. // http://msdn.microsoft.com/en-us/library/ms531194%28VS.85%29.aspx
  43758. styleSheets[0].addRule('.zrvml', 'behavior:url(#default#VML)');
  43759. }
  43760. }
  43761. // http://www.w3.org/TR/NOTE-VML
  43762. // TODO Use proxy like svg instead of overwrite brush methods
  43763. var CMD$3 = PathProxy.CMD;
  43764. var round$2 = Math.round;
  43765. var sqrt = Math.sqrt;
  43766. var abs$1 = Math.abs;
  43767. var cos = Math.cos;
  43768. var sin = Math.sin;
  43769. var mathMax$5 = Math.max;
  43770. if (!env$1.canvasSupported) {
  43771. var comma = ',';
  43772. var imageTransformPrefix = 'progid:DXImageTransform.Microsoft';
  43773. var Z = 21600;
  43774. var Z2 = Z / 2;
  43775. var ZLEVEL_BASE = 100000;
  43776. var Z_BASE = 1000;
  43777. var initRootElStyle = function (el) {
  43778. el.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;';
  43779. el.coordsize = Z + ',' + Z;
  43780. el.coordorigin = '0,0';
  43781. };
  43782. var encodeHtmlAttribute = function (s) {
  43783. return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
  43784. };
  43785. var rgb2Str = function (r, g, b) {
  43786. return 'rgb(' + [r, g, b].join(',') + ')';
  43787. };
  43788. var append = function (parent, child) {
  43789. if (child && parent && child.parentNode !== parent) {
  43790. parent.appendChild(child);
  43791. }
  43792. };
  43793. var remove = function (parent, child) {
  43794. if (child && parent && child.parentNode === parent) {
  43795. parent.removeChild(child);
  43796. }
  43797. };
  43798. var getZIndex = function (zlevel, z, z2) {
  43799. // z 的取值范围为 [0, 1000]
  43800. return (parseFloat(zlevel) || 0) * ZLEVEL_BASE + (parseFloat(z) || 0) * Z_BASE + z2;
  43801. };
  43802. var parsePercent$3 = function (value, maxValue) {
  43803. if (typeof value === 'string') {
  43804. if (value.lastIndexOf('%') >= 0) {
  43805. return parseFloat(value) / 100 * maxValue;
  43806. }
  43807. return parseFloat(value);
  43808. }
  43809. return value;
  43810. };
  43811. /***************************************************
  43812. * PATH
  43813. **************************************************/
  43814. var setColorAndOpacity = function (el, color, opacity) {
  43815. var colorArr = parse(color);
  43816. opacity = +opacity;
  43817. if (isNaN(opacity)) {
  43818. opacity = 1;
  43819. }
  43820. if (colorArr) {
  43821. el.color = rgb2Str(colorArr[0], colorArr[1], colorArr[2]);
  43822. el.opacity = opacity * colorArr[3];
  43823. }
  43824. };
  43825. var getColorAndAlpha = function (color) {
  43826. var colorArr = parse(color);
  43827. return [
  43828. rgb2Str(colorArr[0], colorArr[1], colorArr[2]),
  43829. colorArr[3]
  43830. ];
  43831. };
  43832. var updateFillNode = function (el, style, zrEl) {
  43833. // TODO pattern
  43834. var fill = style.fill;
  43835. if (fill != null) {
  43836. // Modified from excanvas
  43837. if (fill instanceof Gradient) {
  43838. var gradientType;
  43839. var angle = 0;
  43840. var focus = [0, 0];
  43841. // additional offset
  43842. var shift = 0;
  43843. // scale factor for offset
  43844. var expansion = 1;
  43845. var rect = zrEl.getBoundingRect();
  43846. var rectWidth = rect.width;
  43847. var rectHeight = rect.height;
  43848. if (fill.type === 'linear') {
  43849. gradientType = 'gradient';
  43850. var transform = zrEl.transform;
  43851. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  43852. var p1 = [fill.x2 * rectWidth, fill.y2 * rectHeight];
  43853. if (transform) {
  43854. applyTransform(p0, p0, transform);
  43855. applyTransform(p1, p1, transform);
  43856. }
  43857. var dx = p1[0] - p0[0];
  43858. var dy = p1[1] - p0[1];
  43859. angle = Math.atan2(dx, dy) * 180 / Math.PI;
  43860. // The angle should be a non-negative number.
  43861. if (angle < 0) {
  43862. angle += 360;
  43863. }
  43864. // Very small angles produce an unexpected result because they are
  43865. // converted to a scientific notation string.
  43866. if (angle < 1e-6) {
  43867. angle = 0;
  43868. }
  43869. }
  43870. else {
  43871. gradientType = 'gradientradial';
  43872. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  43873. var transform = zrEl.transform;
  43874. var scale$$1 = zrEl.scale;
  43875. var width = rectWidth;
  43876. var height = rectHeight;
  43877. focus = [
  43878. // Percent in bounding rect
  43879. (p0[0] - rect.x) / width,
  43880. (p0[1] - rect.y) / height
  43881. ];
  43882. if (transform) {
  43883. applyTransform(p0, p0, transform);
  43884. }
  43885. width /= scale$$1[0] * Z;
  43886. height /= scale$$1[1] * Z;
  43887. var dimension = mathMax$5(width, height);
  43888. shift = 2 * 0 / dimension;
  43889. expansion = 2 * fill.r / dimension - shift;
  43890. }
  43891. // We need to sort the color stops in ascending order by offset,
  43892. // otherwise IE won't interpret it correctly.
  43893. var stops = fill.colorStops.slice();
  43894. stops.sort(function(cs1, cs2) {
  43895. return cs1.offset - cs2.offset;
  43896. });
  43897. var length$$1 = stops.length;
  43898. // Color and alpha list of first and last stop
  43899. var colorAndAlphaList = [];
  43900. var colors = [];
  43901. for (var i = 0; i < length$$1; i++) {
  43902. var stop = stops[i];
  43903. var colorAndAlpha = getColorAndAlpha(stop.color);
  43904. colors.push(stop.offset * expansion + shift + ' ' + colorAndAlpha[0]);
  43905. if (i === 0 || i === length$$1 - 1) {
  43906. colorAndAlphaList.push(colorAndAlpha);
  43907. }
  43908. }
  43909. if (length$$1 >= 2) {
  43910. var color1 = colorAndAlphaList[0][0];
  43911. var color2 = colorAndAlphaList[1][0];
  43912. var opacity1 = colorAndAlphaList[0][1] * style.opacity;
  43913. var opacity2 = colorAndAlphaList[1][1] * style.opacity;
  43914. el.type = gradientType;
  43915. el.method = 'none';
  43916. el.focus = '100%';
  43917. el.angle = angle;
  43918. el.color = color1;
  43919. el.color2 = color2;
  43920. el.colors = colors.join(',');
  43921. // When colors attribute is used, the meanings of opacity and o:opacity2
  43922. // are reversed.
  43923. el.opacity = opacity2;
  43924. // FIXME g_o_:opacity ?
  43925. el.opacity2 = opacity1;
  43926. }
  43927. if (gradientType === 'radial') {
  43928. el.focusposition = focus.join(',');
  43929. }
  43930. }
  43931. else {
  43932. // FIXME Change from Gradient fill to color fill
  43933. setColorAndOpacity(el, fill, style.opacity);
  43934. }
  43935. }
  43936. };
  43937. var updateStrokeNode = function (el, style) {
  43938. // if (style.lineJoin != null) {
  43939. // el.joinstyle = style.lineJoin;
  43940. // }
  43941. // if (style.miterLimit != null) {
  43942. // el.miterlimit = style.miterLimit * Z;
  43943. // }
  43944. // if (style.lineCap != null) {
  43945. // el.endcap = style.lineCap;
  43946. // }
  43947. if (style.lineDash != null) {
  43948. el.dashstyle = style.lineDash.join(' ');
  43949. }
  43950. if (style.stroke != null && !(style.stroke instanceof Gradient)) {
  43951. setColorAndOpacity(el, style.stroke, style.opacity);
  43952. }
  43953. };
  43954. var updateFillAndStroke = function (vmlEl, type, style, zrEl) {
  43955. var isFill = type == 'fill';
  43956. var el = vmlEl.getElementsByTagName(type)[0];
  43957. // Stroke must have lineWidth
  43958. if (style[type] != null && style[type] !== 'none' && (isFill || (!isFill && style.lineWidth))) {
  43959. vmlEl[isFill ? 'filled' : 'stroked'] = 'true';
  43960. // FIXME Remove before updating, or set `colors` will throw error
  43961. if (style[type] instanceof Gradient) {
  43962. remove(vmlEl, el);
  43963. }
  43964. if (!el) {
  43965. el = createNode(type);
  43966. }
  43967. isFill ? updateFillNode(el, style, zrEl) : updateStrokeNode(el, style);
  43968. append(vmlEl, el);
  43969. }
  43970. else {
  43971. vmlEl[isFill ? 'filled' : 'stroked'] = 'false';
  43972. remove(vmlEl, el);
  43973. }
  43974. };
  43975. var points$1 = [[], [], []];
  43976. var pathDataToString = function (path, m) {
  43977. var M = CMD$3.M;
  43978. var C = CMD$3.C;
  43979. var L = CMD$3.L;
  43980. var A = CMD$3.A;
  43981. var Q = CMD$3.Q;
  43982. var str = [];
  43983. var nPoint;
  43984. var cmdStr;
  43985. var cmd;
  43986. var i;
  43987. var xi;
  43988. var yi;
  43989. var data = path.data;
  43990. var dataLength = path.len();
  43991. for (i = 0; i < dataLength;) {
  43992. cmd = data[i++];
  43993. cmdStr = '';
  43994. nPoint = 0;
  43995. switch (cmd) {
  43996. case M:
  43997. cmdStr = ' m ';
  43998. nPoint = 1;
  43999. xi = data[i++];
  44000. yi = data[i++];
  44001. points$1[0][0] = xi;
  44002. points$1[0][1] = yi;
  44003. break;
  44004. case L:
  44005. cmdStr = ' l ';
  44006. nPoint = 1;
  44007. xi = data[i++];
  44008. yi = data[i++];
  44009. points$1[0][0] = xi;
  44010. points$1[0][1] = yi;
  44011. break;
  44012. case Q:
  44013. case C:
  44014. cmdStr = ' c ';
  44015. nPoint = 3;
  44016. var x1 = data[i++];
  44017. var y1 = data[i++];
  44018. var x2 = data[i++];
  44019. var y2 = data[i++];
  44020. var x3;
  44021. var y3;
  44022. if (cmd === Q) {
  44023. // Convert quadratic to cubic using degree elevation
  44024. x3 = x2;
  44025. y3 = y2;
  44026. x2 = (x2 + 2 * x1) / 3;
  44027. y2 = (y2 + 2 * y1) / 3;
  44028. x1 = (xi + 2 * x1) / 3;
  44029. y1 = (yi + 2 * y1) / 3;
  44030. }
  44031. else {
  44032. x3 = data[i++];
  44033. y3 = data[i++];
  44034. }
  44035. points$1[0][0] = x1;
  44036. points$1[0][1] = y1;
  44037. points$1[1][0] = x2;
  44038. points$1[1][1] = y2;
  44039. points$1[2][0] = x3;
  44040. points$1[2][1] = y3;
  44041. xi = x3;
  44042. yi = y3;
  44043. break;
  44044. case A:
  44045. var x = 0;
  44046. var y = 0;
  44047. var sx = 1;
  44048. var sy = 1;
  44049. var angle = 0;
  44050. if (m) {
  44051. // Extract SRT from matrix
  44052. x = m[4];
  44053. y = m[5];
  44054. sx = sqrt(m[0] * m[0] + m[1] * m[1]);
  44055. sy = sqrt(m[2] * m[2] + m[3] * m[3]);
  44056. angle = Math.atan2(-m[1] / sy, m[0] / sx);
  44057. }
  44058. var cx = data[i++];
  44059. var cy = data[i++];
  44060. var rx = data[i++];
  44061. var ry = data[i++];
  44062. var startAngle = data[i++] + angle;
  44063. var endAngle = data[i++] + startAngle + angle;
  44064. // FIXME
  44065. // var psi = data[i++];
  44066. i++;
  44067. var clockwise = data[i++];
  44068. var x0 = cx + cos(startAngle) * rx;
  44069. var y0 = cy + sin(startAngle) * ry;
  44070. var x1 = cx + cos(endAngle) * rx;
  44071. var y1 = cy + sin(endAngle) * ry;
  44072. var type = clockwise ? ' wa ' : ' at ';
  44073. if (Math.abs(x0 - x1) < 1e-4) {
  44074. // IE won't render arches drawn counter clockwise if x0 == x1.
  44075. if (Math.abs(endAngle - startAngle) > 1e-2) {
  44076. // Offset x0 by 1/80 of a pixel. Use something
  44077. // that can be represented in binary
  44078. if (clockwise) {
  44079. x0 += 270 / Z;
  44080. }
  44081. }
  44082. else {
  44083. // Avoid case draw full circle
  44084. if (Math.abs(y0 - cy) < 1e-4) {
  44085. if ((clockwise && x0 < cx) || (!clockwise && x0 > cx)) {
  44086. y1 -= 270 / Z;
  44087. }
  44088. else {
  44089. y1 += 270 / Z;
  44090. }
  44091. }
  44092. else if ((clockwise && y0 < cy) || (!clockwise && y0 > cy)) {
  44093. x1 += 270 / Z;
  44094. }
  44095. else {
  44096. x1 -= 270 / Z;
  44097. }
  44098. }
  44099. }
  44100. str.push(
  44101. type,
  44102. round$2(((cx - rx) * sx + x) * Z - Z2), comma,
  44103. round$2(((cy - ry) * sy + y) * Z - Z2), comma,
  44104. round$2(((cx + rx) * sx + x) * Z - Z2), comma,
  44105. round$2(((cy + ry) * sy + y) * Z - Z2), comma,
  44106. round$2((x0 * sx + x) * Z - Z2), comma,
  44107. round$2((y0 * sy + y) * Z - Z2), comma,
  44108. round$2((x1 * sx + x) * Z - Z2), comma,
  44109. round$2((y1 * sy + y) * Z - Z2)
  44110. );
  44111. xi = x1;
  44112. yi = y1;
  44113. break;
  44114. case CMD$3.R:
  44115. var p0 = points$1[0];
  44116. var p1 = points$1[1];
  44117. // x0, y0
  44118. p0[0] = data[i++];
  44119. p0[1] = data[i++];
  44120. // x1, y1
  44121. p1[0] = p0[0] + data[i++];
  44122. p1[1] = p0[1] + data[i++];
  44123. if (m) {
  44124. applyTransform(p0, p0, m);
  44125. applyTransform(p1, p1, m);
  44126. }
  44127. p0[0] = round$2(p0[0] * Z - Z2);
  44128. p1[0] = round$2(p1[0] * Z - Z2);
  44129. p0[1] = round$2(p0[1] * Z - Z2);
  44130. p1[1] = round$2(p1[1] * Z - Z2);
  44131. str.push(
  44132. // x0, y0
  44133. ' m ', p0[0], comma, p0[1],
  44134. // x1, y0
  44135. ' l ', p1[0], comma, p0[1],
  44136. // x1, y1
  44137. ' l ', p1[0], comma, p1[1],
  44138. // x0, y1
  44139. ' l ', p0[0], comma, p1[1]
  44140. );
  44141. break;
  44142. case CMD$3.Z:
  44143. // FIXME Update xi, yi
  44144. str.push(' x ');
  44145. }
  44146. if (nPoint > 0) {
  44147. str.push(cmdStr);
  44148. for (var k = 0; k < nPoint; k++) {
  44149. var p = points$1[k];
  44150. m && applyTransform(p, p, m);
  44151. // 不 round 会非常慢
  44152. str.push(
  44153. round$2(p[0] * Z - Z2), comma, round$2(p[1] * Z - Z2),
  44154. k < nPoint - 1 ? comma : ''
  44155. );
  44156. }
  44157. }
  44158. }
  44159. return str.join('');
  44160. };
  44161. // Rewrite the original path method
  44162. Path.prototype.brushVML = function (vmlRoot) {
  44163. var style = this.style;
  44164. var vmlEl = this._vmlEl;
  44165. if (!vmlEl) {
  44166. vmlEl = createNode('shape');
  44167. initRootElStyle(vmlEl);
  44168. this._vmlEl = vmlEl;
  44169. }
  44170. updateFillAndStroke(vmlEl, 'fill', style, this);
  44171. updateFillAndStroke(vmlEl, 'stroke', style, this);
  44172. var m = this.transform;
  44173. var needTransform = m != null;
  44174. var strokeEl = vmlEl.getElementsByTagName('stroke')[0];
  44175. if (strokeEl) {
  44176. var lineWidth = style.lineWidth;
  44177. // Get the line scale.
  44178. // Determinant of this.m_ means how much the area is enlarged by the
  44179. // transformation. So its square root can be used as a scale factor
  44180. // for width.
  44181. if (needTransform && !style.strokeNoScale) {
  44182. var det = m[0] * m[3] - m[1] * m[2];
  44183. lineWidth *= sqrt(abs$1(det));
  44184. }
  44185. strokeEl.weight = lineWidth + 'px';
  44186. }
  44187. var path = this.path || (this.path = new PathProxy());
  44188. if (this.__dirtyPath) {
  44189. path.beginPath();
  44190. this.buildPath(path, this.shape);
  44191. path.toStatic();
  44192. this.__dirtyPath = false;
  44193. }
  44194. vmlEl.path = pathDataToString(path, this.transform);
  44195. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  44196. // Append to root
  44197. append(vmlRoot, vmlEl);
  44198. // Text
  44199. if (style.text != null) {
  44200. this.drawRectText(vmlRoot, this.getBoundingRect());
  44201. }
  44202. else {
  44203. this.removeRectText(vmlRoot);
  44204. }
  44205. };
  44206. Path.prototype.onRemove = function (vmlRoot) {
  44207. remove(vmlRoot, this._vmlEl);
  44208. this.removeRectText(vmlRoot);
  44209. };
  44210. Path.prototype.onAdd = function (vmlRoot) {
  44211. append(vmlRoot, this._vmlEl);
  44212. this.appendRectText(vmlRoot);
  44213. };
  44214. /***************************************************
  44215. * IMAGE
  44216. **************************************************/
  44217. var isImage = function (img) {
  44218. // FIXME img instanceof Image 如果 img 是一个字符串的时候,IE8 下会报错
  44219. return (typeof img === 'object') && img.tagName && img.tagName.toUpperCase() === 'IMG';
  44220. // return img instanceof Image;
  44221. };
  44222. // Rewrite the original path method
  44223. ZImage.prototype.brushVML = function (vmlRoot) {
  44224. var style = this.style;
  44225. var image = style.image;
  44226. // Image original width, height
  44227. var ow;
  44228. var oh;
  44229. if (isImage(image)) {
  44230. var src = image.src;
  44231. if (src === this._imageSrc) {
  44232. ow = this._imageWidth;
  44233. oh = this._imageHeight;
  44234. }
  44235. else {
  44236. var imageRuntimeStyle = image.runtimeStyle;
  44237. var oldRuntimeWidth = imageRuntimeStyle.width;
  44238. var oldRuntimeHeight = imageRuntimeStyle.height;
  44239. imageRuntimeStyle.width = 'auto';
  44240. imageRuntimeStyle.height = 'auto';
  44241. // get the original size
  44242. ow = image.width;
  44243. oh = image.height;
  44244. // and remove overides
  44245. imageRuntimeStyle.width = oldRuntimeWidth;
  44246. imageRuntimeStyle.height = oldRuntimeHeight;
  44247. // Caching image original width, height and src
  44248. this._imageSrc = src;
  44249. this._imageWidth = ow;
  44250. this._imageHeight = oh;
  44251. }
  44252. image = src;
  44253. }
  44254. else {
  44255. if (image === this._imageSrc) {
  44256. ow = this._imageWidth;
  44257. oh = this._imageHeight;
  44258. }
  44259. }
  44260. if (!image) {
  44261. return;
  44262. }
  44263. var x = style.x || 0;
  44264. var y = style.y || 0;
  44265. var dw = style.width;
  44266. var dh = style.height;
  44267. var sw = style.sWidth;
  44268. var sh = style.sHeight;
  44269. var sx = style.sx || 0;
  44270. var sy = style.sy || 0;
  44271. var hasCrop = sw && sh;
  44272. var vmlEl = this._vmlEl;
  44273. if (!vmlEl) {
  44274. // FIXME 使用 group 在 left, top 都不是 0 的时候就无法显示了。
  44275. // vmlEl = vmlCore.createNode('group');
  44276. vmlEl = doc.createElement('div');
  44277. initRootElStyle(vmlEl);
  44278. this._vmlEl = vmlEl;
  44279. }
  44280. var vmlElStyle = vmlEl.style;
  44281. var hasRotation = false;
  44282. var m;
  44283. var scaleX = 1;
  44284. var scaleY = 1;
  44285. if (this.transform) {
  44286. m = this.transform;
  44287. scaleX = sqrt(m[0] * m[0] + m[1] * m[1]);
  44288. scaleY = sqrt(m[2] * m[2] + m[3] * m[3]);
  44289. hasRotation = m[1] || m[2];
  44290. }
  44291. if (hasRotation) {
  44292. // If filters are necessary (rotation exists), create them
  44293. // filters are bog-slow, so only create them if abbsolutely necessary
  44294. // The following check doesn't account for skews (which don't exist
  44295. // in the canvas spec (yet) anyway.
  44296. // From excanvas
  44297. var p0 = [x, y];
  44298. var p1 = [x + dw, y];
  44299. var p2 = [x, y + dh];
  44300. var p3 = [x + dw, y + dh];
  44301. applyTransform(p0, p0, m);
  44302. applyTransform(p1, p1, m);
  44303. applyTransform(p2, p2, m);
  44304. applyTransform(p3, p3, m);
  44305. var maxX = mathMax$5(p0[0], p1[0], p2[0], p3[0]);
  44306. var maxY = mathMax$5(p0[1], p1[1], p2[1], p3[1]);
  44307. var transformFilter = [];
  44308. transformFilter.push('M11=', m[0] / scaleX, comma,
  44309. 'M12=', m[2] / scaleY, comma,
  44310. 'M21=', m[1] / scaleX, comma,
  44311. 'M22=', m[3] / scaleY, comma,
  44312. 'Dx=', round$2(x * scaleX + m[4]), comma,
  44313. 'Dy=', round$2(y * scaleY + m[5]));
  44314. vmlElStyle.padding = '0 ' + round$2(maxX) + 'px ' + round$2(maxY) + 'px 0';
  44315. // FIXME DXImageTransform 在 IE11 的兼容模式下不起作用
  44316. vmlElStyle.filter = imageTransformPrefix + '.Matrix('
  44317. + transformFilter.join('') + ', SizingMethod=clip)';
  44318. }
  44319. else {
  44320. if (m) {
  44321. x = x * scaleX + m[4];
  44322. y = y * scaleY + m[5];
  44323. }
  44324. vmlElStyle.filter = '';
  44325. vmlElStyle.left = round$2(x) + 'px';
  44326. vmlElStyle.top = round$2(y) + 'px';
  44327. }
  44328. var imageEl = this._imageEl;
  44329. var cropEl = this._cropEl;
  44330. if (!imageEl) {
  44331. imageEl = doc.createElement('div');
  44332. this._imageEl = imageEl;
  44333. }
  44334. var imageELStyle = imageEl.style;
  44335. if (hasCrop) {
  44336. // Needs know image original width and height
  44337. if (! (ow && oh)) {
  44338. var tmpImage = new Image();
  44339. var self = this;
  44340. tmpImage.onload = function () {
  44341. tmpImage.onload = null;
  44342. ow = tmpImage.width;
  44343. oh = tmpImage.height;
  44344. // Adjust image width and height to fit the ratio destinationSize / sourceSize
  44345. imageELStyle.width = round$2(scaleX * ow * dw / sw) + 'px';
  44346. imageELStyle.height = round$2(scaleY * oh * dh / sh) + 'px';
  44347. // Caching image original width, height and src
  44348. self._imageWidth = ow;
  44349. self._imageHeight = oh;
  44350. self._imageSrc = image;
  44351. };
  44352. tmpImage.src = image;
  44353. }
  44354. else {
  44355. imageELStyle.width = round$2(scaleX * ow * dw / sw) + 'px';
  44356. imageELStyle.height = round$2(scaleY * oh * dh / sh) + 'px';
  44357. }
  44358. if (! cropEl) {
  44359. cropEl = doc.createElement('div');
  44360. cropEl.style.overflow = 'hidden';
  44361. this._cropEl = cropEl;
  44362. }
  44363. var cropElStyle = cropEl.style;
  44364. cropElStyle.width = round$2((dw + sx * dw / sw) * scaleX);
  44365. cropElStyle.height = round$2((dh + sy * dh / sh) * scaleY);
  44366. cropElStyle.filter = imageTransformPrefix + '.Matrix(Dx='
  44367. + (-sx * dw / sw * scaleX) + ',Dy=' + (-sy * dh / sh * scaleY) + ')';
  44368. if (! cropEl.parentNode) {
  44369. vmlEl.appendChild(cropEl);
  44370. }
  44371. if (imageEl.parentNode != cropEl) {
  44372. cropEl.appendChild(imageEl);
  44373. }
  44374. }
  44375. else {
  44376. imageELStyle.width = round$2(scaleX * dw) + 'px';
  44377. imageELStyle.height = round$2(scaleY * dh) + 'px';
  44378. vmlEl.appendChild(imageEl);
  44379. if (cropEl && cropEl.parentNode) {
  44380. vmlEl.removeChild(cropEl);
  44381. this._cropEl = null;
  44382. }
  44383. }
  44384. var filterStr = '';
  44385. var alpha = style.opacity;
  44386. if (alpha < 1) {
  44387. filterStr += '.Alpha(opacity=' + round$2(alpha * 100) + ') ';
  44388. }
  44389. filterStr += imageTransformPrefix + '.AlphaImageLoader(src=' + image + ', SizingMethod=scale)';
  44390. imageELStyle.filter = filterStr;
  44391. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  44392. // Append to root
  44393. append(vmlRoot, vmlEl);
  44394. // Text
  44395. if (style.text != null) {
  44396. this.drawRectText(vmlRoot, this.getBoundingRect());
  44397. }
  44398. };
  44399. ZImage.prototype.onRemove = function (vmlRoot) {
  44400. remove(vmlRoot, this._vmlEl);
  44401. this._vmlEl = null;
  44402. this._cropEl = null;
  44403. this._imageEl = null;
  44404. this.removeRectText(vmlRoot);
  44405. };
  44406. ZImage.prototype.onAdd = function (vmlRoot) {
  44407. append(vmlRoot, this._vmlEl);
  44408. this.appendRectText(vmlRoot);
  44409. };
  44410. /***************************************************
  44411. * TEXT
  44412. **************************************************/
  44413. var DEFAULT_STYLE_NORMAL = 'normal';
  44414. var fontStyleCache = {};
  44415. var fontStyleCacheCount = 0;
  44416. var MAX_FONT_CACHE_SIZE = 100;
  44417. var fontEl = document.createElement('div');
  44418. var getFontStyle = function (fontString) {
  44419. var fontStyle = fontStyleCache[fontString];
  44420. if (!fontStyle) {
  44421. // Clear cache
  44422. if (fontStyleCacheCount > MAX_FONT_CACHE_SIZE) {
  44423. fontStyleCacheCount = 0;
  44424. fontStyleCache = {};
  44425. }
  44426. var style = fontEl.style;
  44427. var fontFamily;
  44428. try {
  44429. style.font = fontString;
  44430. fontFamily = style.fontFamily.split(',')[0];
  44431. }
  44432. catch (e) {
  44433. }
  44434. fontStyle = {
  44435. style: style.fontStyle || DEFAULT_STYLE_NORMAL,
  44436. variant: style.fontVariant || DEFAULT_STYLE_NORMAL,
  44437. weight: style.fontWeight || DEFAULT_STYLE_NORMAL,
  44438. size: parseFloat(style.fontSize || 12) | 0,
  44439. family: fontFamily || 'Microsoft YaHei'
  44440. };
  44441. fontStyleCache[fontString] = fontStyle;
  44442. fontStyleCacheCount++;
  44443. }
  44444. return fontStyle;
  44445. };
  44446. var textMeasureEl;
  44447. // Overwrite measure text method
  44448. $override$1('measureText', function (text, textFont) {
  44449. var doc$$1 = doc;
  44450. if (!textMeasureEl) {
  44451. textMeasureEl = doc$$1.createElement('div');
  44452. textMeasureEl.style.cssText = 'position:absolute;top:-20000px;left:0;'
  44453. + 'padding:0;margin:0;border:none;white-space:pre;';
  44454. doc.body.appendChild(textMeasureEl);
  44455. }
  44456. try {
  44457. textMeasureEl.style.font = textFont;
  44458. } catch (ex) {
  44459. // Ignore failures to set to invalid font.
  44460. }
  44461. textMeasureEl.innerHTML = '';
  44462. // Don't use innerHTML or innerText because they allow markup/whitespace.
  44463. textMeasureEl.appendChild(doc$$1.createTextNode(text));
  44464. return {
  44465. width: textMeasureEl.offsetWidth
  44466. };
  44467. });
  44468. var tmpRect$2 = new BoundingRect();
  44469. var drawRectText = function (vmlRoot, rect, textRect, fromTextEl) {
  44470. var style = this.style;
  44471. // Optimize, avoid normalize every time.
  44472. this.__dirty && normalizeTextStyle(style, true);
  44473. var text = style.text;
  44474. // Convert to string
  44475. text != null && (text += '');
  44476. if (!text) {
  44477. return;
  44478. }
  44479. // Convert rich text to plain text. Rich text is not supported in
  44480. // IE8-, but tags in rich text template will be removed.
  44481. if (style.rich) {
  44482. var contentBlock = parseRichText(text, style);
  44483. text = [];
  44484. for (var i = 0; i < contentBlock.lines.length; i++) {
  44485. var tokens = contentBlock.lines[i].tokens;
  44486. var textLine = [];
  44487. for (var j = 0; j < tokens.length; j++) {
  44488. textLine.push(tokens[j].text);
  44489. }
  44490. text.push(textLine.join(''));
  44491. }
  44492. text = text.join('\n');
  44493. }
  44494. var x;
  44495. var y;
  44496. var align = style.textAlign;
  44497. var verticalAlign = style.textVerticalAlign;
  44498. var fontStyle = getFontStyle(style.font);
  44499. // FIXME encodeHtmlAttribute ?
  44500. var font = fontStyle.style + ' ' + fontStyle.variant + ' ' + fontStyle.weight + ' '
  44501. + fontStyle.size + 'px "' + fontStyle.family + '"';
  44502. textRect = textRect || getBoundingRect(text, font, align, verticalAlign);
  44503. // Transform rect to view space
  44504. var m = this.transform;
  44505. // Ignore transform for text in other element
  44506. if (m && !fromTextEl) {
  44507. tmpRect$2.copy(rect);
  44508. tmpRect$2.applyTransform(m);
  44509. rect = tmpRect$2;
  44510. }
  44511. if (!fromTextEl) {
  44512. var textPosition = style.textPosition;
  44513. var distance$$1 = style.textDistance;
  44514. // Text position represented by coord
  44515. if (textPosition instanceof Array) {
  44516. x = rect.x + parsePercent$3(textPosition[0], rect.width);
  44517. y = rect.y + parsePercent$3(textPosition[1], rect.height);
  44518. align = align || 'left';
  44519. }
  44520. else {
  44521. var res = adjustTextPositionOnRect(
  44522. textPosition, rect, distance$$1
  44523. );
  44524. x = res.x;
  44525. y = res.y;
  44526. // Default align and baseline when has textPosition
  44527. align = align || res.textAlign;
  44528. verticalAlign = verticalAlign || res.textVerticalAlign;
  44529. }
  44530. }
  44531. else {
  44532. x = rect.x;
  44533. y = rect.y;
  44534. }
  44535. x = adjustTextX(x, textRect.width, align);
  44536. y = adjustTextY(y, textRect.height, verticalAlign);
  44537. // Force baseline 'middle'
  44538. y += textRect.height / 2;
  44539. // var fontSize = fontStyle.size;
  44540. // 1.75 is an arbitrary number, as there is no info about the text baseline
  44541. // switch (baseline) {
  44542. // case 'hanging':
  44543. // case 'top':
  44544. // y += fontSize / 1.75;
  44545. // break;
  44546. // case 'middle':
  44547. // break;
  44548. // default:
  44549. // // case null:
  44550. // // case 'alphabetic':
  44551. // // case 'ideographic':
  44552. // // case 'bottom':
  44553. // y -= fontSize / 2.25;
  44554. // break;
  44555. // }
  44556. // switch (align) {
  44557. // case 'left':
  44558. // break;
  44559. // case 'center':
  44560. // x -= textRect.width / 2;
  44561. // break;
  44562. // case 'right':
  44563. // x -= textRect.width;
  44564. // break;
  44565. // case 'end':
  44566. // align = elementStyle.direction == 'ltr' ? 'right' : 'left';
  44567. // break;
  44568. // case 'start':
  44569. // align = elementStyle.direction == 'rtl' ? 'right' : 'left';
  44570. // break;
  44571. // default:
  44572. // align = 'left';
  44573. // }
  44574. var createNode$$1 = createNode;
  44575. var textVmlEl = this._textVmlEl;
  44576. var pathEl;
  44577. var textPathEl;
  44578. var skewEl;
  44579. if (!textVmlEl) {
  44580. textVmlEl = createNode$$1('line');
  44581. pathEl = createNode$$1('path');
  44582. textPathEl = createNode$$1('textpath');
  44583. skewEl = createNode$$1('skew');
  44584. // FIXME Why here is not cammel case
  44585. // Align 'center' seems wrong
  44586. textPathEl.style['v-text-align'] = 'left';
  44587. initRootElStyle(textVmlEl);
  44588. pathEl.textpathok = true;
  44589. textPathEl.on = true;
  44590. textVmlEl.from = '0 0';
  44591. textVmlEl.to = '1000 0.05';
  44592. append(textVmlEl, skewEl);
  44593. append(textVmlEl, pathEl);
  44594. append(textVmlEl, textPathEl);
  44595. this._textVmlEl = textVmlEl;
  44596. }
  44597. else {
  44598. // 这里是在前面 appendChild 保证顺序的前提下
  44599. skewEl = textVmlEl.firstChild;
  44600. pathEl = skewEl.nextSibling;
  44601. textPathEl = pathEl.nextSibling;
  44602. }
  44603. var coords = [x, y];
  44604. var textVmlElStyle = textVmlEl.style;
  44605. // Ignore transform for text in other element
  44606. if (m && fromTextEl) {
  44607. applyTransform(coords, coords, m);
  44608. skewEl.on = true;
  44609. skewEl.matrix = m[0].toFixed(3) + comma + m[2].toFixed(3) + comma +
  44610. m[1].toFixed(3) + comma + m[3].toFixed(3) + ',0,0';
  44611. // Text position
  44612. skewEl.offset = (round$2(coords[0]) || 0) + ',' + (round$2(coords[1]) || 0);
  44613. // Left top point as origin
  44614. skewEl.origin = '0 0';
  44615. textVmlElStyle.left = '0px';
  44616. textVmlElStyle.top = '0px';
  44617. }
  44618. else {
  44619. skewEl.on = false;
  44620. textVmlElStyle.left = round$2(x) + 'px';
  44621. textVmlElStyle.top = round$2(y) + 'px';
  44622. }
  44623. textPathEl.string = encodeHtmlAttribute(text);
  44624. // TODO
  44625. try {
  44626. textPathEl.style.font = font;
  44627. }
  44628. // Error font format
  44629. catch (e) {}
  44630. updateFillAndStroke(textVmlEl, 'fill', {
  44631. fill: style.textFill,
  44632. opacity: style.opacity
  44633. }, this);
  44634. updateFillAndStroke(textVmlEl, 'stroke', {
  44635. stroke: style.textStroke,
  44636. opacity: style.opacity,
  44637. lineDash: style.lineDash
  44638. }, this);
  44639. textVmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  44640. // Attached to root
  44641. append(vmlRoot, textVmlEl);
  44642. };
  44643. var removeRectText = function (vmlRoot) {
  44644. remove(vmlRoot, this._textVmlEl);
  44645. this._textVmlEl = null;
  44646. };
  44647. var appendRectText = function (vmlRoot) {
  44648. append(vmlRoot, this._textVmlEl);
  44649. };
  44650. var list = [RectText, Displayable, ZImage, Path, Text];
  44651. // In case Displayable has been mixed in RectText
  44652. for (var i$1 = 0; i$1 < list.length; i$1++) {
  44653. var proto$7 = list[i$1].prototype;
  44654. proto$7.drawRectText = drawRectText;
  44655. proto$7.removeRectText = removeRectText;
  44656. proto$7.appendRectText = appendRectText;
  44657. }
  44658. Text.prototype.brushVML = function (vmlRoot) {
  44659. var style = this.style;
  44660. if (style.text != null) {
  44661. this.drawRectText(vmlRoot, {
  44662. x: style.x || 0, y: style.y || 0,
  44663. width: 0, height: 0
  44664. }, this.getBoundingRect(), true);
  44665. }
  44666. else {
  44667. this.removeRectText(vmlRoot);
  44668. }
  44669. };
  44670. Text.prototype.onRemove = function (vmlRoot) {
  44671. this.removeRectText(vmlRoot);
  44672. };
  44673. Text.prototype.onAdd = function (vmlRoot) {
  44674. this.appendRectText(vmlRoot);
  44675. };
  44676. }
  44677. /**
  44678. * VML Painter.
  44679. *
  44680. * @module zrender/vml/Painter
  44681. */
  44682. function parseInt10$1(val) {
  44683. return parseInt(val, 10);
  44684. }
  44685. /**
  44686. * @alias module:zrender/vml/Painter
  44687. */
  44688. function VMLPainter(root, storage) {
  44689. initVML();
  44690. this.root = root;
  44691. this.storage = storage;
  44692. var vmlViewport = document.createElement('div');
  44693. var vmlRoot = document.createElement('div');
  44694. vmlViewport.style.cssText = 'display:inline-block;overflow:hidden;position:relative;width:300px;height:150px;';
  44695. vmlRoot.style.cssText = 'position:absolute;left:0;top:0;';
  44696. root.appendChild(vmlViewport);
  44697. this._vmlRoot = vmlRoot;
  44698. this._vmlViewport = vmlViewport;
  44699. this.resize();
  44700. // Modify storage
  44701. var oldDelFromStorage = storage.delFromStorage;
  44702. var oldAddToStorage = storage.addToStorage;
  44703. storage.delFromStorage = function (el) {
  44704. oldDelFromStorage.call(storage, el);
  44705. if (el) {
  44706. el.onRemove && el.onRemove(vmlRoot);
  44707. }
  44708. };
  44709. storage.addToStorage = function (el) {
  44710. // Displayable already has a vml node
  44711. el.onAdd && el.onAdd(vmlRoot);
  44712. oldAddToStorage.call(storage, el);
  44713. };
  44714. this._firstPaint = true;
  44715. }
  44716. VMLPainter.prototype = {
  44717. constructor: VMLPainter,
  44718. getType: function () {
  44719. return 'vml';
  44720. },
  44721. /**
  44722. * @return {HTMLDivElement}
  44723. */
  44724. getViewportRoot: function () {
  44725. return this._vmlViewport;
  44726. },
  44727. getViewportRootOffset: function () {
  44728. var viewportRoot = this.getViewportRoot();
  44729. if (viewportRoot) {
  44730. return {
  44731. offsetLeft: viewportRoot.offsetLeft || 0,
  44732. offsetTop: viewportRoot.offsetTop || 0
  44733. };
  44734. }
  44735. },
  44736. /**
  44737. * 刷新
  44738. */
  44739. refresh: function () {
  44740. var list = this.storage.getDisplayList(true, true);
  44741. this._paintList(list);
  44742. },
  44743. _paintList: function (list) {
  44744. var vmlRoot = this._vmlRoot;
  44745. for (var i = 0; i < list.length; i++) {
  44746. var el = list[i];
  44747. if (el.invisible || el.ignore) {
  44748. if (!el.__alreadyNotVisible) {
  44749. el.onRemove(vmlRoot);
  44750. }
  44751. // Set as already invisible
  44752. el.__alreadyNotVisible = true;
  44753. }
  44754. else {
  44755. if (el.__alreadyNotVisible) {
  44756. el.onAdd(vmlRoot);
  44757. }
  44758. el.__alreadyNotVisible = false;
  44759. if (el.__dirty) {
  44760. el.beforeBrush && el.beforeBrush();
  44761. (el.brushVML || el.brush).call(el, vmlRoot);
  44762. el.afterBrush && el.afterBrush();
  44763. }
  44764. }
  44765. el.__dirty = false;
  44766. }
  44767. if (this._firstPaint) {
  44768. // Detached from document at first time
  44769. // to avoid page refreshing too many times
  44770. // FIXME 如果每次都先 removeChild 可能会导致一些填充和描边的效果改变
  44771. this._vmlViewport.appendChild(vmlRoot);
  44772. this._firstPaint = false;
  44773. }
  44774. },
  44775. resize: function (width, height) {
  44776. var width = width == null ? this._getWidth() : width;
  44777. var height = height == null ? this._getHeight() : height;
  44778. if (this._width != width || this._height != height) {
  44779. this._width = width;
  44780. this._height = height;
  44781. var vmlViewportStyle = this._vmlViewport.style;
  44782. vmlViewportStyle.width = width + 'px';
  44783. vmlViewportStyle.height = height + 'px';
  44784. }
  44785. },
  44786. dispose: function () {
  44787. this.root.innerHTML = '';
  44788. this._vmlRoot =
  44789. this._vmlViewport =
  44790. this.storage = null;
  44791. },
  44792. getWidth: function () {
  44793. return this._width;
  44794. },
  44795. getHeight: function () {
  44796. return this._height;
  44797. },
  44798. clear: function () {
  44799. if (this._vmlViewport) {
  44800. this.root.removeChild(this._vmlViewport);
  44801. }
  44802. },
  44803. _getWidth: function () {
  44804. var root = this.root;
  44805. var stl = root.currentStyle;
  44806. return ((root.clientWidth || parseInt10$1(stl.width))
  44807. - parseInt10$1(stl.paddingLeft)
  44808. - parseInt10$1(stl.paddingRight)) | 0;
  44809. },
  44810. _getHeight: function () {
  44811. var root = this.root;
  44812. var stl = root.currentStyle;
  44813. return ((root.clientHeight || parseInt10$1(stl.height))
  44814. - parseInt10$1(stl.paddingTop)
  44815. - parseInt10$1(stl.paddingBottom)) | 0;
  44816. }
  44817. };
  44818. // Not supported methods
  44819. function createMethodNotSupport(method) {
  44820. return function () {
  44821. zrLog('In IE8.0 VML mode painter not support method "' + method + '"');
  44822. };
  44823. }
  44824. // Unsupported methods
  44825. each$1([
  44826. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer', 'eachOtherLayer', 'getLayers',
  44827. 'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage'
  44828. ], function (name) {
  44829. VMLPainter.prototype[name] = createMethodNotSupport(name);
  44830. });
  44831. registerPainter('vml', VMLPainter);
  44832. var svgURI = 'http://www.w3.org/2000/svg';
  44833. function createElement(name) {
  44834. return document.createElementNS(svgURI, name);
  44835. }
  44836. // TODO
  44837. // 1. shadow
  44838. // 2. Image: sx, sy, sw, sh
  44839. var CMD$4 = PathProxy.CMD;
  44840. var arrayJoin = Array.prototype.join;
  44841. var NONE = 'none';
  44842. var mathRound = Math.round;
  44843. var mathSin$3 = Math.sin;
  44844. var mathCos$3 = Math.cos;
  44845. var PI$3 = Math.PI;
  44846. var PI2$5 = Math.PI * 2;
  44847. var degree = 180 / PI$3;
  44848. var EPSILON$4 = 1e-4;
  44849. function round4(val) {
  44850. return mathRound(val * 1e4) / 1e4;
  44851. }
  44852. function isAroundZero$1(val) {
  44853. return val < EPSILON$4 && val > -EPSILON$4;
  44854. }
  44855. function pathHasFill(style, isText) {
  44856. var fill = isText ? style.textFill : style.fill;
  44857. return fill != null && fill !== NONE;
  44858. }
  44859. function pathHasStroke(style, isText) {
  44860. var stroke = isText ? style.textStroke : style.stroke;
  44861. return stroke != null && stroke !== NONE;
  44862. }
  44863. function setTransform(svgEl, m) {
  44864. if (m) {
  44865. attr(svgEl, 'transform', 'matrix(' + arrayJoin.call(m, ',') + ')');
  44866. }
  44867. }
  44868. function attr(el, key, val) {
  44869. if (!val || val.type !== 'linear' && val.type !== 'radial') {
  44870. // Don't set attribute for gradient, since it need new dom nodes
  44871. el.setAttribute(key, val);
  44872. }
  44873. }
  44874. function attrXLink(el, key, val) {
  44875. el.setAttributeNS('http://www.w3.org/1999/xlink', key, val);
  44876. }
  44877. function bindStyle(svgEl, style, isText) {
  44878. if (pathHasFill(style, isText)) {
  44879. var fill = isText ? style.textFill : style.fill;
  44880. fill = fill === 'transparent' ? NONE : fill;
  44881. /**
  44882. * FIXME:
  44883. * This is a temporary fix for Chrome's clipping bug
  44884. * that happens when a clip-path is referring another one.
  44885. * This fix should be used before Chrome's bug is fixed.
  44886. * For an element that has clip-path, and fill is none,
  44887. * set it to be "rgba(0, 0, 0, 0.002)" will hide the element.
  44888. * Otherwise, it will show black fill color.
  44889. * 0.002 is used because this won't work for alpha values smaller
  44890. * than 0.002.
  44891. *
  44892. * See
  44893. * https://bugs.chromium.org/p/chromium/issues/detail?id=659790
  44894. * for more information.
  44895. */
  44896. if (svgEl.getAttribute('clip-path') !== 'none' && fill === NONE) {
  44897. fill = 'rgba(0, 0, 0, 0.002)';
  44898. }
  44899. attr(svgEl, 'fill', fill);
  44900. attr(svgEl, 'fill-opacity', style.opacity);
  44901. }
  44902. else {
  44903. attr(svgEl, 'fill', NONE);
  44904. }
  44905. if (pathHasStroke(style, isText)) {
  44906. var stroke = isText ? style.textStroke : style.stroke;
  44907. stroke = stroke === 'transparent' ? NONE : stroke;
  44908. attr(svgEl, 'stroke', stroke);
  44909. var strokeWidth = isText
  44910. ? style.textStrokeWidth
  44911. : style.lineWidth;
  44912. var strokeScale = !isText && style.strokeNoScale
  44913. ? style.host.getLineScale()
  44914. : 1;
  44915. attr(svgEl, 'stroke-width', strokeWidth / strokeScale);
  44916. // stroke then fill for text; fill then stroke for others
  44917. attr(svgEl, 'paint-order', isText ? 'stroke' : 'fill');
  44918. attr(svgEl, 'stroke-opacity', style.opacity);
  44919. var lineDash = style.lineDash;
  44920. if (lineDash) {
  44921. attr(svgEl, 'stroke-dasharray', style.lineDash.join(','));
  44922. attr(svgEl, 'stroke-dashoffset', mathRound(style.lineDashOffset || 0));
  44923. }
  44924. else {
  44925. attr(svgEl, 'stroke-dasharray', '');
  44926. }
  44927. // PENDING
  44928. style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap);
  44929. style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin);
  44930. style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit);
  44931. }
  44932. else {
  44933. attr(svgEl, 'stroke', NONE);
  44934. }
  44935. }
  44936. /***************************************************
  44937. * PATH
  44938. **************************************************/
  44939. function pathDataToString$1(path) {
  44940. var str = [];
  44941. var data = path.data;
  44942. var dataLength = path.len();
  44943. for (var i = 0; i < dataLength;) {
  44944. var cmd = data[i++];
  44945. var cmdStr = '';
  44946. var nData = 0;
  44947. switch (cmd) {
  44948. case CMD$4.M:
  44949. cmdStr = 'M';
  44950. nData = 2;
  44951. break;
  44952. case CMD$4.L:
  44953. cmdStr = 'L';
  44954. nData = 2;
  44955. break;
  44956. case CMD$4.Q:
  44957. cmdStr = 'Q';
  44958. nData = 4;
  44959. break;
  44960. case CMD$4.C:
  44961. cmdStr = 'C';
  44962. nData = 6;
  44963. break;
  44964. case CMD$4.A:
  44965. var cx = data[i++];
  44966. var cy = data[i++];
  44967. var rx = data[i++];
  44968. var ry = data[i++];
  44969. var theta = data[i++];
  44970. var dTheta = data[i++];
  44971. var psi = data[i++];
  44972. var clockwise = data[i++];
  44973. var dThetaPositive = Math.abs(dTheta);
  44974. var isCircle = isAroundZero$1(dThetaPositive - PI2$5)
  44975. && !isAroundZero$1(dThetaPositive);
  44976. var large = false;
  44977. if (dThetaPositive >= PI2$5) {
  44978. large = true;
  44979. }
  44980. else if (isAroundZero$1(dThetaPositive)) {
  44981. large = false;
  44982. }
  44983. else {
  44984. large = (dTheta > -PI$3 && dTheta < 0 || dTheta > PI$3)
  44985. === !!clockwise;
  44986. }
  44987. var x0 = round4(cx + rx * mathCos$3(theta));
  44988. var y0 = round4(cy + ry * mathSin$3(theta));
  44989. // It will not draw if start point and end point are exactly the same
  44990. // We need to shift the end point with a small value
  44991. // FIXME A better way to draw circle ?
  44992. if (isCircle) {
  44993. if (clockwise) {
  44994. dTheta = PI2$5 - 1e-4;
  44995. }
  44996. else {
  44997. dTheta = -PI2$5 + 1e-4;
  44998. }
  44999. large = true;
  45000. if (i === 9) {
  45001. // Move to (x0, y0) only when CMD.A comes at the
  45002. // first position of a shape.
  45003. // For instance, when drawing a ring, CMD.A comes
  45004. // after CMD.M, so it's unnecessary to move to
  45005. // (x0, y0).
  45006. str.push('M', x0, y0);
  45007. }
  45008. }
  45009. var x = round4(cx + rx * mathCos$3(theta + dTheta));
  45010. var y = round4(cy + ry * mathSin$3(theta + dTheta));
  45011. // FIXME Ellipse
  45012. str.push('A', round4(rx), round4(ry),
  45013. mathRound(psi * degree), +large, +clockwise, x, y);
  45014. break;
  45015. case CMD$4.Z:
  45016. cmdStr = 'Z';
  45017. break;
  45018. case CMD$4.R:
  45019. var x = round4(data[i++]);
  45020. var y = round4(data[i++]);
  45021. var w = round4(data[i++]);
  45022. var h = round4(data[i++]);
  45023. str.push(
  45024. 'M', x, y,
  45025. 'L', x + w, y,
  45026. 'L', x + w, y + h,
  45027. 'L', x, y + h,
  45028. 'L', x, y
  45029. );
  45030. break;
  45031. }
  45032. cmdStr && str.push(cmdStr);
  45033. for (var j = 0; j < nData; j++) {
  45034. // PENDING With scale
  45035. str.push(round4(data[i++]));
  45036. }
  45037. }
  45038. return str.join(' ');
  45039. }
  45040. var svgPath = {};
  45041. svgPath.brush = function (el) {
  45042. var style = el.style;
  45043. var svgEl = el.__svgEl;
  45044. if (!svgEl) {
  45045. svgEl = createElement('path');
  45046. el.__svgEl = svgEl;
  45047. }
  45048. if (!el.path) {
  45049. el.createPathProxy();
  45050. }
  45051. var path = el.path;
  45052. if (el.__dirtyPath) {
  45053. path.beginPath();
  45054. el.buildPath(path, el.shape);
  45055. el.__dirtyPath = false;
  45056. var pathStr = pathDataToString$1(path);
  45057. if (pathStr.indexOf('NaN') < 0) {
  45058. // Ignore illegal path, which may happen such in out-of-range
  45059. // data in Calendar series.
  45060. attr(svgEl, 'd', pathStr);
  45061. }
  45062. }
  45063. bindStyle(svgEl, style);
  45064. setTransform(svgEl, el.transform);
  45065. if (style.text != null) {
  45066. svgTextDrawRectText(el, el.getBoundingRect());
  45067. }
  45068. };
  45069. /***************************************************
  45070. * IMAGE
  45071. **************************************************/
  45072. var svgImage = {};
  45073. svgImage.brush = function (el) {
  45074. var style = el.style;
  45075. var image = style.image;
  45076. if (image instanceof HTMLImageElement) {
  45077. var src = image.src;
  45078. image = src;
  45079. }
  45080. if (! image) {
  45081. return;
  45082. }
  45083. var x = style.x || 0;
  45084. var y = style.y || 0;
  45085. var dw = style.width;
  45086. var dh = style.height;
  45087. var svgEl = el.__svgEl;
  45088. if (! svgEl) {
  45089. svgEl = createElement('image');
  45090. el.__svgEl = svgEl;
  45091. }
  45092. if (image !== el.__imageSrc) {
  45093. attrXLink(svgEl, 'href', image);
  45094. // Caching image src
  45095. el.__imageSrc = image;
  45096. }
  45097. attr(svgEl, 'width', dw);
  45098. attr(svgEl, 'height', dh);
  45099. attr(svgEl, 'x', x);
  45100. attr(svgEl, 'y', y);
  45101. setTransform(svgEl, el.transform);
  45102. if (style.text != null) {
  45103. svgTextDrawRectText(el, el.getBoundingRect());
  45104. }
  45105. };
  45106. /***************************************************
  45107. * TEXT
  45108. **************************************************/
  45109. var svgText = {};
  45110. var tmpRect$3 = new BoundingRect();
  45111. var svgTextDrawRectText = function (el, rect, textRect) {
  45112. var style = el.style;
  45113. el.__dirty && normalizeTextStyle(style, true);
  45114. var text = style.text;
  45115. // Convert to string
  45116. if (text == null) {
  45117. // Draw no text only when text is set to null, but not ''
  45118. return;
  45119. }
  45120. else {
  45121. text += '';
  45122. }
  45123. var textSvgEl = el.__textSvgEl;
  45124. if (! textSvgEl) {
  45125. textSvgEl = createElement('text');
  45126. el.__textSvgEl = textSvgEl;
  45127. }
  45128. var x;
  45129. var y;
  45130. var textPosition = style.textPosition;
  45131. var distance = style.textDistance;
  45132. var align = style.textAlign || 'left';
  45133. if (typeof style.fontSize === 'number') {
  45134. style.fontSize += 'px';
  45135. }
  45136. var font = style.font
  45137. || [
  45138. style.fontStyle || '',
  45139. style.fontWeight || '',
  45140. style.fontSize || '',
  45141. style.fontFamily || ''
  45142. ].join(' ')
  45143. || DEFAULT_FONT;
  45144. var verticalAlign = getVerticalAlignForSvg(style.textVerticalAlign);
  45145. textRect = getBoundingRect(text, font, align,
  45146. verticalAlign);
  45147. var lineHeight = textRect.lineHeight;
  45148. // Text position represented by coord
  45149. if (textPosition instanceof Array) {
  45150. x = rect.x + textPosition[0];
  45151. y = rect.y + textPosition[1];
  45152. }
  45153. else {
  45154. var newPos = adjustTextPositionOnRect(
  45155. textPosition, rect, distance
  45156. );
  45157. x = newPos.x;
  45158. y = newPos.y;
  45159. verticalAlign = getVerticalAlignForSvg(newPos.textVerticalAlign);
  45160. align = newPos.textAlign;
  45161. }
  45162. attr(textSvgEl, 'alignment-baseline', verticalAlign);
  45163. if (font) {
  45164. textSvgEl.style.font = font;
  45165. }
  45166. var textPadding = style.textPadding;
  45167. // Make baseline top
  45168. attr(textSvgEl, 'x', x);
  45169. attr(textSvgEl, 'y', y);
  45170. bindStyle(textSvgEl, style, true);
  45171. if (el instanceof Text || el.style.transformText) {
  45172. // Transform text with element
  45173. setTransform(textSvgEl, el.transform);
  45174. }
  45175. else {
  45176. if (el.transform) {
  45177. tmpRect$3.copy(rect);
  45178. tmpRect$3.applyTransform(el.transform);
  45179. rect = tmpRect$3;
  45180. }
  45181. else {
  45182. var pos = el.transformCoordToGlobal(rect.x, rect.y);
  45183. rect.x = pos[0];
  45184. rect.y = pos[1];
  45185. }
  45186. // Text rotation, but no element transform
  45187. var origin = style.textOrigin;
  45188. if (origin === 'center') {
  45189. x = textRect.width / 2 + x;
  45190. y = textRect.height / 2 + y;
  45191. }
  45192. else if (origin) {
  45193. x = origin[0] + x;
  45194. y = origin[1] + y;
  45195. }
  45196. var rotate = -style.textRotation * 180 / Math.PI;
  45197. attr(textSvgEl, 'transform', 'rotate(' + rotate + ','
  45198. + x + ',' + y + ')');
  45199. }
  45200. var textLines = text.split('\n');
  45201. var nTextLines = textLines.length;
  45202. var textAnchor = align;
  45203. // PENDING
  45204. if (textAnchor === 'left') {
  45205. textAnchor = 'start';
  45206. textPadding && (x += textPadding[3]);
  45207. }
  45208. else if (textAnchor === 'right') {
  45209. textAnchor = 'end';
  45210. textPadding && (x -= textPadding[1]);
  45211. }
  45212. else if (textAnchor === 'center') {
  45213. textAnchor = 'middle';
  45214. textPadding && (x += (textPadding[3] - textPadding[1]) / 2);
  45215. }
  45216. var dy = 0;
  45217. if (verticalAlign === 'baseline') {
  45218. dy = -textRect.height + lineHeight;
  45219. textPadding && (dy -= textPadding[2]);
  45220. }
  45221. else if (verticalAlign === 'middle') {
  45222. dy = (-textRect.height + lineHeight) / 2;
  45223. textPadding && (y += (textPadding[0] - textPadding[2]) / 2);
  45224. }
  45225. else {
  45226. textPadding && (dy += textPadding[0]);
  45227. }
  45228. // Font may affect position of each tspan elements
  45229. if (el.__text !== text || el.__textFont !== font) {
  45230. var tspanList = el.__tspanList || [];
  45231. el.__tspanList = tspanList;
  45232. for (var i = 0; i < nTextLines; i++) {
  45233. // Using cached tspan elements
  45234. var tspan = tspanList[i];
  45235. if (! tspan) {
  45236. tspan = tspanList[i] = createElement('tspan');
  45237. textSvgEl.appendChild(tspan);
  45238. attr(tspan, 'alignment-baseline', verticalAlign);
  45239. attr(tspan, 'text-anchor', textAnchor);
  45240. }
  45241. else {
  45242. tspan.innerHTML = '';
  45243. }
  45244. attr(tspan, 'x', x);
  45245. attr(tspan, 'y', y + i * lineHeight + dy);
  45246. tspan.appendChild(document.createTextNode(textLines[i]));
  45247. }
  45248. // Remove unsed tspan elements
  45249. for (; i < tspanList.length; i++) {
  45250. textSvgEl.removeChild(tspanList[i]);
  45251. }
  45252. tspanList.length = nTextLines;
  45253. el.__text = text;
  45254. el.__textFont = font;
  45255. }
  45256. else if (el.__tspanList.length) {
  45257. // Update span x and y
  45258. var len = el.__tspanList.length;
  45259. for (var i = 0; i < len; ++i) {
  45260. var tspan = el.__tspanList[i];
  45261. if (tspan) {
  45262. attr(tspan, 'x', x);
  45263. attr(tspan, 'y', y + i * lineHeight + dy);
  45264. }
  45265. }
  45266. }
  45267. };
  45268. function getVerticalAlignForSvg(verticalAlign) {
  45269. if (verticalAlign === 'middle') {
  45270. return 'middle';
  45271. }
  45272. else if (verticalAlign === 'bottom') {
  45273. return 'baseline';
  45274. }
  45275. else {
  45276. return 'hanging';
  45277. }
  45278. }
  45279. svgText.drawRectText = svgTextDrawRectText;
  45280. svgText.brush = function (el) {
  45281. var style = el.style;
  45282. if (style.text != null) {
  45283. // 强制设置 textPosition
  45284. style.textPosition = [0, 0];
  45285. svgTextDrawRectText(el, {
  45286. x: style.x || 0, y: style.y || 0,
  45287. width: 0, height: 0
  45288. }, el.getBoundingRect());
  45289. }
  45290. };
  45291. // Myers' Diff Algorithm
  45292. // Modified from https://github.com/kpdecker/jsdiff/blob/master/src/diff/base.js
  45293. function Diff() {}
  45294. Diff.prototype = {
  45295. diff: function (oldArr, newArr, equals) {
  45296. if (!equals) {
  45297. equals = function (a, b) {
  45298. return a === b;
  45299. };
  45300. }
  45301. this.equals = equals;
  45302. var self = this;
  45303. oldArr = oldArr.slice();
  45304. newArr = newArr.slice();
  45305. // Allow subclasses to massage the input prior to running
  45306. var newLen = newArr.length;
  45307. var oldLen = oldArr.length;
  45308. var editLength = 1;
  45309. var maxEditLength = newLen + oldLen;
  45310. var bestPath = [{ newPos: -1, components: [] }];
  45311. // Seed editLength = 0, i.e. the content starts with the same values
  45312. var oldPos = this.extractCommon(bestPath[0], newArr, oldArr, 0);
  45313. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  45314. var indices = [];
  45315. for (var i = 0; i < newArr.length; i++) {
  45316. indices.push(i);
  45317. }
  45318. // Identity per the equality and tokenizer
  45319. return [{
  45320. indices: indices, count: newArr.length
  45321. }];
  45322. }
  45323. // Main worker method. checks all permutations of a given edit length for acceptance.
  45324. function execEditLength() {
  45325. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  45326. var basePath;
  45327. var addPath = bestPath[diagonalPath - 1];
  45328. var removePath = bestPath[diagonalPath + 1];
  45329. var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  45330. if (addPath) {
  45331. // No one else is going to attempt to use this value, clear it
  45332. bestPath[diagonalPath - 1] = undefined;
  45333. }
  45334. var canAdd = addPath && addPath.newPos + 1 < newLen;
  45335. var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
  45336. if (!canAdd && !canRemove) {
  45337. // If this path is a terminal then prune
  45338. bestPath[diagonalPath] = undefined;
  45339. continue;
  45340. }
  45341. // Select the diagonal that we want to branch from. We select the prior
  45342. // path whose position in the new string is the farthest from the origin
  45343. // and does not pass the bounds of the diff graph
  45344. if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
  45345. basePath = clonePath(removePath);
  45346. self.pushComponent(basePath.components, undefined, true);
  45347. }
  45348. else {
  45349. basePath = addPath; // No need to clone, we've pulled it from the list
  45350. basePath.newPos++;
  45351. self.pushComponent(basePath.components, true, undefined);
  45352. }
  45353. oldPos = self.extractCommon(basePath, newArr, oldArr, diagonalPath);
  45354. // If we have hit the end of both strings, then we are done
  45355. if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  45356. return buildValues(self, basePath.components, newArr, oldArr);
  45357. }
  45358. else {
  45359. // Otherwise track this path as a potential candidate and continue.
  45360. bestPath[diagonalPath] = basePath;
  45361. }
  45362. }
  45363. editLength++;
  45364. }
  45365. while (editLength <= maxEditLength) {
  45366. var ret = execEditLength();
  45367. if (ret) {
  45368. return ret;
  45369. }
  45370. }
  45371. },
  45372. pushComponent: function (components, added, removed) {
  45373. var last = components[components.length - 1];
  45374. if (last && last.added === added && last.removed === removed) {
  45375. // We need to clone here as the component clone operation is just
  45376. // as shallow array clone
  45377. components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
  45378. }
  45379. else {
  45380. components.push({count: 1, added: added, removed: removed });
  45381. }
  45382. },
  45383. extractCommon: function (basePath, newArr, oldArr, diagonalPath) {
  45384. var newLen = newArr.length;
  45385. var oldLen = oldArr.length;
  45386. var newPos = basePath.newPos;
  45387. var oldPos = newPos - diagonalPath;
  45388. var commonCount = 0;
  45389. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newArr[newPos + 1], oldArr[oldPos + 1])) {
  45390. newPos++;
  45391. oldPos++;
  45392. commonCount++;
  45393. }
  45394. if (commonCount) {
  45395. basePath.components.push({count: commonCount});
  45396. }
  45397. basePath.newPos = newPos;
  45398. return oldPos;
  45399. },
  45400. tokenize: function (value) {
  45401. return value.slice();
  45402. },
  45403. join: function (value) {
  45404. return value.slice();
  45405. }
  45406. };
  45407. function buildValues(diff, components, newArr, oldArr) {
  45408. var componentPos = 0;
  45409. var componentLen = components.length;
  45410. var newPos = 0;
  45411. var oldPos = 0;
  45412. for (; componentPos < componentLen; componentPos++) {
  45413. var component = components[componentPos];
  45414. if (!component.removed) {
  45415. var indices = [];
  45416. for (var i = newPos; i < newPos + component.count; i++) {
  45417. indices.push(i);
  45418. }
  45419. component.indices = indices;
  45420. newPos += component.count;
  45421. // Common case
  45422. if (!component.added) {
  45423. oldPos += component.count;
  45424. }
  45425. }
  45426. else {
  45427. var indices = [];
  45428. for (var i = oldPos; i < oldPos + component.count; i++) {
  45429. indices.push(i);
  45430. }
  45431. component.indices = indices;
  45432. oldPos += component.count;
  45433. }
  45434. }
  45435. return components;
  45436. }
  45437. function clonePath(path) {
  45438. return { newPos: path.newPos, components: path.components.slice(0) };
  45439. }
  45440. var arrayDiff = new Diff();
  45441. var arrayDiff$1 = function (oldArr, newArr, callback) {
  45442. return arrayDiff.diff(oldArr, newArr, callback);
  45443. };
  45444. /**
  45445. * @file Manages elements that can be defined in <defs> in SVG,
  45446. * e.g., gradients, clip path, etc.
  45447. * @author Zhang Wenli
  45448. */
  45449. var MARK_UNUSED = '0';
  45450. var MARK_USED = '1';
  45451. /**
  45452. * Manages elements that can be defined in <defs> in SVG,
  45453. * e.g., gradients, clip path, etc.
  45454. *
  45455. * @class
  45456. * @param {number} zrId zrender instance id
  45457. * @param {SVGElement} svgRoot root of SVG document
  45458. * @param {string|string[]} tagNames possible tag names
  45459. * @param {string} markLabel label name to make if the element
  45460. * is used
  45461. */
  45462. function Definable(
  45463. zrId,
  45464. svgRoot,
  45465. tagNames,
  45466. markLabel,
  45467. domName
  45468. ) {
  45469. this._zrId = zrId;
  45470. this._svgRoot = svgRoot;
  45471. this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames;
  45472. this._markLabel = markLabel;
  45473. this._domName = domName || '_dom';
  45474. this.nextId = 0;
  45475. }
  45476. Definable.prototype.createElement = createElement;
  45477. /**
  45478. * Get the <defs> tag for svgRoot; optionally creates one if not exists.
  45479. *
  45480. * @param {boolean} isForceCreating if need to create when not exists
  45481. * @return {SVGDefsElement} SVG <defs> element, null if it doesn't
  45482. * exist and isForceCreating is false
  45483. */
  45484. Definable.prototype.getDefs = function (isForceCreating) {
  45485. var svgRoot = this._svgRoot;
  45486. var defs = this._svgRoot.getElementsByTagName('defs');
  45487. if (defs.length === 0) {
  45488. // Not exist
  45489. if (isForceCreating) {
  45490. defs = svgRoot.insertBefore(
  45491. this.createElement('defs'), // Create new tag
  45492. svgRoot.firstChild // Insert in the front of svg
  45493. );
  45494. if (!defs.contains) {
  45495. // IE doesn't support contains method
  45496. defs.contains = function (el) {
  45497. var children = defs.children;
  45498. if (!children) {
  45499. return false;
  45500. }
  45501. for (var i = children.length - 1; i >= 0; --i) {
  45502. if (children[i] === el) {
  45503. return true;
  45504. }
  45505. }
  45506. return false;
  45507. };
  45508. }
  45509. return defs;
  45510. }
  45511. else {
  45512. return null;
  45513. }
  45514. }
  45515. else {
  45516. return defs[0];
  45517. }
  45518. };
  45519. /**
  45520. * Update DOM element if necessary.
  45521. *
  45522. * @param {Object|string} element style element. e.g., for gradient,
  45523. * it may be '#ccc' or {type: 'linear', ...}
  45524. * @param {Function|undefined} onUpdate update callback
  45525. */
  45526. Definable.prototype.update = function (element, onUpdate) {
  45527. if (!element) {
  45528. return;
  45529. }
  45530. var defs = this.getDefs(false);
  45531. if (element[this._domName] && defs.contains(element[this._domName])) {
  45532. // Update DOM
  45533. if (typeof onUpdate === 'function') {
  45534. onUpdate(element);
  45535. }
  45536. }
  45537. else {
  45538. // No previous dom, create new
  45539. var dom = this.add(element);
  45540. if (dom) {
  45541. element[this._domName] = dom;
  45542. }
  45543. }
  45544. };
  45545. /**
  45546. * Add gradient dom to defs
  45547. *
  45548. * @param {SVGElement} dom DOM to be added to <defs>
  45549. */
  45550. Definable.prototype.addDom = function (dom) {
  45551. var defs = this.getDefs(true);
  45552. defs.appendChild(dom);
  45553. };
  45554. /**
  45555. * Remove DOM of a given element.
  45556. *
  45557. * @param {SVGElement} element element to remove dom
  45558. */
  45559. Definable.prototype.removeDom = function (element) {
  45560. var defs = this.getDefs(false);
  45561. if (defs && element[this._domName]) {
  45562. defs.removeChild(element[this._domName]);
  45563. element[this._domName] = null;
  45564. }
  45565. };
  45566. /**
  45567. * Get DOMs of this element.
  45568. *
  45569. * @return {HTMLDomElement} doms of this defineable elements in <defs>
  45570. */
  45571. Definable.prototype.getDoms = function () {
  45572. var defs = this.getDefs(false);
  45573. if (!defs) {
  45574. // No dom when defs is not defined
  45575. return [];
  45576. }
  45577. var doms = [];
  45578. each$1(this._tagNames, function (tagName) {
  45579. var tags = defs.getElementsByTagName(tagName);
  45580. // Note that tags is HTMLCollection, which is array-like
  45581. // rather than real array.
  45582. // So `doms.concat(tags)` add tags as one object.
  45583. doms = doms.concat([].slice.call(tags));
  45584. });
  45585. return doms;
  45586. };
  45587. /**
  45588. * Mark DOMs to be unused before painting, and clear unused ones at the end
  45589. * of the painting.
  45590. */
  45591. Definable.prototype.markAllUnused = function () {
  45592. var doms = this.getDoms();
  45593. var that = this;
  45594. each$1(doms, function (dom) {
  45595. dom[that._markLabel] = MARK_UNUSED;
  45596. });
  45597. };
  45598. /**
  45599. * Mark a single DOM to be used.
  45600. *
  45601. * @param {SVGElement} dom DOM to mark
  45602. */
  45603. Definable.prototype.markUsed = function (dom) {
  45604. if (dom) {
  45605. dom[this._markLabel] = MARK_USED;
  45606. }
  45607. };
  45608. /**
  45609. * Remove unused DOMs defined in <defs>
  45610. */
  45611. Definable.prototype.removeUnused = function () {
  45612. var defs = this.getDefs(false);
  45613. if (!defs) {
  45614. // Nothing to remove
  45615. return;
  45616. }
  45617. var doms = this.getDoms();
  45618. var that = this;
  45619. each$1(doms, function (dom) {
  45620. if (dom[that._markLabel] !== MARK_USED) {
  45621. // Remove gradient
  45622. defs.removeChild(dom);
  45623. }
  45624. });
  45625. };
  45626. /**
  45627. * Get SVG proxy.
  45628. *
  45629. * @param {Displayable} displayable displayable element
  45630. * @return {Path|Image|Text} svg proxy of given element
  45631. */
  45632. Definable.prototype.getSvgProxy = function (displayable) {
  45633. if (displayable instanceof Path) {
  45634. return svgPath;
  45635. }
  45636. else if (displayable instanceof ZImage) {
  45637. return svgImage;
  45638. }
  45639. else if (displayable instanceof Text) {
  45640. return svgText;
  45641. }
  45642. else {
  45643. return svgPath;
  45644. }
  45645. };
  45646. /**
  45647. * Get text SVG element.
  45648. *
  45649. * @param {Displayable} displayable displayable element
  45650. * @return {SVGElement} SVG element of text
  45651. */
  45652. Definable.prototype.getTextSvgElement = function (displayable) {
  45653. return displayable.__textSvgEl;
  45654. };
  45655. /**
  45656. * Get SVG element.
  45657. *
  45658. * @param {Displayable} displayable displayable element
  45659. * @return {SVGElement} SVG element
  45660. */
  45661. Definable.prototype.getSvgElement = function (displayable) {
  45662. return displayable.__svgEl;
  45663. };
  45664. /**
  45665. * @file Manages SVG gradient elements.
  45666. * @author Zhang Wenli
  45667. */
  45668. /**
  45669. * Manages SVG gradient elements.
  45670. *
  45671. * @class
  45672. * @extends Definable
  45673. * @param {number} zrId zrender instance id
  45674. * @param {SVGElement} svgRoot root of SVG document
  45675. */
  45676. function GradientManager(zrId, svgRoot) {
  45677. Definable.call(
  45678. this,
  45679. zrId,
  45680. svgRoot,
  45681. ['linearGradient', 'radialGradient'],
  45682. '__gradient_in_use__'
  45683. );
  45684. }
  45685. inherits(GradientManager, Definable);
  45686. /**
  45687. * Create new gradient DOM for fill or stroke if not exist,
  45688. * but will not update gradient if exists.
  45689. *
  45690. * @param {SvgElement} svgElement SVG element to paint
  45691. * @param {Displayable} displayable zrender displayable element
  45692. */
  45693. GradientManager.prototype.addWithoutUpdate = function (
  45694. svgElement,
  45695. displayable
  45696. ) {
  45697. if (displayable && displayable.style) {
  45698. var that = this;
  45699. each$1(['fill', 'stroke'], function (fillOrStroke) {
  45700. if (displayable.style[fillOrStroke]
  45701. && (displayable.style[fillOrStroke].type === 'linear'
  45702. || displayable.style[fillOrStroke].type === 'radial')
  45703. ) {
  45704. var gradient = displayable.style[fillOrStroke];
  45705. var defs = that.getDefs(true);
  45706. // Create dom in <defs> if not exists
  45707. var dom;
  45708. if (gradient._dom) {
  45709. // Gradient exists
  45710. dom = gradient._dom;
  45711. if (!defs.contains(gradient._dom)) {
  45712. // _dom is no longer in defs, recreate
  45713. that.addDom(dom);
  45714. }
  45715. }
  45716. else {
  45717. // New dom
  45718. dom = that.add(gradient);
  45719. }
  45720. that.markUsed(displayable);
  45721. var id = dom.getAttribute('id');
  45722. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  45723. }
  45724. });
  45725. }
  45726. };
  45727. /**
  45728. * Add a new gradient tag in <defs>
  45729. *
  45730. * @param {Gradient} gradient zr gradient instance
  45731. * @return {SVGLinearGradientElement | SVGRadialGradientElement}
  45732. * created DOM
  45733. */
  45734. GradientManager.prototype.add = function (gradient) {
  45735. var dom;
  45736. if (gradient.type === 'linear') {
  45737. dom = this.createElement('linearGradient');
  45738. }
  45739. else if (gradient.type === 'radial') {
  45740. dom = this.createElement('radialGradient');
  45741. }
  45742. else {
  45743. zrLog('Illegal gradient type.');
  45744. return null;
  45745. }
  45746. // Set dom id with gradient id, since each gradient instance
  45747. // will have no more than one dom element.
  45748. // id may exists before for those dirty elements, in which case
  45749. // id should remain the same, and other attributes should be
  45750. // updated.
  45751. gradient.id = gradient.id || this.nextId++;
  45752. dom.setAttribute('id', 'zr' + this._zrId
  45753. + '-gradient-' + gradient.id);
  45754. this.updateDom(gradient, dom);
  45755. this.addDom(dom);
  45756. return dom;
  45757. };
  45758. /**
  45759. * Update gradient.
  45760. *
  45761. * @param {Gradient} gradient zr gradient instance
  45762. */
  45763. GradientManager.prototype.update = function (gradient) {
  45764. var that = this;
  45765. Definable.prototype.update.call(this, gradient, function () {
  45766. var type = gradient.type;
  45767. var tagName = gradient._dom.tagName;
  45768. if (type === 'linear' && tagName === 'linearGradient'
  45769. || type === 'radial' && tagName === 'radialGradient'
  45770. ) {
  45771. // Gradient type is not changed, update gradient
  45772. that.updateDom(gradient, gradient._dom);
  45773. }
  45774. else {
  45775. // Remove and re-create if type is changed
  45776. that.removeDom(gradient);
  45777. that.add(gradient);
  45778. }
  45779. });
  45780. };
  45781. /**
  45782. * Update gradient dom
  45783. *
  45784. * @param {Gradient} gradient zr gradient instance
  45785. * @param {SVGLinearGradientElement | SVGRadialGradientElement} dom
  45786. * DOM to update
  45787. */
  45788. GradientManager.prototype.updateDom = function (gradient, dom) {
  45789. if (gradient.type === 'linear') {
  45790. dom.setAttribute('x1', gradient.x);
  45791. dom.setAttribute('y1', gradient.y);
  45792. dom.setAttribute('x2', gradient.x2);
  45793. dom.setAttribute('y2', gradient.y2);
  45794. }
  45795. else if (gradient.type === 'radial') {
  45796. dom.setAttribute('cx', gradient.x);
  45797. dom.setAttribute('cy', gradient.y);
  45798. dom.setAttribute('r', gradient.r);
  45799. }
  45800. else {
  45801. zrLog('Illegal gradient type.');
  45802. return;
  45803. }
  45804. if (gradient.global) {
  45805. // x1, x2, y1, y2 in range of 0 to canvas width or height
  45806. dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  45807. }
  45808. else {
  45809. // x1, x2, y1, y2 in range of 0 to 1
  45810. dom.setAttribute('gradientUnits', 'objectBoundingBox');
  45811. }
  45812. // Remove color stops if exists
  45813. dom.innerHTML = '';
  45814. // Add color stops
  45815. var colors = gradient.colorStops;
  45816. for (var i = 0, len = colors.length; i < len; ++i) {
  45817. var stop = this.createElement('stop');
  45818. stop.setAttribute('offset', colors[i].offset * 100 + '%');
  45819. stop.setAttribute('stop-color', colors[i].color);
  45820. dom.appendChild(stop);
  45821. }
  45822. // Store dom element in gradient, to avoid creating multiple
  45823. // dom instances for the same gradient element
  45824. gradient._dom = dom;
  45825. };
  45826. /**
  45827. * Mark a single gradient to be used
  45828. *
  45829. * @param {Displayable} displayable displayable element
  45830. */
  45831. GradientManager.prototype.markUsed = function (displayable) {
  45832. if (displayable.style) {
  45833. var gradient = displayable.style.fill;
  45834. if (gradient && gradient._dom) {
  45835. Definable.prototype.markUsed.call(this, gradient._dom);
  45836. }
  45837. gradient = displayable.style.stroke;
  45838. if (gradient && gradient._dom) {
  45839. Definable.prototype.markUsed.call(this, gradient._dom);
  45840. }
  45841. }
  45842. };
  45843. /**
  45844. * @file Manages SVG clipPath elements.
  45845. * @author Zhang Wenli
  45846. */
  45847. /**
  45848. * Manages SVG clipPath elements.
  45849. *
  45850. * @class
  45851. * @extends Definable
  45852. * @param {number} zrId zrender instance id
  45853. * @param {SVGElement} svgRoot root of SVG document
  45854. */
  45855. function ClippathManager(zrId, svgRoot) {
  45856. Definable.call(this, zrId, svgRoot, 'clipPath', '__clippath_in_use__');
  45857. }
  45858. inherits(ClippathManager, Definable);
  45859. /**
  45860. * Update clipPath.
  45861. *
  45862. * @param {Displayable} displayable displayable element
  45863. */
  45864. ClippathManager.prototype.update = function (displayable) {
  45865. var svgEl = this.getSvgElement(displayable);
  45866. if (svgEl) {
  45867. this.updateDom(svgEl, displayable.__clipPaths, false);
  45868. }
  45869. var textEl = this.getTextSvgElement(displayable);
  45870. if (textEl) {
  45871. // Make another clipPath for text, since it's transform
  45872. // matrix is not the same with svgElement
  45873. this.updateDom(textEl, displayable.__clipPaths, true);
  45874. }
  45875. this.markUsed(displayable);
  45876. };
  45877. /**
  45878. * Create an SVGElement of displayable and create a <clipPath> of its
  45879. * clipPath
  45880. *
  45881. * @param {Displayable} parentEl parent element
  45882. * @param {ClipPath[]} clipPaths clipPaths of parent element
  45883. * @param {boolean} isText if parent element is Text
  45884. */
  45885. ClippathManager.prototype.updateDom = function (
  45886. parentEl,
  45887. clipPaths,
  45888. isText
  45889. ) {
  45890. if (clipPaths && clipPaths.length > 0) {
  45891. // Has clipPath, create <clipPath> with the first clipPath
  45892. var defs = this.getDefs(true);
  45893. var clipPath = clipPaths[0];
  45894. var clipPathEl;
  45895. var id;
  45896. var dom = isText ? '_textDom' : '_dom';
  45897. if (clipPath[dom]) {
  45898. // Use a dom that is already in <defs>
  45899. id = clipPath[dom].getAttribute('id');
  45900. clipPathEl = clipPath[dom];
  45901. // Use a dom that is already in <defs>
  45902. if (!defs.contains(clipPathEl)) {
  45903. // This happens when set old clipPath that has
  45904. // been previously removed
  45905. defs.appendChild(clipPathEl);
  45906. }
  45907. }
  45908. else {
  45909. // New <clipPath>
  45910. id = 'zr' + this._zrId + '-clip-' + this.nextId;
  45911. ++this.nextId;
  45912. clipPathEl = this.createElement('clipPath');
  45913. clipPathEl.setAttribute('id', id);
  45914. defs.appendChild(clipPathEl);
  45915. clipPath[dom] = clipPathEl;
  45916. }
  45917. // Build path and add to <clipPath>
  45918. var svgProxy = this.getSvgProxy(clipPath);
  45919. if (clipPath.transform
  45920. && clipPath.parent.invTransform
  45921. && !isText
  45922. ) {
  45923. /**
  45924. * If a clipPath has a parent with transform, the transform
  45925. * of parent should not be considered when setting transform
  45926. * of clipPath. So we need to transform back from parent's
  45927. * transform, which is done by multiplying parent's inverse
  45928. * transform.
  45929. */
  45930. // Store old transform
  45931. var transform = Array.prototype.slice.call(
  45932. clipPath.transform
  45933. );
  45934. // Transform back from parent, and brush path
  45935. mul$1(
  45936. clipPath.transform,
  45937. clipPath.parent.invTransform,
  45938. clipPath.transform
  45939. );
  45940. svgProxy.brush(clipPath);
  45941. // Set back transform of clipPath
  45942. clipPath.transform = transform;
  45943. }
  45944. else {
  45945. svgProxy.brush(clipPath);
  45946. }
  45947. var pathEl = this.getSvgElement(clipPath);
  45948. clipPathEl.innerHTML = '';
  45949. /**
  45950. * Use `cloneNode()` here to appendChild to multiple parents,
  45951. * which may happend when Text and other shapes are using the same
  45952. * clipPath. Since Text will create an extra clipPath DOM due to
  45953. * different transform rules.
  45954. */
  45955. clipPathEl.appendChild(pathEl.cloneNode());
  45956. parentEl.setAttribute('clip-path', 'url(#' + id + ')');
  45957. if (clipPaths.length > 1) {
  45958. // Make the other clipPaths recursively
  45959. this.updateDom(clipPathEl, clipPaths.slice(1), isText);
  45960. }
  45961. }
  45962. else {
  45963. // No clipPath
  45964. if (parentEl) {
  45965. parentEl.setAttribute('clip-path', 'none');
  45966. }
  45967. }
  45968. };
  45969. /**
  45970. * Mark a single clipPath to be used
  45971. *
  45972. * @param {Displayable} displayable displayable element
  45973. */
  45974. ClippathManager.prototype.markUsed = function (displayable) {
  45975. var that = this;
  45976. if (displayable.__clipPaths && displayable.__clipPaths.length > 0) {
  45977. each$1(displayable.__clipPaths, function (clipPath) {
  45978. if (clipPath._dom) {
  45979. Definable.prototype.markUsed.call(that, clipPath._dom);
  45980. }
  45981. if (clipPath._textDom) {
  45982. Definable.prototype.markUsed.call(that, clipPath._textDom);
  45983. }
  45984. });
  45985. }
  45986. };
  45987. /**
  45988. * @file Manages SVG shadow elements.
  45989. * @author Zhang Wenli
  45990. */
  45991. /**
  45992. * Manages SVG shadow elements.
  45993. *
  45994. * @class
  45995. * @extends Definable
  45996. * @param {number} zrId zrender instance id
  45997. * @param {SVGElement} svgRoot root of SVG document
  45998. */
  45999. function ShadowManager(zrId, svgRoot) {
  46000. Definable.call(
  46001. this,
  46002. zrId,
  46003. svgRoot,
  46004. ['filter'],
  46005. '__filter_in_use__',
  46006. '_shadowDom'
  46007. );
  46008. }
  46009. inherits(ShadowManager, Definable);
  46010. /**
  46011. * Create new shadow DOM for fill or stroke if not exist,
  46012. * but will not update shadow if exists.
  46013. *
  46014. * @param {SvgElement} svgElement SVG element to paint
  46015. * @param {Displayable} displayable zrender displayable element
  46016. */
  46017. ShadowManager.prototype.addWithoutUpdate = function (
  46018. svgElement,
  46019. displayable
  46020. ) {
  46021. if (displayable && hasShadow(displayable.style)) {
  46022. var style = displayable.style;
  46023. // Create dom in <defs> if not exists
  46024. var dom;
  46025. if (style._shadowDom) {
  46026. // Gradient exists
  46027. dom = style._shadowDom;
  46028. var defs = this.getDefs(true);
  46029. if (!defs.contains(style._shadowDom)) {
  46030. // _shadowDom is no longer in defs, recreate
  46031. this.addDom(dom);
  46032. }
  46033. }
  46034. else {
  46035. // New dom
  46036. dom = this.add(displayable);
  46037. }
  46038. this.markUsed(displayable);
  46039. var id = dom.getAttribute('id');
  46040. svgElement.style.filter = 'url(#' + id + ')';
  46041. }
  46042. };
  46043. /**
  46044. * Add a new shadow tag in <defs>
  46045. *
  46046. * @param {Displayable} displayable zrender displayable element
  46047. * @return {SVGFilterElement} created DOM
  46048. */
  46049. ShadowManager.prototype.add = function (displayable) {
  46050. var dom = this.createElement('filter');
  46051. var style = displayable.style;
  46052. // Set dom id with shadow id, since each shadow instance
  46053. // will have no more than one dom element.
  46054. // id may exists before for those dirty elements, in which case
  46055. // id should remain the same, and other attributes should be
  46056. // updated.
  46057. style._shadowDomId = style._shadowDomId || this.nextId++;
  46058. dom.setAttribute('id', 'zr' + this._zrId
  46059. + '-shadow-' + style._shadowDomId);
  46060. this.updateDom(displayable, dom);
  46061. this.addDom(dom);
  46062. return dom;
  46063. };
  46064. /**
  46065. * Update shadow.
  46066. *
  46067. * @param {Displayable} displayable zrender displayable element
  46068. */
  46069. ShadowManager.prototype.update = function (svgElement, displayable) {
  46070. var style = displayable.style;
  46071. if (hasShadow(style)) {
  46072. var that = this;
  46073. Definable.prototype.update.call(this, displayable, function (style) {
  46074. that.updateDom(displayable, style._shadowDom);
  46075. });
  46076. }
  46077. else {
  46078. // Remove shadow
  46079. this.remove(svgElement, style);
  46080. }
  46081. };
  46082. /**
  46083. * Remove DOM and clear parent filter
  46084. */
  46085. ShadowManager.prototype.remove = function (svgElement, style) {
  46086. if (style._shadowDomId != null) {
  46087. this.removeDom(style);
  46088. svgElement.style.filter = '';
  46089. }
  46090. };
  46091. /**
  46092. * Update shadow dom
  46093. *
  46094. * @param {Displayable} displayable zrender displayable element
  46095. * @param {SVGFilterElement} dom DOM to update
  46096. */
  46097. ShadowManager.prototype.updateDom = function (displayable, dom) {
  46098. var domChild = dom.getElementsByTagName('feDropShadow');
  46099. if (domChild.length === 0) {
  46100. domChild = this.createElement('feDropShadow');
  46101. }
  46102. else {
  46103. domChild = domChild[0];
  46104. }
  46105. var style = displayable.style;
  46106. var scaleX = displayable.scale ? (displayable.scale[0] || 1) : 1;
  46107. var scaleY = displayable.scale ? (displayable.scale[1] || 1) : 1;
  46108. // TODO: textBoxShadowBlur is not supported yet
  46109. var offsetX, offsetY, blur, color;
  46110. if (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY) {
  46111. offsetX = style.shadowOffsetX || 0;
  46112. offsetY = style.shadowOffsetY || 0;
  46113. blur = style.shadowBlur;
  46114. color = style.shadowColor;
  46115. }
  46116. else if (style.textShadowBlur) {
  46117. offsetX = style.textShadowOffsetX || 0;
  46118. offsetY = style.textShadowOffsetY || 0;
  46119. blur = style.textShadowBlur;
  46120. color = style.textShadowColor;
  46121. }
  46122. else {
  46123. // Remove shadow
  46124. this.removeDom(dom, style);
  46125. return;
  46126. }
  46127. domChild.setAttribute('dx', offsetX / scaleX);
  46128. domChild.setAttribute('dy', offsetY / scaleY);
  46129. domChild.setAttribute('flood-color', color);
  46130. // Divide by two here so that it looks the same as in canvas
  46131. // See: https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowblur
  46132. var stdDx = blur / 2 / scaleX;
  46133. var stdDy = blur / 2 / scaleY;
  46134. var stdDeviation = stdDx + ' ' + stdDy;
  46135. domChild.setAttribute('stdDeviation', stdDeviation);
  46136. // Fix filter clipping problem
  46137. dom.setAttribute('x', '-100%');
  46138. dom.setAttribute('y', '-100%');
  46139. dom.setAttribute('width', Math.ceil(blur / 2 * 200) + '%');
  46140. dom.setAttribute('height', Math.ceil(blur / 2 * 200) + '%');
  46141. dom.appendChild(domChild);
  46142. // Store dom element in shadow, to avoid creating multiple
  46143. // dom instances for the same shadow element
  46144. style._shadowDom = dom;
  46145. };
  46146. /**
  46147. * Mark a single shadow to be used
  46148. *
  46149. * @param {Displayable} displayable displayable element
  46150. */
  46151. ShadowManager.prototype.markUsed = function (displayable) {
  46152. var style = displayable.style;
  46153. if (style && style._shadowDom) {
  46154. Definable.prototype.markUsed.call(this, style._shadowDom);
  46155. }
  46156. };
  46157. function hasShadow(style) {
  46158. // TODO: textBoxShadowBlur is not supported yet
  46159. return style
  46160. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY
  46161. || style.textShadowBlur || style.textShadowOffsetX
  46162. || style.textShadowOffsetY);
  46163. }
  46164. /**
  46165. * SVG Painter
  46166. * @module zrender/svg/Painter
  46167. */
  46168. function parseInt10$2(val) {
  46169. return parseInt(val, 10);
  46170. }
  46171. function getSvgProxy(el) {
  46172. if (el instanceof Path) {
  46173. return svgPath;
  46174. }
  46175. else if (el instanceof ZImage) {
  46176. return svgImage;
  46177. }
  46178. else if (el instanceof Text) {
  46179. return svgText;
  46180. }
  46181. else {
  46182. return svgPath;
  46183. }
  46184. }
  46185. function checkParentAvailable(parent, child) {
  46186. return child && parent && child.parentNode !== parent;
  46187. }
  46188. function insertAfter(parent, child, prevSibling) {
  46189. if (checkParentAvailable(parent, child) && prevSibling) {
  46190. var nextSibling = prevSibling.nextSibling;
  46191. nextSibling ? parent.insertBefore(child, nextSibling)
  46192. : parent.appendChild(child);
  46193. }
  46194. }
  46195. function prepend(parent, child) {
  46196. if (checkParentAvailable(parent, child)) {
  46197. var firstChild = parent.firstChild;
  46198. firstChild ? parent.insertBefore(child, firstChild)
  46199. : parent.appendChild(child);
  46200. }
  46201. }
  46202. function remove$1(parent, child) {
  46203. if (child && parent && child.parentNode === parent) {
  46204. parent.removeChild(child);
  46205. }
  46206. }
  46207. function getTextSvgElement(displayable) {
  46208. return displayable.__textSvgEl;
  46209. }
  46210. function getSvgElement(displayable) {
  46211. return displayable.__svgEl;
  46212. }
  46213. /**
  46214. * @alias module:zrender/svg/Painter
  46215. * @constructor
  46216. * @param {HTMLElement} root 绘图容器
  46217. * @param {module:zrender/Storage} storage
  46218. * @param {Object} opts
  46219. */
  46220. var SVGPainter = function (root, storage, opts, zrId) {
  46221. this.root = root;
  46222. this.storage = storage;
  46223. this._opts = opts = extend({}, opts || {});
  46224. var svgRoot = createElement('svg');
  46225. svgRoot.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  46226. svgRoot.setAttribute('version', '1.1');
  46227. svgRoot.setAttribute('baseProfile', 'full');
  46228. svgRoot.style.cssText = 'user-select:none;position:absolute;left:0;top:0;';
  46229. this.gradientManager = new GradientManager(zrId, svgRoot);
  46230. this.clipPathManager = new ClippathManager(zrId, svgRoot);
  46231. this.shadowManager = new ShadowManager(zrId, svgRoot);
  46232. var viewport = document.createElement('div');
  46233. viewport.style.cssText = 'overflow:hidden;position:relative';
  46234. this._svgRoot = svgRoot;
  46235. this._viewport = viewport;
  46236. root.appendChild(viewport);
  46237. viewport.appendChild(svgRoot);
  46238. this.resize(opts.width, opts.height);
  46239. this._visibleList = [];
  46240. };
  46241. SVGPainter.prototype = {
  46242. constructor: SVGPainter,
  46243. getType: function () {
  46244. return 'svg';
  46245. },
  46246. getViewportRoot: function () {
  46247. return this._viewport;
  46248. },
  46249. getViewportRootOffset: function () {
  46250. var viewportRoot = this.getViewportRoot();
  46251. if (viewportRoot) {
  46252. return {
  46253. offsetLeft: viewportRoot.offsetLeft || 0,
  46254. offsetTop: viewportRoot.offsetTop || 0
  46255. };
  46256. }
  46257. },
  46258. refresh: function () {
  46259. var list = this.storage.getDisplayList(true);
  46260. this._paintList(list);
  46261. },
  46262. setBackgroundColor: function (backgroundColor) {
  46263. // TODO gradient
  46264. this._viewport.style.background = backgroundColor;
  46265. },
  46266. _paintList: function (list) {
  46267. this.gradientManager.markAllUnused();
  46268. this.clipPathManager.markAllUnused();
  46269. this.shadowManager.markAllUnused();
  46270. var svgRoot = this._svgRoot;
  46271. var visibleList = this._visibleList;
  46272. var listLen = list.length;
  46273. var newVisibleList = [];
  46274. var i;
  46275. for (i = 0; i < listLen; i++) {
  46276. var displayable = list[i];
  46277. var svgProxy = getSvgProxy(displayable);
  46278. var svgElement = getSvgElement(displayable)
  46279. || getTextSvgElement(displayable);
  46280. if (!displayable.invisible) {
  46281. if (displayable.__dirty) {
  46282. svgProxy && svgProxy.brush(displayable);
  46283. // Update clipPath
  46284. this.clipPathManager.update(displayable);
  46285. // Update gradient and shadow
  46286. if (displayable.style) {
  46287. this.gradientManager
  46288. .update(displayable.style.fill);
  46289. this.gradientManager
  46290. .update(displayable.style.stroke);
  46291. this.shadowManager
  46292. .update(svgElement, displayable);
  46293. }
  46294. displayable.__dirty = false;
  46295. }
  46296. newVisibleList.push(displayable);
  46297. }
  46298. }
  46299. var diff = arrayDiff$1(visibleList, newVisibleList);
  46300. var prevSvgElement;
  46301. // First do remove, in case element moved to the head and do remove
  46302. // after add
  46303. for (i = 0; i < diff.length; i++) {
  46304. var item = diff[i];
  46305. if (item.removed) {
  46306. for (var k = 0; k < item.count; k++) {
  46307. var displayable = visibleList[item.indices[k]];
  46308. var svgElement = getSvgElement(displayable);
  46309. var textSvgElement = getTextSvgElement(displayable);
  46310. remove$1(svgRoot, svgElement);
  46311. remove$1(svgRoot, textSvgElement);
  46312. }
  46313. }
  46314. }
  46315. for (i = 0; i < diff.length; i++) {
  46316. var item = diff[i];
  46317. if (item.added) {
  46318. for (var k = 0; k < item.count; k++) {
  46319. var displayable = newVisibleList[item.indices[k]];
  46320. var svgElement = getSvgElement(displayable);
  46321. var textSvgElement = getTextSvgElement(displayable);
  46322. prevSvgElement
  46323. ? insertAfter(svgRoot, svgElement, prevSvgElement)
  46324. : prepend(svgRoot, svgElement);
  46325. if (svgElement) {
  46326. insertAfter(svgRoot, textSvgElement, svgElement);
  46327. }
  46328. else if (prevSvgElement) {
  46329. insertAfter(
  46330. svgRoot, textSvgElement, prevSvgElement
  46331. );
  46332. }
  46333. else {
  46334. prepend(svgRoot, textSvgElement);
  46335. }
  46336. // Insert text
  46337. insertAfter(svgRoot, textSvgElement, svgElement);
  46338. prevSvgElement = textSvgElement || svgElement
  46339. || prevSvgElement;
  46340. this.gradientManager
  46341. .addWithoutUpdate(svgElement, displayable);
  46342. this.shadowManager
  46343. .addWithoutUpdate(prevSvgElement, displayable);
  46344. this.clipPathManager.markUsed(displayable);
  46345. }
  46346. }
  46347. else if (!item.removed) {
  46348. for (var k = 0; k < item.count; k++) {
  46349. var displayable = newVisibleList[item.indices[k]];
  46350. prevSvgElement
  46351. = svgElement
  46352. = getTextSvgElement(displayable)
  46353. || getSvgElement(displayable)
  46354. || prevSvgElement;
  46355. this.gradientManager.markUsed(displayable);
  46356. this.gradientManager
  46357. .addWithoutUpdate(svgElement, displayable);
  46358. this.shadowManager.markUsed(displayable);
  46359. this.shadowManager
  46360. .addWithoutUpdate(svgElement, displayable);
  46361. this.clipPathManager.markUsed(displayable);
  46362. }
  46363. }
  46364. }
  46365. this.gradientManager.removeUnused();
  46366. this.clipPathManager.removeUnused();
  46367. this.shadowManager.removeUnused();
  46368. this._visibleList = newVisibleList;
  46369. },
  46370. _getDefs: function (isForceCreating) {
  46371. var svgRoot = this._svgRoot;
  46372. var defs = this._svgRoot.getElementsByTagName('defs');
  46373. if (defs.length === 0) {
  46374. // Not exist
  46375. if (isForceCreating) {
  46376. var defs = svgRoot.insertBefore(
  46377. createElement('defs'), // Create new tag
  46378. svgRoot.firstChild // Insert in the front of svg
  46379. );
  46380. if (!defs.contains) {
  46381. // IE doesn't support contains method
  46382. defs.contains = function (el) {
  46383. var children = defs.children;
  46384. if (!children) {
  46385. return false;
  46386. }
  46387. for (var i = children.length - 1; i >= 0; --i) {
  46388. if (children[i] === el) {
  46389. return true;
  46390. }
  46391. }
  46392. return false;
  46393. };
  46394. }
  46395. return defs;
  46396. }
  46397. else {
  46398. return null;
  46399. }
  46400. }
  46401. else {
  46402. return defs[0];
  46403. }
  46404. },
  46405. resize: function (width, height) {
  46406. var viewport = this._viewport;
  46407. // FIXME Why ?
  46408. viewport.style.display = 'none';
  46409. // Save input w/h
  46410. var opts = this._opts;
  46411. width != null && (opts.width = width);
  46412. height != null && (opts.height = height);
  46413. width = this._getSize(0);
  46414. height = this._getSize(1);
  46415. viewport.style.display = '';
  46416. if (this._width !== width || this._height !== height) {
  46417. this._width = width;
  46418. this._height = height;
  46419. var viewportStyle = viewport.style;
  46420. viewportStyle.width = width + 'px';
  46421. viewportStyle.height = height + 'px';
  46422. var svgRoot = this._svgRoot;
  46423. // Set width by 'svgRoot.width = width' is invalid
  46424. svgRoot.setAttribute('width', width);
  46425. svgRoot.setAttribute('height', height);
  46426. }
  46427. },
  46428. /**
  46429. * 获取绘图区域宽度
  46430. */
  46431. getWidth: function () {
  46432. return this._width;
  46433. },
  46434. /**
  46435. * 获取绘图区域高度
  46436. */
  46437. getHeight: function () {
  46438. return this._height;
  46439. },
  46440. _getSize: function (whIdx) {
  46441. var opts = this._opts;
  46442. var wh = ['width', 'height'][whIdx];
  46443. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  46444. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  46445. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  46446. if (opts[wh] != null && opts[wh] !== 'auto') {
  46447. return parseFloat(opts[wh]);
  46448. }
  46449. var root = this.root;
  46450. // IE8 does not support getComputedStyle, but it use VML.
  46451. var stl = document.defaultView.getComputedStyle(root);
  46452. return (
  46453. (root[cwh] || parseInt10$2(stl[wh]) || parseInt10$2(root.style[wh]))
  46454. - (parseInt10$2(stl[plt]) || 0)
  46455. - (parseInt10$2(stl[prb]) || 0)
  46456. ) | 0;
  46457. },
  46458. dispose: function () {
  46459. this.root.innerHTML = '';
  46460. this._svgRoot
  46461. = this._viewport
  46462. = this.storage
  46463. = null;
  46464. },
  46465. clear: function () {
  46466. if (this._viewport) {
  46467. this.root.removeChild(this._viewport);
  46468. }
  46469. },
  46470. pathToDataUrl: function () {
  46471. this.refresh();
  46472. var html = this._svgRoot.outerHTML;
  46473. return 'data:image/svg+xml;charset=UTF-8,' + html;
  46474. }
  46475. };
  46476. // Not supported methods
  46477. function createMethodNotSupport$1(method) {
  46478. return function () {
  46479. zrLog('In SVG mode painter not support method "' + method + '"');
  46480. };
  46481. }
  46482. // Unsuppoted methods
  46483. each$1([
  46484. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer',
  46485. 'eachOtherLayer', 'getLayers', 'modLayer', 'delLayer', 'clearLayer',
  46486. 'toDataURL', 'pathToImage'
  46487. ], function (name) {
  46488. SVGPainter.prototype[name] = createMethodNotSupport$1(name);
  46489. });
  46490. registerPainter('svg', SVGPainter);
  46491. exports.version = version;
  46492. exports.dependencies = dependencies;
  46493. exports.PRIORITY = PRIORITY;
  46494. exports.init = init;
  46495. exports.connect = connect;
  46496. exports.disConnect = disConnect;
  46497. exports.disconnect = disconnect;
  46498. exports.dispose = dispose;
  46499. exports.getInstanceByDom = getInstanceByDom;
  46500. exports.getInstanceById = getInstanceById;
  46501. exports.registerTheme = registerTheme;
  46502. exports.registerPreprocessor = registerPreprocessor;
  46503. exports.registerProcessor = registerProcessor;
  46504. exports.registerPostUpdate = registerPostUpdate;
  46505. exports.registerAction = registerAction;
  46506. exports.registerCoordinateSystem = registerCoordinateSystem;
  46507. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  46508. exports.registerLayout = registerLayout;
  46509. exports.registerVisual = registerVisual;
  46510. exports.registerLoading = registerLoading;
  46511. exports.extendComponentModel = extendComponentModel;
  46512. exports.extendComponentView = extendComponentView;
  46513. exports.extendSeriesModel = extendSeriesModel;
  46514. exports.extendChartView = extendChartView;
  46515. exports.setCanvasCreator = setCanvasCreator;
  46516. exports.registerMap = registerMap;
  46517. exports.getMap = getMap;
  46518. exports.dataTool = dataTool;
  46519. exports.zrender = zrender;
  46520. exports.graphic = graphic;
  46521. exports.number = number;
  46522. exports.format = format;
  46523. exports.throttle = throttle;
  46524. exports.helper = helper;
  46525. exports.matrix = matrix;
  46526. exports.vector = vector;
  46527. exports.color = color;
  46528. exports.parseGeoJSON = parseGeoJSON;
  46529. exports.parseGeoJson = parseGeoJson;
  46530. exports.util = ecUtil;
  46531. exports.List = List;
  46532. exports.Model = Model;
  46533. exports.Axis = Axis;
  46534. exports.env = env$1;
  46535. })));