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.
 
 
 
 
 
 

53943 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: 'Box Select',
  19986. polygon: 'Lasso Select',
  19987. lineX: 'Horizontally Select',
  19988. lineY: 'Vertically Select',
  19989. keep: 'Keep Selections',
  19990. clear: 'Clear Selections'
  19991. }
  19992. },
  19993. dataView: {
  19994. title: 'Data View',
  19995. lang: ['Data View', 'Close', 'Refresh']
  19996. },
  19997. dataZoom: {
  19998. title: {
  19999. zoom: 'Zoom',
  20000. back: 'Zoom Reset'
  20001. }
  20002. },
  20003. magicType: {
  20004. title: {
  20005. line: 'Switch to Line Chart',
  20006. bar: 'Switch to Bar Chart',
  20007. stack: 'Stack',
  20008. tiled: 'Tile'
  20009. }
  20010. },
  20011. restore: {
  20012. title: 'Restore'
  20013. },
  20014. saveAsImage: {
  20015. title: 'Save as Image',
  20016. lang: ['Right Click to Save Image']
  20017. }
  20018. }
  20019. };
  20020. var aria = function (dom, ecModel) {
  20021. var ariaModel = ecModel.getModel('aria');
  20022. if (!ariaModel.get('show')) {
  20023. return;
  20024. }
  20025. else if (ariaModel.get('description')) {
  20026. dom.setAttribute('aria-label', ariaModel.get('description'));
  20027. return;
  20028. }
  20029. var seriesCnt = 0;
  20030. ecModel.eachSeries(function (seriesModel, idx) {
  20031. ++seriesCnt;
  20032. }, this);
  20033. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  20034. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  20035. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  20036. var ariaLabel;
  20037. if (seriesCnt < 1) {
  20038. // No series, no aria label
  20039. return;
  20040. }
  20041. else {
  20042. var title = getTitle();
  20043. if (title) {
  20044. ariaLabel = replace(getConfig('general.withTitle'), {
  20045. title: title
  20046. });
  20047. }
  20048. else {
  20049. ariaLabel = getConfig('general.withoutTitle');
  20050. }
  20051. var seriesLabels = [];
  20052. var prefix = seriesCnt > 1
  20053. ? 'series.multiple.prefix'
  20054. : 'series.single.prefix';
  20055. ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });
  20056. ecModel.eachSeries(function (seriesModel, idx) {
  20057. if (idx < displaySeriesCnt) {
  20058. var seriesLabel;
  20059. var seriesName = seriesModel.get('name');
  20060. var seriesTpl = 'series.'
  20061. + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  20062. seriesLabel = getConfig(seriesName
  20063. ? seriesTpl + 'withName'
  20064. : seriesTpl + 'withoutName');
  20065. seriesLabel = replace(seriesLabel, {
  20066. seriesId: seriesModel.seriesIndex,
  20067. seriesName: seriesModel.get('name'),
  20068. seriesType: getSeriesTypeName(seriesModel.subType)
  20069. });
  20070. var data = seriesModel.getData();
  20071. window.data = data;
  20072. if (data.count() > maxDataCnt) {
  20073. // Show part of data
  20074. seriesLabel += replace(getConfig('data.partialData'), {
  20075. displayCnt: maxDataCnt
  20076. });
  20077. }
  20078. else {
  20079. seriesLabel += getConfig('data.allData');
  20080. }
  20081. var dataLabels = [];
  20082. for (var i = 0; i < data.count(); i++) {
  20083. if (i < maxDataCnt) {
  20084. var name = data.getName(i);
  20085. var value = retrieveRawValue(data, i);
  20086. dataLabels.push(
  20087. replace(
  20088. name
  20089. ? getConfig('data.withName')
  20090. : getConfig('data.withoutName'),
  20091. {
  20092. name: name,
  20093. value: value
  20094. }
  20095. )
  20096. );
  20097. }
  20098. }
  20099. seriesLabel += dataLabels
  20100. .join(getConfig('data.separator.middle'))
  20101. + getConfig('data.separator.end');
  20102. seriesLabels.push(seriesLabel);
  20103. }
  20104. });
  20105. ariaLabel += seriesLabels
  20106. .join(getConfig('series.multiple.separator.middle'))
  20107. + getConfig('series.multiple.separator.end');
  20108. dom.setAttribute('aria-label', ariaLabel);
  20109. }
  20110. function replace(str, keyValues) {
  20111. if (typeof str !== 'string') {
  20112. return str;
  20113. }
  20114. var result = str;
  20115. each$1(keyValues, function (value, key) {
  20116. result = result.replace(
  20117. new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
  20118. value
  20119. );
  20120. });
  20121. return result;
  20122. }
  20123. function getConfig(path) {
  20124. var userConfig = ariaModel.get(path);
  20125. if (userConfig == null) {
  20126. var pathArr = path.split('.');
  20127. var result = lang.aria;
  20128. for (var i = 0; i < pathArr.length; ++i) {
  20129. result = result[pathArr[i]];
  20130. }
  20131. return result;
  20132. }
  20133. else {
  20134. return userConfig;
  20135. }
  20136. }
  20137. function getTitle() {
  20138. var title = ecModel.getModel('title').option;
  20139. if (title && title.length) {
  20140. title = title[0];
  20141. }
  20142. return title && title.text;
  20143. }
  20144. function getSeriesTypeName(type) {
  20145. return lang.series.typeNames[type] || '自定义图';
  20146. }
  20147. };
  20148. var PI$1 = Math.PI;
  20149. /**
  20150. * @param {module:echarts/ExtensionAPI} api
  20151. * @param {Object} [opts]
  20152. * @param {string} [opts.text]
  20153. * @param {string} [opts.color]
  20154. * @param {string} [opts.textColor]
  20155. * @return {module:zrender/Element}
  20156. */
  20157. var loadingDefault = function (api, opts) {
  20158. opts = opts || {};
  20159. defaults(opts, {
  20160. text: 'loading',
  20161. color: '#c23531',
  20162. textColor: '#000',
  20163. maskColor: 'rgba(255, 255, 255, 0.8)',
  20164. zlevel: 0
  20165. });
  20166. var mask = new Rect({
  20167. style: {
  20168. fill: opts.maskColor
  20169. },
  20170. zlevel: opts.zlevel,
  20171. z: 10000
  20172. });
  20173. var arc = new Arc({
  20174. shape: {
  20175. startAngle: -PI$1 / 2,
  20176. endAngle: -PI$1 / 2 + 0.1,
  20177. r: 10
  20178. },
  20179. style: {
  20180. stroke: opts.color,
  20181. lineCap: 'round',
  20182. lineWidth: 5
  20183. },
  20184. zlevel: opts.zlevel,
  20185. z: 10001
  20186. });
  20187. var labelRect = new Rect({
  20188. style: {
  20189. fill: 'none',
  20190. text: opts.text,
  20191. textPosition: 'right',
  20192. textDistance: 10,
  20193. textFill: opts.textColor
  20194. },
  20195. zlevel: opts.zlevel,
  20196. z: 10001
  20197. });
  20198. arc.animateShape(true)
  20199. .when(1000, {
  20200. endAngle: PI$1 * 3 / 2
  20201. })
  20202. .start('circularInOut');
  20203. arc.animateShape(true)
  20204. .when(1000, {
  20205. startAngle: PI$1 * 3 / 2
  20206. })
  20207. .delay(300)
  20208. .start('circularInOut');
  20209. var group = new Group();
  20210. group.add(arc);
  20211. group.add(labelRect);
  20212. group.add(mask);
  20213. // Inject resize
  20214. group.resize = function () {
  20215. var cx = api.getWidth() / 2;
  20216. var cy = api.getHeight() / 2;
  20217. arc.setShape({
  20218. cx: cx,
  20219. cy: cy
  20220. });
  20221. var r = arc.shape.r;
  20222. labelRect.setShape({
  20223. x: cx - r,
  20224. y: cy - r,
  20225. width: r * 2,
  20226. height: r * 2
  20227. });
  20228. mask.setShape({
  20229. x: 0,
  20230. y: 0,
  20231. width: api.getWidth(),
  20232. height: api.getHeight()
  20233. });
  20234. };
  20235. group.resize();
  20236. return group;
  20237. };
  20238. /**
  20239. * @module echarts/stream/Scheduler
  20240. */
  20241. /**
  20242. * @constructor
  20243. */
  20244. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  20245. // this._pipelineMap = createHashMap();
  20246. this.ecInstance = ecInstance;
  20247. this.api = api;
  20248. this.unfinished;
  20249. // Fix current processors in case that in some rear cases that
  20250. // processors might be registered after echarts instance created.
  20251. // Register processors incrementally for a echarts instance is
  20252. // not supported by this stream architecture.
  20253. this._dataProcessorHandlers = dataProcessorHandlers.slice();
  20254. this._visualHandlers = visualHandlers.slice();
  20255. /**
  20256. * @private
  20257. * @type {
  20258. * [handlerUID: string]: {
  20259. * seriesTaskMap?: {
  20260. * [seriesUID: string]: Task
  20261. * },
  20262. * overallTask?: Task
  20263. * }
  20264. * }
  20265. */
  20266. this._stageTaskMap = createHashMap();
  20267. }
  20268. var proto = Scheduler.prototype;
  20269. // If seriesModel provided, incremental threshold is check by series data.
  20270. proto.getPerformArgs = function (task, isBlock) {
  20271. // For overall task
  20272. if (!task.__pipeline) {
  20273. return;
  20274. }
  20275. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  20276. var pCtx = pipeline.context;
  20277. var incremental = !isBlock
  20278. && pipeline.progressiveEnabled
  20279. && (!pCtx || pCtx.canProgressiveRender)
  20280. && task.__idxInPipeline > pipeline.bockIndex;
  20281. return {step: incremental ? pipeline.step : null};
  20282. };
  20283. proto.getPipeline = function (pipelineId) {
  20284. return this._pipelineMap.get(pipelineId);
  20285. };
  20286. /**
  20287. * Current, progressive rendering starts from visual and layout.
  20288. * Always detect render mode in the same stage, avoiding that incorrect
  20289. * detection caused by data filtering.
  20290. * Caution:
  20291. * `updateStreamModes` use `seriesModel.getData()`.
  20292. */
  20293. proto.updateStreamModes = function (seriesModel, view) {
  20294. var pipeline = this._pipelineMap.get(seriesModel.uid);
  20295. var data = seriesModel.getData();
  20296. var dataLen = data.count();
  20297. // `canProgressiveRender` means that can render progressively in each
  20298. // animation frame. Note that some types of series do not provide
  20299. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  20300. // use the term `incremental` but not `progressive` to describe the
  20301. // case that `chart.appendData`.
  20302. var canProgressiveRender = pipeline.progressiveEnabled
  20303. && view.incrementalPrepareRender
  20304. && dataLen >= pipeline.threshold;
  20305. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  20306. seriesModel.pipelineContext = pipeline.context = {
  20307. canProgressiveRender: canProgressiveRender,
  20308. large: large
  20309. };
  20310. };
  20311. proto.restorePipelines = function (ecModel) {
  20312. var scheduler = this;
  20313. var pipelineMap = scheduler._pipelineMap = createHashMap();
  20314. ecModel.eachSeries(function (seriesModel) {
  20315. var progressive = seriesModel.getProgressive();
  20316. var pipelineId = seriesModel.uid;
  20317. pipelineMap.set(pipelineId, {
  20318. id: pipelineId,
  20319. head: null,
  20320. tail: null,
  20321. threshold: seriesModel.getProgressiveThreshold(),
  20322. progressiveEnabled: progressive
  20323. && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  20324. bockIndex: -1,
  20325. step: progressive || 700, // ??? Temporarily number
  20326. count: 0
  20327. });
  20328. pipe(scheduler, seriesModel, seriesModel.dataTask);
  20329. });
  20330. };
  20331. proto.prepareStageTasks = function () {
  20332. var stageTaskMap = this._stageTaskMap;
  20333. var ecModel = this.ecInstance.getModel();
  20334. var api = this.api;
  20335. each$1([this._dataProcessorHandlers, this._visualHandlers], function (stageHandlers) {
  20336. each$1(stageHandlers, function (handler) {
  20337. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  20338. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  20339. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  20340. }, this);
  20341. }, this);
  20342. };
  20343. proto.prepareView = function (view, model, ecModel, api) {
  20344. var renderTask = view.renderTask;
  20345. var context = renderTask.context;
  20346. context.model = model;
  20347. context.ecModel = ecModel;
  20348. context.api = api;
  20349. renderTask.__block = !view.incrementalPrepareRender;
  20350. pipe(this, model, renderTask);
  20351. };
  20352. proto.performDataProcessorTasks = function (ecModel, payload) {
  20353. // If we do not use `block` here, it should be considered when to update modes.
  20354. performStageTasks(this, this._dataProcessorHandlers, ecModel, payload, {block: true});
  20355. };
  20356. // opt
  20357. // opt.visualType: 'visual' or 'layout'
  20358. // opt.setDirty
  20359. proto.performVisualTasks = function (ecModel, payload, opt) {
  20360. performStageTasks(this, this._visualHandlers, ecModel, payload, opt);
  20361. };
  20362. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  20363. opt = opt || {};
  20364. var unfinished;
  20365. each$1(stageHandlers, function (stageHandler, idx) {
  20366. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  20367. return;
  20368. }
  20369. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  20370. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  20371. var overallTask = stageHandlerRecord.overallTask;
  20372. if (overallTask) {
  20373. var overallNeedDirty;
  20374. var agentStubMap = overallTask.agentStubMap;
  20375. agentStubMap.each(function (stub) {
  20376. if (needSetDirty(opt, stub)) {
  20377. stub.dirty();
  20378. overallNeedDirty = true;
  20379. }
  20380. });
  20381. overallNeedDirty && overallTask.dirty();
  20382. updatePayload(overallTask, payload);
  20383. var performArgs = scheduler.getPerformArgs(overallTask, opt.block);
  20384. // Execute stubs firstly, which may set the overall task dirty,
  20385. // then execute the overall task. And stub will call seriesModel.setData,
  20386. // which ensures that in the overallTask seriesModel.getData() will not
  20387. // return incorrect data.
  20388. agentStubMap.each(function (stub) {
  20389. stub.perform(performArgs);
  20390. });
  20391. unfinished |= overallTask.perform(performArgs);
  20392. }
  20393. else if (seriesTaskMap) {
  20394. seriesTaskMap.each(function (task, pipelineId) {
  20395. if (needSetDirty(opt, task)) {
  20396. task.dirty();
  20397. }
  20398. var performArgs = scheduler.getPerformArgs(task, opt.block);
  20399. performArgs.skip = !stageHandler.performRawSeries
  20400. && ecModel.isSeriesFiltered(task.context.model);
  20401. updatePayload(task, payload);
  20402. unfinished |= task.perform(performArgs);
  20403. });
  20404. }
  20405. });
  20406. function needSetDirty(opt, task) {
  20407. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  20408. }
  20409. scheduler.unfinished |= unfinished;
  20410. }
  20411. proto.performSeriesTasks = function (ecModel) {
  20412. var unfinished;
  20413. ecModel.eachSeries(function (seriesModel) {
  20414. // Progress to the end for dataInit and dataRestore.
  20415. unfinished |= seriesModel.dataTask.perform();
  20416. });
  20417. this.unfinished |= unfinished;
  20418. };
  20419. proto.plan = function () {
  20420. // Travel pipelines, check block.
  20421. this._pipelineMap.each(function (pipeline) {
  20422. var task = pipeline.tail;
  20423. do {
  20424. if (task.__block) {
  20425. pipeline.bockIndex = task.__idxInPipeline;
  20426. break;
  20427. }
  20428. task = task.getUpstream();
  20429. }
  20430. while (task);
  20431. });
  20432. };
  20433. var updatePayload = proto.updatePayload = function (task, payload) {
  20434. payload !== 'remain' && (task.context.payload = payload);
  20435. };
  20436. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  20437. var seriesTaskMap = stageHandlerRecord.seriesTaskMap
  20438. || (stageHandlerRecord.seriesTaskMap = createHashMap());
  20439. var seriesType = stageHandler.seriesType;
  20440. var getTargetSeries = stageHandler.getTargetSeries;
  20441. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  20442. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  20443. // it works but it may cause other irrelevant charts blocked.
  20444. if (stageHandler.createOnAllSeries) {
  20445. ecModel.eachRawSeries(create);
  20446. }
  20447. else if (seriesType) {
  20448. ecModel.eachRawSeriesByType(seriesType, create);
  20449. }
  20450. else if (getTargetSeries) {
  20451. getTargetSeries(ecModel, api).each(create);
  20452. }
  20453. function create(seriesModel) {
  20454. var pipelineId = seriesModel.uid;
  20455. // Init tasks for each seriesModel only once.
  20456. // Reuse original task instance.
  20457. var task = seriesTaskMap.get(pipelineId)
  20458. || seriesTaskMap.set(pipelineId, createTask({
  20459. plan: seriesTaskPlan,
  20460. reset: seriesTaskReset,
  20461. count: seriesTaskCount
  20462. }));
  20463. task.context = {
  20464. model: seriesModel,
  20465. ecModel: ecModel,
  20466. api: api,
  20467. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  20468. plan: stageHandler.plan,
  20469. reset: stageHandler.reset,
  20470. scheduler: scheduler
  20471. };
  20472. pipe(scheduler, seriesModel, task);
  20473. }
  20474. // Clear unused series tasks.
  20475. var pipelineMap = scheduler._pipelineMap;
  20476. seriesTaskMap.each(function (task, pipelineId) {
  20477. if (!pipelineMap.get(pipelineId)) {
  20478. task.dispose();
  20479. seriesTaskMap.removeKey(pipelineId);
  20480. }
  20481. });
  20482. }
  20483. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  20484. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  20485. // For overall task, the function only be called on reset stage.
  20486. || createTask({reset: overallTaskReset});
  20487. overallTask.context = {
  20488. ecModel: ecModel,
  20489. api: api,
  20490. overallReset: stageHandler.overallReset,
  20491. scheduler: scheduler
  20492. };
  20493. // Reuse orignal stubs.
  20494. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  20495. var seriesType = stageHandler.seriesType;
  20496. var getTargetSeries = stageHandler.getTargetSeries;
  20497. var overallProgress = true;
  20498. var isOverallFilter = stageHandler.isOverallFilter;
  20499. // An overall task with seriesType detected or has `getTargetSeries`, we add
  20500. // stub in each pipelines, it will set the overall task dirty when the pipeline
  20501. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  20502. // we set the pipeline block.
  20503. if (seriesType) {
  20504. ecModel.eachRawSeriesByType(seriesType, createStub);
  20505. }
  20506. else if (getTargetSeries) {
  20507. getTargetSeries(ecModel, api).each(createStub);
  20508. }
  20509. // Otherwise, (usually it is legancy case), the overall task will only be
  20510. // executed when upstream dirty. Otherwise the progressive rendering of all
  20511. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  20512. // dirty info from upsteam.
  20513. else {
  20514. overallProgress = false;
  20515. each$1(ecModel.getSeries(), createStub);
  20516. }
  20517. function createStub(seriesModel) {
  20518. var pipelineId = seriesModel.uid;
  20519. var stub = agentStubMap.get(pipelineId) || agentStubMap.set(pipelineId, createTask(
  20520. {reset: stubReset, onDirty: stubOnDirty}
  20521. ));
  20522. stub.context = {
  20523. model: seriesModel,
  20524. overallProgress: overallProgress,
  20525. isOverallFilter: isOverallFilter
  20526. };
  20527. stub.agent = overallTask;
  20528. stub.__block = overallProgress;
  20529. pipe(scheduler, seriesModel, stub);
  20530. }
  20531. // Clear unused stubs.
  20532. var pipelineMap = scheduler._pipelineMap;
  20533. agentStubMap.each(function (stub, pipelineId) {
  20534. if (!pipelineMap.get(pipelineId)) {
  20535. stub.dispose();
  20536. agentStubMap.removeKey(pipelineId);
  20537. }
  20538. });
  20539. }
  20540. function overallTaskReset(context) {
  20541. context.overallReset(
  20542. context.ecModel, context.api, context.payload
  20543. );
  20544. }
  20545. function stubReset(context, upstreamContext) {
  20546. return context.overallProgress && stubProgress;
  20547. }
  20548. function stubProgress() {
  20549. this.agent.dirty();
  20550. this.getDownstream().dirty();
  20551. }
  20552. function stubOnDirty() {
  20553. this.agent && this.agent.dirty();
  20554. }
  20555. function seriesTaskPlan(context) {
  20556. return context.plan && context.plan(
  20557. context.model, context.ecModel, context.api, context.payload
  20558. );
  20559. }
  20560. function seriesTaskReset(context) {
  20561. if (context.useClearVisual) {
  20562. context.data.clearAllVisual();
  20563. }
  20564. var resetDefines = context.resetDefines = normalizeToArray(context.reset(
  20565. context.model, context.ecModel, context.api, context.payload
  20566. ));
  20567. if (resetDefines.length) {
  20568. return seriesTaskProgress;
  20569. }
  20570. }
  20571. function seriesTaskProgress(params, context) {
  20572. var data = context.data;
  20573. var resetDefines = context.resetDefines;
  20574. for (var k = 0; k < resetDefines.length; k++) {
  20575. var resetDefine = resetDefines[k];
  20576. if (resetDefine && resetDefine.dataEach) {
  20577. for (var i = params.start; i < params.end; i++) {
  20578. resetDefine.dataEach(data, i);
  20579. }
  20580. }
  20581. else if (resetDefine && resetDefine.progress) {
  20582. resetDefine.progress(params, data);
  20583. }
  20584. }
  20585. }
  20586. function seriesTaskCount(context) {
  20587. return context.data.count();
  20588. }
  20589. function pipe(scheduler, seriesModel, task) {
  20590. var pipelineId = seriesModel.uid;
  20591. var pipeline = scheduler._pipelineMap.get(pipelineId);
  20592. !pipeline.head && (pipeline.head = task);
  20593. pipeline.tail && pipeline.tail.pipe(task);
  20594. pipeline.tail = task;
  20595. task.__idxInPipeline = pipeline.count++;
  20596. task.__pipeline = pipeline;
  20597. }
  20598. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  20599. if (isFunction$1(stageHandler)) {
  20600. stageHandler = {
  20601. overallReset: stageHandler,
  20602. seriesType: detectSeriseType(stageHandler)
  20603. };
  20604. }
  20605. stageHandler.uid = getUID('stageHandler');
  20606. visualType && (stageHandler.visualType = visualType);
  20607. return stageHandler;
  20608. };
  20609. /**
  20610. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  20611. * To ensure that they can work normally, they should work in block mode, that is,
  20612. * they should not be started util the previous tasks finished. So they cause the
  20613. * progressive rendering disabled. We try to detect the series type, to narrow down
  20614. * the block range to only the series type they concern, but not all series.
  20615. */
  20616. function detectSeriseType(legacyFunc) {
  20617. seriesType = null;
  20618. try {
  20619. // Assume there is no async when calling `eachSeriesByType`.
  20620. legacyFunc(ecModelMock, apiMock);
  20621. }
  20622. catch (e) {
  20623. }
  20624. return seriesType;
  20625. }
  20626. var ecModelMock = {};
  20627. var apiMock = {};
  20628. var seriesType;
  20629. mockMethods(ecModelMock, GlobalModel);
  20630. mockMethods(apiMock, ExtensionAPI);
  20631. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  20632. seriesType = type;
  20633. };
  20634. ecModelMock.eachComponent = function (cond) {
  20635. if (cond.mainType === 'series' && cond.subType) {
  20636. seriesType = cond.subType;
  20637. }
  20638. };
  20639. function mockMethods(target, Clz) {
  20640. for (var name in Clz.prototype) {
  20641. // Do not use hasOwnProperty
  20642. target[name] = noop;
  20643. }
  20644. }
  20645. var colorAll = ['#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C','#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'];
  20646. var lightTheme = {
  20647. color: colorAll,
  20648. colorLayer: [
  20649. ['#37A2DA', '#ffd85c', '#fd7b5f'],
  20650. ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'],
  20651. ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'],
  20652. colorAll
  20653. ]
  20654. };
  20655. var contrastColor = '#eee';
  20656. var axisCommon = function () {
  20657. return {
  20658. axisLine: {
  20659. lineStyle: {
  20660. color: contrastColor
  20661. }
  20662. },
  20663. axisTick: {
  20664. lineStyle: {
  20665. color: contrastColor
  20666. }
  20667. },
  20668. axisLabel: {
  20669. textStyle: {
  20670. color: contrastColor
  20671. }
  20672. },
  20673. splitLine: {
  20674. lineStyle: {
  20675. type: 'dashed',
  20676. color: '#aaa'
  20677. }
  20678. },
  20679. splitArea: {
  20680. areaStyle: {
  20681. color: contrastColor
  20682. }
  20683. }
  20684. };
  20685. };
  20686. var colorPalette = ['#dd6b66','#759aa0','#e69d87','#8dc1a9','#ea7e53','#eedd78','#73a373','#73b9bc','#7289ab', '#91ca8c','#f49f42'];
  20687. var theme = {
  20688. color: colorPalette,
  20689. backgroundColor: '#333',
  20690. tooltip: {
  20691. axisPointer: {
  20692. lineStyle: {
  20693. color: contrastColor
  20694. },
  20695. crossStyle: {
  20696. color: contrastColor
  20697. }
  20698. }
  20699. },
  20700. legend: {
  20701. textStyle: {
  20702. color: contrastColor
  20703. }
  20704. },
  20705. textStyle: {
  20706. color: contrastColor
  20707. },
  20708. title: {
  20709. textStyle: {
  20710. color: contrastColor
  20711. }
  20712. },
  20713. toolbox: {
  20714. iconStyle: {
  20715. normal: {
  20716. borderColor: contrastColor
  20717. }
  20718. }
  20719. },
  20720. dataZoom: {
  20721. textStyle: {
  20722. color: contrastColor
  20723. }
  20724. },
  20725. visualMap: {
  20726. textStyle: {
  20727. color: contrastColor
  20728. }
  20729. },
  20730. timeline: {
  20731. lineStyle: {
  20732. color: contrastColor
  20733. },
  20734. itemStyle: {
  20735. normal: {
  20736. color: colorPalette[1]
  20737. }
  20738. },
  20739. label: {
  20740. normal: {
  20741. textStyle: {
  20742. color: contrastColor
  20743. }
  20744. }
  20745. },
  20746. controlStyle: {
  20747. normal: {
  20748. color: contrastColor,
  20749. borderColor: contrastColor
  20750. }
  20751. }
  20752. },
  20753. timeAxis: axisCommon(),
  20754. logAxis: axisCommon(),
  20755. valueAxis: axisCommon(),
  20756. categoryAxis: axisCommon(),
  20757. line: {
  20758. symbol: 'circle'
  20759. },
  20760. graph: {
  20761. color: colorPalette
  20762. },
  20763. gauge: {
  20764. title: {
  20765. textStyle: {
  20766. color: contrastColor
  20767. }
  20768. }
  20769. },
  20770. candlestick: {
  20771. itemStyle: {
  20772. normal: {
  20773. color: '#FD1050',
  20774. color0: '#0CF49B',
  20775. borderColor: '#FD1050',
  20776. borderColor0: '#0CF49B'
  20777. }
  20778. }
  20779. }
  20780. };
  20781. theme.categoryAxis.splitLine.show = false;
  20782. /*!
  20783. * ECharts, a free, powerful charting and visualization library.
  20784. *
  20785. * Copyright (c) 2017, Baidu Inc.
  20786. * All rights reserved.
  20787. *
  20788. * LICENSE
  20789. * https://github.com/ecomfe/echarts/blob/master/LICENSE.txt
  20790. */
  20791. var assert = assert$1;
  20792. var each = each$1;
  20793. var isFunction = isFunction$1;
  20794. var isObject = isObject$1;
  20795. var parseClassType = ComponentModel.parseClassType;
  20796. var version = '4.0.4';
  20797. var dependencies = {
  20798. zrender: '4.0.3'
  20799. };
  20800. var TEST_FRAME_REMAIN_TIME = 1;
  20801. var PRIORITY_PROCESSOR_FILTER = 1000;
  20802. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  20803. var PRIORITY_VISUAL_LAYOUT = 1000;
  20804. var PRIORITY_VISUAL_GLOBAL = 2000;
  20805. var PRIORITY_VISUAL_CHART = 3000;
  20806. var PRIORITY_VISUAL_COMPONENT = 4000;
  20807. // FIXME
  20808. // necessary?
  20809. var PRIORITY_VISUAL_BRUSH = 5000;
  20810. var PRIORITY = {
  20811. PROCESSOR: {
  20812. FILTER: PRIORITY_PROCESSOR_FILTER,
  20813. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  20814. },
  20815. VISUAL: {
  20816. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  20817. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  20818. CHART: PRIORITY_VISUAL_CHART,
  20819. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  20820. BRUSH: PRIORITY_VISUAL_BRUSH
  20821. }
  20822. };
  20823. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  20824. // where they must not be invoked nestedly, except the only case: invoke
  20825. // dispatchAction with updateMethod "none" in main process.
  20826. // This flag is used to carry out this rule.
  20827. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  20828. var IN_MAIN_PROCESS = '__flagInMainProcess';
  20829. var OPTION_UPDATED = '__optionUpdated';
  20830. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  20831. function createRegisterEventWithLowercaseName(method) {
  20832. return function (eventName, handler, context) {
  20833. // Event name is all lowercase
  20834. eventName = eventName && eventName.toLowerCase();
  20835. Eventful.prototype[method].call(this, eventName, handler, context);
  20836. };
  20837. }
  20838. /**
  20839. * @module echarts~MessageCenter
  20840. */
  20841. function MessageCenter() {
  20842. Eventful.call(this);
  20843. }
  20844. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on');
  20845. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off');
  20846. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one');
  20847. mixin(MessageCenter, Eventful);
  20848. /**
  20849. * @module echarts~ECharts
  20850. */
  20851. function ECharts(dom, theme$$1, opts) {
  20852. opts = opts || {};
  20853. // Get theme by name
  20854. if (typeof theme$$1 === 'string') {
  20855. theme$$1 = themeStorage[theme$$1];
  20856. }
  20857. /**
  20858. * @type {string}
  20859. */
  20860. this.id;
  20861. /**
  20862. * Group id
  20863. * @type {string}
  20864. */
  20865. this.group;
  20866. /**
  20867. * @type {HTMLElement}
  20868. * @private
  20869. */
  20870. this._dom = dom;
  20871. var defaultRenderer = 'canvas';
  20872. if (__DEV__) {
  20873. defaultRenderer = (
  20874. typeof window === 'undefined' ? global : window
  20875. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  20876. }
  20877. /**
  20878. * @type {module:zrender/ZRender}
  20879. * @private
  20880. */
  20881. var zr = this._zr = init$1(dom, {
  20882. renderer: opts.renderer || defaultRenderer,
  20883. devicePixelRatio: opts.devicePixelRatio,
  20884. width: opts.width,
  20885. height: opts.height
  20886. });
  20887. /**
  20888. * Expect 60 pfs.
  20889. * @type {Function}
  20890. * @private
  20891. */
  20892. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  20893. var theme$$1 = clone(theme$$1);
  20894. theme$$1 && backwardCompat(theme$$1, true);
  20895. /**
  20896. * @type {Object}
  20897. * @private
  20898. */
  20899. this._theme = theme$$1;
  20900. /**
  20901. * @type {Array.<module:echarts/view/Chart>}
  20902. * @private
  20903. */
  20904. this._chartsViews = [];
  20905. /**
  20906. * @type {Object.<string, module:echarts/view/Chart>}
  20907. * @private
  20908. */
  20909. this._chartsMap = {};
  20910. /**
  20911. * @type {Array.<module:echarts/view/Component>}
  20912. * @private
  20913. */
  20914. this._componentsViews = [];
  20915. /**
  20916. * @type {Object.<string, module:echarts/view/Component>}
  20917. * @private
  20918. */
  20919. this._componentsMap = {};
  20920. /**
  20921. * @type {module:echarts/CoordinateSystem}
  20922. * @private
  20923. */
  20924. this._coordSysMgr = new CoordinateSystemManager();
  20925. /**
  20926. * @type {module:echarts/ExtensionAPI}
  20927. * @private
  20928. */
  20929. var api = this._api = createExtensionAPI(this);
  20930. // Sort on demand
  20931. function prioritySortFunc(a, b) {
  20932. return a.__prio - b.__prio;
  20933. }
  20934. sort(visualFuncs, prioritySortFunc);
  20935. sort(dataProcessorFuncs, prioritySortFunc);
  20936. /**
  20937. * @type {module:echarts/stream/Scheduler}
  20938. */
  20939. this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs);
  20940. Eventful.call(this);
  20941. /**
  20942. * @type {module:echarts~MessageCenter}
  20943. * @private
  20944. */
  20945. this._messageCenter = new MessageCenter();
  20946. // Init mouse events
  20947. this._initEvents();
  20948. // In case some people write `window.onresize = chart.resize`
  20949. this.resize = bind(this.resize, this);
  20950. // Can't dispatch action during rendering procedure
  20951. this._pendingActions = [];
  20952. zr.animation.on('frame', this._onframe, this);
  20953. bindRenderedEvent(zr, this);
  20954. // ECharts instance can be used as value.
  20955. setAsPrimitive(this);
  20956. }
  20957. var echartsProto = ECharts.prototype;
  20958. echartsProto._onframe = function () {
  20959. if (this._disposed) {
  20960. return;
  20961. }
  20962. var scheduler = this._scheduler;
  20963. // Lazy update
  20964. if (this[OPTION_UPDATED]) {
  20965. var silent = this[OPTION_UPDATED].silent;
  20966. this[IN_MAIN_PROCESS] = true;
  20967. prepare(this);
  20968. updateMethods.update.call(this);
  20969. this[IN_MAIN_PROCESS] = false;
  20970. this[OPTION_UPDATED] = false;
  20971. flushPendingActions.call(this, silent);
  20972. triggerUpdatedEvent.call(this, silent);
  20973. }
  20974. // Avoid do both lazy update and progress in one frame.
  20975. else if (scheduler.unfinished) {
  20976. // Stream progress.
  20977. var remainTime = TEST_FRAME_REMAIN_TIME;
  20978. var ecModel = this._model;
  20979. var api = this._api;
  20980. scheduler.unfinished = false;
  20981. do {
  20982. var startTime = +new Date();
  20983. scheduler.performSeriesTasks(ecModel);
  20984. // Currently dataProcessorFuncs do not check threshold.
  20985. scheduler.performDataProcessorTasks(ecModel);
  20986. updateStreamModes(this, ecModel);
  20987. // Do not update coordinate system here. Because that coord system update in
  20988. // each frame is not a good user experience. So we follow the rule that
  20989. // the extent of the coordinate system is determin in the first frame (the
  20990. // frame is executed immedietely after task reset.
  20991. // this._coordSysMgr.update(ecModel, api);
  20992. // console.log('--- ec frame visual ---', remainTime);
  20993. scheduler.performVisualTasks(ecModel);
  20994. renderSeries(this, this._model, api, 'remain');
  20995. remainTime -= (+new Date() - startTime);
  20996. }
  20997. while (remainTime > 0 && scheduler.unfinished);
  20998. // Call flush explicitly for trigger finished event.
  20999. if (!scheduler.unfinished) {
  21000. this._zr.flush();
  21001. }
  21002. // Else, zr flushing be ensue within the same frame,
  21003. // because zr flushing is after onframe event.
  21004. }
  21005. };
  21006. /**
  21007. * @return {HTMLElement}
  21008. */
  21009. echartsProto.getDom = function () {
  21010. return this._dom;
  21011. };
  21012. /**
  21013. * @return {module:zrender~ZRender}
  21014. */
  21015. echartsProto.getZr = function () {
  21016. return this._zr;
  21017. };
  21018. /**
  21019. * Usage:
  21020. * chart.setOption(option, notMerge, lazyUpdate);
  21021. * chart.setOption(option, {
  21022. * notMerge: ...,
  21023. * lazyUpdate: ...,
  21024. * silent: ...
  21025. * });
  21026. *
  21027. * @param {Object} option
  21028. * @param {Object|boolean} [opts] opts or notMerge.
  21029. * @param {boolean} [opts.notMerge=false]
  21030. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  21031. */
  21032. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  21033. if (__DEV__) {
  21034. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  21035. }
  21036. var silent;
  21037. if (isObject(notMerge)) {
  21038. lazyUpdate = notMerge.lazyUpdate;
  21039. silent = notMerge.silent;
  21040. notMerge = notMerge.notMerge;
  21041. }
  21042. this[IN_MAIN_PROCESS] = true;
  21043. if (!this._model || notMerge) {
  21044. var optionManager = new OptionManager(this._api);
  21045. var theme$$1 = this._theme;
  21046. var ecModel = this._model = new GlobalModel(null, null, theme$$1, optionManager);
  21047. ecModel.scheduler = this._scheduler;
  21048. ecModel.init(null, null, theme$$1, optionManager);
  21049. }
  21050. this._model.setOption(option, optionPreprocessorFuncs);
  21051. if (lazyUpdate) {
  21052. this[OPTION_UPDATED] = {silent: silent};
  21053. this[IN_MAIN_PROCESS] = false;
  21054. }
  21055. else {
  21056. prepare(this);
  21057. updateMethods.update.call(this);
  21058. // Ensure zr refresh sychronously, and then pixel in canvas can be
  21059. // fetched after `setOption`.
  21060. this._zr.flush();
  21061. this[OPTION_UPDATED] = false;
  21062. this[IN_MAIN_PROCESS] = false;
  21063. flushPendingActions.call(this, silent);
  21064. triggerUpdatedEvent.call(this, silent);
  21065. }
  21066. };
  21067. /**
  21068. * @DEPRECATED
  21069. */
  21070. echartsProto.setTheme = function () {
  21071. console.log('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  21072. };
  21073. /**
  21074. * @return {module:echarts/model/Global}
  21075. */
  21076. echartsProto.getModel = function () {
  21077. return this._model;
  21078. };
  21079. /**
  21080. * @return {Object}
  21081. */
  21082. echartsProto.getOption = function () {
  21083. return this._model && this._model.getOption();
  21084. };
  21085. /**
  21086. * @return {number}
  21087. */
  21088. echartsProto.getWidth = function () {
  21089. return this._zr.getWidth();
  21090. };
  21091. /**
  21092. * @return {number}
  21093. */
  21094. echartsProto.getHeight = function () {
  21095. return this._zr.getHeight();
  21096. };
  21097. /**
  21098. * @return {number}
  21099. */
  21100. echartsProto.getDevicePixelRatio = function () {
  21101. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  21102. };
  21103. /**
  21104. * Get canvas which has all thing rendered
  21105. * @param {Object} opts
  21106. * @param {string} [opts.backgroundColor]
  21107. * @return {string}
  21108. */
  21109. echartsProto.getRenderedCanvas = function (opts) {
  21110. if (!env$1.canvasSupported) {
  21111. return;
  21112. }
  21113. opts = opts || {};
  21114. opts.pixelRatio = opts.pixelRatio || 1;
  21115. opts.backgroundColor = opts.backgroundColor
  21116. || this._model.get('backgroundColor');
  21117. var zr = this._zr;
  21118. // var list = zr.storage.getDisplayList();
  21119. // Stop animations
  21120. // Never works before in init animation, so remove it.
  21121. // zrUtil.each(list, function (el) {
  21122. // el.stopAnimation(true);
  21123. // });
  21124. return zr.painter.getRenderedCanvas(opts);
  21125. };
  21126. /**
  21127. * Get svg data url
  21128. * @return {string}
  21129. */
  21130. echartsProto.getSvgDataUrl = function () {
  21131. if (!env$1.svgSupported) {
  21132. return;
  21133. }
  21134. var zr = this._zr;
  21135. var list = zr.storage.getDisplayList();
  21136. // Stop animations
  21137. each$1(list, function (el) {
  21138. el.stopAnimation(true);
  21139. });
  21140. return zr.painter.pathToDataUrl();
  21141. };
  21142. /**
  21143. * @return {string}
  21144. * @param {Object} opts
  21145. * @param {string} [opts.type='png']
  21146. * @param {string} [opts.pixelRatio=1]
  21147. * @param {string} [opts.backgroundColor]
  21148. * @param {string} [opts.excludeComponents]
  21149. */
  21150. echartsProto.getDataURL = function (opts) {
  21151. opts = opts || {};
  21152. var excludeComponents = opts.excludeComponents;
  21153. var ecModel = this._model;
  21154. var excludesComponentViews = [];
  21155. var self = this;
  21156. each(excludeComponents, function (componentType) {
  21157. ecModel.eachComponent({
  21158. mainType: componentType
  21159. }, function (component) {
  21160. var view = self._componentsMap[component.__viewId];
  21161. if (!view.group.ignore) {
  21162. excludesComponentViews.push(view);
  21163. view.group.ignore = true;
  21164. }
  21165. });
  21166. });
  21167. var url = this._zr.painter.getType() === 'svg'
  21168. ? this.getSvgDataUrl()
  21169. : this.getRenderedCanvas(opts).toDataURL(
  21170. 'image/' + (opts && opts.type || 'png')
  21171. );
  21172. each(excludesComponentViews, function (view) {
  21173. view.group.ignore = false;
  21174. });
  21175. return url;
  21176. };
  21177. /**
  21178. * @return {string}
  21179. * @param {Object} opts
  21180. * @param {string} [opts.type='png']
  21181. * @param {string} [opts.pixelRatio=1]
  21182. * @param {string} [opts.backgroundColor]
  21183. */
  21184. echartsProto.getConnectedDataURL = function (opts) {
  21185. if (!env$1.canvasSupported) {
  21186. return;
  21187. }
  21188. var groupId = this.group;
  21189. var mathMin = Math.min;
  21190. var mathMax = Math.max;
  21191. var MAX_NUMBER = Infinity;
  21192. if (connectedGroups[groupId]) {
  21193. var left = MAX_NUMBER;
  21194. var top = MAX_NUMBER;
  21195. var right = -MAX_NUMBER;
  21196. var bottom = -MAX_NUMBER;
  21197. var canvasList = [];
  21198. var dpr = (opts && opts.pixelRatio) || 1;
  21199. each$1(instances, function (chart, id) {
  21200. if (chart.group === groupId) {
  21201. var canvas = chart.getRenderedCanvas(
  21202. clone(opts)
  21203. );
  21204. var boundingRect = chart.getDom().getBoundingClientRect();
  21205. left = mathMin(boundingRect.left, left);
  21206. top = mathMin(boundingRect.top, top);
  21207. right = mathMax(boundingRect.right, right);
  21208. bottom = mathMax(boundingRect.bottom, bottom);
  21209. canvasList.push({
  21210. dom: canvas,
  21211. left: boundingRect.left,
  21212. top: boundingRect.top
  21213. });
  21214. }
  21215. });
  21216. left *= dpr;
  21217. top *= dpr;
  21218. right *= dpr;
  21219. bottom *= dpr;
  21220. var width = right - left;
  21221. var height = bottom - top;
  21222. var targetCanvas = createCanvas();
  21223. targetCanvas.width = width;
  21224. targetCanvas.height = height;
  21225. var zr = init$1(targetCanvas);
  21226. each(canvasList, function (item) {
  21227. var img = new ZImage({
  21228. style: {
  21229. x: item.left * dpr - left,
  21230. y: item.top * dpr - top,
  21231. image: item.dom
  21232. }
  21233. });
  21234. zr.add(img);
  21235. });
  21236. zr.refreshImmediately();
  21237. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  21238. }
  21239. else {
  21240. return this.getDataURL(opts);
  21241. }
  21242. };
  21243. /**
  21244. * Convert from logical coordinate system to pixel coordinate system.
  21245. * See CoordinateSystem#convertToPixel.
  21246. * @param {string|Object} finder
  21247. * If string, e.g., 'geo', means {geoIndex: 0}.
  21248. * If Object, could contain some of these properties below:
  21249. * {
  21250. * seriesIndex / seriesId / seriesName,
  21251. * geoIndex / geoId, geoName,
  21252. * bmapIndex / bmapId / bmapName,
  21253. * xAxisIndex / xAxisId / xAxisName,
  21254. * yAxisIndex / yAxisId / yAxisName,
  21255. * gridIndex / gridId / gridName,
  21256. * ... (can be extended)
  21257. * }
  21258. * @param {Array|number} value
  21259. * @return {Array|number} result
  21260. */
  21261. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  21262. /**
  21263. * Convert from pixel coordinate system to logical coordinate system.
  21264. * See CoordinateSystem#convertFromPixel.
  21265. * @param {string|Object} finder
  21266. * If string, e.g., 'geo', means {geoIndex: 0}.
  21267. * If Object, could contain some of these properties below:
  21268. * {
  21269. * seriesIndex / seriesId / seriesName,
  21270. * geoIndex / geoId / geoName,
  21271. * bmapIndex / bmapId / bmapName,
  21272. * xAxisIndex / xAxisId / xAxisName,
  21273. * yAxisIndex / yAxisId / yAxisName
  21274. * gridIndex / gridId / gridName,
  21275. * ... (can be extended)
  21276. * }
  21277. * @param {Array|number} value
  21278. * @return {Array|number} result
  21279. */
  21280. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  21281. function doConvertPixel(methodName, finder, value) {
  21282. var ecModel = this._model;
  21283. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  21284. var result;
  21285. finder = parseFinder(ecModel, finder);
  21286. for (var i = 0; i < coordSysList.length; i++) {
  21287. var coordSys = coordSysList[i];
  21288. if (coordSys[methodName]
  21289. && (result = coordSys[methodName](ecModel, finder, value)) != null
  21290. ) {
  21291. return result;
  21292. }
  21293. }
  21294. if (__DEV__) {
  21295. console.warn(
  21296. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  21297. );
  21298. }
  21299. }
  21300. /**
  21301. * Is the specified coordinate systems or components contain the given pixel point.
  21302. * @param {string|Object} finder
  21303. * If string, e.g., 'geo', means {geoIndex: 0}.
  21304. * If Object, could contain some of these properties below:
  21305. * {
  21306. * seriesIndex / seriesId / seriesName,
  21307. * geoIndex / geoId / geoName,
  21308. * bmapIndex / bmapId / bmapName,
  21309. * xAxisIndex / xAxisId / xAxisName,
  21310. * yAxisIndex / yAxisId / yAxisName,
  21311. * gridIndex / gridId / gridName,
  21312. * ... (can be extended)
  21313. * }
  21314. * @param {Array|number} value
  21315. * @return {boolean} result
  21316. */
  21317. echartsProto.containPixel = function (finder, value) {
  21318. var ecModel = this._model;
  21319. var result;
  21320. finder = parseFinder(ecModel, finder);
  21321. each$1(finder, function (models, key) {
  21322. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  21323. var coordSys = model.coordinateSystem;
  21324. if (coordSys && coordSys.containPoint) {
  21325. result |= !!coordSys.containPoint(value);
  21326. }
  21327. else if (key === 'seriesModels') {
  21328. var view = this._chartsMap[model.__viewId];
  21329. if (view && view.containPoint) {
  21330. result |= view.containPoint(value, model);
  21331. }
  21332. else {
  21333. if (__DEV__) {
  21334. console.warn(key + ': ' + (view
  21335. ? 'The found component do not support containPoint.'
  21336. : 'No view mapping to the found component.'
  21337. ));
  21338. }
  21339. }
  21340. }
  21341. else {
  21342. if (__DEV__) {
  21343. console.warn(key + ': containPoint is not supported');
  21344. }
  21345. }
  21346. }, this);
  21347. }, this);
  21348. return !!result;
  21349. };
  21350. /**
  21351. * Get visual from series or data.
  21352. * @param {string|Object} finder
  21353. * If string, e.g., 'series', means {seriesIndex: 0}.
  21354. * If Object, could contain some of these properties below:
  21355. * {
  21356. * seriesIndex / seriesId / seriesName,
  21357. * dataIndex / dataIndexInside
  21358. * }
  21359. * If dataIndex is not specified, series visual will be fetched,
  21360. * but not data item visual.
  21361. * If all of seriesIndex, seriesId, seriesName are not specified,
  21362. * visual will be fetched from first series.
  21363. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  21364. */
  21365. echartsProto.getVisual = function (finder, visualType) {
  21366. var ecModel = this._model;
  21367. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  21368. var seriesModel = finder.seriesModel;
  21369. if (__DEV__) {
  21370. if (!seriesModel) {
  21371. console.warn('There is no specified seires model');
  21372. }
  21373. }
  21374. var data = seriesModel.getData();
  21375. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  21376. ? finder.dataIndexInside
  21377. : finder.hasOwnProperty('dataIndex')
  21378. ? data.indexOfRawIndex(finder.dataIndex)
  21379. : null;
  21380. return dataIndexInside != null
  21381. ? data.getItemVisual(dataIndexInside, visualType)
  21382. : data.getVisual(visualType);
  21383. };
  21384. /**
  21385. * Get view of corresponding component model
  21386. * @param {module:echarts/model/Component} componentModel
  21387. * @return {module:echarts/view/Component}
  21388. */
  21389. echartsProto.getViewOfComponentModel = function (componentModel) {
  21390. return this._componentsMap[componentModel.__viewId];
  21391. };
  21392. /**
  21393. * Get view of corresponding series model
  21394. * @param {module:echarts/model/Series} seriesModel
  21395. * @return {module:echarts/view/Chart}
  21396. */
  21397. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  21398. return this._chartsMap[seriesModel.__viewId];
  21399. };
  21400. var updateMethods = {
  21401. prepareAndUpdate: function (payload) {
  21402. prepare(this);
  21403. updateMethods.update.call(this, payload);
  21404. },
  21405. /**
  21406. * @param {Object} payload
  21407. * @private
  21408. */
  21409. update: function (payload) {
  21410. // console.profile && console.profile('update');
  21411. var ecModel = this._model;
  21412. var api = this._api;
  21413. var zr = this._zr;
  21414. var coordSysMgr = this._coordSysMgr;
  21415. var scheduler = this._scheduler;
  21416. // update before setOption
  21417. if (!ecModel) {
  21418. return;
  21419. }
  21420. ecModel.restoreData(payload);
  21421. scheduler.performSeriesTasks(ecModel);
  21422. // TODO
  21423. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  21424. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  21425. // Create new coordinate system each update
  21426. // In LineView may save the old coordinate system and use it to get the orignal point
  21427. coordSysMgr.create(ecModel, api);
  21428. scheduler.performDataProcessorTasks(ecModel, payload);
  21429. // Current stream render is not supported in data process. So we can update
  21430. // stream modes after data processing, where the filtered data is used to
  21431. // deteming whether use progressive rendering.
  21432. updateStreamModes(this, ecModel);
  21433. // stackSeriesData(ecModel);
  21434. coordSysMgr.update(ecModel, api);
  21435. clearColorPalette(ecModel);
  21436. scheduler.performVisualTasks(ecModel, payload);
  21437. render(this, ecModel, api, payload);
  21438. // Set background
  21439. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  21440. // In IE8
  21441. if (!env$1.canvasSupported) {
  21442. var colorArr = parse(backgroundColor);
  21443. backgroundColor = stringify(colorArr, 'rgb');
  21444. if (colorArr[3] === 0) {
  21445. backgroundColor = 'transparent';
  21446. }
  21447. }
  21448. else {
  21449. zr.setBackgroundColor(backgroundColor);
  21450. }
  21451. performPostUpdateFuncs(ecModel, api);
  21452. // console.profile && console.profileEnd('update');
  21453. },
  21454. /**
  21455. * @param {Object} payload
  21456. * @private
  21457. */
  21458. updateTransform: function (payload) {
  21459. var ecModel = this._model;
  21460. var ecIns = this;
  21461. var api = this._api;
  21462. // update before setOption
  21463. if (!ecModel) {
  21464. return;
  21465. }
  21466. // ChartView.markUpdateMethod(payload, 'updateTransform');
  21467. var componentDirtyList = [];
  21468. ecModel.eachComponent(function (componentType, componentModel) {
  21469. var componentView = ecIns.getViewOfComponentModel(componentModel);
  21470. if (componentView && componentView.__alive) {
  21471. if (componentView.updateTransform) {
  21472. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  21473. result && result.update && componentDirtyList.push(componentView);
  21474. }
  21475. else {
  21476. componentDirtyList.push(componentView);
  21477. }
  21478. }
  21479. });
  21480. var seriesDirtyMap = createHashMap();
  21481. ecModel.eachSeries(function (seriesModel) {
  21482. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  21483. if (chartView.updateTransform) {
  21484. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  21485. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  21486. }
  21487. else {
  21488. seriesDirtyMap.set(seriesModel.uid, 1);
  21489. }
  21490. });
  21491. clearColorPalette(ecModel);
  21492. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21493. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  21494. this._scheduler.performVisualTasks(
  21495. ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
  21496. );
  21497. // Currently, not call render of components. Geo render cost a lot.
  21498. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  21499. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  21500. performPostUpdateFuncs(ecModel, this._api);
  21501. },
  21502. /**
  21503. * @param {Object} payload
  21504. * @private
  21505. */
  21506. updateView: function (payload) {
  21507. var ecModel = this._model;
  21508. // update before setOption
  21509. if (!ecModel) {
  21510. return;
  21511. }
  21512. Chart.markUpdateMethod(payload, 'updateView');
  21513. clearColorPalette(ecModel);
  21514. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21515. this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  21516. render(this, this._model, this._api, payload);
  21517. performPostUpdateFuncs(ecModel, this._api);
  21518. },
  21519. /**
  21520. * @param {Object} payload
  21521. * @private
  21522. */
  21523. updateVisual: function (payload) {
  21524. updateMethods.update.call(this, payload);
  21525. // var ecModel = this._model;
  21526. // // update before setOption
  21527. // if (!ecModel) {
  21528. // return;
  21529. // }
  21530. // ChartView.markUpdateMethod(payload, 'updateVisual');
  21531. // clearColorPalette(ecModel);
  21532. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21533. // this._scheduler.performVisualTasks(ecModel, payload, {visualType: 'visual', setDirty: true});
  21534. // render(this, this._model, this._api, payload);
  21535. // performPostUpdateFuncs(ecModel, this._api);
  21536. },
  21537. /**
  21538. * @param {Object} payload
  21539. * @private
  21540. */
  21541. updateLayout: function (payload) {
  21542. updateMethods.update.call(this, payload);
  21543. // var ecModel = this._model;
  21544. // // update before setOption
  21545. // if (!ecModel) {
  21546. // return;
  21547. // }
  21548. // ChartView.markUpdateMethod(payload, 'updateLayout');
  21549. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21550. // // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  21551. // this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  21552. // render(this, this._model, this._api, payload);
  21553. // performPostUpdateFuncs(ecModel, this._api);
  21554. }
  21555. };
  21556. function prepare(ecIns) {
  21557. var ecModel = ecIns._model;
  21558. var scheduler = ecIns._scheduler;
  21559. scheduler.restorePipelines(ecModel);
  21560. scheduler.prepareStageTasks();
  21561. prepareView(ecIns, 'component', ecModel, scheduler);
  21562. prepareView(ecIns, 'chart', ecModel, scheduler);
  21563. scheduler.plan();
  21564. }
  21565. /**
  21566. * @private
  21567. */
  21568. function updateDirectly(ecIns, method, payload, mainType, subType) {
  21569. var ecModel = ecIns._model;
  21570. // broadcast
  21571. if (!mainType) {
  21572. // FIXME
  21573. // Chart will not be update directly here, except set dirty.
  21574. // But there is no such scenario now.
  21575. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  21576. return;
  21577. }
  21578. var query = {};
  21579. query[mainType + 'Id'] = payload[mainType + 'Id'];
  21580. query[mainType + 'Index'] = payload[mainType + 'Index'];
  21581. query[mainType + 'Name'] = payload[mainType + 'Name'];
  21582. var condition = {mainType: mainType, query: query};
  21583. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  21584. // If dispatchAction before setOption, do nothing.
  21585. ecModel && ecModel.eachComponent(condition, function (model, index) {
  21586. callView(ecIns[
  21587. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  21588. ][model.__viewId]);
  21589. }, ecIns);
  21590. function callView(view) {
  21591. view && view.__alive && view[method] && view[method](
  21592. view.__model, ecModel, ecIns._api, payload
  21593. );
  21594. }
  21595. }
  21596. /**
  21597. * Resize the chart
  21598. * @param {Object} opts
  21599. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  21600. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  21601. * @param {boolean} [opts.silent=false]
  21602. */
  21603. echartsProto.resize = function (opts) {
  21604. if (__DEV__) {
  21605. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  21606. }
  21607. this._zr.resize(opts);
  21608. var ecModel = this._model;
  21609. // Resize loading effect
  21610. this._loadingFX && this._loadingFX.resize();
  21611. if (!ecModel) {
  21612. return;
  21613. }
  21614. var optionChanged = ecModel.resetOption('media');
  21615. var silent = opts && opts.silent;
  21616. this[IN_MAIN_PROCESS] = true;
  21617. optionChanged && prepare(this);
  21618. updateMethods.update.call(this);
  21619. this[IN_MAIN_PROCESS] = false;
  21620. flushPendingActions.call(this, silent);
  21621. triggerUpdatedEvent.call(this, silent);
  21622. };
  21623. function updateStreamModes(ecIns, ecModel) {
  21624. var chartsMap = ecIns._chartsMap;
  21625. var scheduler = ecIns._scheduler;
  21626. ecModel.eachSeries(function (seriesModel) {
  21627. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  21628. });
  21629. }
  21630. /**
  21631. * Show loading effect
  21632. * @param {string} [name='default']
  21633. * @param {Object} [cfg]
  21634. */
  21635. echartsProto.showLoading = function (name, cfg) {
  21636. if (isObject(name)) {
  21637. cfg = name;
  21638. name = '';
  21639. }
  21640. name = name || 'default';
  21641. this.hideLoading();
  21642. if (!loadingEffects[name]) {
  21643. if (__DEV__) {
  21644. console.warn('Loading effects ' + name + ' not exists.');
  21645. }
  21646. return;
  21647. }
  21648. var el = loadingEffects[name](this._api, cfg);
  21649. var zr = this._zr;
  21650. this._loadingFX = el;
  21651. zr.add(el);
  21652. };
  21653. /**
  21654. * Hide loading effect
  21655. */
  21656. echartsProto.hideLoading = function () {
  21657. this._loadingFX && this._zr.remove(this._loadingFX);
  21658. this._loadingFX = null;
  21659. };
  21660. /**
  21661. * @param {Object} eventObj
  21662. * @return {Object}
  21663. */
  21664. echartsProto.makeActionFromEvent = function (eventObj) {
  21665. var payload = extend({}, eventObj);
  21666. payload.type = eventActionMap[eventObj.type];
  21667. return payload;
  21668. };
  21669. /**
  21670. * @pubilc
  21671. * @param {Object} payload
  21672. * @param {string} [payload.type] Action type
  21673. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  21674. * @param {boolean} [opt.silent=false] Whether trigger events.
  21675. * @param {boolean} [opt.flush=undefined]
  21676. * true: Flush immediately, and then pixel in canvas can be fetched
  21677. * immediately. Caution: it might affect performance.
  21678. * false: Not not flush.
  21679. * undefined: Auto decide whether perform flush.
  21680. */
  21681. echartsProto.dispatchAction = function (payload, opt) {
  21682. if (!isObject(opt)) {
  21683. opt = {silent: !!opt};
  21684. }
  21685. if (!actions[payload.type]) {
  21686. return;
  21687. }
  21688. // Avoid dispatch action before setOption. Especially in `connect`.
  21689. if (!this._model) {
  21690. return;
  21691. }
  21692. // May dispatchAction in rendering procedure
  21693. if (this[IN_MAIN_PROCESS]) {
  21694. this._pendingActions.push(payload);
  21695. return;
  21696. }
  21697. doDispatchAction.call(this, payload, opt.silent);
  21698. if (opt.flush) {
  21699. this._zr.flush(true);
  21700. }
  21701. else if (opt.flush !== false && env$1.browser.weChat) {
  21702. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  21703. // hang when sliding page (on touch event), which cause that zr does not
  21704. // refresh util user interaction finished, which is not expected.
  21705. // But `dispatchAction` may be called too frequently when pan on touch
  21706. // screen, which impacts performance if do not throttle them.
  21707. this._throttledZrFlush();
  21708. }
  21709. flushPendingActions.call(this, opt.silent);
  21710. triggerUpdatedEvent.call(this, opt.silent);
  21711. };
  21712. function doDispatchAction(payload, silent) {
  21713. var payloadType = payload.type;
  21714. var escapeConnect = payload.escapeConnect;
  21715. var actionWrap = actions[payloadType];
  21716. var actionInfo = actionWrap.actionInfo;
  21717. var cptType = (actionInfo.update || 'update').split(':');
  21718. var updateMethod = cptType.pop();
  21719. cptType = cptType[0] != null && parseClassType(cptType[0]);
  21720. this[IN_MAIN_PROCESS] = true;
  21721. var payloads = [payload];
  21722. var batched = false;
  21723. // Batch action
  21724. if (payload.batch) {
  21725. batched = true;
  21726. payloads = map(payload.batch, function (item) {
  21727. item = defaults(extend({}, item), payload);
  21728. item.batch = null;
  21729. return item;
  21730. });
  21731. }
  21732. var eventObjBatch = [];
  21733. var eventObj;
  21734. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  21735. each(payloads, function (batchItem) {
  21736. // Action can specify the event by return it.
  21737. eventObj = actionWrap.action(batchItem, this._model, this._api);
  21738. // Emit event outside
  21739. eventObj = eventObj || extend({}, batchItem);
  21740. // Convert type to eventType
  21741. eventObj.type = actionInfo.event || eventObj.type;
  21742. eventObjBatch.push(eventObj);
  21743. // light update does not perform data process, layout and visual.
  21744. if (isHighDown) {
  21745. // method, payload, mainType, subType
  21746. updateDirectly(this, updateMethod, batchItem, 'series');
  21747. }
  21748. else if (cptType) {
  21749. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  21750. }
  21751. }, this);
  21752. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  21753. // Still dirty
  21754. if (this[OPTION_UPDATED]) {
  21755. // FIXME Pass payload ?
  21756. prepare(this);
  21757. updateMethods.update.call(this, payload);
  21758. this[OPTION_UPDATED] = false;
  21759. }
  21760. else {
  21761. updateMethods[updateMethod].call(this, payload);
  21762. }
  21763. }
  21764. // Follow the rule of action batch
  21765. if (batched) {
  21766. eventObj = {
  21767. type: actionInfo.event || payloadType,
  21768. escapeConnect: escapeConnect,
  21769. batch: eventObjBatch
  21770. };
  21771. }
  21772. else {
  21773. eventObj = eventObjBatch[0];
  21774. }
  21775. this[IN_MAIN_PROCESS] = false;
  21776. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  21777. }
  21778. function flushPendingActions(silent) {
  21779. var pendingActions = this._pendingActions;
  21780. while (pendingActions.length) {
  21781. var payload = pendingActions.shift();
  21782. doDispatchAction.call(this, payload, silent);
  21783. }
  21784. }
  21785. function triggerUpdatedEvent(silent) {
  21786. !silent && this.trigger('updated');
  21787. }
  21788. /**
  21789. * Event `rendered` is triggered when zr
  21790. * rendered. It is useful for realtime
  21791. * snapshot (reflect animation).
  21792. *
  21793. * Event `finished` is triggered when:
  21794. * (1) zrender rendering finished.
  21795. * (2) initial animation finished.
  21796. * (3) progressive rendering finished.
  21797. * (4) no pending action.
  21798. * (5) no delayed setOption needs to be processed.
  21799. */
  21800. function bindRenderedEvent(zr, ecIns) {
  21801. zr.on('rendered', function () {
  21802. ecIns.trigger('rendered');
  21803. // The `finished` event should not be triggered repeatly,
  21804. // so it should only be triggered when rendering indeed happend
  21805. // in zrender. (Consider the case that dipatchAction is keep
  21806. // triggering when mouse move).
  21807. if (
  21808. // Although zr is dirty if initial animation is not finished
  21809. // and this checking is called on frame, we also check
  21810. // animation finished for robustness.
  21811. zr.animation.isFinished()
  21812. && !ecIns[OPTION_UPDATED]
  21813. && !ecIns._scheduler.unfinished
  21814. && !ecIns._pendingActions.length
  21815. ) {
  21816. ecIns.trigger('finished');
  21817. }
  21818. });
  21819. }
  21820. /**
  21821. * @param {Object} params
  21822. * @param {number} params.seriesIndex
  21823. * @param {Array|TypedArray} params.data
  21824. */
  21825. echartsProto.appendData = function (params) {
  21826. var seriesIndex = params.seriesIndex;
  21827. var ecModel = this.getModel();
  21828. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  21829. if (__DEV__) {
  21830. assert(params.data && seriesModel);
  21831. }
  21832. seriesModel.appendData(params);
  21833. // Note: `appendData` does not support that update extent of coordinate
  21834. // system, util some scenario require that. In the expected usage of
  21835. // `appendData`, the initial extent of coordinate system should better
  21836. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  21837. // the extent changed while `appendData`, the location of the painted
  21838. // graphic elements have to be changed, which make the usage of
  21839. // `appendData` meaningless.
  21840. this._scheduler.unfinished = true;
  21841. };
  21842. /**
  21843. * Register event
  21844. * @method
  21845. */
  21846. echartsProto.on = createRegisterEventWithLowercaseName('on');
  21847. echartsProto.off = createRegisterEventWithLowercaseName('off');
  21848. echartsProto.one = createRegisterEventWithLowercaseName('one');
  21849. /**
  21850. * Prepare view instances of charts and components
  21851. * @param {module:echarts/model/Global} ecModel
  21852. * @private
  21853. */
  21854. function prepareView(ecIns, type, ecModel, scheduler) {
  21855. var isComponent = type === 'component';
  21856. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  21857. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  21858. var zr = ecIns._zr;
  21859. var api = ecIns._api;
  21860. for (var i = 0; i < viewList.length; i++) {
  21861. viewList[i].__alive = false;
  21862. }
  21863. isComponent
  21864. ? ecModel.eachComponent(function (componentType, model) {
  21865. componentType !== 'series' && doPrepare(model);
  21866. })
  21867. : ecModel.eachSeries(doPrepare);
  21868. function doPrepare(model) {
  21869. // Consider: id same and type changed.
  21870. var viewId = '_ec_' + model.id + '_' + model.type;
  21871. var view = viewMap[viewId];
  21872. if (!view) {
  21873. var classType = parseClassType(model.type);
  21874. var Clazz = isComponent
  21875. ? Component$1.getClass(classType.main, classType.sub)
  21876. : Chart.getClass(classType.sub);
  21877. if (__DEV__) {
  21878. assert(Clazz, classType.sub + ' does not exist.');
  21879. }
  21880. view = new Clazz();
  21881. view.init(ecModel, api);
  21882. viewMap[viewId] = view;
  21883. viewList.push(view);
  21884. zr.add(view.group);
  21885. }
  21886. model.__viewId = view.__id = viewId;
  21887. view.__alive = true;
  21888. view.__model = model;
  21889. view.group.__ecComponentInfo = {
  21890. mainType: model.mainType,
  21891. index: model.componentIndex
  21892. };
  21893. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  21894. }
  21895. for (var i = 0; i < viewList.length;) {
  21896. var view = viewList[i];
  21897. if (!view.__alive) {
  21898. !isComponent && view.renderTask.dispose();
  21899. zr.remove(view.group);
  21900. view.dispose(ecModel, api);
  21901. viewList.splice(i, 1);
  21902. delete viewMap[view.__id];
  21903. view.__id = view.group.__ecComponentInfo = null;
  21904. }
  21905. else {
  21906. i++;
  21907. }
  21908. }
  21909. }
  21910. // /**
  21911. // * Encode visual infomation from data after data processing
  21912. // *
  21913. // * @param {module:echarts/model/Global} ecModel
  21914. // * @param {object} layout
  21915. // * @param {boolean} [layoutFilter] `true`: only layout,
  21916. // * `false`: only not layout,
  21917. // * `null`/`undefined`: all.
  21918. // * @param {string} taskBaseTag
  21919. // * @private
  21920. // */
  21921. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  21922. // each(visualFuncs, function (visual, index) {
  21923. // var isLayout = visual.isLayout;
  21924. // if (layoutFilter == null
  21925. // || (layoutFilter === false && !isLayout)
  21926. // || (layoutFilter === true && isLayout)
  21927. // ) {
  21928. // visual.func(ecModel, api, payload);
  21929. // }
  21930. // });
  21931. // }
  21932. function clearColorPalette(ecModel) {
  21933. ecModel.clearColorPalette();
  21934. ecModel.eachSeries(function (seriesModel) {
  21935. seriesModel.clearColorPalette();
  21936. });
  21937. }
  21938. function render(ecIns, ecModel, api, payload) {
  21939. renderComponents(ecIns, ecModel, api, payload);
  21940. each(ecIns._chartsViews, function (chart) {
  21941. chart.__alive = false;
  21942. });
  21943. renderSeries(ecIns, ecModel, api, payload);
  21944. // Remove groups of unrendered charts
  21945. each(ecIns._chartsViews, function (chart) {
  21946. if (!chart.__alive) {
  21947. chart.remove(ecModel, api);
  21948. }
  21949. });
  21950. }
  21951. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  21952. each(dirtyList || ecIns._componentsViews, function (componentView) {
  21953. var componentModel = componentView.__model;
  21954. componentView.render(componentModel, ecModel, api, payload);
  21955. updateZ(componentModel, componentView);
  21956. });
  21957. }
  21958. /**
  21959. * Render each chart and component
  21960. * @private
  21961. */
  21962. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  21963. // Render all charts
  21964. var scheduler = ecIns._scheduler;
  21965. var unfinished;
  21966. ecModel.eachSeries(function (seriesModel) {
  21967. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  21968. chartView.__alive = true;
  21969. var renderTask = chartView.renderTask;
  21970. scheduler.updatePayload(renderTask, payload);
  21971. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  21972. renderTask.dirty();
  21973. }
  21974. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  21975. chartView.group.silent = !!seriesModel.get('silent');
  21976. updateZ(seriesModel, chartView);
  21977. updateBlend(seriesModel, chartView);
  21978. });
  21979. scheduler.unfinished |= unfinished;
  21980. // If use hover layer
  21981. updateHoverLayerStatus(ecIns._zr, ecModel);
  21982. // Add aria
  21983. aria(ecIns._zr.dom, ecModel);
  21984. }
  21985. function performPostUpdateFuncs(ecModel, api) {
  21986. each(postUpdateFuncs, function (func) {
  21987. func(ecModel, api);
  21988. });
  21989. }
  21990. var MOUSE_EVENT_NAMES = [
  21991. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  21992. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  21993. ];
  21994. /**
  21995. * @private
  21996. */
  21997. echartsProto._initEvents = function () {
  21998. each(MOUSE_EVENT_NAMES, function (eveName) {
  21999. this._zr.on(eveName, function (e) {
  22000. var ecModel = this.getModel();
  22001. var el = e.target;
  22002. var params;
  22003. // no e.target when 'globalout'.
  22004. if (eveName === 'globalout') {
  22005. params = {};
  22006. }
  22007. else if (el && el.dataIndex != null) {
  22008. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  22009. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType) || {};
  22010. }
  22011. // If element has custom eventData of components
  22012. else if (el && el.eventData) {
  22013. params = extend({}, el.eventData);
  22014. }
  22015. if (params) {
  22016. params.event = e;
  22017. params.type = eveName;
  22018. this.trigger(eveName, params);
  22019. }
  22020. }, this);
  22021. }, this);
  22022. each(eventActionMap, function (actionType, eventType) {
  22023. this._messageCenter.on(eventType, function (event) {
  22024. this.trigger(eventType, event);
  22025. }, this);
  22026. }, this);
  22027. };
  22028. /**
  22029. * @return {boolean}
  22030. */
  22031. echartsProto.isDisposed = function () {
  22032. return this._disposed;
  22033. };
  22034. /**
  22035. * Clear
  22036. */
  22037. echartsProto.clear = function () {
  22038. this.setOption({ series: [] }, true);
  22039. };
  22040. /**
  22041. * Dispose instance
  22042. */
  22043. echartsProto.dispose = function () {
  22044. if (this._disposed) {
  22045. if (__DEV__) {
  22046. console.warn('Instance ' + this.id + ' has been disposed');
  22047. }
  22048. return;
  22049. }
  22050. this._disposed = true;
  22051. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  22052. var api = this._api;
  22053. var ecModel = this._model;
  22054. each(this._componentsViews, function (component) {
  22055. component.dispose(ecModel, api);
  22056. });
  22057. each(this._chartsViews, function (chart) {
  22058. chart.dispose(ecModel, api);
  22059. });
  22060. // Dispose after all views disposed
  22061. this._zr.dispose();
  22062. delete instances[this.id];
  22063. };
  22064. mixin(ECharts, Eventful);
  22065. function updateHoverLayerStatus(zr, ecModel) {
  22066. var storage = zr.storage;
  22067. var elCount = 0;
  22068. storage.traverse(function (el) {
  22069. if (!el.isGroup) {
  22070. elCount++;
  22071. }
  22072. });
  22073. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  22074. storage.traverse(function (el) {
  22075. if (!el.isGroup) {
  22076. // Don't switch back.
  22077. el.useHoverLayer = true;
  22078. }
  22079. });
  22080. }
  22081. }
  22082. /**
  22083. * Update chart progressive and blend.
  22084. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  22085. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  22086. */
  22087. function updateBlend(seriesModel, chartView) {
  22088. var blendMode = seriesModel.get('blendMode') || null;
  22089. if (__DEV__) {
  22090. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  22091. console.warn('Only canvas support blendMode');
  22092. }
  22093. }
  22094. chartView.group.traverse(function (el) {
  22095. // FIXME marker and other components
  22096. if (!el.isGroup) {
  22097. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  22098. if (el.style.blend !== blendMode) {
  22099. el.setStyle('blend', blendMode);
  22100. }
  22101. }
  22102. if (el.eachPendingDisplayable) {
  22103. el.eachPendingDisplayable(function (displayable) {
  22104. displayable.setStyle('blend', blendMode);
  22105. });
  22106. }
  22107. });
  22108. }
  22109. /**
  22110. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  22111. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  22112. */
  22113. function updateZ(model, view) {
  22114. var z = model.get('z');
  22115. var zlevel = model.get('zlevel');
  22116. // Set z and zlevel
  22117. view.group.traverse(function (el) {
  22118. if (el.type !== 'group') {
  22119. z != null && (el.z = z);
  22120. zlevel != null && (el.zlevel = zlevel);
  22121. }
  22122. });
  22123. }
  22124. function createExtensionAPI(ecInstance) {
  22125. var coordSysMgr = ecInstance._coordSysMgr;
  22126. return extend(new ExtensionAPI(ecInstance), {
  22127. // Inject methods
  22128. getCoordinateSystems: bind(
  22129. coordSysMgr.getCoordinateSystems, coordSysMgr
  22130. ),
  22131. getComponentByElement: function (el) {
  22132. while (el) {
  22133. var modelInfo = el.__ecComponentInfo;
  22134. if (modelInfo != null) {
  22135. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  22136. }
  22137. el = el.parent;
  22138. }
  22139. }
  22140. });
  22141. }
  22142. /**
  22143. * @type {Object} key: actionType.
  22144. * @inner
  22145. */
  22146. var actions = {};
  22147. /**
  22148. * Map eventType to actionType
  22149. * @type {Object}
  22150. */
  22151. var eventActionMap = {};
  22152. /**
  22153. * Data processor functions of each stage
  22154. * @type {Array.<Object.<string, Function>>}
  22155. * @inner
  22156. */
  22157. var dataProcessorFuncs = [];
  22158. /**
  22159. * @type {Array.<Function>}
  22160. * @inner
  22161. */
  22162. var optionPreprocessorFuncs = [];
  22163. /**
  22164. * @type {Array.<Function>}
  22165. * @inner
  22166. */
  22167. var postUpdateFuncs = [];
  22168. /**
  22169. * Visual encoding functions of each stage
  22170. * @type {Array.<Object.<string, Function>>}
  22171. */
  22172. var visualFuncs = [];
  22173. /**
  22174. * Theme storage
  22175. * @type {Object.<key, Object>}
  22176. */
  22177. var themeStorage = {};
  22178. /**
  22179. * Loading effects
  22180. */
  22181. var loadingEffects = {};
  22182. var instances = {};
  22183. var connectedGroups = {};
  22184. var idBase = new Date() - 0;
  22185. var groupIdBase = new Date() - 0;
  22186. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  22187. var mapDataStores = {};
  22188. function enableConnect(chart) {
  22189. var STATUS_PENDING = 0;
  22190. var STATUS_UPDATING = 1;
  22191. var STATUS_UPDATED = 2;
  22192. var STATUS_KEY = '__connectUpdateStatus';
  22193. function updateConnectedChartsStatus(charts, status) {
  22194. for (var i = 0; i < charts.length; i++) {
  22195. var otherChart = charts[i];
  22196. otherChart[STATUS_KEY] = status;
  22197. }
  22198. }
  22199. each(eventActionMap, function (actionType, eventType) {
  22200. chart._messageCenter.on(eventType, function (event) {
  22201. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  22202. if (event && event.escapeConnect) {
  22203. return;
  22204. }
  22205. var action = chart.makeActionFromEvent(event);
  22206. var otherCharts = [];
  22207. each(instances, function (otherChart) {
  22208. if (otherChart !== chart && otherChart.group === chart.group) {
  22209. otherCharts.push(otherChart);
  22210. }
  22211. });
  22212. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  22213. each(otherCharts, function (otherChart) {
  22214. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  22215. otherChart.dispatchAction(action);
  22216. }
  22217. });
  22218. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  22219. }
  22220. });
  22221. });
  22222. }
  22223. /**
  22224. * @param {HTMLElement} dom
  22225. * @param {Object} [theme]
  22226. * @param {Object} opts
  22227. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  22228. * @param {string} [opts.renderer] Currently only 'canvas' is supported.
  22229. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  22230. * Can be 'auto' (the same as null/undefined)
  22231. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  22232. * Can be 'auto' (the same as null/undefined)
  22233. */
  22234. function init(dom, theme$$1, opts) {
  22235. if (__DEV__) {
  22236. // Check version
  22237. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  22238. throw new Error(
  22239. 'zrender/src ' + version$1
  22240. + ' is too old for ECharts ' + version
  22241. + '. Current version need ZRender '
  22242. + dependencies.zrender + '+'
  22243. );
  22244. }
  22245. if (!dom) {
  22246. throw new Error('Initialize failed: invalid dom.');
  22247. }
  22248. }
  22249. var existInstance = getInstanceByDom(dom);
  22250. if (existInstance) {
  22251. if (__DEV__) {
  22252. console.warn('There is a chart instance already initialized on the dom.');
  22253. }
  22254. return existInstance;
  22255. }
  22256. if (__DEV__) {
  22257. if (isDom(dom)
  22258. && dom.nodeName.toUpperCase() !== 'CANVAS'
  22259. && (
  22260. (!dom.clientWidth && (!opts || opts.width == null))
  22261. || (!dom.clientHeight && (!opts || opts.height == null))
  22262. )
  22263. ) {
  22264. console.warn('Can\'t get dom width or height');
  22265. }
  22266. }
  22267. var chart = new ECharts(dom, theme$$1, opts);
  22268. chart.id = 'ec_' + idBase++;
  22269. instances[chart.id] = chart;
  22270. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  22271. enableConnect(chart);
  22272. return chart;
  22273. }
  22274. /**
  22275. * @return {string|Array.<module:echarts~ECharts>} groupId
  22276. */
  22277. function connect(groupId) {
  22278. // Is array of charts
  22279. if (isArray(groupId)) {
  22280. var charts = groupId;
  22281. groupId = null;
  22282. // If any chart has group
  22283. each(charts, function (chart) {
  22284. if (chart.group != null) {
  22285. groupId = chart.group;
  22286. }
  22287. });
  22288. groupId = groupId || ('g_' + groupIdBase++);
  22289. each(charts, function (chart) {
  22290. chart.group = groupId;
  22291. });
  22292. }
  22293. connectedGroups[groupId] = true;
  22294. return groupId;
  22295. }
  22296. /**
  22297. * @DEPRECATED
  22298. * @return {string} groupId
  22299. */
  22300. function disConnect(groupId) {
  22301. connectedGroups[groupId] = false;
  22302. }
  22303. /**
  22304. * @return {string} groupId
  22305. */
  22306. var disconnect = disConnect;
  22307. /**
  22308. * Dispose a chart instance
  22309. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  22310. */
  22311. function dispose(chart) {
  22312. if (typeof chart === 'string') {
  22313. chart = instances[chart];
  22314. }
  22315. else if (!(chart instanceof ECharts)){
  22316. // Try to treat as dom
  22317. chart = getInstanceByDom(chart);
  22318. }
  22319. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  22320. chart.dispose();
  22321. }
  22322. }
  22323. /**
  22324. * @param {HTMLElement} dom
  22325. * @return {echarts~ECharts}
  22326. */
  22327. function getInstanceByDom(dom) {
  22328. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  22329. }
  22330. /**
  22331. * @param {string} key
  22332. * @return {echarts~ECharts}
  22333. */
  22334. function getInstanceById(key) {
  22335. return instances[key];
  22336. }
  22337. /**
  22338. * Register theme
  22339. */
  22340. function registerTheme(name, theme$$1) {
  22341. themeStorage[name] = theme$$1;
  22342. }
  22343. /**
  22344. * Register option preprocessor
  22345. * @param {Function} preprocessorFunc
  22346. */
  22347. function registerPreprocessor(preprocessorFunc) {
  22348. optionPreprocessorFuncs.push(preprocessorFunc);
  22349. }
  22350. /**
  22351. * @param {number} [priority=1000]
  22352. * @param {Object|Function} processor
  22353. */
  22354. function registerProcessor(priority, processor) {
  22355. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  22356. }
  22357. /**
  22358. * Register postUpdater
  22359. * @param {Function} postUpdateFunc
  22360. */
  22361. function registerPostUpdate(postUpdateFunc) {
  22362. postUpdateFuncs.push(postUpdateFunc);
  22363. }
  22364. /**
  22365. * Usage:
  22366. * registerAction('someAction', 'someEvent', function () { ... });
  22367. * registerAction('someAction', function () { ... });
  22368. * registerAction(
  22369. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  22370. * function () { ... }
  22371. * );
  22372. *
  22373. * @param {(string|Object)} actionInfo
  22374. * @param {string} actionInfo.type
  22375. * @param {string} [actionInfo.event]
  22376. * @param {string} [actionInfo.update]
  22377. * @param {string} [eventName]
  22378. * @param {Function} action
  22379. */
  22380. function registerAction(actionInfo, eventName, action) {
  22381. if (typeof eventName === 'function') {
  22382. action = eventName;
  22383. eventName = '';
  22384. }
  22385. var actionType = isObject(actionInfo)
  22386. ? actionInfo.type
  22387. : ([actionInfo, actionInfo = {
  22388. event: eventName
  22389. }][0]);
  22390. // Event name is all lowercase
  22391. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  22392. eventName = actionInfo.event;
  22393. // Validate action type and event name.
  22394. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  22395. if (!actions[actionType]) {
  22396. actions[actionType] = {action: action, actionInfo: actionInfo};
  22397. }
  22398. eventActionMap[eventName] = actionType;
  22399. }
  22400. /**
  22401. * @param {string} type
  22402. * @param {*} CoordinateSystem
  22403. */
  22404. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  22405. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  22406. }
  22407. /**
  22408. * Get dimensions of specified coordinate system.
  22409. * @param {string} type
  22410. * @return {Array.<string|Object>}
  22411. */
  22412. function getCoordinateSystemDimensions(type) {
  22413. var coordSysCreator = CoordinateSystemManager.get(type);
  22414. if (coordSysCreator) {
  22415. return coordSysCreator.getDimensionsInfo
  22416. ? coordSysCreator.getDimensionsInfo()
  22417. : coordSysCreator.dimensions.slice();
  22418. }
  22419. }
  22420. /**
  22421. * Layout is a special stage of visual encoding
  22422. * Most visual encoding like color are common for different chart
  22423. * But each chart has it's own layout algorithm
  22424. *
  22425. * @param {number} [priority=1000]
  22426. * @param {Function} layoutTask
  22427. */
  22428. function registerLayout(priority, layoutTask) {
  22429. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  22430. }
  22431. /**
  22432. * @param {number} [priority=3000]
  22433. * @param {module:echarts/stream/Task} visualTask
  22434. */
  22435. function registerVisual(priority, visualTask) {
  22436. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  22437. }
  22438. /**
  22439. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  22440. */
  22441. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  22442. if (isFunction(priority) || isObject(priority)) {
  22443. fn = priority;
  22444. priority = defaultPriority;
  22445. }
  22446. if (__DEV__) {
  22447. if (isNaN(priority) || priority == null) {
  22448. throw new Error('Illegal priority');
  22449. }
  22450. // Check duplicate
  22451. each(targetList, function (wrap) {
  22452. assert(wrap.__raw !== fn);
  22453. });
  22454. }
  22455. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  22456. stageHandler.__prio = priority;
  22457. stageHandler.__raw = fn;
  22458. targetList.push(stageHandler);
  22459. return stageHandler;
  22460. }
  22461. /**
  22462. * @param {string} name
  22463. */
  22464. function registerLoading(name, loadingFx) {
  22465. loadingEffects[name] = loadingFx;
  22466. }
  22467. /**
  22468. * @param {Object} opts
  22469. * @param {string} [superClass]
  22470. */
  22471. function extendComponentModel(opts/*, superClass*/) {
  22472. // var Clazz = ComponentModel;
  22473. // if (superClass) {
  22474. // var classType = parseClassType(superClass);
  22475. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  22476. // }
  22477. return ComponentModel.extend(opts);
  22478. }
  22479. /**
  22480. * @param {Object} opts
  22481. * @param {string} [superClass]
  22482. */
  22483. function extendComponentView(opts/*, superClass*/) {
  22484. // var Clazz = ComponentView;
  22485. // if (superClass) {
  22486. // var classType = parseClassType(superClass);
  22487. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  22488. // }
  22489. return Component$1.extend(opts);
  22490. }
  22491. /**
  22492. * @param {Object} opts
  22493. * @param {string} [superClass]
  22494. */
  22495. function extendSeriesModel(opts/*, superClass*/) {
  22496. // var Clazz = SeriesModel;
  22497. // if (superClass) {
  22498. // superClass = 'series.' + superClass.replace('series.', '');
  22499. // var classType = parseClassType(superClass);
  22500. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  22501. // }
  22502. return SeriesModel.extend(opts);
  22503. }
  22504. /**
  22505. * @param {Object} opts
  22506. * @param {string} [superClass]
  22507. */
  22508. function extendChartView(opts/*, superClass*/) {
  22509. // var Clazz = ChartView;
  22510. // if (superClass) {
  22511. // superClass = superClass.replace('series.', '');
  22512. // var classType = parseClassType(superClass);
  22513. // Clazz = ChartView.getClass(classType.main, true);
  22514. // }
  22515. return Chart.extend(opts);
  22516. }
  22517. /**
  22518. * ZRender need a canvas context to do measureText.
  22519. * But in node environment canvas may be created by node-canvas.
  22520. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  22521. *
  22522. * Be careful of using it in the browser.
  22523. *
  22524. * @param {Function} creator
  22525. * @example
  22526. * var Canvas = require('canvas');
  22527. * var echarts = require('echarts');
  22528. * echarts.setCanvasCreator(function () {
  22529. * // Small size is enough.
  22530. * return new Canvas(32, 32);
  22531. * });
  22532. */
  22533. function setCanvasCreator(creator) {
  22534. $override('createCanvas', creator);
  22535. }
  22536. /**
  22537. * @param {string} mapName
  22538. * @param {Object|string} geoJson
  22539. * @param {Object} [specialAreas]
  22540. *
  22541. * @example
  22542. * $.get('USA.json', function (geoJson) {
  22543. * echarts.registerMap('USA', geoJson);
  22544. * // Or
  22545. * echarts.registerMap('USA', {
  22546. * geoJson: geoJson,
  22547. * specialAreas: {}
  22548. * })
  22549. * });
  22550. */
  22551. function registerMap(mapName, geoJson, specialAreas) {
  22552. if (geoJson.geoJson && !geoJson.features) {
  22553. specialAreas = geoJson.specialAreas;
  22554. geoJson = geoJson.geoJson;
  22555. }
  22556. if (typeof geoJson === 'string') {
  22557. geoJson = (typeof JSON !== 'undefined' && JSON.parse)
  22558. ? JSON.parse(geoJson) : (new Function('return (' + geoJson + ');'))();
  22559. }
  22560. mapDataStores[mapName] = {
  22561. geoJson: geoJson,
  22562. specialAreas: specialAreas
  22563. };
  22564. }
  22565. /**
  22566. * @param {string} mapName
  22567. * @return {Object}
  22568. */
  22569. function getMap(mapName) {
  22570. return mapDataStores[mapName];
  22571. }
  22572. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  22573. registerPreprocessor(backwardCompat);
  22574. registerProcessor(PRIORITY_PROCESSOR_STATISTIC, dataStack);
  22575. registerLoading('default', loadingDefault);
  22576. // Default actions
  22577. registerAction({
  22578. type: 'highlight',
  22579. event: 'highlight',
  22580. update: 'highlight'
  22581. }, noop);
  22582. registerAction({
  22583. type: 'downplay',
  22584. event: 'downplay',
  22585. update: 'downplay'
  22586. }, noop);
  22587. // Default theme
  22588. registerTheme('light', lightTheme);
  22589. registerTheme('dark', theme);
  22590. // For backward compatibility, where the namespace `dataTool` will
  22591. // be mounted on `echarts` is the extension `dataTool` is imported.
  22592. var dataTool = {};
  22593. function defaultKeyGetter(item) {
  22594. return item;
  22595. }
  22596. /**
  22597. * @param {Array} oldArr
  22598. * @param {Array} newArr
  22599. * @param {Function} oldKeyGetter
  22600. * @param {Function} newKeyGetter
  22601. * @param {Object} [context] Can be visited by this.context in callback.
  22602. */
  22603. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  22604. this._old = oldArr;
  22605. this._new = newArr;
  22606. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  22607. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  22608. this.context = context;
  22609. }
  22610. DataDiffer.prototype = {
  22611. constructor: DataDiffer,
  22612. /**
  22613. * Callback function when add a data
  22614. */
  22615. add: function (func) {
  22616. this._add = func;
  22617. return this;
  22618. },
  22619. /**
  22620. * Callback function when update a data
  22621. */
  22622. update: function (func) {
  22623. this._update = func;
  22624. return this;
  22625. },
  22626. /**
  22627. * Callback function when remove a data
  22628. */
  22629. remove: function (func) {
  22630. this._remove = func;
  22631. return this;
  22632. },
  22633. execute: function () {
  22634. var oldArr = this._old;
  22635. var newArr = this._new;
  22636. var oldDataIndexMap = {};
  22637. var newDataIndexMap = {};
  22638. var oldDataKeyArr = [];
  22639. var newDataKeyArr = [];
  22640. var i;
  22641. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  22642. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  22643. // Travel by inverted order to make sure order consistency
  22644. // when duplicate keys exists (consider newDataIndex.pop() below).
  22645. // For performance consideration, these code below do not look neat.
  22646. for (i = 0; i < oldArr.length; i++) {
  22647. var key = oldDataKeyArr[i];
  22648. var idx = newDataIndexMap[key];
  22649. // idx can never be empty array here. see 'set null' logic below.
  22650. if (idx != null) {
  22651. // Consider there is duplicate key (for example, use dataItem.name as key).
  22652. // We should make sure every item in newArr and oldArr can be visited.
  22653. var len = idx.length;
  22654. if (len) {
  22655. len === 1 && (newDataIndexMap[key] = null);
  22656. idx = idx.unshift();
  22657. }
  22658. else {
  22659. newDataIndexMap[key] = null;
  22660. }
  22661. this._update && this._update(idx, i);
  22662. }
  22663. else {
  22664. this._remove && this._remove(i);
  22665. }
  22666. }
  22667. for (var i = 0; i < newDataKeyArr.length; i++) {
  22668. var key = newDataKeyArr[i];
  22669. if (newDataIndexMap.hasOwnProperty(key)) {
  22670. var idx = newDataIndexMap[key];
  22671. if (idx == null) {
  22672. continue;
  22673. }
  22674. // idx can never be empty array here. see 'set null' logic above.
  22675. if (!idx.length) {
  22676. this._add && this._add(idx);
  22677. }
  22678. else {
  22679. for (var j = 0, len = idx.length; j < len; j++) {
  22680. this._add && this._add(idx[j]);
  22681. }
  22682. }
  22683. }
  22684. }
  22685. }
  22686. };
  22687. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  22688. for (var i = 0; i < arr.length; i++) {
  22689. // Add prefix to avoid conflict with Object.prototype.
  22690. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  22691. var existence = map[key];
  22692. if (existence == null) {
  22693. keyArr.push(key);
  22694. map[key] = i;
  22695. }
  22696. else {
  22697. if (!existence.length) {
  22698. map[key] = existence = [existence];
  22699. }
  22700. existence.push(i);
  22701. }
  22702. }
  22703. }
  22704. var OTHER_DIMENSIONS = createHashMap([
  22705. 'tooltip', 'label', 'itemName', 'itemId', 'seriesName'
  22706. ]);
  22707. function summarizeDimensions(data) {
  22708. var summary = {};
  22709. var encode = summary.encode = {};
  22710. var notExtraCoordDimMap = createHashMap();
  22711. var defaultedLabel = [];
  22712. each$1(data.dimensions, function (dimName) {
  22713. var dimItem = data.getDimensionInfo(dimName);
  22714. var coordDim = dimItem.coordDim;
  22715. if (coordDim) {
  22716. if (__DEV__) {
  22717. assert$1(OTHER_DIMENSIONS.get(coordDim) == null);
  22718. }
  22719. var coordDimArr = encode[coordDim];
  22720. if (!encode.hasOwnProperty(coordDim)) {
  22721. coordDimArr = encode[coordDim] = [];
  22722. }
  22723. coordDimArr[dimItem.coordDimIndex] = dimName;
  22724. if (!dimItem.isExtraCoord) {
  22725. notExtraCoordDimMap.set(coordDim, 1);
  22726. // Use the last coord dim (and label friendly) as default label,
  22727. // because when dataset is used, it is hard to guess which dimension
  22728. // can be value dimension. If both show x, y on label is not look good,
  22729. // and conventionally y axis is focused more.
  22730. if (mayLabelDimType(dimItem.type)) {
  22731. defaultedLabel[0] = dimName;
  22732. }
  22733. }
  22734. }
  22735. OTHER_DIMENSIONS.each(function (v, otherDim) {
  22736. var otherDimArr = encode[otherDim];
  22737. if (!encode.hasOwnProperty(otherDim)) {
  22738. otherDimArr = encode[otherDim] = [];
  22739. }
  22740. var dimIndex = dimItem.otherDims[otherDim];
  22741. if (dimIndex != null && dimIndex !== false) {
  22742. otherDimArr[dimIndex] = dimItem.name;
  22743. }
  22744. });
  22745. });
  22746. var dataDimsOnCoord = [];
  22747. var encodeFirstDimNotExtra = {};
  22748. notExtraCoordDimMap.each(function (v, coordDim) {
  22749. var dimArr = encode[coordDim];
  22750. // ??? FIXME extra coord should not be set in dataDimsOnCoord.
  22751. // But should fix the case that radar axes: simplify the logic
  22752. // of `completeDimension`, remove `extraPrefix`.
  22753. encodeFirstDimNotExtra[coordDim] = dimArr[0];
  22754. // Not necessary to remove duplicate, because a data
  22755. // dim canot on more than one coordDim.
  22756. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  22757. });
  22758. summary.dataDimsOnCoord = dataDimsOnCoord;
  22759. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  22760. var encodeLabel = encode.label;
  22761. // FIXME `encode.label` is not recommanded, because formatter can not be set
  22762. // in this way. Use label.formatter instead. May be remove this approach someday.
  22763. if (encodeLabel && encodeLabel.length) {
  22764. defaultedLabel = encodeLabel.slice();
  22765. }
  22766. var defaultedTooltip = defaultedLabel.slice();
  22767. var encodeTooltip = encode.tooltip;
  22768. if (encodeTooltip && encodeTooltip.length) {
  22769. defaultedTooltip = encodeTooltip.slice();
  22770. }
  22771. encode.defaultedLabel = defaultedLabel;
  22772. encode.defaultedTooltip = defaultedTooltip;
  22773. return summary;
  22774. }
  22775. function getDimensionTypeByAxis(axisType) {
  22776. return axisType === 'category'
  22777. ? 'ordinal'
  22778. : axisType === 'time'
  22779. ? 'time'
  22780. : 'float';
  22781. }
  22782. function mayLabelDimType(dimType) {
  22783. // In most cases, ordinal and time do not suitable for label.
  22784. // Ordinal info can be displayed on axis. Time is too long.
  22785. return !(dimType === 'ordinal' || dimType === 'time');
  22786. }
  22787. // function findTheLastDimMayLabel(data) {
  22788. // // Get last value dim
  22789. // var dimensions = data.dimensions.slice();
  22790. // var valueType;
  22791. // var valueDim;
  22792. // while (dimensions.length && (
  22793. // valueDim = dimensions.pop(),
  22794. // valueType = data.getDimensionInfo(valueDim).type,
  22795. // valueType === 'ordinal' || valueType === 'time'
  22796. // )) {} // jshint ignore:line
  22797. // return valueDim;
  22798. // }
  22799. /**
  22800. * List for data storage
  22801. * @module echarts/data/List
  22802. */
  22803. var isObject$4 = isObject$1;
  22804. var UNDEFINED = 'undefined';
  22805. var globalObj = typeof window === UNDEFINED ? global : window;
  22806. // Use prefix to avoid index to be the same as otherIdList[idx],
  22807. // which will cause weird udpate animation.
  22808. var ID_PREFIX = 'e\0\0';
  22809. var dataCtors = {
  22810. 'float': typeof globalObj.Float64Array === UNDEFINED
  22811. ? Array : globalObj.Float64Array,
  22812. 'int': typeof globalObj.Int32Array === UNDEFINED
  22813. ? Array : globalObj.Int32Array,
  22814. // Ordinal data type can be string or int
  22815. 'ordinal': Array,
  22816. 'number': Array,
  22817. 'time': Array
  22818. };
  22819. var CtorUint32Array = typeof globalObj.Uint32Array === UNDEFINED ? Array : globalObj.Uint32Array;
  22820. var CtorUint16Array = typeof globalObj.Uint16Array === UNDEFINED ? Array : globalObj.Uint16Array;
  22821. function getIndicesCtor(list) {
  22822. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  22823. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  22824. }
  22825. function cloneChunk(originalChunk) {
  22826. var Ctor = originalChunk.constructor;
  22827. // Only shallow clone is enough when Array.
  22828. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  22829. }
  22830. var TRANSFERABLE_PROPERTIES = [
  22831. 'hasItemOption', '_nameList', '_idList', '_calculationInfo', '_invertedIndicesMap',
  22832. '_rawData', '_rawExtent', '_chunkSize', '_chunkCount',
  22833. '_dimValueGetter', '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
  22834. ];
  22835. function transferProperties(a, b) {
  22836. each$1(TRANSFERABLE_PROPERTIES.concat(b.__wrappedMethods || []), function (propName) {
  22837. if (b.hasOwnProperty(propName)) {
  22838. a[propName] = b[propName];
  22839. }
  22840. });
  22841. a.__wrappedMethods = b.__wrappedMethods;
  22842. }
  22843. /**
  22844. * @constructor
  22845. * @alias module:echarts/data/List
  22846. *
  22847. * @param {Array.<string|Object>} dimensions
  22848. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  22849. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  22850. * Spetial fields: {
  22851. * ordinalMeta: <module:echarts/data/OrdinalMeta>
  22852. * createInvertedIndices: <boolean>
  22853. * }
  22854. * @param {module:echarts/model/Model} hostModel
  22855. */
  22856. var List = function (dimensions, hostModel) {
  22857. dimensions = dimensions || ['x', 'y'];
  22858. var dimensionInfos = {};
  22859. var dimensionNames = [];
  22860. var invertedIndicesMap = {};
  22861. for (var i = 0; i < dimensions.length; i++) {
  22862. // Use the original dimensions[i], where other flag props may exists.
  22863. var dimensionInfo = dimensions[i];
  22864. if (isString(dimensionInfo)) {
  22865. dimensionInfo = {name: dimensionInfo};
  22866. }
  22867. var dimensionName = dimensionInfo.name;
  22868. dimensionInfo.type = dimensionInfo.type || 'float';
  22869. if (!dimensionInfo.coordDim) {
  22870. dimensionInfo.coordDim = dimensionName;
  22871. dimensionInfo.coordDimIndex = 0;
  22872. }
  22873. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  22874. dimensionNames.push(dimensionName);
  22875. dimensionInfos[dimensionName] = dimensionInfo;
  22876. dimensionInfo.index = i;
  22877. if (dimensionInfo.createInvertedIndices) {
  22878. invertedIndicesMap[dimensionName] = [];
  22879. }
  22880. }
  22881. /**
  22882. * @readOnly
  22883. * @type {Array.<string>}
  22884. */
  22885. this.dimensions = dimensionNames;
  22886. /**
  22887. * Infomation of each data dimension, like data type.
  22888. * @type {Object}
  22889. */
  22890. this._dimensionInfos = dimensionInfos;
  22891. /**
  22892. * @type {module:echarts/model/Model}
  22893. */
  22894. this.hostModel = hostModel;
  22895. /**
  22896. * @type {module:echarts/model/Model}
  22897. */
  22898. this.dataType;
  22899. /**
  22900. * Indices stores the indices of data subset after filtered.
  22901. * This data subset will be used in chart.
  22902. * @type {Array.<number>}
  22903. * @readOnly
  22904. */
  22905. this._indices = null;
  22906. this._count = 0;
  22907. this._rawCount = 0;
  22908. /**
  22909. * Data storage
  22910. * @type {Object.<key, Array.<TypedArray|Array>>}
  22911. * @private
  22912. */
  22913. this._storage = {};
  22914. /**
  22915. * @type {Array.<string>}
  22916. */
  22917. this._nameList = [];
  22918. /**
  22919. * @type {Array.<string>}
  22920. */
  22921. this._idList = [];
  22922. /**
  22923. * Models of data option is stored sparse for optimizing memory cost
  22924. * @type {Array.<module:echarts/model/Model>}
  22925. * @private
  22926. */
  22927. this._optionModels = [];
  22928. /**
  22929. * Global visual properties after visual coding
  22930. * @type {Object}
  22931. * @private
  22932. */
  22933. this._visual = {};
  22934. /**
  22935. * Globel layout properties.
  22936. * @type {Object}
  22937. * @private
  22938. */
  22939. this._layout = {};
  22940. /**
  22941. * Item visual properties after visual coding
  22942. * @type {Array.<Object>}
  22943. * @private
  22944. */
  22945. this._itemVisuals = [];
  22946. /**
  22947. * Key: visual type, Value: boolean
  22948. * @type {Object}
  22949. * @readOnly
  22950. */
  22951. this.hasItemVisual = {};
  22952. /**
  22953. * Item layout properties after layout
  22954. * @type {Array.<Object>}
  22955. * @private
  22956. */
  22957. this._itemLayouts = [];
  22958. /**
  22959. * Graphic elemnents
  22960. * @type {Array.<module:zrender/Element>}
  22961. * @private
  22962. */
  22963. this._graphicEls = [];
  22964. /**
  22965. * Max size of each chunk.
  22966. * @type {number}
  22967. * @private
  22968. */
  22969. this._chunkSize = 1e5;
  22970. /**
  22971. * @type {number}
  22972. * @private
  22973. */
  22974. this._chunkCount = 0;
  22975. /**
  22976. * @type {Array.<Array|Object>}
  22977. * @private
  22978. */
  22979. this._rawData;
  22980. /**
  22981. * Raw extent will not be cloned, but only transfered.
  22982. * It will not be calculated util needed.
  22983. * key: dim,
  22984. * value: {end: number, extent: Array.<number>}
  22985. * @type {Object}
  22986. * @private
  22987. */
  22988. this._rawExtent = {};
  22989. /**
  22990. * @type {Object}
  22991. * @private
  22992. */
  22993. this._extent = {};
  22994. /**
  22995. * key: dim
  22996. * value: extent
  22997. * @type {Object}
  22998. * @private
  22999. */
  23000. this._approximateExtent = {};
  23001. /**
  23002. * Cache summary info for fast visit. See "dimensionHelper".
  23003. * @type {Object}
  23004. * @private
  23005. */
  23006. this._dimensionsSummary = summarizeDimensions(this);
  23007. /**
  23008. * @type {Object.<Array|TypedArray>}
  23009. * @private
  23010. */
  23011. this._invertedIndicesMap = invertedIndicesMap;
  23012. /**
  23013. * @type {Object}
  23014. * @private
  23015. */
  23016. this._calculationInfo = {};
  23017. };
  23018. var listProto = List.prototype;
  23019. listProto.type = 'list';
  23020. /**
  23021. * If each data item has it's own option
  23022. * @type {boolean}
  23023. */
  23024. listProto.hasItemOption = true;
  23025. /**
  23026. * Get dimension name
  23027. * @param {string|number} dim
  23028. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  23029. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  23030. * @return {string} Concrete dim name.
  23031. */
  23032. listProto.getDimension = function (dim) {
  23033. if (!isNaN(dim)) {
  23034. dim = this.dimensions[dim] || dim;
  23035. }
  23036. return dim;
  23037. };
  23038. /**
  23039. * Get type and calculation info of particular dimension
  23040. * @param {string|number} dim
  23041. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  23042. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  23043. */
  23044. listProto.getDimensionInfo = function (dim) {
  23045. // Do not clone, because there may be categories in dimInfo.
  23046. return this._dimensionInfos[this.getDimension(dim)];
  23047. };
  23048. /**
  23049. * @return {Array.<string>} concrete dimension name list on coord.
  23050. */
  23051. listProto.getDimensionsOnCoord = function () {
  23052. return this._dimensionsSummary.dataDimsOnCoord.slice();
  23053. };
  23054. /**
  23055. * @param {string} coordDim
  23056. * @param {number} [idx] A coordDim may map to more than one data dim.
  23057. * If idx is `true`, return a array of all mapped dims.
  23058. * If idx is not specified, return the first dim not extra.
  23059. * @return {string|Array.<string>} concrete data dim.
  23060. * If idx is number, and not found, return null/undefined.
  23061. * If idx is `true`, and not found, return empty array (always return array).
  23062. */
  23063. listProto.mapDimension = function (coordDim, idx) {
  23064. var dimensionsSummary = this._dimensionsSummary;
  23065. if (idx == null) {
  23066. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  23067. }
  23068. var dims = dimensionsSummary.encode[coordDim];
  23069. return idx === true
  23070. // always return array if idx is `true`
  23071. ? (dims || []).slice()
  23072. : (dims && dims[idx]);
  23073. };
  23074. /**
  23075. * Initialize from data
  23076. * @param {Array.<Object|number|Array>} data source or data or data provider.
  23077. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  23078. * defualt label/tooltip.
  23079. * A name can be specified in encode.itemName,
  23080. * or dataItem.name (only for series option data),
  23081. * or provided in nameList from outside.
  23082. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  23083. */
  23084. listProto.initData = function (data, nameList, dimValueGetter) {
  23085. var notProvider = Source.isInstance(data) || isArrayLike(data);
  23086. if (notProvider) {
  23087. data = new DefaultDataProvider(data, this.dimensions.length);
  23088. }
  23089. if (__DEV__) {
  23090. if (!notProvider && (typeof data.getItem != 'function' || typeof data.count != 'function')) {
  23091. throw new Error('Inavlid data provider.');
  23092. }
  23093. }
  23094. this._rawData = data;
  23095. // Clear
  23096. this._storage = {};
  23097. this._indices = null;
  23098. this._nameList = nameList || [];
  23099. this._idList = [];
  23100. this._nameRepeatCount = {};
  23101. if (!dimValueGetter) {
  23102. this.hasItemOption = false;
  23103. }
  23104. /**
  23105. * @readOnly
  23106. */
  23107. this.defaultDimValueGetter = defaultDimValueGetters[
  23108. this._rawData.getSource().sourceFormat
  23109. ];
  23110. // Default dim value getter
  23111. this._dimValueGetter = dimValueGetter = dimValueGetter
  23112. || this.defaultDimValueGetter;
  23113. // Reset raw extent.
  23114. this._rawExtent = {};
  23115. this._initDataFromProvider(0, data.count());
  23116. // If data has no item option.
  23117. if (data.pure) {
  23118. this.hasItemOption = false;
  23119. }
  23120. };
  23121. listProto.getProvider = function () {
  23122. return this._rawData;
  23123. };
  23124. listProto.appendData = function (data) {
  23125. if (__DEV__) {
  23126. assert$1(!this._indices, 'appendData can only be called on raw data.');
  23127. }
  23128. var rawData = this._rawData;
  23129. var start = this.count();
  23130. rawData.appendData(data);
  23131. var end = rawData.count();
  23132. if (!rawData.persistent) {
  23133. end += start;
  23134. }
  23135. this._initDataFromProvider(start, end);
  23136. };
  23137. listProto._initDataFromProvider = function (start, end) {
  23138. // Optimize.
  23139. if (start >= end) {
  23140. return;
  23141. }
  23142. var chunkSize = this._chunkSize;
  23143. var rawData = this._rawData;
  23144. var storage = this._storage;
  23145. var dimensions = this.dimensions;
  23146. var dimensionInfoMap = this._dimensionInfos;
  23147. var nameList = this._nameList;
  23148. var idList = this._idList;
  23149. var rawExtent = this._rawExtent;
  23150. var nameRepeatCount = this._nameRepeatCount = {};
  23151. var nameDimIdx;
  23152. var chunkCount = this._chunkCount;
  23153. var lastChunkIndex = chunkCount - 1;
  23154. for (var i = 0; i < dimensions.length; i++) {
  23155. var dim = dimensions[i];
  23156. if (!rawExtent[dim]) {
  23157. rawExtent[dim] = getInitialExtent();
  23158. }
  23159. var dimInfo = dimensionInfoMap[dim];
  23160. if (dimInfo.otherDims.itemName === 0) {
  23161. nameDimIdx = this._nameDimIdx = i;
  23162. }
  23163. if (dimInfo.otherDims.itemId === 0) {
  23164. this._idDimIdx = i;
  23165. }
  23166. var DataCtor = dataCtors[dimInfo.type];
  23167. if (!storage[dim]) {
  23168. storage[dim] = [];
  23169. }
  23170. var resizeChunkArray = storage[dim][lastChunkIndex];
  23171. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  23172. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
  23173. // The cost of the copy is probably inconsiderable
  23174. // within the initial chunkSize.
  23175. for (var j = 0; j < resizeChunkArray.length; j++) {
  23176. newStore[j] = resizeChunkArray[j];
  23177. }
  23178. storage[dim][lastChunkIndex] = newStore;
  23179. }
  23180. // Create new chunks.
  23181. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  23182. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  23183. }
  23184. this._chunkCount = storage[dim].length;
  23185. }
  23186. for (var idx = start; idx < end; idx++) {
  23187. // NOTICE: Try not to write things into dataItem
  23188. var dataItem = rawData.getItem(idx);
  23189. // Each data item is value
  23190. // [1, 2]
  23191. // 2
  23192. // Bar chart, line chart which uses category axis
  23193. // only gives the 'y' value. 'x' value is the indices of category
  23194. // Use a tempValue to normalize the value to be a (x, y) value
  23195. var chunkIndex = Math.floor(idx / chunkSize);
  23196. var chunkOffset = idx % chunkSize;
  23197. // Store the data by dimensions
  23198. for (var k = 0; k < dimensions.length; k++) {
  23199. var dim = dimensions[k];
  23200. var dimStorage = storage[dim][chunkIndex];
  23201. // PENDING NULL is empty or zero
  23202. var val = this._dimValueGetter(dataItem, dim, idx, k);
  23203. dimStorage[chunkOffset] = val;
  23204. if (val < rawExtent[dim][0]) {
  23205. rawExtent[dim][0] = val;
  23206. }
  23207. if (val > rawExtent[dim][1]) {
  23208. rawExtent[dim][1] = val;
  23209. }
  23210. }
  23211. // ??? FIXME not check by pure but sourceFormat?
  23212. // TODO refactor these logic.
  23213. if (!rawData.pure) {
  23214. var name = nameList[idx];
  23215. if (dataItem && !name) {
  23216. if (nameDimIdx != null) {
  23217. name = this._getNameFromStore(idx);
  23218. }
  23219. else if (dataItem.name != null) {
  23220. // There is no other place to persistent dataItem.name,
  23221. // so save it to nameList.
  23222. nameList[idx] = name = dataItem.name;
  23223. }
  23224. }
  23225. // Try using the id in option
  23226. // id or name is used on dynamical data, mapping old and new items.
  23227. var id = dataItem == null ? null : dataItem.id;
  23228. if (id == null && name != null) {
  23229. // Use name as id and add counter to avoid same name
  23230. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  23231. id = name;
  23232. if (nameRepeatCount[name] > 0) {
  23233. id += '__ec__' + nameRepeatCount[name];
  23234. }
  23235. nameRepeatCount[name]++;
  23236. }
  23237. id != null && (idList[idx] = id);
  23238. }
  23239. }
  23240. if (!rawData.persistent && rawData.clean) {
  23241. // Clean unused data if data source is typed array.
  23242. rawData.clean();
  23243. }
  23244. this._rawCount = this._count = end;
  23245. // Reset data extent
  23246. this._extent = {};
  23247. prepareInvertedIndex(this);
  23248. };
  23249. function prepareInvertedIndex(list) {
  23250. var invertedIndicesMap = list._invertedIndicesMap;
  23251. each$1(invertedIndicesMap, function (invertedIndices, dim) {
  23252. var dimInfo = list._dimensionInfos[dim];
  23253. // Currently, only dimensions that has ordinalMeta can create inverted indices.
  23254. var ordinalMeta = dimInfo.ordinalMeta;
  23255. if (ordinalMeta) {
  23256. invertedIndices = invertedIndicesMap[dim] = new CtorUint32Array(
  23257. ordinalMeta.categories.length
  23258. );
  23259. // The default value of TypedArray is 0. To avoid miss
  23260. // mapping to 0, we should set it as NaN.
  23261. for (var i = 0; i < invertedIndices.length; i++) {
  23262. invertedIndices[i] = NaN;
  23263. }
  23264. for (var i = 0; i < list._count; i++) {
  23265. // Only support the case that all values are distinct.
  23266. invertedIndices[list.get(dim, i)] = i;
  23267. }
  23268. }
  23269. });
  23270. }
  23271. // TODO refactor
  23272. listProto._getNameFromStore = function (rawIndex) {
  23273. var nameDimIdx = this._nameDimIdx;
  23274. if (nameDimIdx != null) {
  23275. var chunkSize = this._chunkSize;
  23276. var chunkIndex = Math.floor(rawIndex / chunkSize);
  23277. var chunkOffset = rawIndex % chunkSize;
  23278. var dim = this.dimensions[nameDimIdx];
  23279. var ordinalMeta = this._dimensionInfos[dim].ordinalMeta;
  23280. if (ordinalMeta) {
  23281. return ordinalMeta.categories[rawIndex];
  23282. }
  23283. else {
  23284. var chunk = this._storage[dim][chunkIndex];
  23285. return chunk && chunk[chunkOffset];
  23286. }
  23287. }
  23288. };
  23289. // TODO refactor
  23290. listProto._getIdFromStore = function (rawIndex) {
  23291. var idDimIdx = this._idDimIdx;
  23292. if (idDimIdx != null) {
  23293. var chunkSize = this._chunkSize;
  23294. var chunkIndex = Math.floor(rawIndex / chunkSize);
  23295. var chunkOffset = rawIndex % chunkSize;
  23296. var dim = this.dimensions[idDimIdx];
  23297. var ordinalMeta = this._dimensionInfos[dim].ordinalMeta;
  23298. if (ordinalMeta) {
  23299. return ordinalMeta.categories[rawIndex];
  23300. }
  23301. else {
  23302. var chunk = this._storage[dim][chunkIndex];
  23303. return chunk && chunk[chunkOffset];
  23304. }
  23305. }
  23306. };
  23307. /**
  23308. * @return {number}
  23309. */
  23310. listProto.count = function () {
  23311. return this._count;
  23312. };
  23313. listProto.getIndices = function () {
  23314. if (this._indices) {
  23315. var Ctor = this._indices.constructor;
  23316. return new Ctor(this._indices.buffer, 0, this._count);
  23317. }
  23318. var Ctor = getIndicesCtor(this);
  23319. var arr = new Ctor(this.count());
  23320. for (var i = 0; i < arr.length; i++) {
  23321. arr[i] = i;
  23322. }
  23323. return arr;
  23324. };
  23325. /**
  23326. * Get value. Return NaN if idx is out of range.
  23327. * @param {string} dim Dim must be concrete name.
  23328. * @param {number} idx
  23329. * @param {boolean} stack
  23330. * @return {number}
  23331. */
  23332. listProto.get = function (dim, idx /*, stack */) {
  23333. if (!(idx >= 0 && idx < this._count)) {
  23334. return NaN;
  23335. }
  23336. var storage = this._storage;
  23337. if (!storage[dim]) {
  23338. // TODO Warn ?
  23339. return NaN;
  23340. }
  23341. idx = this.getRawIndex(idx);
  23342. var chunkIndex = Math.floor(idx / this._chunkSize);
  23343. var chunkOffset = idx % this._chunkSize;
  23344. var chunkStore = storage[dim][chunkIndex];
  23345. var value = chunkStore[chunkOffset];
  23346. // FIXME ordinal data type is not stackable
  23347. // if (stack) {
  23348. // var dimensionInfo = this._dimensionInfos[dim];
  23349. // if (dimensionInfo && dimensionInfo.stackable) {
  23350. // var stackedOn = this.stackedOn;
  23351. // while (stackedOn) {
  23352. // // Get no stacked data of stacked on
  23353. // var stackedValue = stackedOn.get(dim, idx);
  23354. // // Considering positive stack, negative stack and empty data
  23355. // if ((value >= 0 && stackedValue > 0) // Positive stack
  23356. // || (value <= 0 && stackedValue < 0) // Negative stack
  23357. // ) {
  23358. // value += stackedValue;
  23359. // }
  23360. // stackedOn = stackedOn.stackedOn;
  23361. // }
  23362. // }
  23363. // }
  23364. return value;
  23365. };
  23366. /**
  23367. * @param {string} dim concrete dim
  23368. * @param {number} rawIndex
  23369. * @return {number|string}
  23370. */
  23371. listProto.getByRawIndex = function (dim, rawIdx) {
  23372. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  23373. return NaN;
  23374. }
  23375. var dimStore = this._storage[dim];
  23376. if (!dimStore) {
  23377. // TODO Warn ?
  23378. return NaN;
  23379. }
  23380. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  23381. var chunkOffset = rawIdx % this._chunkSize;
  23382. var chunkStore = dimStore[chunkIndex];
  23383. return chunkStore[chunkOffset];
  23384. };
  23385. /**
  23386. * FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  23387. * Hack a much simpler _getFast
  23388. * @private
  23389. */
  23390. listProto._getFast = function (dim, rawIdx) {
  23391. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  23392. var chunkOffset = rawIdx % this._chunkSize;
  23393. var chunkStore = this._storage[dim][chunkIndex];
  23394. return chunkStore[chunkOffset];
  23395. };
  23396. /**
  23397. * Get value for multi dimensions.
  23398. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  23399. * @param {number} idx
  23400. * @return {number}
  23401. */
  23402. listProto.getValues = function (dimensions, idx /*, stack */) {
  23403. var values = [];
  23404. if (!isArray(dimensions)) {
  23405. // stack = idx;
  23406. idx = dimensions;
  23407. dimensions = this.dimensions;
  23408. }
  23409. for (var i = 0, len = dimensions.length; i < len; i++) {
  23410. values.push(this.get(dimensions[i], idx /*, stack */));
  23411. }
  23412. return values;
  23413. };
  23414. /**
  23415. * If value is NaN. Inlcuding '-'
  23416. * Only check the coord dimensions.
  23417. * @param {string} dim
  23418. * @param {number} idx
  23419. * @return {number}
  23420. */
  23421. listProto.hasValue = function (idx) {
  23422. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  23423. var dimensionInfos = this._dimensionInfos;
  23424. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  23425. if (
  23426. // Ordinal type can be string or number
  23427. dimensionInfos[dataDimsOnCoord[i]].type !== 'ordinal'
  23428. // FIXME check ordinal when using index?
  23429. && isNaN(this.get(dataDimsOnCoord[i], idx))
  23430. ) {
  23431. return false;
  23432. }
  23433. }
  23434. return true;
  23435. };
  23436. /**
  23437. * Get extent of data in one dimension
  23438. * @param {string} dim
  23439. * @param {boolean} stack
  23440. */
  23441. listProto.getDataExtent = function (dim /*, stack */) {
  23442. // Make sure use concrete dim as cache name.
  23443. dim = this.getDimension(dim);
  23444. var dimData = this._storage[dim];
  23445. var initialExtent = getInitialExtent();
  23446. // stack = !!((stack || false) && this.getCalculationInfo(dim));
  23447. if (!dimData) {
  23448. return initialExtent;
  23449. }
  23450. // Make more strict checkings to ensure hitting cache.
  23451. var currEnd = this.count();
  23452. // var cacheName = [dim, !!stack].join('_');
  23453. // var cacheName = dim;
  23454. // Consider the most cases when using data zoom, `getDataExtent`
  23455. // happened before filtering. We cache raw extent, which is not
  23456. // necessary to be cleared and recalculated when restore data.
  23457. var useRaw = !this._indices; // && !stack;
  23458. var dimExtent;
  23459. if (useRaw) {
  23460. return this._rawExtent[dim].slice();
  23461. }
  23462. dimExtent = this._extent[dim];
  23463. if (dimExtent) {
  23464. return dimExtent.slice();
  23465. }
  23466. dimExtent = initialExtent;
  23467. var min = dimExtent[0];
  23468. var max = dimExtent[1];
  23469. for (var i = 0; i < currEnd; i++) {
  23470. // var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  23471. var value = this._getFast(dim, this.getRawIndex(i));
  23472. value < min && (min = value);
  23473. value > max && (max = value);
  23474. }
  23475. dimExtent = [min, max];
  23476. this._extent[dim] = dimExtent;
  23477. return dimExtent;
  23478. };
  23479. /**
  23480. * Optimize for the scenario that data is filtered by a given extent.
  23481. * Consider that if data amount is more than hundreds of thousand,
  23482. * extent calculation will cost more than 10ms and the cache will
  23483. * be erased because of the filtering.
  23484. */
  23485. listProto.getApproximateExtent = function (dim /*, stack */) {
  23486. dim = this.getDimension(dim);
  23487. return this._approximateExtent[dim] || this.getDataExtent(dim /*, stack */);
  23488. };
  23489. listProto.setApproximateExtent = function (extent, dim /*, stack */) {
  23490. dim = this.getDimension(dim);
  23491. this._approximateExtent[dim] = extent.slice();
  23492. };
  23493. /**
  23494. * @param {string} key
  23495. * @return {*}
  23496. */
  23497. listProto.getCalculationInfo = function (key) {
  23498. return this._calculationInfo[key];
  23499. };
  23500. /**
  23501. * @param {string|Object} key or k-v object
  23502. * @param {*} [value]
  23503. */
  23504. listProto.setCalculationInfo = function (key, value) {
  23505. isObject$4(key)
  23506. ? extend(this._calculationInfo, key)
  23507. : (this._calculationInfo[key] = value);
  23508. };
  23509. /**
  23510. * Get sum of data in one dimension
  23511. * @param {string} dim
  23512. */
  23513. listProto.getSum = function (dim /*, stack */) {
  23514. var dimData = this._storage[dim];
  23515. var sum = 0;
  23516. if (dimData) {
  23517. for (var i = 0, len = this.count(); i < len; i++) {
  23518. var value = this.get(dim, i /*, stack */);
  23519. if (!isNaN(value)) {
  23520. sum += value;
  23521. }
  23522. }
  23523. }
  23524. return sum;
  23525. };
  23526. // /**
  23527. // * Retreive the index with given value
  23528. // * @param {string} dim Concrete dimension.
  23529. // * @param {number} value
  23530. // * @return {number}
  23531. // */
  23532. // Currently incorrect: should return dataIndex but not rawIndex.
  23533. // Do not fix it until this method is to be used somewhere.
  23534. // FIXME Precision of float value
  23535. // listProto.indexOf = function (dim, value) {
  23536. // var storage = this._storage;
  23537. // var dimData = storage[dim];
  23538. // var chunkSize = this._chunkSize;
  23539. // if (dimData) {
  23540. // for (var i = 0, len = this.count(); i < len; i++) {
  23541. // var chunkIndex = Math.floor(i / chunkSize);
  23542. // var chunkOffset = i % chunkSize;
  23543. // if (dimData[chunkIndex][chunkOffset] === value) {
  23544. // return i;
  23545. // }
  23546. // }
  23547. // }
  23548. // return -1;
  23549. // };
  23550. /**
  23551. * Only support the dimension which inverted index created.
  23552. * Do not support other cases until required.
  23553. * @param {string} concrete dim
  23554. * @param {number|string} value
  23555. * @return {number} rawIndex
  23556. */
  23557. listProto.rawIndexOf = function (dim, value) {
  23558. var invertedIndices = dim && this._invertedIndicesMap[dim];
  23559. if (__DEV__) {
  23560. if (!invertedIndices) {
  23561. throw new Error('Do not supported yet');
  23562. }
  23563. }
  23564. var rawIndex = invertedIndices[value];
  23565. if (rawIndex == null || isNaN(rawIndex)) {
  23566. return -1;
  23567. }
  23568. return rawIndex;
  23569. };
  23570. /**
  23571. * Retreive the index with given name
  23572. * @param {number} idx
  23573. * @param {number} name
  23574. * @return {number}
  23575. */
  23576. listProto.indexOfName = function (name) {
  23577. for (var i = 0, len = this.count(); i < len; i++) {
  23578. if (this.getName(i) === name) {
  23579. return i;
  23580. }
  23581. }
  23582. return -1;
  23583. };
  23584. /**
  23585. * Retreive the index with given raw data index
  23586. * @param {number} idx
  23587. * @param {number} name
  23588. * @return {number}
  23589. */
  23590. listProto.indexOfRawIndex = function (rawIndex) {
  23591. if (!this._indices) {
  23592. return rawIndex;
  23593. }
  23594. if (rawIndex >= this._rawCount || rawIndex < 0) {
  23595. return -1;
  23596. }
  23597. // Indices are ascending
  23598. var indices = this._indices;
  23599. // If rawIndex === dataIndex
  23600. var rawDataIndex = indices[rawIndex];
  23601. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  23602. return rawIndex;
  23603. }
  23604. var left = 0;
  23605. var right = this._count - 1;
  23606. while (left <= right) {
  23607. var mid = (left + right) / 2 | 0;
  23608. if (indices[mid] < rawIndex) {
  23609. left = mid + 1;
  23610. }
  23611. else if (indices[mid] > rawIndex) {
  23612. right = mid - 1;
  23613. }
  23614. else {
  23615. return mid;
  23616. }
  23617. }
  23618. return -1;
  23619. };
  23620. /**
  23621. * Retreive the index of nearest value
  23622. * @param {string} dim
  23623. * @param {number} value
  23624. * @param {number} [maxDistance=Infinity]
  23625. * @return {Array.<number>} Considere multiple points has the same value.
  23626. */
  23627. listProto.indicesOfNearest = function (dim, value, maxDistance) {
  23628. var storage = this._storage;
  23629. var dimData = storage[dim];
  23630. var nearestIndices = [];
  23631. if (!dimData) {
  23632. return nearestIndices;
  23633. }
  23634. if (maxDistance == null) {
  23635. maxDistance = Infinity;
  23636. }
  23637. var minDist = Number.MAX_VALUE;
  23638. var minDiff = -1;
  23639. for (var i = 0, len = this.count(); i < len; i++) {
  23640. var diff = value - this.get(dim, i /*, stack */);
  23641. var dist = Math.abs(diff);
  23642. if (diff <= maxDistance && dist <= minDist) {
  23643. // For the case of two data are same on xAxis, which has sequence data.
  23644. // Show the nearest index
  23645. // https://github.com/ecomfe/echarts/issues/2869
  23646. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  23647. minDist = dist;
  23648. minDiff = diff;
  23649. nearestIndices.length = 0;
  23650. }
  23651. nearestIndices.push(i);
  23652. }
  23653. }
  23654. return nearestIndices;
  23655. };
  23656. /**
  23657. * Get raw data index
  23658. * @param {number} idx
  23659. * @return {number}
  23660. */
  23661. listProto.getRawIndex = getRawIndexWithoutIndices;
  23662. function getRawIndexWithoutIndices(idx) {
  23663. return idx;
  23664. }
  23665. function getRawIndexWithIndices(idx) {
  23666. if (idx < this._count && idx >= 0) {
  23667. return this._indices[idx];
  23668. }
  23669. return -1;
  23670. }
  23671. /**
  23672. * Get raw data item
  23673. * @param {number} idx
  23674. * @return {number}
  23675. */
  23676. listProto.getRawDataItem = function (idx) {
  23677. if (!this._rawData.persistent) {
  23678. var val = [];
  23679. for (var i = 0; i < this.dimensions.length; i++) {
  23680. var dim = this.dimensions[i];
  23681. val.push(this.get(dim, idx));
  23682. }
  23683. return val;
  23684. }
  23685. else {
  23686. return this._rawData.getItem(this.getRawIndex(idx));
  23687. }
  23688. };
  23689. /**
  23690. * @param {number} idx
  23691. * @param {boolean} [notDefaultIdx=false]
  23692. * @return {string}
  23693. */
  23694. listProto.getName = function (idx) {
  23695. var rawIndex = this.getRawIndex(idx);
  23696. return this._nameList[rawIndex]
  23697. || this._getNameFromStore(rawIndex)
  23698. || '';
  23699. };
  23700. /**
  23701. * @param {number} idx
  23702. * @param {boolean} [notDefaultIdx=false]
  23703. * @return {string}
  23704. */
  23705. listProto.getId = function (idx) {
  23706. return getId(this, this.getRawIndex(idx));
  23707. };
  23708. function getId(list, rawIndex) {
  23709. var id = list._idList[rawIndex];
  23710. if (id == null) {
  23711. id = list._getIdFromStore(rawIndex);
  23712. }
  23713. if (id == null) {
  23714. // FIXME Check the usage in graph, should not use prefix.
  23715. id = ID_PREFIX + rawIndex;
  23716. }
  23717. return id;
  23718. }
  23719. function normalizeDimensions(dimensions) {
  23720. if (!isArray(dimensions)) {
  23721. dimensions = [dimensions];
  23722. }
  23723. return dimensions;
  23724. }
  23725. function validateDimensions(list, dims) {
  23726. for (var i = 0; i < dims.length; i++) {
  23727. // stroage may be empty when no data, so use
  23728. // dimensionInfos to check.
  23729. if (!list._dimensionInfos[dims[i]]) {
  23730. console.error('Unkown dimension ' + dims[i]);
  23731. }
  23732. }
  23733. }
  23734. /**
  23735. * Data iteration
  23736. * @param {string|Array.<string>}
  23737. * @param {Function} cb
  23738. * @param {*} [context=this]
  23739. *
  23740. * @example
  23741. * list.each('x', function (x, idx) {});
  23742. * list.each(['x', 'y'], function (x, y, idx) {});
  23743. * list.each(function (idx) {})
  23744. */
  23745. listProto.each = function (dims, cb, context, contextCompat) {
  23746. 'use strict';
  23747. if (!this._count) {
  23748. return;
  23749. }
  23750. if (typeof dims === 'function') {
  23751. contextCompat = context;
  23752. context = cb;
  23753. cb = dims;
  23754. dims = [];
  23755. }
  23756. // contextCompat just for compat echarts3
  23757. context = context || contextCompat || this;
  23758. dims = map(normalizeDimensions(dims), this.getDimension, this);
  23759. if (__DEV__) {
  23760. validateDimensions(this, dims);
  23761. }
  23762. var dimSize = dims.length;
  23763. for (var i = 0; i < this.count(); i++) {
  23764. // Simple optimization
  23765. switch (dimSize) {
  23766. case 0:
  23767. cb.call(context, i);
  23768. break;
  23769. case 1:
  23770. cb.call(context, this.get(dims[0], i), i);
  23771. break;
  23772. case 2:
  23773. cb.call(context, this.get(dims[0], i), this.get(dims[1], i), i);
  23774. break;
  23775. default:
  23776. var k = 0;
  23777. var value = [];
  23778. for (; k < dimSize; k++) {
  23779. value[k] = this.get(dims[k], i);
  23780. }
  23781. // Index
  23782. value[k] = i;
  23783. cb.apply(context, value);
  23784. }
  23785. }
  23786. };
  23787. /**
  23788. * Data filter
  23789. * @param {string|Array.<string>}
  23790. * @param {Function} cb
  23791. * @param {*} [context=this]
  23792. */
  23793. listProto.filterSelf = function (dimensions, cb, context, contextCompat) {
  23794. 'use strict';
  23795. if (!this._count) {
  23796. return;
  23797. }
  23798. if (typeof dimensions === 'function') {
  23799. contextCompat = context;
  23800. context = cb;
  23801. cb = dimensions;
  23802. dimensions = [];
  23803. }
  23804. // contextCompat just for compat echarts3
  23805. context = context || contextCompat || this;
  23806. dimensions = map(
  23807. normalizeDimensions(dimensions), this.getDimension, this
  23808. );
  23809. if (__DEV__) {
  23810. validateDimensions(this, dimensions);
  23811. }
  23812. var count = this.count();
  23813. var Ctor = getIndicesCtor(this);
  23814. var newIndices = new Ctor(count);
  23815. var value = [];
  23816. var dimSize = dimensions.length;
  23817. var offset = 0;
  23818. var dim0 = dimensions[0];
  23819. for (var i = 0; i < count; i++) {
  23820. var keep;
  23821. var rawIdx = this.getRawIndex(i);
  23822. // Simple optimization
  23823. if (dimSize === 0) {
  23824. keep = cb.call(context, i);
  23825. }
  23826. else if (dimSize === 1) {
  23827. var val = this._getFast(dim0, rawIdx);
  23828. keep = cb.call(context, val, i);
  23829. }
  23830. else {
  23831. for (var k = 0; k < dimSize; k++) {
  23832. value[k] = this._getFast(dim0, rawIdx);
  23833. }
  23834. value[k] = i;
  23835. keep = cb.apply(context, value);
  23836. }
  23837. if (keep) {
  23838. newIndices[offset++] = rawIdx;
  23839. }
  23840. }
  23841. // Set indices after filtered.
  23842. if (offset < count) {
  23843. this._indices = newIndices;
  23844. }
  23845. this._count = offset;
  23846. // Reset data extent
  23847. this._extent = {};
  23848. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  23849. return this;
  23850. };
  23851. /**
  23852. * Select data in range. (For optimization of filter)
  23853. * (Manually inline code, support 5 million data filtering in data zoom.)
  23854. */
  23855. listProto.selectRange = function (range /*, stack */) {
  23856. 'use strict';
  23857. if (!this._count) {
  23858. return;
  23859. }
  23860. // stack = stack || false;
  23861. var dimensions = [];
  23862. for (var dim in range) {
  23863. if (range.hasOwnProperty(dim)) {
  23864. dimensions.push(dim);
  23865. }
  23866. }
  23867. if (__DEV__) {
  23868. validateDimensions(this, dimensions);
  23869. }
  23870. var dimSize = dimensions.length;
  23871. if (!dimSize) {
  23872. return;
  23873. }
  23874. var originalCount = this.count();
  23875. var Ctor = getIndicesCtor(this);
  23876. var newIndices = new Ctor(originalCount);
  23877. var offset = 0;
  23878. var dim0 = dimensions[0];
  23879. var min = range[dim0][0];
  23880. var max = range[dim0][1];
  23881. var quickFinished = false;
  23882. if (!this._indices /* && !stack */) {
  23883. // Extreme optimization for common case. About 2x faster in chrome.
  23884. var idx = 0;
  23885. if (dimSize === 1) {
  23886. var dimStorage = this._storage[dimensions[0]];
  23887. for (var k = 0; k < this._chunkCount; k++) {
  23888. var chunkStorage = dimStorage[k];
  23889. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  23890. for (var i = 0; i < len; i++) {
  23891. var val = chunkStorage[i];
  23892. if (val >= min && val <= max) {
  23893. newIndices[offset++] = idx;
  23894. }
  23895. idx++;
  23896. }
  23897. }
  23898. quickFinished = true;
  23899. }
  23900. else if (dimSize === 2) {
  23901. var dimStorage = this._storage[dim0];
  23902. var dimStorage2 = this._storage[dimensions[1]];
  23903. var min2 = range[dimensions[1]][0];
  23904. var max2 = range[dimensions[1]][1];
  23905. for (var k = 0; k < this._chunkCount; k++) {
  23906. var chunkStorage = dimStorage[k];
  23907. var chunkStorage2= dimStorage2[k];
  23908. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  23909. for (var i = 0; i < len; i++) {
  23910. var val = chunkStorage[i];
  23911. var val2 = chunkStorage2[i];
  23912. if (val >= min && val <= max && val2 >= min2 && val2 <= max2) {
  23913. newIndices[offset++] = idx;
  23914. }
  23915. idx++;
  23916. }
  23917. }
  23918. quickFinished = true;
  23919. }
  23920. }
  23921. if (!quickFinished) {
  23922. if (dimSize === 1) {
  23923. // stack = stack || !!this.getCalculationInfo(dim0);
  23924. for (var i = 0; i < originalCount; i++) {
  23925. var rawIndex = this.getRawIndex(i);
  23926. // var val = stack ? this.get(dim0, i, true) : this._getFast(dim0, rawIndex);
  23927. var val = this._getFast(dim0, rawIndex);
  23928. if (val >= min && val <= max) {
  23929. newIndices[offset++] = rawIndex;
  23930. }
  23931. }
  23932. }
  23933. else {
  23934. for (var i = 0; i < originalCount; i++) {
  23935. var keep = true;
  23936. var rawIndex = this.getRawIndex(i);
  23937. for (var k = 0; k < dimSize; k++) {
  23938. var dimk = dimensions[k];
  23939. // var val = stack ? this.get(dimk, i, true) : this._getFast(dim, rawIndex);
  23940. var val = this._getFast(dim, rawIndex);
  23941. if (val < range[dimk][0] || val > range[dimk][1]) {
  23942. keep = false;
  23943. }
  23944. }
  23945. if (keep) {
  23946. newIndices[offset++] = this.getRawIndex(i);
  23947. }
  23948. }
  23949. }
  23950. }
  23951. // Set indices after filtered.
  23952. if (offset < originalCount) {
  23953. this._indices = newIndices;
  23954. }
  23955. this._count = offset;
  23956. // Reset data extent
  23957. this._extent = {};
  23958. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  23959. return this;
  23960. };
  23961. /**
  23962. * Data mapping to a plain array
  23963. * @param {string|Array.<string>} [dimensions]
  23964. * @param {Function} cb
  23965. * @param {*} [context=this]
  23966. * @return {Array}
  23967. */
  23968. listProto.mapArray = function (dimensions, cb, context, contextCompat) {
  23969. 'use strict';
  23970. if (typeof dimensions === 'function') {
  23971. contextCompat = context;
  23972. context = cb;
  23973. cb = dimensions;
  23974. dimensions = [];
  23975. }
  23976. // contextCompat just for compat echarts3
  23977. context = context || contextCompat || this;
  23978. var result = [];
  23979. this.each(dimensions, function () {
  23980. result.push(cb && cb.apply(this, arguments));
  23981. }, context);
  23982. return result;
  23983. };
  23984. // Data in excludeDimensions is copied, otherwise transfered.
  23985. function cloneListForMapAndSample(original, excludeDimensions) {
  23986. var allDimensions = original.dimensions;
  23987. var list = new List(
  23988. map(allDimensions, original.getDimensionInfo, original),
  23989. original.hostModel
  23990. );
  23991. // FIXME If needs stackedOn, value may already been stacked
  23992. transferProperties(list, original);
  23993. var storage = list._storage = {};
  23994. var originalStorage = original._storage;
  23995. var rawExtent = extend({}, original._rawExtent);
  23996. // Init storage
  23997. for (var i = 0; i < allDimensions.length; i++) {
  23998. var dim = allDimensions[i];
  23999. if (originalStorage[dim]) {
  24000. if (indexOf(excludeDimensions, dim) >= 0) {
  24001. storage[dim] = cloneDimStore(originalStorage[dim]);
  24002. rawExtent[dim] = getInitialExtent();
  24003. }
  24004. else {
  24005. // Direct reference for other dimensions
  24006. storage[dim] = originalStorage[dim];
  24007. }
  24008. }
  24009. }
  24010. return list;
  24011. }
  24012. function cloneDimStore(originalDimStore) {
  24013. var newDimStore = new Array(originalDimStore.length);
  24014. for (var j = 0; j < originalDimStore.length; j++) {
  24015. newDimStore[j] = cloneChunk(originalDimStore[j]);
  24016. }
  24017. return newDimStore;
  24018. }
  24019. function getInitialExtent() {
  24020. return [Infinity, -Infinity];
  24021. }
  24022. /**
  24023. * Data mapping to a new List with given dimensions
  24024. * @param {string|Array.<string>} dimensions
  24025. * @param {Function} cb
  24026. * @param {*} [context=this]
  24027. * @return {Array}
  24028. */
  24029. listProto.map = function (dimensions, cb, context, contextCompat) {
  24030. 'use strict';
  24031. // contextCompat just for compat echarts3
  24032. context = context || contextCompat || this;
  24033. dimensions = map(
  24034. normalizeDimensions(dimensions), this.getDimension, this
  24035. );
  24036. if (__DEV__) {
  24037. validateDimensions(this, dimensions);
  24038. }
  24039. var list = cloneListForMapAndSample(this, dimensions);
  24040. // Following properties are all immutable.
  24041. // So we can reference to the same value
  24042. list._indices = this._indices;
  24043. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  24044. var storage = list._storage;
  24045. var tmpRetValue = [];
  24046. var chunkSize = this._chunkSize;
  24047. var dimSize = dimensions.length;
  24048. var dataCount = this.count();
  24049. var values = [];
  24050. var rawExtent = list._rawExtent;
  24051. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  24052. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  24053. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex /*, stack */);
  24054. }
  24055. values[dimSize] = dataIndex;
  24056. var retValue = cb && cb.apply(context, values);
  24057. if (retValue != null) {
  24058. // a number or string (in oridinal dimension)?
  24059. if (typeof retValue !== 'object') {
  24060. tmpRetValue[0] = retValue;
  24061. retValue = tmpRetValue;
  24062. }
  24063. var rawIndex = this.getRawIndex(dataIndex);
  24064. var chunkIndex = Math.floor(rawIndex / chunkSize);
  24065. var chunkOffset = rawIndex % chunkSize;
  24066. for (var i = 0; i < retValue.length; i++) {
  24067. var dim = dimensions[i];
  24068. var val = retValue[i];
  24069. var rawExtentOnDim = rawExtent[dim];
  24070. var dimStore = storage[dim];
  24071. if (dimStore) {
  24072. dimStore[chunkIndex][chunkOffset] = val;
  24073. }
  24074. if (val < rawExtentOnDim[0]) {
  24075. rawExtentOnDim[0] = val;
  24076. }
  24077. if (val > rawExtentOnDim[1]) {
  24078. rawExtentOnDim[1] = val;
  24079. }
  24080. }
  24081. }
  24082. }
  24083. return list;
  24084. };
  24085. /**
  24086. * Large data down sampling on given dimension
  24087. * @param {string} dimension
  24088. * @param {number} rate
  24089. * @param {Function} sampleValue
  24090. * @param {Function} sampleIndex Sample index for name and id
  24091. */
  24092. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  24093. var list = cloneListForMapAndSample(this, [dimension]);
  24094. var targetStorage = list._storage;
  24095. var frameValues = [];
  24096. var frameSize = Math.floor(1 / rate);
  24097. var dimStore = targetStorage[dimension];
  24098. var len = this.count();
  24099. var chunkSize = this._chunkSize;
  24100. var rawExtentOnDim = list._rawExtent[dimension];
  24101. var newIndices = new (getIndicesCtor(this))(len);
  24102. var offset = 0;
  24103. for (var i = 0; i < len; i += frameSize) {
  24104. // Last frame
  24105. if (frameSize > len - i) {
  24106. frameSize = len - i;
  24107. frameValues.length = frameSize;
  24108. }
  24109. for (var k = 0; k < frameSize; k++) {
  24110. var dataIdx = this.getRawIndex(i + k);
  24111. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  24112. var originalChunkOffset = dataIdx % chunkSize;
  24113. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  24114. }
  24115. var value = sampleValue(frameValues);
  24116. var sampleFrameIdx = this.getRawIndex(
  24117. Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
  24118. );
  24119. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  24120. var sampleChunkOffset = sampleFrameIdx % chunkSize;
  24121. // Only write value on the filtered data
  24122. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  24123. if (value < rawExtentOnDim[0]) {
  24124. rawExtentOnDim[0] = value;
  24125. }
  24126. if (value > rawExtentOnDim[1]) {
  24127. rawExtentOnDim[1] = value;
  24128. }
  24129. newIndices[offset++] = sampleFrameIdx;
  24130. }
  24131. list._count = offset;
  24132. list._indices = newIndices;
  24133. list.getRawIndex = getRawIndexWithIndices;
  24134. return list;
  24135. };
  24136. /**
  24137. * Get model of one data item.
  24138. *
  24139. * @param {number} idx
  24140. */
  24141. // FIXME Model proxy ?
  24142. listProto.getItemModel = function (idx) {
  24143. var hostModel = this.hostModel;
  24144. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  24145. };
  24146. /**
  24147. * Create a data differ
  24148. * @param {module:echarts/data/List} otherList
  24149. * @return {module:echarts/data/DataDiffer}
  24150. */
  24151. listProto.diff = function (otherList) {
  24152. var thisList = this;
  24153. return new DataDiffer(
  24154. otherList ? otherList.getIndices() : [],
  24155. this.getIndices(),
  24156. function (idx) {
  24157. return getId(otherList, idx);
  24158. },
  24159. function (idx) {
  24160. return getId(thisList, idx);
  24161. }
  24162. );
  24163. };
  24164. /**
  24165. * Get visual property.
  24166. * @param {string} key
  24167. */
  24168. listProto.getVisual = function (key) {
  24169. var visual = this._visual;
  24170. return visual && visual[key];
  24171. };
  24172. /**
  24173. * Set visual property
  24174. * @param {string|Object} key
  24175. * @param {*} [value]
  24176. *
  24177. * @example
  24178. * setVisual('color', color);
  24179. * setVisual({
  24180. * 'color': color
  24181. * });
  24182. */
  24183. listProto.setVisual = function (key, val) {
  24184. if (isObject$4(key)) {
  24185. for (var name in key) {
  24186. if (key.hasOwnProperty(name)) {
  24187. this.setVisual(name, key[name]);
  24188. }
  24189. }
  24190. return;
  24191. }
  24192. this._visual = this._visual || {};
  24193. this._visual[key] = val;
  24194. };
  24195. /**
  24196. * Set layout property.
  24197. * @param {string|Object} key
  24198. * @param {*} [val]
  24199. */
  24200. listProto.setLayout = function (key, val) {
  24201. if (isObject$4(key)) {
  24202. for (var name in key) {
  24203. if (key.hasOwnProperty(name)) {
  24204. this.setLayout(name, key[name]);
  24205. }
  24206. }
  24207. return;
  24208. }
  24209. this._layout[key] = val;
  24210. };
  24211. /**
  24212. * Get layout property.
  24213. * @param {string} key.
  24214. * @return {*}
  24215. */
  24216. listProto.getLayout = function (key) {
  24217. return this._layout[key];
  24218. };
  24219. /**
  24220. * Get layout of single data item
  24221. * @param {number} idx
  24222. */
  24223. listProto.getItemLayout = function (idx) {
  24224. return this._itemLayouts[idx];
  24225. };
  24226. /**
  24227. * Set layout of single data item
  24228. * @param {number} idx
  24229. * @param {Object} layout
  24230. * @param {boolean=} [merge=false]
  24231. */
  24232. listProto.setItemLayout = function (idx, layout, merge$$1) {
  24233. this._itemLayouts[idx] = merge$$1
  24234. ? extend(this._itemLayouts[idx] || {}, layout)
  24235. : layout;
  24236. };
  24237. /**
  24238. * Clear all layout of single data item
  24239. */
  24240. listProto.clearItemLayouts = function () {
  24241. this._itemLayouts.length = 0;
  24242. };
  24243. /**
  24244. * Get visual property of single data item
  24245. * @param {number} idx
  24246. * @param {string} key
  24247. * @param {boolean} [ignoreParent=false]
  24248. */
  24249. listProto.getItemVisual = function (idx, key, ignoreParent) {
  24250. var itemVisual = this._itemVisuals[idx];
  24251. var val = itemVisual && itemVisual[key];
  24252. if (val == null && !ignoreParent) {
  24253. // Use global visual property
  24254. return this.getVisual(key);
  24255. }
  24256. return val;
  24257. };
  24258. /**
  24259. * Set visual property of single data item
  24260. *
  24261. * @param {number} idx
  24262. * @param {string|Object} key
  24263. * @param {*} [value]
  24264. *
  24265. * @example
  24266. * setItemVisual(0, 'color', color);
  24267. * setItemVisual(0, {
  24268. * 'color': color
  24269. * });
  24270. */
  24271. listProto.setItemVisual = function (idx, key, value) {
  24272. var itemVisual = this._itemVisuals[idx] || {};
  24273. var hasItemVisual = this.hasItemVisual;
  24274. this._itemVisuals[idx] = itemVisual;
  24275. if (isObject$4(key)) {
  24276. for (var name in key) {
  24277. if (key.hasOwnProperty(name)) {
  24278. itemVisual[name] = key[name];
  24279. hasItemVisual[name] = true;
  24280. }
  24281. }
  24282. return;
  24283. }
  24284. itemVisual[key] = value;
  24285. hasItemVisual[key] = true;
  24286. };
  24287. /**
  24288. * Clear itemVisuals and list visual.
  24289. */
  24290. listProto.clearAllVisual = function () {
  24291. this._visual = {};
  24292. this._itemVisuals = [];
  24293. this.hasItemVisual = {};
  24294. };
  24295. var setItemDataAndSeriesIndex = function (child) {
  24296. child.seriesIndex = this.seriesIndex;
  24297. child.dataIndex = this.dataIndex;
  24298. child.dataType = this.dataType;
  24299. };
  24300. /**
  24301. * Set graphic element relative to data. It can be set as null
  24302. * @param {number} idx
  24303. * @param {module:zrender/Element} [el]
  24304. */
  24305. listProto.setItemGraphicEl = function (idx, el) {
  24306. var hostModel = this.hostModel;
  24307. if (el) {
  24308. // Add data index and series index for indexing the data by element
  24309. // Useful in tooltip
  24310. el.dataIndex = idx;
  24311. el.dataType = this.dataType;
  24312. el.seriesIndex = hostModel && hostModel.seriesIndex;
  24313. if (el.type === 'group') {
  24314. el.traverse(setItemDataAndSeriesIndex, el);
  24315. }
  24316. }
  24317. this._graphicEls[idx] = el;
  24318. };
  24319. /**
  24320. * @param {number} idx
  24321. * @return {module:zrender/Element}
  24322. */
  24323. listProto.getItemGraphicEl = function (idx) {
  24324. return this._graphicEls[idx];
  24325. };
  24326. /**
  24327. * @param {Function} cb
  24328. * @param {*} context
  24329. */
  24330. listProto.eachItemGraphicEl = function (cb, context) {
  24331. each$1(this._graphicEls, function (el, idx) {
  24332. if (el) {
  24333. cb && cb.call(context, el, idx);
  24334. }
  24335. });
  24336. };
  24337. /**
  24338. * Shallow clone a new list except visual and layout properties, and graph elements.
  24339. * New list only change the indices.
  24340. */
  24341. listProto.cloneShallow = function (list) {
  24342. if (!list) {
  24343. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  24344. list = new List(dimensionInfoList, this.hostModel);
  24345. }
  24346. // FIXME
  24347. list._storage = this._storage;
  24348. transferProperties(list, this);
  24349. // Clone will not change the data extent and indices
  24350. if (this._indices) {
  24351. var Ctor = this._indices.constructor;
  24352. list._indices = new Ctor(this._indices);
  24353. }
  24354. else {
  24355. list._indices = null;
  24356. }
  24357. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  24358. list._extent = clone(this._extent);
  24359. list._approximateExtent = clone(this._approximateExtent);
  24360. return list;
  24361. };
  24362. /**
  24363. * Wrap some method to add more feature
  24364. * @param {string} methodName
  24365. * @param {Function} injectFunction
  24366. */
  24367. listProto.wrapMethod = function (methodName, injectFunction) {
  24368. var originalMethod = this[methodName];
  24369. if (typeof originalMethod !== 'function') {
  24370. return;
  24371. }
  24372. this.__wrappedMethods = this.__wrappedMethods || [];
  24373. this.__wrappedMethods.push(methodName);
  24374. this[methodName] = function () {
  24375. var res = originalMethod.apply(this, arguments);
  24376. return injectFunction.apply(this, [res].concat(slice(arguments)));
  24377. };
  24378. };
  24379. // Methods that create a new list based on this list should be listed here.
  24380. // Notice that those method should `RETURN` the new list.
  24381. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  24382. // Methods that change indices of this list should be listed here.
  24383. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  24384. /**
  24385. * @deprecated
  24386. * Use `echarts/data/helper/createDimensions` instead.
  24387. */
  24388. /**
  24389. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  24390. *
  24391. * Complete the dimensions array, by user defined `dimension` and `encode`,
  24392. * and guessing from the data structure.
  24393. * If no 'value' dimension specified, the first no-named dimension will be
  24394. * named as 'value'.
  24395. *
  24396. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  24397. * provides not only dim template, but also default order.
  24398. * properties: 'name', 'type', 'displayName'.
  24399. * `name` of each item provides default coord name.
  24400. * [{dimsDef: [string...]}, ...] dimsDef of sysDim item provides default dim name, and
  24401. * provide dims count that the sysDim required.
  24402. * [{ordinalMeta}] can be specified.
  24403. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  24404. * @param {Object} [opt]
  24405. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  24406. * For example: ['asdf', {name, type}, ...].
  24407. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  24408. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  24409. * If not specified, extra dim names will be:
  24410. * 'value', 'value0', 'value1', ...
  24411. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  24412. * If `generateCoordCount` specified, the generated dim names will be:
  24413. * `generateCoord` + 0, `generateCoord` + 1, ...
  24414. * can be Infinity, indicate that use all of the remain columns.
  24415. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  24416. * @param {number} [opt.encodeDefaulter] If not specified, auto find the next available data dim.
  24417. * @return {Array.<Object>} [{
  24418. * name: string mandatory,
  24419. * displayName: string, the origin name in dimsDef, see source helper.
  24420. * If displayName given, the tooltip will displayed vertically.
  24421. * coordDim: string mandatory,
  24422. * coordDimIndex: number mandatory,
  24423. * type: string optional,
  24424. * otherDims: { never null/undefined
  24425. * tooltip: number optional,
  24426. * label: number optional,
  24427. * itemName: number optional,
  24428. * seriesName: number optional,
  24429. * },
  24430. * isExtraCoord: boolean true if coord is generated
  24431. * (not specified in encode and not series specified)
  24432. * other props ...
  24433. * }]
  24434. */
  24435. function completeDimensions(sysDims, source, opt) {
  24436. if (!Source.isInstance(source)) {
  24437. source = Source.seriesDataToSource(source);
  24438. }
  24439. opt = opt || {};
  24440. sysDims = (sysDims || []).slice();
  24441. var dimsDef = (opt.dimsDef || []).slice();
  24442. var encodeDef = createHashMap(opt.encodeDef);
  24443. var dataDimNameMap = createHashMap();
  24444. var coordDimNameMap = createHashMap();
  24445. // var valueCandidate;
  24446. var result = [];
  24447. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount);
  24448. // Apply user defined dims (`name` and `type`) and init result.
  24449. for (var i = 0; i < dimCount; i++) {
  24450. var dimDefItem = dimsDef[i] = extend(
  24451. {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]}
  24452. );
  24453. var userDimName = dimDefItem.name;
  24454. var resultItem = result[i] = {otherDims: {}};
  24455. // Name will be applied later for avoiding duplication.
  24456. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  24457. // Only if `series.dimensions` is defined in option
  24458. // displayName, will be set, and dimension will be diplayed vertically in
  24459. // tooltip by default.
  24460. resultItem.name = resultItem.displayName = userDimName;
  24461. dataDimNameMap.set(userDimName, i);
  24462. }
  24463. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  24464. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  24465. }
  24466. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  24467. encodeDef.each(function (dataDims, coordDim) {
  24468. dataDims = normalizeToArray(dataDims).slice();
  24469. var validDataDims = encodeDef.set(coordDim, []);
  24470. each$1(dataDims, function (resultDimIdx, idx) {
  24471. // The input resultDimIdx can be dim name or index.
  24472. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  24473. if (resultDimIdx != null && resultDimIdx < dimCount) {
  24474. validDataDims[idx] = resultDimIdx;
  24475. applyDim(result[resultDimIdx], coordDim, idx);
  24476. }
  24477. });
  24478. });
  24479. // Apply templetes and default order from `sysDims`.
  24480. var availDimIdx = 0;
  24481. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  24482. var coordDim;
  24483. var sysDimItem;
  24484. var sysDimItemDimsDef;
  24485. var sysDimItemOtherDims;
  24486. if (isString(sysDimItem)) {
  24487. coordDim = sysDimItem;
  24488. sysDimItem = {};
  24489. }
  24490. else {
  24491. coordDim = sysDimItem.name;
  24492. var ordinalMeta = sysDimItem.ordinalMeta;
  24493. sysDimItem.ordinalMeta = null;
  24494. sysDimItem = clone(sysDimItem);
  24495. sysDimItem.ordinalMeta = ordinalMeta;
  24496. // `coordDimIndex` should not be set directly.
  24497. sysDimItemDimsDef = sysDimItem.dimsDef;
  24498. sysDimItemOtherDims = sysDimItem.otherDims;
  24499. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex
  24500. = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  24501. }
  24502. var dataDims = normalizeToArray(encodeDef.get(coordDim));
  24503. // dimensions provides default dim sequences.
  24504. if (!dataDims.length) {
  24505. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  24506. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  24507. availDimIdx++;
  24508. }
  24509. availDimIdx < result.length && dataDims.push(availDimIdx++);
  24510. }
  24511. }
  24512. // Apply templates.
  24513. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  24514. var resultItem = result[resultDimIdx];
  24515. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  24516. if (resultItem.name == null && sysDimItemDimsDef) {
  24517. resultItem.name = resultItem.displayName = sysDimItemDimsDef[coordDimIndex];
  24518. }
  24519. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  24520. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  24521. });
  24522. });
  24523. function applyDim(resultItem, coordDim, coordDimIndex) {
  24524. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  24525. resultItem.otherDims[coordDim] = coordDimIndex;
  24526. }
  24527. else {
  24528. resultItem.coordDim = coordDim;
  24529. resultItem.coordDimIndex = coordDimIndex;
  24530. coordDimNameMap.set(coordDim, true);
  24531. }
  24532. }
  24533. // Make sure the first extra dim is 'value'.
  24534. var generateCoord = opt.generateCoord;
  24535. var generateCoordCount = opt.generateCoordCount;
  24536. var fromZero = generateCoordCount != null;
  24537. generateCoordCount = generateCoord ? (generateCoordCount || 1) : 0;
  24538. var extra = generateCoord || 'value';
  24539. // Set dim `name` and other `coordDim` and other props.
  24540. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  24541. var resultItem = result[resultDimIdx] = result[resultDimIdx] || {};
  24542. var coordDim = resultItem.coordDim;
  24543. if (coordDim == null) {
  24544. resultItem.coordDim = genName(
  24545. extra, coordDimNameMap, fromZero
  24546. );
  24547. resultItem.coordDimIndex = 0;
  24548. if (!generateCoord || generateCoordCount <= 0) {
  24549. resultItem.isExtraCoord = true;
  24550. }
  24551. generateCoordCount--;
  24552. }
  24553. resultItem.name == null && (resultItem.name = genName(
  24554. resultItem.coordDim,
  24555. dataDimNameMap
  24556. ));
  24557. if (resultItem.type == null && guessOrdinal(source, resultDimIdx, resultItem.name)) {
  24558. resultItem.type = 'ordinal';
  24559. }
  24560. }
  24561. return result;
  24562. }
  24563. // ??? TODO
  24564. // Originally detect dimCount by data[0]. Should we
  24565. // optimize it to only by sysDims and dimensions and encode.
  24566. // So only necessary dims will be initialized.
  24567. // But
  24568. // (1) custom series should be considered. where other dims
  24569. // may be visited.
  24570. // (2) sometimes user need to calcualte bubble size or use visualMap
  24571. // on other dimensions besides coordSys needed.
  24572. // So, dims that is not used by system, should be shared in storage?
  24573. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  24574. // Note that the result dimCount should not small than columns count
  24575. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  24576. var dimCount = Math.max(
  24577. source.dimensionsDetectCount || 1,
  24578. sysDims.length,
  24579. dimsDef.length,
  24580. optDimCount || 0
  24581. );
  24582. each$1(sysDims, function (sysDimItem) {
  24583. var sysDimItemDimsDef = sysDimItem.dimsDef;
  24584. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  24585. });
  24586. return dimCount;
  24587. }
  24588. function genName(name, map$$1, fromZero) {
  24589. if (fromZero || map$$1.get(name) != null) {
  24590. var i = 0;
  24591. while (map$$1.get(name + i) != null) {
  24592. i++;
  24593. }
  24594. name += i;
  24595. }
  24596. map$$1.set(name, true);
  24597. return name;
  24598. }
  24599. /**
  24600. * Substitute `completeDimensions`.
  24601. * `completeDimensions` is to be deprecated.
  24602. */
  24603. /**
  24604. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  24605. * @param {Object|Array} [opt]
  24606. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  24607. * @param {number} [opt.dimensionsCount]
  24608. * @param {string} [opt.generateCoord]
  24609. * @param {string} [opt.generateCoordCount]
  24610. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  24611. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  24612. * @return {Array.<Object>} dimensionsInfo
  24613. */
  24614. var createDimensions = function (source, opt) {
  24615. opt = opt || {};
  24616. return completeDimensions(opt.coordDimensions || [], source, {
  24617. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  24618. encodeDef: opt.encodeDefine || source.encodeDefine,
  24619. dimCount: opt.dimensionsCount,
  24620. generateCoord: opt.generateCoord,
  24621. generateCoordCount: opt.generateCoordCount
  24622. });
  24623. };
  24624. /**
  24625. * Note that it is too complicated to support 3d stack by value
  24626. * (have to create two-dimension inverted index), so in 3d case
  24627. * we just support that stacked by index.
  24628. *
  24629. * @param {module:echarts/model/Series} seriesModel
  24630. * @param {Array.<string|Object>} dimensionInfoList The same as the input of <module:echarts/data/List>.
  24631. * The input dimensionInfoList will be modified.
  24632. * @param {Object} [opt]
  24633. * @param {boolean} [opt.stackedCoordDimension=''] Specify a coord dimension if needed.
  24634. * @param {boolean} [opt.byIndex=false]
  24635. * @return {Object} calculationInfo
  24636. * {
  24637. * stackedDimension: string
  24638. * stackedByDimension: string
  24639. * isStackedByIndex: boolean
  24640. * stackedOverDimension: string
  24641. * stackResultDimension: string
  24642. * }
  24643. */
  24644. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  24645. opt = opt || {};
  24646. var byIndex = opt.byIndex;
  24647. var stackedCoordDimension = opt.stackedCoordDimension;
  24648. // Compatibal: when `stack` is set as '', do not stack.
  24649. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  24650. var stackedByDimInfo;
  24651. var stackedDimInfo;
  24652. var stackResultDimension;
  24653. var stackedOverDimension;
  24654. each$1(dimensionInfoList, function (dimensionInfo, index) {
  24655. if (isString(dimensionInfo)) {
  24656. dimensionInfoList[index] = dimensionInfo = {name: dimensionInfo};
  24657. }
  24658. if (mayStack && !dimensionInfo.isExtraCoord) {
  24659. // Find the first ordinal dimension as the stackedByDimInfo.
  24660. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  24661. stackedByDimInfo = dimensionInfo;
  24662. }
  24663. // Find the first stackable dimension as the stackedDimInfo.
  24664. if (!stackedDimInfo
  24665. && dimensionInfo.type !== 'ordinal'
  24666. && dimensionInfo.type !== 'time'
  24667. && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)
  24668. ) {
  24669. stackedDimInfo = dimensionInfo;
  24670. }
  24671. }
  24672. });
  24673. // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  24674. // That put stack logic in List is for using conveniently in echarts extensions, but it
  24675. // might not be a good way.
  24676. if (stackedDimInfo && (byIndex || stackedByDimInfo)) {
  24677. // Use a weird name that not duplicated with other names.
  24678. stackResultDimension = '__\0ecstackresult';
  24679. stackedOverDimension = '__\0ecstackedover';
  24680. // Create inverted index to fast query index by value.
  24681. if (stackedByDimInfo) {
  24682. stackedByDimInfo.createInvertedIndices = true;
  24683. }
  24684. var stackedDimCoordDim = stackedDimInfo.coordDim;
  24685. var stackedDimType = stackedDimInfo.type;
  24686. var stackedDimCoordIndex = 0;
  24687. each$1(dimensionInfoList, function (dimensionInfo) {
  24688. if (dimensionInfo.coordDim === stackedDimCoordDim) {
  24689. stackedDimCoordIndex++;
  24690. }
  24691. });
  24692. dimensionInfoList.push({
  24693. name: stackResultDimension,
  24694. coordDim: stackedDimCoordDim,
  24695. coordDimIndex: stackedDimCoordIndex,
  24696. type: stackedDimType,
  24697. isExtraCoord: true,
  24698. isCalculationCoord: true
  24699. });
  24700. stackedDimCoordIndex++;
  24701. dimensionInfoList.push({
  24702. name: stackedOverDimension,
  24703. // This dimension contains stack base (generally, 0), so do not set it as
  24704. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  24705. coordDim: stackedOverDimension,
  24706. coordDimIndex: stackedDimCoordIndex,
  24707. type: stackedDimType,
  24708. isExtraCoord: true,
  24709. isCalculationCoord: true
  24710. });
  24711. }
  24712. return {
  24713. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  24714. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  24715. isStackedByIndex: byIndex,
  24716. stackedOverDimension: stackedOverDimension,
  24717. stackResultDimension: stackResultDimension
  24718. };
  24719. }
  24720. /**
  24721. * @param {module:echarts/data/List} data
  24722. * @param {string} stackedDim
  24723. * @param {string} [stackedByDim] If not input this parameter, check whether
  24724. * stacked by index.
  24725. */
  24726. function isDimensionStacked(data, stackedDim, stackedByDim) {
  24727. return stackedDim
  24728. && stackedDim === data.getCalculationInfo('stackedDimension')
  24729. && (
  24730. stackedByDim != null
  24731. ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  24732. : data.getCalculationInfo('isStackedByIndex')
  24733. );
  24734. }
  24735. /**
  24736. * @param {module:echarts/data/Source|Array} source Or raw data.
  24737. * @param {module:echarts/model/Series} seriesModel
  24738. * @param {Object} [opt]
  24739. * @param {string} [opt.generateCoord]
  24740. */
  24741. function createListFromArray(source, seriesModel, opt) {
  24742. opt = opt || {};
  24743. if (!Source.isInstance(source)) {
  24744. source = Source.seriesDataToSource(source);
  24745. }
  24746. var coordSysName = seriesModel.get('coordinateSystem');
  24747. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  24748. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  24749. var coordSysDimDefs;
  24750. if (coordSysDefine) {
  24751. coordSysDimDefs = map(coordSysDefine.coordSysDims, function (dim) {
  24752. var dimInfo = {name: dim};
  24753. var axisModel = coordSysDefine.axisMap.get(dim);
  24754. if (axisModel) {
  24755. var axisType = axisModel.get('type');
  24756. dimInfo.type = getDimensionTypeByAxis(axisType);
  24757. // dimInfo.stackable = isStackable(axisType);
  24758. }
  24759. return dimInfo;
  24760. });
  24761. }
  24762. if (!coordSysDimDefs) {
  24763. // Get dimensions from registered coordinate system
  24764. coordSysDimDefs = (registeredCoordSys && (
  24765. registeredCoordSys.getDimensionsInfo
  24766. ? registeredCoordSys.getDimensionsInfo()
  24767. : registeredCoordSys.dimensions.slice()
  24768. )) || ['x', 'y'];
  24769. }
  24770. var dimInfoList = createDimensions(source, {
  24771. coordDimensions: coordSysDimDefs,
  24772. generateCoord: opt.generateCoord
  24773. });
  24774. var firstCategoryDimIndex;
  24775. var hasNameEncode;
  24776. coordSysDefine && each$1(dimInfoList, function (dimInfo, dimIndex) {
  24777. var coordDim = dimInfo.coordDim;
  24778. var categoryAxisModel = coordSysDefine.categoryAxisMap.get(coordDim);
  24779. if (categoryAxisModel) {
  24780. if (firstCategoryDimIndex == null) {
  24781. firstCategoryDimIndex = dimIndex;
  24782. }
  24783. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  24784. }
  24785. if (dimInfo.otherDims.itemName != null) {
  24786. hasNameEncode = true;
  24787. }
  24788. });
  24789. if (!hasNameEncode && firstCategoryDimIndex != null) {
  24790. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  24791. }
  24792. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  24793. var list = new List(dimInfoList, seriesModel);
  24794. list.setCalculationInfo(stackCalculationInfo);
  24795. var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source))
  24796. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  24797. // Use dataIndex as ordinal value in categoryAxis
  24798. return dimIndex === firstCategoryDimIndex
  24799. ? dataIndex
  24800. : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  24801. }
  24802. : null;
  24803. list.hasItemOption = false;
  24804. list.initData(source, null, dimValueGetter);
  24805. return list;
  24806. }
  24807. function isNeedCompleteOrdinalData(source) {
  24808. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  24809. var sampleItem = firstDataNotNull(source.data || []);
  24810. return sampleItem != null
  24811. && !isArray(getDataItemValue(sampleItem));
  24812. }
  24813. }
  24814. function firstDataNotNull(data) {
  24815. var i = 0;
  24816. while (i < data.length && data[i] == null) {
  24817. i++;
  24818. }
  24819. return data[i];
  24820. }
  24821. /**
  24822. * // Scale class management
  24823. * @module echarts/scale/Scale
  24824. */
  24825. /**
  24826. * @param {Object} [setting]
  24827. */
  24828. function Scale(setting) {
  24829. this._setting = setting || {};
  24830. /**
  24831. * Extent
  24832. * @type {Array.<number>}
  24833. * @protected
  24834. */
  24835. this._extent = [Infinity, -Infinity];
  24836. /**
  24837. * Step is calculated in adjustExtent
  24838. * @type {Array.<number>}
  24839. * @protected
  24840. */
  24841. this._interval = 0;
  24842. this.init && this.init.apply(this, arguments);
  24843. }
  24844. /**
  24845. * Parse input val to valid inner number.
  24846. * @param {*} val
  24847. * @return {number}
  24848. */
  24849. Scale.prototype.parse = function (val) {
  24850. // Notice: This would be a trap here, If the implementation
  24851. // of this method depends on extent, and this method is used
  24852. // before extent set (like in dataZoom), it would be wrong.
  24853. // Nevertheless, parse does not depend on extent generally.
  24854. return val;
  24855. };
  24856. Scale.prototype.getSetting = function (name) {
  24857. return this._setting[name];
  24858. };
  24859. Scale.prototype.contain = function (val) {
  24860. var extent = this._extent;
  24861. return val >= extent[0] && val <= extent[1];
  24862. };
  24863. /**
  24864. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  24865. * @param {number} val
  24866. * @return {number}
  24867. */
  24868. Scale.prototype.normalize = function (val) {
  24869. var extent = this._extent;
  24870. if (extent[1] === extent[0]) {
  24871. return 0.5;
  24872. }
  24873. return (val - extent[0]) / (extent[1] - extent[0]);
  24874. };
  24875. /**
  24876. * Scale normalized value
  24877. * @param {number} val
  24878. * @return {number}
  24879. */
  24880. Scale.prototype.scale = function (val) {
  24881. var extent = this._extent;
  24882. return val * (extent[1] - extent[0]) + extent[0];
  24883. };
  24884. /**
  24885. * Set extent from data
  24886. * @param {Array.<number>} other
  24887. */
  24888. Scale.prototype.unionExtent = function (other) {
  24889. var extent = this._extent;
  24890. other[0] < extent[0] && (extent[0] = other[0]);
  24891. other[1] > extent[1] && (extent[1] = other[1]);
  24892. // not setExtent because in log axis it may transformed to power
  24893. // this.setExtent(extent[0], extent[1]);
  24894. };
  24895. /**
  24896. * Set extent from data
  24897. * @param {module:echarts/data/List} data
  24898. * @param {string} dim
  24899. */
  24900. Scale.prototype.unionExtentFromData = function (data, dim) {
  24901. this.unionExtent(data.getApproximateExtent(dim));
  24902. };
  24903. /**
  24904. * Get extent
  24905. * @return {Array.<number>}
  24906. */
  24907. Scale.prototype.getExtent = function () {
  24908. return this._extent.slice();
  24909. };
  24910. /**
  24911. * Set extent
  24912. * @param {number} start
  24913. * @param {number} end
  24914. */
  24915. Scale.prototype.setExtent = function (start, end) {
  24916. var thisExtent = this._extent;
  24917. if (!isNaN(start)) {
  24918. thisExtent[0] = start;
  24919. }
  24920. if (!isNaN(end)) {
  24921. thisExtent[1] = end;
  24922. }
  24923. };
  24924. /**
  24925. * @return {Array.<string>}
  24926. */
  24927. Scale.prototype.getTicksLabels = function () {
  24928. var labels = [];
  24929. var ticks = this.getTicks();
  24930. for (var i = 0; i < ticks.length; i++) {
  24931. labels.push(this.getLabel(ticks[i]));
  24932. }
  24933. return labels;
  24934. };
  24935. /**
  24936. * When axis extent depends on data and no data exists,
  24937. * axis ticks should not be drawn, which is named 'blank'.
  24938. */
  24939. Scale.prototype.isBlank = function () {
  24940. return this._isBlank;
  24941. },
  24942. /**
  24943. * When axis extent depends on data and no data exists,
  24944. * axis ticks should not be drawn, which is named 'blank'.
  24945. */
  24946. Scale.prototype.setBlank = function (isBlank) {
  24947. this._isBlank = isBlank;
  24948. };
  24949. enableClassExtend(Scale);
  24950. enableClassManagement(Scale, {
  24951. registerWhenExtend: true
  24952. });
  24953. /**
  24954. * @constructor
  24955. * @param {Object} [opt]
  24956. * @param {Object} [opt.categories=[]]
  24957. * @param {Object} [opt.needCollect=false]
  24958. * @param {Object} [opt.deduplication=false]
  24959. */
  24960. function OrdinalMeta(opt) {
  24961. /**
  24962. * @readOnly
  24963. * @type {Array.<string>}
  24964. */
  24965. this.categories = opt.categories || [];
  24966. /**
  24967. * @private
  24968. * @type {boolean}
  24969. */
  24970. this._needCollect = opt.needCollect;
  24971. /**
  24972. * @private
  24973. * @type {boolean}
  24974. */
  24975. this._deduplication = opt.deduplication;
  24976. /**
  24977. * @private
  24978. * @type {boolean}
  24979. */
  24980. this._map;
  24981. }
  24982. /**
  24983. * @param {module:echarts/model/Model} axisModel
  24984. * @return {module:echarts/data/OrdinalMeta}
  24985. */
  24986. OrdinalMeta.createByAxisModel = function (axisModel) {
  24987. var option = axisModel.option;
  24988. var data = option.data;
  24989. var categories = data && map(data, getName);
  24990. return new OrdinalMeta({
  24991. categories: categories,
  24992. needCollect: !categories,
  24993. // deduplication is default in axis.
  24994. deduplication: option.dedplication !== false
  24995. });
  24996. };
  24997. var proto$1 = OrdinalMeta.prototype;
  24998. /**
  24999. * @param {string} category
  25000. * @return {number} ordinal
  25001. */
  25002. proto$1.getOrdinal = function (category) {
  25003. return getOrCreateMap(this).get(category);
  25004. };
  25005. /**
  25006. * @param {*} category
  25007. * @return {number} The ordinal. If not found, return NaN.
  25008. */
  25009. proto$1.parseAndCollect = function (category) {
  25010. var index;
  25011. var needCollect = this._needCollect;
  25012. // The value of category dim can be the index of the given category set.
  25013. // This feature is only supported when !needCollect, because we should
  25014. // consider a common case: a value is 2017, which is a number but is
  25015. // expected to be tread as a category. This case usually happen in dataset,
  25016. // where it happent to be no need of the index feature.
  25017. if (typeof category !== 'string' && !needCollect) {
  25018. return category;
  25019. }
  25020. // Optimize for the scenario:
  25021. // category is ['2012-01-01', '2012-01-02', ...], where the input
  25022. // data has been ensured not duplicate and is large data.
  25023. // Notice, if a dataset dimension provide categroies, usually echarts
  25024. // should remove duplication except user tell echarts dont do that
  25025. // (set axis.deduplication = false), because echarts do not know whether
  25026. // the values in the category dimension has duplication (consider the
  25027. // parallel-aqi example)
  25028. if (needCollect && !this._deduplication) {
  25029. index = this.categories.length;
  25030. this.categories[index] = category;
  25031. return index;
  25032. }
  25033. var map$$1 = getOrCreateMap(this);
  25034. index = map$$1.get(category);
  25035. if (index == null) {
  25036. if (needCollect) {
  25037. index = this.categories.length;
  25038. this.categories[index] = category;
  25039. map$$1.set(category, index);
  25040. }
  25041. else {
  25042. index = NaN;
  25043. }
  25044. }
  25045. return index;
  25046. };
  25047. // Consider big data, do not create map until needed.
  25048. function getOrCreateMap(ordinalMeta) {
  25049. return ordinalMeta._map || (
  25050. ordinalMeta._map = createHashMap(ordinalMeta.categories)
  25051. );
  25052. }
  25053. function getName(obj) {
  25054. if (isObject$1(obj) && obj.value != null) {
  25055. return obj.value;
  25056. }
  25057. else {
  25058. return obj + '';
  25059. }
  25060. }
  25061. /**
  25062. * Linear continuous scale
  25063. * @module echarts/coord/scale/Ordinal
  25064. *
  25065. * http://en.wikipedia.org/wiki/Level_of_measurement
  25066. */
  25067. // FIXME only one data
  25068. var scaleProto = Scale.prototype;
  25069. var OrdinalScale = Scale.extend({
  25070. type: 'ordinal',
  25071. /**
  25072. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  25073. */
  25074. init: function (ordinalMeta, extent) {
  25075. // Caution: Should not use instanceof, consider ec-extensions using
  25076. // import approach to get OrdinalMeta class.
  25077. if (!ordinalMeta || isArray(ordinalMeta)) {
  25078. ordinalMeta = new OrdinalMeta({categories: ordinalMeta});
  25079. }
  25080. this._ordinalMeta = ordinalMeta;
  25081. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  25082. },
  25083. parse: function (val) {
  25084. return typeof val === 'string'
  25085. ? this._ordinalMeta.getOrdinal(val)
  25086. // val might be float.
  25087. : Math.round(val);
  25088. },
  25089. contain: function (rank) {
  25090. rank = this.parse(rank);
  25091. return scaleProto.contain.call(this, rank)
  25092. && this._ordinalMeta.categories[rank] != null;
  25093. },
  25094. /**
  25095. * Normalize given rank or name to linear [0, 1]
  25096. * @param {number|string} [val]
  25097. * @return {number}
  25098. */
  25099. normalize: function (val) {
  25100. return scaleProto.normalize.call(this, this.parse(val));
  25101. },
  25102. scale: function (val) {
  25103. return Math.round(scaleProto.scale.call(this, val));
  25104. },
  25105. /**
  25106. * @return {Array}
  25107. */
  25108. getTicks: function () {
  25109. var ticks = [];
  25110. var extent = this._extent;
  25111. var rank = extent[0];
  25112. while (rank <= extent[1]) {
  25113. ticks.push(rank);
  25114. rank++;
  25115. }
  25116. return ticks;
  25117. },
  25118. /**
  25119. * Get item on rank n
  25120. * @param {number} n
  25121. * @return {string}
  25122. */
  25123. getLabel: function (n) {
  25124. return this._ordinalMeta.categories[n];
  25125. },
  25126. /**
  25127. * @return {number}
  25128. */
  25129. count: function () {
  25130. return this._extent[1] - this._extent[0] + 1;
  25131. },
  25132. /**
  25133. * @override
  25134. */
  25135. unionExtentFromData: function (data, dim) {
  25136. this.unionExtent(data.getApproximateExtent(dim));
  25137. },
  25138. niceTicks: noop,
  25139. niceExtent: noop
  25140. });
  25141. /**
  25142. * @return {module:echarts/scale/Time}
  25143. */
  25144. OrdinalScale.create = function () {
  25145. return new OrdinalScale();
  25146. };
  25147. /**
  25148. * For testable.
  25149. */
  25150. var roundNumber$1 = round$1;
  25151. /**
  25152. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  25153. * Should be extent[0] < extent[1].
  25154. * @param {number} splitNumber splitNumber should be >= 1.
  25155. * @param {number} [minInterval]
  25156. * @param {number} [maxInterval]
  25157. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  25158. */
  25159. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  25160. var result = {};
  25161. var span = extent[1] - extent[0];
  25162. var interval = result.interval = nice(span / splitNumber, true);
  25163. if (minInterval != null && interval < minInterval) {
  25164. interval = result.interval = minInterval;
  25165. }
  25166. if (maxInterval != null && interval > maxInterval) {
  25167. interval = result.interval = maxInterval;
  25168. }
  25169. // Tow more digital for tick.
  25170. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  25171. // Niced extent inside original extent
  25172. var niceTickExtent = result.niceTickExtent = [
  25173. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  25174. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  25175. ];
  25176. fixExtent(niceTickExtent, extent);
  25177. return result;
  25178. }
  25179. /**
  25180. * @param {number} interval
  25181. * @return {number} interval precision
  25182. */
  25183. function getIntervalPrecision(interval) {
  25184. // Tow more digital for tick.
  25185. return getPrecisionSafe(interval) + 2;
  25186. }
  25187. function clamp(niceTickExtent, idx, extent) {
  25188. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  25189. }
  25190. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  25191. function fixExtent(niceTickExtent, extent) {
  25192. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  25193. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  25194. clamp(niceTickExtent, 0, extent);
  25195. clamp(niceTickExtent, 1, extent);
  25196. if (niceTickExtent[0] > niceTickExtent[1]) {
  25197. niceTickExtent[0] = niceTickExtent[1];
  25198. }
  25199. }
  25200. function intervalScaleGetTicks(interval, extent, niceTickExtent, intervalPrecision) {
  25201. var ticks = [];
  25202. // If interval is 0, return [];
  25203. if (!interval) {
  25204. return ticks;
  25205. }
  25206. // Consider this case: using dataZoom toolbox, zoom and zoom.
  25207. var safeLimit = 10000;
  25208. if (extent[0] < niceTickExtent[0]) {
  25209. ticks.push(extent[0]);
  25210. }
  25211. var tick = niceTickExtent[0];
  25212. while (tick <= niceTickExtent[1]) {
  25213. ticks.push(tick);
  25214. // Avoid rounding error
  25215. tick = roundNumber$1(tick + interval, intervalPrecision);
  25216. if (tick === ticks[ticks.length - 1]) {
  25217. // Consider out of safe float point, e.g.,
  25218. // -3711126.9907707 + 2e-10 === -3711126.9907707
  25219. break;
  25220. }
  25221. if (ticks.length > safeLimit) {
  25222. return [];
  25223. }
  25224. }
  25225. // Consider this case: the last item of ticks is smaller
  25226. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  25227. if (extent[1] > (ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1])) {
  25228. ticks.push(extent[1]);
  25229. }
  25230. return ticks;
  25231. }
  25232. /**
  25233. * Interval scale
  25234. * @module echarts/scale/Interval
  25235. */
  25236. var roundNumber = round$1;
  25237. /**
  25238. * @alias module:echarts/coord/scale/Interval
  25239. * @constructor
  25240. */
  25241. var IntervalScale = Scale.extend({
  25242. type: 'interval',
  25243. _interval: 0,
  25244. _intervalPrecision: 2,
  25245. setExtent: function (start, end) {
  25246. var thisExtent = this._extent;
  25247. //start,end may be a Number like '25',so...
  25248. if (!isNaN(start)) {
  25249. thisExtent[0] = parseFloat(start);
  25250. }
  25251. if (!isNaN(end)) {
  25252. thisExtent[1] = parseFloat(end);
  25253. }
  25254. },
  25255. unionExtent: function (other) {
  25256. var extent = this._extent;
  25257. other[0] < extent[0] && (extent[0] = other[0]);
  25258. other[1] > extent[1] && (extent[1] = other[1]);
  25259. // unionExtent may called by it's sub classes
  25260. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  25261. },
  25262. /**
  25263. * Get interval
  25264. */
  25265. getInterval: function () {
  25266. return this._interval;
  25267. },
  25268. /**
  25269. * Set interval
  25270. */
  25271. setInterval: function (interval) {
  25272. this._interval = interval;
  25273. // Dropped auto calculated niceExtent and use user setted extent
  25274. // We assume user wan't to set both interval, min, max to get a better result
  25275. this._niceExtent = this._extent.slice();
  25276. this._intervalPrecision = getIntervalPrecision(interval);
  25277. },
  25278. /**
  25279. * @return {Array.<number>}
  25280. */
  25281. getTicks: function () {
  25282. return intervalScaleGetTicks(
  25283. this._interval, this._extent, this._niceExtent, this._intervalPrecision
  25284. );
  25285. },
  25286. /**
  25287. * @return {Array.<string>}
  25288. */
  25289. getTicksLabels: function () {
  25290. var labels = [];
  25291. var ticks = this.getTicks();
  25292. for (var i = 0; i < ticks.length; i++) {
  25293. labels.push(this.getLabel(ticks[i]));
  25294. }
  25295. return labels;
  25296. },
  25297. /**
  25298. * @param {number} data
  25299. * @param {Object} [opt]
  25300. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  25301. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  25302. * @return {string}
  25303. */
  25304. getLabel: function (data, opt) {
  25305. if (data == null) {
  25306. return '';
  25307. }
  25308. var precision = opt && opt.precision;
  25309. if (precision == null) {
  25310. precision = getPrecisionSafe(data) || 0;
  25311. }
  25312. else if (precision === 'auto') {
  25313. // Should be more precise then tick.
  25314. precision = this._intervalPrecision;
  25315. }
  25316. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  25317. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  25318. data = roundNumber(data, precision, true);
  25319. return addCommas(data);
  25320. },
  25321. /**
  25322. * Update interval and extent of intervals for nice ticks
  25323. *
  25324. * @param {number} [splitNumber = 5] Desired number of ticks
  25325. * @param {number} [minInterval]
  25326. * @param {number} [maxInterval]
  25327. */
  25328. niceTicks: function (splitNumber, minInterval, maxInterval) {
  25329. splitNumber = splitNumber || 5;
  25330. var extent = this._extent;
  25331. var span = extent[1] - extent[0];
  25332. if (!isFinite(span)) {
  25333. return;
  25334. }
  25335. // User may set axis min 0 and data are all negative
  25336. // FIXME If it needs to reverse ?
  25337. if (span < 0) {
  25338. span = -span;
  25339. extent.reverse();
  25340. }
  25341. var result = intervalScaleNiceTicks(
  25342. extent, splitNumber, minInterval, maxInterval
  25343. );
  25344. this._intervalPrecision = result.intervalPrecision;
  25345. this._interval = result.interval;
  25346. this._niceExtent = result.niceTickExtent;
  25347. },
  25348. /**
  25349. * Nice extent.
  25350. * @param {Object} opt
  25351. * @param {number} [opt.splitNumber = 5] Given approx tick number
  25352. * @param {boolean} [opt.fixMin=false]
  25353. * @param {boolean} [opt.fixMax=false]
  25354. * @param {boolean} [opt.minInterval]
  25355. * @param {boolean} [opt.maxInterval]
  25356. */
  25357. niceExtent: function (opt) {
  25358. var extent = this._extent;
  25359. // If extent start and end are same, expand them
  25360. if (extent[0] === extent[1]) {
  25361. if (extent[0] !== 0) {
  25362. // Expand extent
  25363. var expandSize = extent[0];
  25364. // In the fowllowing case
  25365. // Axis has been fixed max 100
  25366. // Plus data are all 100 and axis extent are [100, 100].
  25367. // Extend to the both side will cause expanded max is larger than fixed max.
  25368. // So only expand to the smaller side.
  25369. if (!opt.fixMax) {
  25370. extent[1] += expandSize / 2;
  25371. extent[0] -= expandSize / 2;
  25372. }
  25373. else {
  25374. extent[0] -= expandSize / 2;
  25375. }
  25376. }
  25377. else {
  25378. extent[1] = 1;
  25379. }
  25380. }
  25381. var span = extent[1] - extent[0];
  25382. // If there are no data and extent are [Infinity, -Infinity]
  25383. if (!isFinite(span)) {
  25384. extent[0] = 0;
  25385. extent[1] = 1;
  25386. }
  25387. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  25388. // var extent = this._extent;
  25389. var interval = this._interval;
  25390. if (!opt.fixMin) {
  25391. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  25392. }
  25393. if (!opt.fixMax) {
  25394. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  25395. }
  25396. }
  25397. });
  25398. /**
  25399. * @return {module:echarts/scale/Time}
  25400. */
  25401. IntervalScale.create = function () {
  25402. return new IntervalScale();
  25403. };
  25404. var STACK_PREFIX = '__ec_stack_';
  25405. function getSeriesStackId(seriesModel) {
  25406. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  25407. }
  25408. function getAxisKey(axis) {
  25409. return axis.dim + axis.index;
  25410. }
  25411. /**
  25412. * @param {Object} opt
  25413. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  25414. * @param {number} opt.count Positive interger.
  25415. * @param {number} [opt.barWidth]
  25416. * @param {number} [opt.barMaxWidth]
  25417. * @param {number} [opt.barGap]
  25418. * @param {number} [opt.barCategoryGap]
  25419. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  25420. */
  25421. function calBarWidthAndOffset(barSeries, api) {
  25422. var seriesInfoList = map(barSeries, function (seriesModel) {
  25423. var data = seriesModel.getData();
  25424. var cartesian = seriesModel.coordinateSystem;
  25425. var baseAxis = cartesian.getBaseAxis();
  25426. var axisExtent = baseAxis.getExtent();
  25427. var bandWidth = baseAxis.type === 'category'
  25428. ? baseAxis.getBandWidth()
  25429. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  25430. var barWidth = parsePercent$1(
  25431. seriesModel.get('barWidth'), bandWidth
  25432. );
  25433. var barMaxWidth = parsePercent$1(
  25434. seriesModel.get('barMaxWidth'), bandWidth
  25435. );
  25436. var barGap = seriesModel.get('barGap');
  25437. var barCategoryGap = seriesModel.get('barCategoryGap');
  25438. return {
  25439. bandWidth: bandWidth,
  25440. barWidth: barWidth,
  25441. barMaxWidth: barMaxWidth,
  25442. barGap: barGap,
  25443. barCategoryGap: barCategoryGap,
  25444. axisKey: getAxisKey(baseAxis),
  25445. stackId: getSeriesStackId(seriesModel)
  25446. };
  25447. });
  25448. return doCalBarWidthAndOffset(seriesInfoList, api);
  25449. }
  25450. function doCalBarWidthAndOffset(seriesInfoList, api) {
  25451. // Columns info on each category axis. Key is cartesian name
  25452. var columnsMap = {};
  25453. each$1(seriesInfoList, function (seriesInfo, idx) {
  25454. var axisKey = seriesInfo.axisKey;
  25455. var bandWidth = seriesInfo.bandWidth;
  25456. var columnsOnAxis = columnsMap[axisKey] || {
  25457. bandWidth: bandWidth,
  25458. remainedWidth: bandWidth,
  25459. autoWidthCount: 0,
  25460. categoryGap: '20%',
  25461. gap: '30%',
  25462. stacks: {}
  25463. };
  25464. var stacks = columnsOnAxis.stacks;
  25465. columnsMap[axisKey] = columnsOnAxis;
  25466. var stackId = seriesInfo.stackId;
  25467. if (!stacks[stackId]) {
  25468. columnsOnAxis.autoWidthCount++;
  25469. }
  25470. stacks[stackId] = stacks[stackId] || {
  25471. width: 0,
  25472. maxWidth: 0
  25473. };
  25474. // Caution: In a single coordinate system, these barGrid attributes
  25475. // will be shared by series. Consider that they have default values,
  25476. // only the attributes set on the last series will work.
  25477. // Do not change this fact unless there will be a break change.
  25478. // TODO
  25479. var barWidth = seriesInfo.barWidth;
  25480. if (barWidth && !stacks[stackId].width) {
  25481. // See #6312, do not restrict width.
  25482. stacks[stackId].width = barWidth;
  25483. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  25484. columnsOnAxis.remainedWidth -= barWidth;
  25485. }
  25486. var barMaxWidth = seriesInfo.barMaxWidth;
  25487. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  25488. var barGap = seriesInfo.barGap;
  25489. (barGap != null) && (columnsOnAxis.gap = barGap);
  25490. var barCategoryGap = seriesInfo.barCategoryGap;
  25491. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  25492. });
  25493. var result = {};
  25494. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  25495. result[coordSysName] = {};
  25496. var stacks = columnsOnAxis.stacks;
  25497. var bandWidth = columnsOnAxis.bandWidth;
  25498. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  25499. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  25500. var remainedWidth = columnsOnAxis.remainedWidth;
  25501. var autoWidthCount = columnsOnAxis.autoWidthCount;
  25502. var autoWidth = (remainedWidth - categoryGap)
  25503. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  25504. autoWidth = Math.max(autoWidth, 0);
  25505. // Find if any auto calculated bar exceeded maxBarWidth
  25506. each$1(stacks, function (column, stack) {
  25507. var maxWidth = column.maxWidth;
  25508. if (maxWidth && maxWidth < autoWidth) {
  25509. maxWidth = Math.min(maxWidth, remainedWidth);
  25510. if (column.width) {
  25511. maxWidth = Math.min(maxWidth, column.width);
  25512. }
  25513. remainedWidth -= maxWidth;
  25514. column.width = maxWidth;
  25515. autoWidthCount--;
  25516. }
  25517. });
  25518. // Recalculate width again
  25519. autoWidth = (remainedWidth - categoryGap)
  25520. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  25521. autoWidth = Math.max(autoWidth, 0);
  25522. var widthSum = 0;
  25523. var lastColumn;
  25524. each$1(stacks, function (column, idx) {
  25525. if (!column.width) {
  25526. column.width = autoWidth;
  25527. }
  25528. lastColumn = column;
  25529. widthSum += column.width * (1 + barGapPercent);
  25530. });
  25531. if (lastColumn) {
  25532. widthSum -= lastColumn.width * barGapPercent;
  25533. }
  25534. var offset = -widthSum / 2;
  25535. each$1(stacks, function (column, stackId) {
  25536. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  25537. offset: offset,
  25538. width: column.width
  25539. };
  25540. offset += column.width * (1 + barGapPercent);
  25541. });
  25542. });
  25543. return result;
  25544. }
  25545. /**
  25546. * @param {string} seriesType
  25547. * @param {module:echarts/model/Global} ecModel
  25548. * @param {module:echarts/ExtensionAPI} api
  25549. */
  25550. function layout(seriesType, ecModel, api) {
  25551. var seriesModels = [];
  25552. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  25553. // Check series coordinate, do layout for cartesian2d only
  25554. if (seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d') {
  25555. seriesModels.push(seriesModel);
  25556. }
  25557. });
  25558. var barWidthAndOffset = calBarWidthAndOffset(seriesModels);
  25559. var lastStackCoords = {};
  25560. each$1(seriesModels, function (seriesModel) {
  25561. var data = seriesModel.getData();
  25562. var cartesian = seriesModel.coordinateSystem;
  25563. var baseAxis = cartesian.getBaseAxis();
  25564. var stackId = getSeriesStackId(seriesModel);
  25565. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  25566. var columnOffset = columnLayoutInfo.offset;
  25567. var columnWidth = columnLayoutInfo.width;
  25568. var valueAxis = cartesian.getOtherAxis(baseAxis);
  25569. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  25570. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  25571. data.setLayout({
  25572. offset: columnOffset,
  25573. size: columnWidth
  25574. });
  25575. var valueDim = data.mapDimension(valueAxis.dim);
  25576. var baseDim = data.mapDimension(baseAxis.dim);
  25577. var stacked = isDimensionStacked(data, valueDim, baseDim);
  25578. var isValueAxisH = valueAxis.isHorizontal();
  25579. var valueAxisStart = (baseAxis.onZero || stacked)
  25580. ? valueAxis.toGlobalCoord(valueAxis.dataToCoord(0))
  25581. : valueAxis.getGlobalExtent()[0];
  25582. for (var idx = 0, len = data.count(); idx < len; idx++) {
  25583. var value = data.get(valueDim, idx);
  25584. var baseValue = data.get(baseDim, idx);
  25585. if (isNaN(value)) {
  25586. continue;
  25587. }
  25588. var sign = value >= 0 ? 'p' : 'n';
  25589. var baseCoord = valueAxisStart;
  25590. // Because of the barMinHeight, we can not use the value in
  25591. // stackResultDimension directly.
  25592. if (stacked) {
  25593. // Only ordinal axis can be stacked.
  25594. if (!lastStackCoords[stackId][baseValue]) {
  25595. lastStackCoords[stackId][baseValue] = {
  25596. p: valueAxisStart, // Positive stack
  25597. n: valueAxisStart // Negative stack
  25598. };
  25599. }
  25600. // Should also consider #4243
  25601. baseCoord = lastStackCoords[stackId][baseValue][sign];
  25602. }
  25603. var x;
  25604. var y;
  25605. var width;
  25606. var height;
  25607. if (isValueAxisH) {
  25608. var coord = cartesian.dataToPoint([value, baseValue]);
  25609. x = baseCoord;
  25610. y = coord[1] + columnOffset;
  25611. width = coord[0] - valueAxisStart;
  25612. height = columnWidth;
  25613. if (Math.abs(width) < barMinHeight) {
  25614. width = (width < 0 ? -1 : 1) * barMinHeight;
  25615. }
  25616. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  25617. }
  25618. else {
  25619. var coord = cartesian.dataToPoint([baseValue, value]);
  25620. x = coord[0] + columnOffset;
  25621. y = baseCoord;
  25622. width = columnWidth;
  25623. height = coord[1] - valueAxisStart;
  25624. if (Math.abs(height) < barMinHeight) {
  25625. // Include zero to has a positive bar
  25626. height = (height <= 0 ? -1 : 1) * barMinHeight;
  25627. }
  25628. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  25629. }
  25630. data.setItemLayout(idx, {
  25631. x: x,
  25632. y: y,
  25633. width: width,
  25634. height: height
  25635. });
  25636. }
  25637. }, this);
  25638. }
  25639. // [About UTC and local time zone]:
  25640. // In most cases, `number.parseDate` will treat input data string as local time
  25641. // (except time zone is specified in time string). And `format.formateTime` returns
  25642. // local time by default. option.useUTC is false by default. This design have
  25643. // concidered these common case:
  25644. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  25645. // in local time by default.
  25646. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  25647. // as its original time, without any time difference.
  25648. var intervalScaleProto = IntervalScale.prototype;
  25649. var mathCeil = Math.ceil;
  25650. var mathFloor = Math.floor;
  25651. var ONE_SECOND = 1000;
  25652. var ONE_MINUTE = ONE_SECOND * 60;
  25653. var ONE_HOUR = ONE_MINUTE * 60;
  25654. var ONE_DAY = ONE_HOUR * 24;
  25655. // FIXME 公用?
  25656. var bisect = function (a, x, lo, hi) {
  25657. while (lo < hi) {
  25658. var mid = lo + hi >>> 1;
  25659. if (a[mid][1] < x) {
  25660. lo = mid + 1;
  25661. }
  25662. else {
  25663. hi = mid;
  25664. }
  25665. }
  25666. return lo;
  25667. };
  25668. /**
  25669. * @alias module:echarts/coord/scale/Time
  25670. * @constructor
  25671. */
  25672. var TimeScale = IntervalScale.extend({
  25673. type: 'time',
  25674. /**
  25675. * @override
  25676. */
  25677. getLabel: function (val) {
  25678. var stepLvl = this._stepLvl;
  25679. var date = new Date(val);
  25680. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  25681. },
  25682. /**
  25683. * @override
  25684. */
  25685. niceExtent: function (opt) {
  25686. var extent = this._extent;
  25687. // If extent start and end are same, expand them
  25688. if (extent[0] === extent[1]) {
  25689. // Expand extent
  25690. extent[0] -= ONE_DAY;
  25691. extent[1] += ONE_DAY;
  25692. }
  25693. // If there are no data and extent are [Infinity, -Infinity]
  25694. if (extent[1] === -Infinity && extent[0] === Infinity) {
  25695. var d = new Date();
  25696. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  25697. extent[0] = extent[1] - ONE_DAY;
  25698. }
  25699. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  25700. // var extent = this._extent;
  25701. var interval = this._interval;
  25702. if (!opt.fixMin) {
  25703. extent[0] = round$1(mathFloor(extent[0] / interval) * interval);
  25704. }
  25705. if (!opt.fixMax) {
  25706. extent[1] = round$1(mathCeil(extent[1] / interval) * interval);
  25707. }
  25708. },
  25709. /**
  25710. * @override
  25711. */
  25712. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  25713. approxTickNum = approxTickNum || 10;
  25714. var extent = this._extent;
  25715. var span = extent[1] - extent[0];
  25716. var approxInterval = span / approxTickNum;
  25717. if (minInterval != null && approxInterval < minInterval) {
  25718. approxInterval = minInterval;
  25719. }
  25720. if (maxInterval != null && approxInterval > maxInterval) {
  25721. approxInterval = maxInterval;
  25722. }
  25723. var scaleLevelsLen = scaleLevels.length;
  25724. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  25725. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  25726. var interval = level[1];
  25727. // Same with interval scale if span is much larger than 1 year
  25728. if (level[0] === 'year') {
  25729. var yearSpan = span / interval;
  25730. // From "Nice Numbers for Graph Labels" of Graphic Gems
  25731. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  25732. var yearStep = nice(yearSpan / approxTickNum, true);
  25733. interval *= yearStep;
  25734. }
  25735. var timezoneOffset = this.getSetting('useUTC')
  25736. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  25737. var niceExtent = [
  25738. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  25739. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  25740. ];
  25741. fixExtent(niceExtent, extent);
  25742. this._stepLvl = level;
  25743. // Interval will be used in getTicks
  25744. this._interval = interval;
  25745. this._niceExtent = niceExtent;
  25746. },
  25747. parse: function (val) {
  25748. // val might be float.
  25749. return +parseDate(val);
  25750. }
  25751. });
  25752. each$1(['contain', 'normalize'], function (methodName) {
  25753. TimeScale.prototype[methodName] = function (val) {
  25754. return intervalScaleProto[methodName].call(this, this.parse(val));
  25755. };
  25756. });
  25757. // Steps from d3
  25758. var scaleLevels = [
  25759. // Format interval
  25760. ['hh:mm:ss', ONE_SECOND], // 1s
  25761. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  25762. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  25763. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  25764. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  25765. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  25766. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  25767. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  25768. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  25769. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  25770. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  25771. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  25772. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  25773. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  25774. ['MM-dd\nyyyy', ONE_DAY], // 1d
  25775. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  25776. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  25777. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  25778. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  25779. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  25780. ['week', ONE_DAY * 7], // 7d
  25781. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  25782. ['week', ONE_DAY * 14], // 2w
  25783. ['week', ONE_DAY * 21], // 3w
  25784. ['month', ONE_DAY * 31], // 1M
  25785. ['week', ONE_DAY * 42], // 6w
  25786. ['month', ONE_DAY * 62], // 2M
  25787. ['week', ONE_DAY * 42], // 10w
  25788. ['quarter', ONE_DAY * 380 / 4], // 3M
  25789. ['month', ONE_DAY * 31 * 4], // 4M
  25790. ['month', ONE_DAY * 31 * 5], // 5M
  25791. ['half-year', ONE_DAY * 380 / 2], // 6M
  25792. ['month', ONE_DAY * 31 * 8], // 8M
  25793. ['month', ONE_DAY * 31 * 10], // 10M
  25794. ['year', ONE_DAY * 380] // 1Y
  25795. ];
  25796. /**
  25797. * @param {module:echarts/model/Model}
  25798. * @return {module:echarts/scale/Time}
  25799. */
  25800. TimeScale.create = function (model) {
  25801. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  25802. };
  25803. /**
  25804. * Log scale
  25805. * @module echarts/scale/Log
  25806. */
  25807. // Use some method of IntervalScale
  25808. var scaleProto$1 = Scale.prototype;
  25809. var intervalScaleProto$1 = IntervalScale.prototype;
  25810. var getPrecisionSafe$1 = getPrecisionSafe;
  25811. var roundingErrorFix = round$1;
  25812. var mathFloor$1 = Math.floor;
  25813. var mathCeil$1 = Math.ceil;
  25814. var mathPow$1 = Math.pow;
  25815. var mathLog = Math.log;
  25816. var LogScale = Scale.extend({
  25817. type: 'log',
  25818. base: 10,
  25819. $constructor: function () {
  25820. Scale.apply(this, arguments);
  25821. this._originalScale = new IntervalScale();
  25822. },
  25823. /**
  25824. * @return {Array.<number>}
  25825. */
  25826. getTicks: function () {
  25827. var originalScale = this._originalScale;
  25828. var extent = this._extent;
  25829. var originalExtent = originalScale.getExtent();
  25830. return map(intervalScaleProto$1.getTicks.call(this), function (val) {
  25831. var powVal = round$1(mathPow$1(this.base, val));
  25832. // Fix #4158
  25833. powVal = (val === extent[0] && originalScale.__fixMin)
  25834. ? fixRoundingError(powVal, originalExtent[0])
  25835. : powVal;
  25836. powVal = (val === extent[1] && originalScale.__fixMax)
  25837. ? fixRoundingError(powVal, originalExtent[1])
  25838. : powVal;
  25839. return powVal;
  25840. }, this);
  25841. },
  25842. /**
  25843. * @param {number} val
  25844. * @return {string}
  25845. */
  25846. getLabel: intervalScaleProto$1.getLabel,
  25847. /**
  25848. * @param {number} val
  25849. * @return {number}
  25850. */
  25851. scale: function (val) {
  25852. val = scaleProto$1.scale.call(this, val);
  25853. return mathPow$1(this.base, val);
  25854. },
  25855. /**
  25856. * @param {number} start
  25857. * @param {number} end
  25858. */
  25859. setExtent: function (start, end) {
  25860. var base = this.base;
  25861. start = mathLog(start) / mathLog(base);
  25862. end = mathLog(end) / mathLog(base);
  25863. intervalScaleProto$1.setExtent.call(this, start, end);
  25864. },
  25865. /**
  25866. * @return {number} end
  25867. */
  25868. getExtent: function () {
  25869. var base = this.base;
  25870. var extent = scaleProto$1.getExtent.call(this);
  25871. extent[0] = mathPow$1(base, extent[0]);
  25872. extent[1] = mathPow$1(base, extent[1]);
  25873. // Fix #4158
  25874. var originalScale = this._originalScale;
  25875. var originalExtent = originalScale.getExtent();
  25876. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  25877. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  25878. return extent;
  25879. },
  25880. /**
  25881. * @param {Array.<number>} extent
  25882. */
  25883. unionExtent: function (extent) {
  25884. this._originalScale.unionExtent(extent);
  25885. var base = this.base;
  25886. extent[0] = mathLog(extent[0]) / mathLog(base);
  25887. extent[1] = mathLog(extent[1]) / mathLog(base);
  25888. scaleProto$1.unionExtent.call(this, extent);
  25889. },
  25890. /**
  25891. * @override
  25892. */
  25893. unionExtentFromData: function (data, dim) {
  25894. // TODO
  25895. // filter value that <= 0
  25896. this.unionExtent(data.getApproximateExtent(dim));
  25897. },
  25898. /**
  25899. * Update interval and extent of intervals for nice ticks
  25900. * @param {number} [approxTickNum = 10] Given approx tick number
  25901. */
  25902. niceTicks: function (approxTickNum) {
  25903. approxTickNum = approxTickNum || 10;
  25904. var extent = this._extent;
  25905. var span = extent[1] - extent[0];
  25906. if (span === Infinity || span <= 0) {
  25907. return;
  25908. }
  25909. var interval = quantity(span);
  25910. var err = approxTickNum / span * interval;
  25911. // Filter ticks to get closer to the desired count.
  25912. if (err <= 0.5) {
  25913. interval *= 10;
  25914. }
  25915. // Interval should be integer
  25916. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  25917. interval *= 10;
  25918. }
  25919. var niceExtent = [
  25920. round$1(mathCeil$1(extent[0] / interval) * interval),
  25921. round$1(mathFloor$1(extent[1] / interval) * interval)
  25922. ];
  25923. this._interval = interval;
  25924. this._niceExtent = niceExtent;
  25925. },
  25926. /**
  25927. * Nice extent.
  25928. * @override
  25929. */
  25930. niceExtent: function (opt) {
  25931. intervalScaleProto$1.niceExtent.call(this, opt);
  25932. var originalScale = this._originalScale;
  25933. originalScale.__fixMin = opt.fixMin;
  25934. originalScale.__fixMax = opt.fixMax;
  25935. }
  25936. });
  25937. each$1(['contain', 'normalize'], function (methodName) {
  25938. LogScale.prototype[methodName] = function (val) {
  25939. val = mathLog(val) / mathLog(this.base);
  25940. return scaleProto$1[methodName].call(this, val);
  25941. };
  25942. });
  25943. LogScale.create = function () {
  25944. return new LogScale();
  25945. };
  25946. function fixRoundingError(val, originalVal) {
  25947. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  25948. }
  25949. /**
  25950. * Get axis scale extent before niced.
  25951. * Item of returned array can only be number (including Infinity and NaN).
  25952. */
  25953. function getScaleExtent(scale, model) {
  25954. var scaleType = scale.type;
  25955. var min = model.getMin();
  25956. var max = model.getMax();
  25957. var fixMin = min != null;
  25958. var fixMax = max != null;
  25959. var originalExtent = scale.getExtent();
  25960. var axisDataLen;
  25961. var boundaryGap;
  25962. var span;
  25963. if (scaleType === 'ordinal') {
  25964. axisDataLen = model.getCategories().length;
  25965. }
  25966. else {
  25967. boundaryGap = model.get('boundaryGap');
  25968. if (!isArray(boundaryGap)) {
  25969. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  25970. }
  25971. if (typeof boundaryGap[0] === 'boolean') {
  25972. if (__DEV__) {
  25973. console.warn('Boolean type for boundaryGap is only '
  25974. + 'allowed for ordinal axis. Please use string in '
  25975. + 'percentage instead, e.g., "20%". Currently, '
  25976. + 'boundaryGap is set to be 0.');
  25977. }
  25978. boundaryGap = [0, 0];
  25979. }
  25980. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  25981. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  25982. span = (originalExtent[1] - originalExtent[0])
  25983. || Math.abs(originalExtent[0]);
  25984. }
  25985. // Notice: When min/max is not set (that is, when there are null/undefined,
  25986. // which is the most common case), these cases should be ensured:
  25987. // (1) For 'ordinal', show all axis.data.
  25988. // (2) For others:
  25989. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  25990. // disabled).
  25991. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  25992. // be the result that originalExtent enlarged by boundaryGap.
  25993. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  25994. // FIXME
  25995. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  25996. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  25997. // that the results processed by boundaryGap are positive/negative?
  25998. if (min == null) {
  25999. min = scaleType === 'ordinal'
  26000. ? (axisDataLen ? 0 : NaN)
  26001. : originalExtent[0] - boundaryGap[0] * span;
  26002. }
  26003. if (max == null) {
  26004. max = scaleType === 'ordinal'
  26005. ? (axisDataLen ? axisDataLen - 1 : NaN)
  26006. : originalExtent[1] + boundaryGap[1] * span;
  26007. }
  26008. if (min === 'dataMin') {
  26009. min = originalExtent[0];
  26010. }
  26011. else if (typeof min === 'function') {
  26012. min = min({
  26013. min: originalExtent[0],
  26014. max: originalExtent[1]
  26015. });
  26016. }
  26017. if (max === 'dataMax') {
  26018. max = originalExtent[1];
  26019. }
  26020. else if (typeof max === 'function') {
  26021. max = max({
  26022. min: originalExtent[0],
  26023. max: originalExtent[1]
  26024. });
  26025. }
  26026. (min == null || !isFinite(min)) && (min = NaN);
  26027. (max == null || !isFinite(max)) && (max = NaN);
  26028. scale.setBlank(eqNaN(min) || eqNaN(max));
  26029. // Evaluate if axis needs cross zero
  26030. if (model.getNeedCrossZero()) {
  26031. // Axis is over zero and min is not set
  26032. if (min > 0 && max > 0 && !fixMin) {
  26033. min = 0;
  26034. }
  26035. // Axis is under zero and max is not set
  26036. if (min < 0 && max < 0 && !fixMax) {
  26037. max = 0;
  26038. }
  26039. }
  26040. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  26041. // is base axis
  26042. // FIXME
  26043. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  26044. // (2) Refactor the logic with `barGrid`. Is it not need to `calBarWidthAndOffset` twice with different extent?
  26045. // Should not depend on series type `bar`?
  26046. // (3) Fix that might overlap when using dataZoom.
  26047. // (4) Consider other chart types using `barGrid`?
  26048. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  26049. var ecModel = model.ecModel;
  26050. if (ecModel && (scaleType === 'time' /*|| scaleType === 'interval' */)) {
  26051. var barSeriesModels = [];
  26052. var isBaseAxisAndHasBarSeries;
  26053. ecModel.eachSeriesByType('bar', function (seriesModel) {
  26054. if (seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d') {
  26055. barSeriesModels.push(seriesModel);
  26056. isBaseAxisAndHasBarSeries |= seriesModel.getBaseAxis() === model.axis;
  26057. }
  26058. });
  26059. if (isBaseAxisAndHasBarSeries) {
  26060. // Adjust axis min and max to account for overflow
  26061. var adjustedScale = adjustScaleForOverflow(min, max, model, barSeriesModels);
  26062. min = adjustedScale.min;
  26063. max = adjustedScale.max;
  26064. }
  26065. }
  26066. return [min, max];
  26067. }
  26068. function adjustScaleForOverflow(min, max, model, barSeriesModels) {
  26069. // Get Axis Length
  26070. var axisExtent = model.axis.getExtent();
  26071. var axisLength = axisExtent[1] - axisExtent[0];
  26072. // Calculate placement of bars on axis
  26073. var barWidthAndOffset = calBarWidthAndOffset(barSeriesModels);
  26074. // Get bars on current base axis and calculate min and max overflow
  26075. var baseAxisKey = model.axis.dim + model.axis.index;
  26076. var barsOnCurrentAxis = barWidthAndOffset[baseAxisKey];
  26077. if (barsOnCurrentAxis === undefined) {
  26078. return {min: min, max: max};
  26079. }
  26080. var minOverflow = Infinity;
  26081. each$1(barsOnCurrentAxis, function (item) {
  26082. minOverflow = Math.min(item.offset, minOverflow);
  26083. });
  26084. var maxOverflow = -Infinity;
  26085. each$1(barsOnCurrentAxis, function (item) {
  26086. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  26087. });
  26088. minOverflow = Math.abs(minOverflow);
  26089. maxOverflow = Math.abs(maxOverflow);
  26090. var totalOverFlow = minOverflow + maxOverflow;
  26091. // Calulate required buffer based on old range and overflow
  26092. var oldRange = max - min;
  26093. var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength);
  26094. var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange);
  26095. max += overflowBuffer * (maxOverflow / totalOverFlow);
  26096. min -= overflowBuffer * (minOverflow / totalOverFlow);
  26097. return {min: min, max: max};
  26098. }
  26099. function niceScaleExtent(scale, model) {
  26100. var extent = getScaleExtent(scale, model);
  26101. var fixMin = model.getMin() != null;
  26102. var fixMax = model.getMax() != null;
  26103. var splitNumber = model.get('splitNumber');
  26104. if (scale.type === 'log') {
  26105. scale.base = model.get('logBase');
  26106. }
  26107. var scaleType = scale.type;
  26108. scale.setExtent(extent[0], extent[1]);
  26109. scale.niceExtent({
  26110. splitNumber: splitNumber,
  26111. fixMin: fixMin,
  26112. fixMax: fixMax,
  26113. minInterval: (scaleType === 'interval' || scaleType === 'time')
  26114. ? model.get('minInterval') : null,
  26115. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  26116. ? model.get('maxInterval') : null
  26117. });
  26118. // If some one specified the min, max. And the default calculated interval
  26119. // is not good enough. He can specify the interval. It is often appeared
  26120. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  26121. // to be 60.
  26122. // FIXME
  26123. var interval = model.get('interval');
  26124. if (interval != null) {
  26125. scale.setInterval && scale.setInterval(interval);
  26126. }
  26127. }
  26128. /**
  26129. * @param {module:echarts/model/Model} model
  26130. * @param {string} [axisType] Default retrieve from model.type
  26131. * @return {module:echarts/scale/*}
  26132. */
  26133. function createScaleByModel(model, axisType) {
  26134. axisType = axisType || model.get('type');
  26135. if (axisType) {
  26136. switch (axisType) {
  26137. // Buildin scale
  26138. case 'category':
  26139. return new OrdinalScale(
  26140. model.getOrdinalMeta
  26141. ? model.getOrdinalMeta()
  26142. : model.getCategories(),
  26143. [Infinity, -Infinity]
  26144. );
  26145. case 'value':
  26146. return new IntervalScale();
  26147. // Extended scale, like time and log
  26148. default:
  26149. return (Scale.getClass(axisType) || IntervalScale).create(model);
  26150. }
  26151. }
  26152. }
  26153. /**
  26154. * Check if the axis corss 0
  26155. */
  26156. function ifAxisCrossZero(axis) {
  26157. var dataExtent = axis.scale.getExtent();
  26158. var min = dataExtent[0];
  26159. var max = dataExtent[1];
  26160. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  26161. }
  26162. /**
  26163. * @param {Array.<number>} tickCoords In axis self coordinate.
  26164. * @param {Array.<string>} labels
  26165. * @param {string} font
  26166. * @param {number} axisRotate 0: towards right horizontally, clock-wise is negative.
  26167. * @param {number} [labelRotate=0] 0: towards right horizontally, clock-wise is negative.
  26168. * @return {number}
  26169. */
  26170. function getAxisLabelInterval(tickCoords, labels, font, axisRotate, labelRotate) {
  26171. var textSpaceTakenRect;
  26172. var autoLabelInterval = 0;
  26173. var accumulatedLabelInterval = 0;
  26174. var rotation = (axisRotate - labelRotate) / 180 * Math.PI;
  26175. var step = 1;
  26176. if (labels.length > 40) {
  26177. // Simple optimization for large amount of labels
  26178. step = Math.floor(labels.length / 40);
  26179. }
  26180. for (var i = 0; i < tickCoords.length; i += step) {
  26181. var tickCoord = tickCoords[i];
  26182. // Not precise, do not consider align and vertical align
  26183. // and each distance from axis line yet.
  26184. var rect = getBoundingRect(
  26185. labels[i], font, 'center', 'top'
  26186. );
  26187. rect.x += tickCoord * Math.cos(rotation);
  26188. rect.y += tickCoord * Math.sin(rotation);
  26189. // Magic number
  26190. rect.width *= 1.3;
  26191. rect.height *= 1.3;
  26192. if (!textSpaceTakenRect) {
  26193. textSpaceTakenRect = rect.clone();
  26194. }
  26195. // There is no space for current label;
  26196. else if (textSpaceTakenRect.intersect(rect)) {
  26197. accumulatedLabelInterval++;
  26198. autoLabelInterval = Math.max(autoLabelInterval, accumulatedLabelInterval);
  26199. }
  26200. else {
  26201. textSpaceTakenRect.union(rect);
  26202. // Reset
  26203. accumulatedLabelInterval = 0;
  26204. }
  26205. }
  26206. if (autoLabelInterval === 0 && step > 1) {
  26207. return step;
  26208. }
  26209. return (autoLabelInterval + 1) * step - 1;
  26210. }
  26211. /**
  26212. * @param {Object} axis
  26213. * @param {Function} labelFormatter
  26214. * @return {Array.<string>}
  26215. */
  26216. function getFormattedLabels(axis, labelFormatter) {
  26217. var scale = axis.scale;
  26218. var labels = scale.getTicksLabels();
  26219. var ticks = scale.getTicks();
  26220. if (typeof labelFormatter === 'string') {
  26221. labelFormatter = (function (tpl) {
  26222. return function (val) {
  26223. return tpl.replace('{value}', val != null ? val : '');
  26224. };
  26225. })(labelFormatter);
  26226. // Consider empty array
  26227. return map(labels, labelFormatter);
  26228. }
  26229. else if (typeof labelFormatter === 'function') {
  26230. return map(ticks, function (tick, idx) {
  26231. return labelFormatter(
  26232. getAxisRawValue(axis, tick),
  26233. idx
  26234. );
  26235. }, this);
  26236. }
  26237. else {
  26238. return labels;
  26239. }
  26240. }
  26241. function getAxisRawValue(axis, value) {
  26242. // In category axis with data zoom, tick is not the original
  26243. // index of axis.data. So tick should not be exposed to user
  26244. // in category axis.
  26245. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  26246. }
  26247. var axisModelCommonMixin = {
  26248. /**
  26249. * Format labels
  26250. * @return {Array.<string>}
  26251. */
  26252. getFormattedLabels: function () {
  26253. return getFormattedLabels(
  26254. this.axis,
  26255. this.get('axisLabel.formatter')
  26256. );
  26257. },
  26258. /**
  26259. * @param {boolean} origin
  26260. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  26261. */
  26262. getMin: function (origin) {
  26263. var option = this.option;
  26264. var min = (!origin && option.rangeStart != null)
  26265. ? option.rangeStart : option.min;
  26266. if (this.axis
  26267. && min != null
  26268. && min !== 'dataMin'
  26269. && typeof min !== 'function'
  26270. && !eqNaN(min)
  26271. ) {
  26272. min = this.axis.scale.parse(min);
  26273. }
  26274. return min;
  26275. },
  26276. /**
  26277. * @param {boolean} origin
  26278. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  26279. */
  26280. getMax: function (origin) {
  26281. var option = this.option;
  26282. var max = (!origin && option.rangeEnd != null)
  26283. ? option.rangeEnd : option.max;
  26284. if (this.axis
  26285. && max != null
  26286. && max !== 'dataMax'
  26287. && typeof max !== 'function'
  26288. && !eqNaN(max)
  26289. ) {
  26290. max = this.axis.scale.parse(max);
  26291. }
  26292. return max;
  26293. },
  26294. /**
  26295. * @return {boolean}
  26296. */
  26297. getNeedCrossZero: function () {
  26298. var option = this.option;
  26299. return (option.rangeStart != null || option.rangeEnd != null)
  26300. ? false : !option.scale;
  26301. },
  26302. /**
  26303. * Should be implemented by each axis model if necessary.
  26304. * @return {module:echarts/model/Component} coordinate system model
  26305. */
  26306. getCoordSysModel: noop,
  26307. /**
  26308. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  26309. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  26310. */
  26311. setRange: function (rangeStart, rangeEnd) {
  26312. this.option.rangeStart = rangeStart;
  26313. this.option.rangeEnd = rangeEnd;
  26314. },
  26315. /**
  26316. * Reset range
  26317. */
  26318. resetRange: function () {
  26319. // rangeStart and rangeEnd is readonly.
  26320. this.option.rangeStart = this.option.rangeEnd = null;
  26321. }
  26322. };
  26323. // Symbol factory
  26324. /**
  26325. * Triangle shape
  26326. * @inner
  26327. */
  26328. var Triangle = extendShape({
  26329. type: 'triangle',
  26330. shape: {
  26331. cx: 0,
  26332. cy: 0,
  26333. width: 0,
  26334. height: 0
  26335. },
  26336. buildPath: function (path, shape) {
  26337. var cx = shape.cx;
  26338. var cy = shape.cy;
  26339. var width = shape.width / 2;
  26340. var height = shape.height / 2;
  26341. path.moveTo(cx, cy - height);
  26342. path.lineTo(cx + width, cy + height);
  26343. path.lineTo(cx - width, cy + height);
  26344. path.closePath();
  26345. }
  26346. });
  26347. /**
  26348. * Diamond shape
  26349. * @inner
  26350. */
  26351. var Diamond = extendShape({
  26352. type: 'diamond',
  26353. shape: {
  26354. cx: 0,
  26355. cy: 0,
  26356. width: 0,
  26357. height: 0
  26358. },
  26359. buildPath: function (path, shape) {
  26360. var cx = shape.cx;
  26361. var cy = shape.cy;
  26362. var width = shape.width / 2;
  26363. var height = shape.height / 2;
  26364. path.moveTo(cx, cy - height);
  26365. path.lineTo(cx + width, cy);
  26366. path.lineTo(cx, cy + height);
  26367. path.lineTo(cx - width, cy);
  26368. path.closePath();
  26369. }
  26370. });
  26371. /**
  26372. * Pin shape
  26373. * @inner
  26374. */
  26375. var Pin = extendShape({
  26376. type: 'pin',
  26377. shape: {
  26378. // x, y on the cusp
  26379. x: 0,
  26380. y: 0,
  26381. width: 0,
  26382. height: 0
  26383. },
  26384. buildPath: function (path, shape) {
  26385. var x = shape.x;
  26386. var y = shape.y;
  26387. var w = shape.width / 5 * 3;
  26388. // Height must be larger than width
  26389. var h = Math.max(w, shape.height);
  26390. var r = w / 2;
  26391. // Dist on y with tangent point and circle center
  26392. var dy = r * r / (h - r);
  26393. var cy = y - h + r + dy;
  26394. var angle = Math.asin(dy / r);
  26395. // Dist on x with tangent point and circle center
  26396. var dx = Math.cos(angle) * r;
  26397. var tanX = Math.sin(angle);
  26398. var tanY = Math.cos(angle);
  26399. var cpLen = r * 0.6;
  26400. var cpLen2 = r * 0.7;
  26401. path.moveTo(x - dx, cy + dy);
  26402. path.arc(
  26403. x, cy, r,
  26404. Math.PI - angle,
  26405. Math.PI * 2 + angle
  26406. );
  26407. path.bezierCurveTo(
  26408. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  26409. x, y - cpLen2,
  26410. x, y
  26411. );
  26412. path.bezierCurveTo(
  26413. x, y - cpLen2,
  26414. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  26415. x - dx, cy + dy
  26416. );
  26417. path.closePath();
  26418. }
  26419. });
  26420. /**
  26421. * Arrow shape
  26422. * @inner
  26423. */
  26424. var Arrow = extendShape({
  26425. type: 'arrow',
  26426. shape: {
  26427. x: 0,
  26428. y: 0,
  26429. width: 0,
  26430. height: 0
  26431. },
  26432. buildPath: function (ctx, shape) {
  26433. var height = shape.height;
  26434. var width = shape.width;
  26435. var x = shape.x;
  26436. var y = shape.y;
  26437. var dx = width / 3 * 2;
  26438. ctx.moveTo(x, y);
  26439. ctx.lineTo(x + dx, y + height);
  26440. ctx.lineTo(x, y + height / 4 * 3);
  26441. ctx.lineTo(x - dx, y + height);
  26442. ctx.lineTo(x, y);
  26443. ctx.closePath();
  26444. }
  26445. });
  26446. /**
  26447. * Map of path contructors
  26448. * @type {Object.<string, module:zrender/graphic/Path>}
  26449. */
  26450. var symbolCtors = {
  26451. line: Line,
  26452. rect: Rect,
  26453. roundRect: Rect,
  26454. square: Rect,
  26455. circle: Circle,
  26456. diamond: Diamond,
  26457. pin: Pin,
  26458. arrow: Arrow,
  26459. triangle: Triangle
  26460. };
  26461. var symbolShapeMakers = {
  26462. line: function (x, y, w, h, shape) {
  26463. // FIXME
  26464. shape.x1 = x;
  26465. shape.y1 = y + h / 2;
  26466. shape.x2 = x + w;
  26467. shape.y2 = y + h / 2;
  26468. },
  26469. rect: function (x, y, w, h, shape) {
  26470. shape.x = x;
  26471. shape.y = y;
  26472. shape.width = w;
  26473. shape.height = h;
  26474. },
  26475. roundRect: function (x, y, w, h, shape) {
  26476. shape.x = x;
  26477. shape.y = y;
  26478. shape.width = w;
  26479. shape.height = h;
  26480. shape.r = Math.min(w, h) / 4;
  26481. },
  26482. square: function (x, y, w, h, shape) {
  26483. var size = Math.min(w, h);
  26484. shape.x = x;
  26485. shape.y = y;
  26486. shape.width = size;
  26487. shape.height = size;
  26488. },
  26489. circle: function (x, y, w, h, shape) {
  26490. // Put circle in the center of square
  26491. shape.cx = x + w / 2;
  26492. shape.cy = y + h / 2;
  26493. shape.r = Math.min(w, h) / 2;
  26494. },
  26495. diamond: function (x, y, w, h, shape) {
  26496. shape.cx = x + w / 2;
  26497. shape.cy = y + h / 2;
  26498. shape.width = w;
  26499. shape.height = h;
  26500. },
  26501. pin: function (x, y, w, h, shape) {
  26502. shape.x = x + w / 2;
  26503. shape.y = y + h / 2;
  26504. shape.width = w;
  26505. shape.height = h;
  26506. },
  26507. arrow: function (x, y, w, h, shape) {
  26508. shape.x = x + w / 2;
  26509. shape.y = y + h / 2;
  26510. shape.width = w;
  26511. shape.height = h;
  26512. },
  26513. triangle: function (x, y, w, h, shape) {
  26514. shape.cx = x + w / 2;
  26515. shape.cy = y + h / 2;
  26516. shape.width = w;
  26517. shape.height = h;
  26518. }
  26519. };
  26520. var symbolBuildProxies = {};
  26521. each$1(symbolCtors, function (Ctor, name) {
  26522. symbolBuildProxies[name] = new Ctor();
  26523. });
  26524. var SymbolClz = extendShape({
  26525. type: 'symbol',
  26526. shape: {
  26527. symbolType: '',
  26528. x: 0,
  26529. y: 0,
  26530. width: 0,
  26531. height: 0
  26532. },
  26533. beforeBrush: function () {
  26534. var style = this.style;
  26535. var shape = this.shape;
  26536. // FIXME
  26537. if (shape.symbolType === 'pin' && style.textPosition === 'inside') {
  26538. style.textPosition = ['50%', '40%'];
  26539. style.textAlign = 'center';
  26540. style.textVerticalAlign = 'middle';
  26541. }
  26542. },
  26543. buildPath: function (ctx, shape, inBundle) {
  26544. var symbolType = shape.symbolType;
  26545. var proxySymbol = symbolBuildProxies[symbolType];
  26546. if (shape.symbolType !== 'none') {
  26547. if (!proxySymbol) {
  26548. // Default rect
  26549. symbolType = 'rect';
  26550. proxySymbol = symbolBuildProxies[symbolType];
  26551. }
  26552. symbolShapeMakers[symbolType](
  26553. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  26554. );
  26555. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  26556. }
  26557. }
  26558. });
  26559. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  26560. function symbolPathSetColor(color, innerColor) {
  26561. if (this.type !== 'image') {
  26562. var symbolStyle = this.style;
  26563. var symbolShape = this.shape;
  26564. if (symbolShape && symbolShape.symbolType === 'line') {
  26565. symbolStyle.stroke = color;
  26566. }
  26567. else if (this.__isEmptyBrush) {
  26568. symbolStyle.stroke = color;
  26569. symbolStyle.fill = innerColor || '#fff';
  26570. }
  26571. else {
  26572. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  26573. symbolStyle.fill && (symbolStyle.fill = color);
  26574. symbolStyle.stroke && (symbolStyle.stroke = color);
  26575. }
  26576. this.dirty(false);
  26577. }
  26578. }
  26579. /**
  26580. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  26581. * @param {string} symbolType
  26582. * @param {number} x
  26583. * @param {number} y
  26584. * @param {number} w
  26585. * @param {number} h
  26586. * @param {string} color
  26587. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  26588. * for path and image only.
  26589. */
  26590. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  26591. // TODO Support image object, DynamicImage.
  26592. var isEmpty = symbolType.indexOf('empty') === 0;
  26593. if (isEmpty) {
  26594. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  26595. }
  26596. var symbolPath;
  26597. if (symbolType.indexOf('image://') === 0) {
  26598. symbolPath = makeImage(
  26599. symbolType.slice(8),
  26600. new BoundingRect(x, y, w, h),
  26601. keepAspect ? 'center' : 'cover'
  26602. );
  26603. }
  26604. else if (symbolType.indexOf('path://') === 0) {
  26605. symbolPath = makePath(
  26606. symbolType.slice(7),
  26607. {},
  26608. new BoundingRect(x, y, w, h),
  26609. keepAspect ? 'center' : 'cover'
  26610. );
  26611. }
  26612. else {
  26613. symbolPath = new SymbolClz({
  26614. shape: {
  26615. symbolType: symbolType,
  26616. x: x,
  26617. y: y,
  26618. width: w,
  26619. height: h
  26620. }
  26621. });
  26622. }
  26623. symbolPath.__isEmptyBrush = isEmpty;
  26624. symbolPath.setColor = symbolPathSetColor;
  26625. symbolPath.setColor(color);
  26626. return symbolPath;
  26627. }
  26628. // import createGraphFromNodeEdge from './chart/helper/createGraphFromNodeEdge';
  26629. /**
  26630. * Create a muti dimension List structure from seriesModel.
  26631. * @param {module:echarts/model/Model} seriesModel
  26632. * @return {module:echarts/data/List} list
  26633. */
  26634. function createList(seriesModel) {
  26635. return createListFromArray(seriesModel.getSource(), seriesModel);
  26636. }
  26637. var dataStack$1 = {
  26638. isDimensionStacked: isDimensionStacked,
  26639. enableDataStack: enableDataStack
  26640. };
  26641. /**
  26642. * Create scale
  26643. * @param {Array.<number>} dataExtent
  26644. * @param {Object|module:echarts/Model} option
  26645. */
  26646. function createScale(dataExtent, option) {
  26647. var axisModel = option;
  26648. if (!Model.isInstance(option)) {
  26649. axisModel = new Model(option);
  26650. mixin(axisModel, axisModelCommonMixin);
  26651. }
  26652. var scale = createScaleByModel(axisModel);
  26653. scale.setExtent(dataExtent[0], dataExtent[1]);
  26654. niceScaleExtent(scale, axisModel);
  26655. return scale;
  26656. }
  26657. /**
  26658. * Mixin common methods to axis model,
  26659. *
  26660. * Inlcude methods
  26661. * `getFormattedLabels() => Array.<string>`
  26662. * `getCategories() => Array.<string>`
  26663. * `getMin(origin: boolean) => number`
  26664. * `getMax(origin: boolean) => number`
  26665. * `getNeedCrossZero() => boolean`
  26666. * `setRange(start: number, end: number)`
  26667. * `resetRange()`
  26668. */
  26669. function mixinAxisModelCommonMethods(Model$$1) {
  26670. mixin(Model$$1, axisModelCommonMixin);
  26671. }
  26672. var helper = (Object.freeze || Object)({
  26673. createList: createList,
  26674. getLayoutRect: getLayoutRect,
  26675. dataStack: dataStack$1,
  26676. createScale: createScale,
  26677. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  26678. completeDimensions: completeDimensions,
  26679. createDimensions: createDimensions,
  26680. createSymbol: createSymbol
  26681. });
  26682. var EPSILON$3 = 1e-8;
  26683. function isAroundEqual$1(a, b) {
  26684. return Math.abs(a - b) < EPSILON$3;
  26685. }
  26686. function contain$1(points, x, y) {
  26687. var w = 0;
  26688. var p = points[0];
  26689. if (!p) {
  26690. return false;
  26691. }
  26692. for (var i = 1; i < points.length; i++) {
  26693. var p2 = points[i];
  26694. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  26695. p = p2;
  26696. }
  26697. // Close polygon
  26698. var p0 = points[0];
  26699. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  26700. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  26701. }
  26702. return w !== 0;
  26703. }
  26704. /**
  26705. * @module echarts/coord/geo/Region
  26706. */
  26707. /**
  26708. * @param {string} name
  26709. * @param {Array} geometries
  26710. * @param {Array.<number>} cp
  26711. */
  26712. function Region(name, geometries, cp) {
  26713. /**
  26714. * @type {string}
  26715. * @readOnly
  26716. */
  26717. this.name = name;
  26718. /**
  26719. * @type {Array.<Array>}
  26720. * @readOnly
  26721. */
  26722. this.geometries = geometries;
  26723. if (!cp) {
  26724. var rect = this.getBoundingRect();
  26725. cp = [
  26726. rect.x + rect.width / 2,
  26727. rect.y + rect.height / 2
  26728. ];
  26729. }
  26730. else {
  26731. cp = [cp[0], cp[1]];
  26732. }
  26733. /**
  26734. * @type {Array.<number>}
  26735. */
  26736. this.center = cp;
  26737. }
  26738. Region.prototype = {
  26739. constructor: Region,
  26740. properties: null,
  26741. /**
  26742. * @return {module:zrender/core/BoundingRect}
  26743. */
  26744. getBoundingRect: function () {
  26745. var rect = this._rect;
  26746. if (rect) {
  26747. return rect;
  26748. }
  26749. var MAX_NUMBER = Number.MAX_VALUE;
  26750. var min$$1 = [MAX_NUMBER, MAX_NUMBER];
  26751. var max$$1 = [-MAX_NUMBER, -MAX_NUMBER];
  26752. var min2 = [];
  26753. var max2 = [];
  26754. var geometries = this.geometries;
  26755. for (var i = 0; i < geometries.length; i++) {
  26756. // Only support polygon
  26757. if (geometries[i].type !== 'polygon') {
  26758. continue;
  26759. }
  26760. // Doesn't consider hole
  26761. var exterior = geometries[i].exterior;
  26762. fromPoints(exterior, min2, max2);
  26763. min(min$$1, min$$1, min2);
  26764. max(max$$1, max$$1, max2);
  26765. }
  26766. // No data
  26767. if (i === 0) {
  26768. min$$1[0] = min$$1[1] = max$$1[0] = max$$1[1] = 0;
  26769. }
  26770. return (this._rect = new BoundingRect(
  26771. min$$1[0], min$$1[1], max$$1[0] - min$$1[0], max$$1[1] - min$$1[1]
  26772. ));
  26773. },
  26774. /**
  26775. * @param {<Array.<number>} coord
  26776. * @return {boolean}
  26777. */
  26778. contain: function (coord) {
  26779. var rect = this.getBoundingRect();
  26780. var geometries = this.geometries;
  26781. if (!rect.contain(coord[0], coord[1])) {
  26782. return false;
  26783. }
  26784. loopGeo: for (var i = 0, len$$1 = geometries.length; i < len$$1; i++) {
  26785. // Only support polygon.
  26786. if (geometries[i].type !== 'polygon') {
  26787. continue;
  26788. }
  26789. var exterior = geometries[i].exterior;
  26790. var interiors = geometries[i].interiors;
  26791. if (contain$1(exterior, coord[0], coord[1])) {
  26792. // Not in the region if point is in the hole.
  26793. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  26794. if (contain$1(interiors[k])) {
  26795. continue loopGeo;
  26796. }
  26797. }
  26798. return true;
  26799. }
  26800. }
  26801. return false;
  26802. },
  26803. transformTo: function (x, y, width, height) {
  26804. var rect = this.getBoundingRect();
  26805. var aspect = rect.width / rect.height;
  26806. if (!width) {
  26807. width = aspect * height;
  26808. }
  26809. else if (!height) {
  26810. height = width / aspect ;
  26811. }
  26812. var target = new BoundingRect(x, y, width, height);
  26813. var transform = rect.calculateTransform(target);
  26814. var geometries = this.geometries;
  26815. for (var i = 0; i < geometries.length; i++) {
  26816. // Only support polygon.
  26817. if (geometries[i].type !== 'polygon') {
  26818. continue;
  26819. }
  26820. var exterior = geometries[i].exterior;
  26821. var interiors = geometries[i].interiors;
  26822. for (var p = 0; p < exterior.length; p++) {
  26823. applyTransform(exterior[p], exterior[p], transform);
  26824. }
  26825. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  26826. for (var p = 0; p < interiors[h].length; p++) {
  26827. applyTransform(interiors[h][p], interiors[h][p], transform);
  26828. }
  26829. }
  26830. }
  26831. rect = this._rect;
  26832. rect.copy(target);
  26833. // Update center
  26834. this.center = [
  26835. rect.x + rect.width / 2,
  26836. rect.y + rect.height / 2
  26837. ];
  26838. }
  26839. };
  26840. /**
  26841. * Parse and decode geo json
  26842. * @module echarts/coord/geo/parseGeoJson
  26843. */
  26844. function decode(json) {
  26845. if (!json.UTF8Encoding) {
  26846. return json;
  26847. }
  26848. var encodeScale = json.UTF8Scale;
  26849. if (encodeScale == null) {
  26850. encodeScale = 1024;
  26851. }
  26852. var features = json.features;
  26853. for (var f = 0; f < features.length; f++) {
  26854. var feature = features[f];
  26855. var geometry = feature.geometry;
  26856. var coordinates = geometry.coordinates;
  26857. var encodeOffsets = geometry.encodeOffsets;
  26858. for (var c = 0; c < coordinates.length; c++) {
  26859. var coordinate = coordinates[c];
  26860. if (geometry.type === 'Polygon') {
  26861. coordinates[c] = decodePolygon(
  26862. coordinate,
  26863. encodeOffsets[c],
  26864. encodeScale
  26865. );
  26866. }
  26867. else if (geometry.type === 'MultiPolygon') {
  26868. for (var c2 = 0; c2 < coordinate.length; c2++) {
  26869. var polygon = coordinate[c2];
  26870. coordinate[c2] = decodePolygon(
  26871. polygon,
  26872. encodeOffsets[c][c2],
  26873. encodeScale
  26874. );
  26875. }
  26876. }
  26877. }
  26878. }
  26879. // Has been decoded
  26880. json.UTF8Encoding = false;
  26881. return json;
  26882. }
  26883. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  26884. var result = [];
  26885. var prevX = encodeOffsets[0];
  26886. var prevY = encodeOffsets[1];
  26887. for (var i = 0; i < coordinate.length; i += 2) {
  26888. var x = coordinate.charCodeAt(i) - 64;
  26889. var y = coordinate.charCodeAt(i + 1) - 64;
  26890. // ZigZag decoding
  26891. x = (x >> 1) ^ (-(x & 1));
  26892. y = (y >> 1) ^ (-(y & 1));
  26893. // Delta deocding
  26894. x += prevX;
  26895. y += prevY;
  26896. prevX = x;
  26897. prevY = y;
  26898. // Dequantize
  26899. result.push([x / encodeScale, y / encodeScale]);
  26900. }
  26901. return result;
  26902. }
  26903. /**
  26904. * @alias module:echarts/coord/geo/parseGeoJson
  26905. * @param {Object} geoJson
  26906. * @return {module:zrender/container/Group}
  26907. */
  26908. var parseGeoJSON = function (geoJson) {
  26909. decode(geoJson);
  26910. return map(filter(geoJson.features, function (featureObj) {
  26911. // Output of mapshaper may have geometry null
  26912. return featureObj.geometry
  26913. && featureObj.properties
  26914. && featureObj.geometry.coordinates.length > 0;
  26915. }), function (featureObj) {
  26916. var properties = featureObj.properties;
  26917. var geo = featureObj.geometry;
  26918. var coordinates = geo.coordinates;
  26919. var geometries = [];
  26920. if (geo.type === 'Polygon') {
  26921. geometries.push({
  26922. type: 'polygon',
  26923. // According to the GeoJSON specification.
  26924. // First must be exterior, and the rest are all interior(holes).
  26925. exterior: coordinates[0],
  26926. interiors: coordinates.slice(1)
  26927. });
  26928. }
  26929. if (geo.type === 'MultiPolygon') {
  26930. each$1(coordinates, function (item) {
  26931. if (item[0]) {
  26932. geometries.push({
  26933. type: 'polygon',
  26934. exterior: item[0],
  26935. interiors: item.slice(1)
  26936. });
  26937. }
  26938. });
  26939. }
  26940. var region = new Region(
  26941. properties.name,
  26942. geometries,
  26943. properties.cp
  26944. );
  26945. region.properties = properties;
  26946. return region;
  26947. });
  26948. };
  26949. var linearMap$1 = linearMap;
  26950. function fixExtentWithBands(extent, nTick) {
  26951. var size = extent[1] - extent[0];
  26952. var len = nTick;
  26953. var margin = size / len / 2;
  26954. extent[0] += margin;
  26955. extent[1] -= margin;
  26956. }
  26957. var normalizedExtent = [0, 1];
  26958. /**
  26959. * @name module:echarts/coord/CartesianAxis
  26960. * @constructor
  26961. */
  26962. var Axis = function (dim, scale, extent) {
  26963. /**
  26964. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'
  26965. * @type {string}
  26966. */
  26967. this.dim = dim;
  26968. /**
  26969. * Axis scale
  26970. * @type {module:echarts/coord/scale/*}
  26971. */
  26972. this.scale = scale;
  26973. /**
  26974. * @type {Array.<number>}
  26975. * @private
  26976. */
  26977. this._extent = extent || [0, 0];
  26978. /**
  26979. * @type {boolean}
  26980. */
  26981. this.inverse = false;
  26982. /**
  26983. * Usually true when axis has a ordinal scale
  26984. * @type {boolean}
  26985. */
  26986. this.onBand = false;
  26987. /**
  26988. * @private
  26989. * @type {number}
  26990. */
  26991. this._labelInterval;
  26992. };
  26993. Axis.prototype = {
  26994. constructor: Axis,
  26995. /**
  26996. * If axis extent contain given coord
  26997. * @param {number} coord
  26998. * @return {boolean}
  26999. */
  27000. contain: function (coord) {
  27001. var extent = this._extent;
  27002. var min = Math.min(extent[0], extent[1]);
  27003. var max = Math.max(extent[0], extent[1]);
  27004. return coord >= min && coord <= max;
  27005. },
  27006. /**
  27007. * If axis extent contain given data
  27008. * @param {number} data
  27009. * @return {boolean}
  27010. */
  27011. containData: function (data) {
  27012. return this.contain(this.dataToCoord(data));
  27013. },
  27014. /**
  27015. * Get coord extent.
  27016. * @return {Array.<number>}
  27017. */
  27018. getExtent: function () {
  27019. return this._extent.slice();
  27020. },
  27021. /**
  27022. * Get precision used for formatting
  27023. * @param {Array.<number>} [dataExtent]
  27024. * @return {number}
  27025. */
  27026. getPixelPrecision: function (dataExtent) {
  27027. return getPixelPrecision(
  27028. dataExtent || this.scale.getExtent(),
  27029. this._extent
  27030. );
  27031. },
  27032. /**
  27033. * Set coord extent
  27034. * @param {number} start
  27035. * @param {number} end
  27036. */
  27037. setExtent: function (start, end) {
  27038. var extent = this._extent;
  27039. extent[0] = start;
  27040. extent[1] = end;
  27041. },
  27042. /**
  27043. * Convert data to coord. Data is the rank if it has an ordinal scale
  27044. * @param {number} data
  27045. * @param {boolean} clamp
  27046. * @return {number}
  27047. */
  27048. dataToCoord: function (data, clamp) {
  27049. var extent = this._extent;
  27050. var scale = this.scale;
  27051. data = scale.normalize(data);
  27052. if (this.onBand && scale.type === 'ordinal') {
  27053. extent = extent.slice();
  27054. fixExtentWithBands(extent, scale.count());
  27055. }
  27056. return linearMap$1(data, normalizedExtent, extent, clamp);
  27057. },
  27058. /**
  27059. * Convert coord to data. Data is the rank if it has an ordinal scale
  27060. * @param {number} coord
  27061. * @param {boolean} clamp
  27062. * @return {number}
  27063. */
  27064. coordToData: function (coord, clamp) {
  27065. var extent = this._extent;
  27066. var scale = this.scale;
  27067. if (this.onBand && scale.type === 'ordinal') {
  27068. extent = extent.slice();
  27069. fixExtentWithBands(extent, scale.count());
  27070. }
  27071. var t = linearMap$1(coord, extent, normalizedExtent, clamp);
  27072. return this.scale.scale(t);
  27073. },
  27074. /**
  27075. * Convert pixel point to data in axis
  27076. * @param {Array.<number>} point
  27077. * @param {boolean} clamp
  27078. * @return {number} data
  27079. */
  27080. pointToData: function (point, clamp) {
  27081. // Should be implemented in derived class if necessary.
  27082. },
  27083. /**
  27084. * @return {Array.<number>}
  27085. */
  27086. getTicksCoords: function (alignWithLabel) {
  27087. if (this.onBand && !alignWithLabel) {
  27088. var bands = this.getBands();
  27089. var coords = [];
  27090. for (var i = 0; i < bands.length; i++) {
  27091. coords.push(bands[i][0]);
  27092. }
  27093. if (bands[i - 1]) {
  27094. coords.push(bands[i - 1][1]);
  27095. }
  27096. return coords;
  27097. }
  27098. else {
  27099. return map(this.scale.getTicks(), this.dataToCoord, this);
  27100. }
  27101. },
  27102. /**
  27103. * Coords of labels are on the ticks or on the middle of bands
  27104. * @return {Array.<number>}
  27105. */
  27106. getLabelsCoords: function () {
  27107. return map(this.scale.getTicks(), this.dataToCoord, this);
  27108. },
  27109. /**
  27110. * Get bands.
  27111. *
  27112. * If axis has labels [1, 2, 3, 4]. Bands on the axis are
  27113. * |---1---|---2---|---3---|---4---|.
  27114. *
  27115. * @return {Array}
  27116. */
  27117. // FIXME Situation when labels is on ticks
  27118. getBands: function () {
  27119. var extent = this.getExtent();
  27120. var bands = [];
  27121. var len = this.scale.count();
  27122. var start = extent[0];
  27123. var end = extent[1];
  27124. var span = end - start;
  27125. for (var i = 0; i < len; i++) {
  27126. bands.push([
  27127. span * i / len + start,
  27128. span * (i + 1) / len + start
  27129. ]);
  27130. }
  27131. return bands;
  27132. },
  27133. /**
  27134. * Get width of band
  27135. * @return {number}
  27136. */
  27137. getBandWidth: function () {
  27138. var axisExtent = this._extent;
  27139. var dataExtent = this.scale.getExtent();
  27140. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  27141. // Fix #2728, avoid NaN when only one data.
  27142. len === 0 && (len = 1);
  27143. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  27144. return Math.abs(size) / len;
  27145. },
  27146. /**
  27147. * @abstract
  27148. * @return {boolean} Is horizontal
  27149. */
  27150. isHorizontal: null,
  27151. /**
  27152. * @abstract
  27153. * @return {number} Get axis rotate, by degree.
  27154. */
  27155. getRotate: null,
  27156. /**
  27157. * Get interval of the axis label.
  27158. * To get precise result, at least one of `getRotate` and `isHorizontal`
  27159. * should be implemented.
  27160. * @return {number}
  27161. */
  27162. getLabelInterval: function () {
  27163. var labelInterval = this._labelInterval;
  27164. if (!labelInterval) {
  27165. var axisModel = this.model;
  27166. var labelModel = axisModel.getModel('axisLabel');
  27167. labelInterval = labelModel.get('interval');
  27168. if (this.type === 'category'
  27169. && (labelInterval == null || labelInterval === 'auto')
  27170. ) {
  27171. labelInterval = getAxisLabelInterval(
  27172. map(this.scale.getTicks(), this.dataToCoord, this),
  27173. axisModel.getFormattedLabels(),
  27174. labelModel.getFont(),
  27175. this.getRotate
  27176. ? this.getRotate()
  27177. : (this.isHorizontal && !this.isHorizontal())
  27178. ? 90
  27179. : 0,
  27180. labelModel.get('rotate')
  27181. );
  27182. }
  27183. this._labelInterval = labelInterval;
  27184. }
  27185. return labelInterval;
  27186. }
  27187. };
  27188. /**
  27189. * Do not mount those modules on 'src/echarts' for better tree shaking.
  27190. */
  27191. var parseGeoJson = parseGeoJSON;
  27192. var ecUtil = {};
  27193. each$1([
  27194. 'map', 'each', 'filter', 'indexOf', 'inherits', 'reduce', 'filter',
  27195. 'bind', 'curry', 'isArray', 'isString', 'isObject', 'isFunction',
  27196. 'extend', 'defaults', 'clone', 'merge'
  27197. ],
  27198. function (name) {
  27199. ecUtil[name] = zrUtil[name];
  27200. }
  27201. );
  27202. var DatasetModel = extendComponentModel({
  27203. type: 'dataset',
  27204. /**
  27205. * @protected
  27206. */
  27207. defaultOption: {
  27208. // 'row', 'column'
  27209. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  27210. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  27211. sourceHeader: null,
  27212. dimensions: null,
  27213. source: null
  27214. },
  27215. optionUpdated: function () {
  27216. detectSourceFormat(this);
  27217. }
  27218. });
  27219. extendComponentView({type: 'dataset'});
  27220. SeriesModel.extend({
  27221. type: 'series.line',
  27222. dependencies: ['grid', 'polar'],
  27223. getInitialData: function (option, ecModel) {
  27224. if (__DEV__) {
  27225. var coordSys = option.coordinateSystem;
  27226. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  27227. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  27228. }
  27229. }
  27230. return createListFromArray(this.getSource(), this);
  27231. },
  27232. defaultOption: {
  27233. zlevel: 0, // 一级层叠
  27234. z: 2, // 二级层叠
  27235. coordinateSystem: 'cartesian2d',
  27236. legendHoverLink: true,
  27237. hoverAnimation: true,
  27238. // stack: null
  27239. // xAxisIndex: 0,
  27240. // yAxisIndex: 0,
  27241. // polarIndex: 0,
  27242. // If clip the overflow value
  27243. clipOverflow: true,
  27244. // cursor: null,
  27245. label: {
  27246. position: 'top'
  27247. },
  27248. // itemStyle: {
  27249. // },
  27250. lineStyle: {
  27251. width: 2,
  27252. type: 'solid'
  27253. },
  27254. // areaStyle: {
  27255. // origin of areaStyle. Valid values:
  27256. // `'auto'/null/undefined`: from axisLine to data
  27257. // `'start'`: from min to data
  27258. // `'end'`: from data to max
  27259. // origin: 'auto'
  27260. // },
  27261. // false, 'start', 'end', 'middle'
  27262. step: false,
  27263. // Disabled if step is true
  27264. smooth: false,
  27265. smoothMonotone: null,
  27266. // 拐点图形类型
  27267. symbol: 'emptyCircle',
  27268. // 拐点图形大小
  27269. symbolSize: 4,
  27270. // 拐点图形旋转控制
  27271. symbolRotate: null,
  27272. // 是否显示 symbol, 只有在 tooltip hover 的时候显示
  27273. showSymbol: true,
  27274. // 标志图形默认只有主轴显示(随主轴标签间隔隐藏策略)
  27275. showAllSymbol: false,
  27276. // 是否连接断点
  27277. connectNulls: false,
  27278. // 数据过滤,'average', 'max', 'min', 'sum'
  27279. sampling: 'none',
  27280. animationEasing: 'linear',
  27281. // Disable progressive
  27282. progressive: 0,
  27283. hoverLayerThreshold: Infinity
  27284. }
  27285. });
  27286. /**
  27287. * @param {module:echarts/data/List} data
  27288. * @param {number} dataIndex
  27289. * @return {string} label string. Not null/undefined
  27290. */
  27291. function getDefaultLabel(data, dataIndex) {
  27292. var labelDims = data.mapDimension('defaultedLabel', true);
  27293. var len = labelDims.length;
  27294. // Simple optimization (in lots of cases, label dims length is 1)
  27295. if (len === 1) {
  27296. return retrieveRawValue(data, dataIndex, labelDims[0]);
  27297. }
  27298. else if (len) {
  27299. var vals = [];
  27300. for (var i = 0; i < labelDims.length; i++) {
  27301. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  27302. vals.push(val);
  27303. }
  27304. return vals.join(' ');
  27305. }
  27306. }
  27307. /**
  27308. * @module echarts/chart/helper/Symbol
  27309. */
  27310. function getSymbolSize(data, idx) {
  27311. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  27312. return symbolSize instanceof Array
  27313. ? symbolSize.slice()
  27314. : [+symbolSize, +symbolSize];
  27315. }
  27316. function getScale(symbolSize) {
  27317. return [symbolSize[0] / 2, symbolSize[1] / 2];
  27318. }
  27319. /**
  27320. * @constructor
  27321. * @alias {module:echarts/chart/helper/Symbol}
  27322. * @param {module:echarts/data/List} data
  27323. * @param {number} idx
  27324. * @extends {module:zrender/graphic/Group}
  27325. */
  27326. function SymbolClz$1(data, idx, seriesScope) {
  27327. Group.call(this);
  27328. this.updateData(data, idx, seriesScope);
  27329. }
  27330. var symbolProto = SymbolClz$1.prototype;
  27331. function driftSymbol(dx, dy) {
  27332. this.parent.drift(dx, dy);
  27333. }
  27334. symbolProto._createSymbol = function (symbolType, data, idx, symbolSize) {
  27335. // Remove paths created before
  27336. this.removeAll();
  27337. var color = data.getItemVisual(idx, 'color');
  27338. // var symbolPath = createSymbol(
  27339. // symbolType, -0.5, -0.5, 1, 1, color
  27340. // );
  27341. // If width/height are set too small (e.g., set to 1) on ios10
  27342. // and macOS Sierra, a circle stroke become a rect, no matter what
  27343. // the scale is set. So we set width/height as 2. See #4150.
  27344. var symbolPath = createSymbol(
  27345. symbolType, -1, -1, 2, 2, color
  27346. );
  27347. symbolPath.attr({
  27348. z2: 100,
  27349. culling: true,
  27350. scale: getScale(symbolSize)
  27351. });
  27352. // Rewrite drift method
  27353. symbolPath.drift = driftSymbol;
  27354. this._symbolType = symbolType;
  27355. this.add(symbolPath);
  27356. };
  27357. /**
  27358. * Stop animation
  27359. * @param {boolean} toLastFrame
  27360. */
  27361. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  27362. this.childAt(0).stopAnimation(toLastFrame);
  27363. };
  27364. /**
  27365. * FIXME:
  27366. * Caution: This method breaks the encapsulation of this module,
  27367. * but it indeed brings convenience. So do not use the method
  27368. * unless you detailedly know all the implements of `Symbol`,
  27369. * especially animation.
  27370. *
  27371. * Get symbol path element.
  27372. */
  27373. symbolProto.getSymbolPath = function () {
  27374. return this.childAt(0);
  27375. };
  27376. /**
  27377. * Get scale(aka, current symbol size).
  27378. * Including the change caused by animation
  27379. */
  27380. symbolProto.getScale = function () {
  27381. return this.childAt(0).scale;
  27382. };
  27383. /**
  27384. * Highlight symbol
  27385. */
  27386. symbolProto.highlight = function () {
  27387. this.childAt(0).trigger('emphasis');
  27388. };
  27389. /**
  27390. * Downplay symbol
  27391. */
  27392. symbolProto.downplay = function () {
  27393. this.childAt(0).trigger('normal');
  27394. };
  27395. /**
  27396. * @param {number} zlevel
  27397. * @param {number} z
  27398. */
  27399. symbolProto.setZ = function (zlevel, z) {
  27400. var symbolPath = this.childAt(0);
  27401. symbolPath.zlevel = zlevel;
  27402. symbolPath.z = z;
  27403. };
  27404. symbolProto.setDraggable = function (draggable) {
  27405. var symbolPath = this.childAt(0);
  27406. symbolPath.draggable = draggable;
  27407. symbolPath.cursor = draggable ? 'move' : 'pointer';
  27408. };
  27409. /**
  27410. * Update symbol properties
  27411. * @param {module:echarts/data/List} data
  27412. * @param {number} idx
  27413. * @param {Object} [seriesScope]
  27414. * @param {Object} [seriesScope.itemStyle]
  27415. * @param {Object} [seriesScope.hoverItemStyle]
  27416. * @param {Object} [seriesScope.symbolRotate]
  27417. * @param {Object} [seriesScope.symbolOffset]
  27418. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  27419. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  27420. * @param {boolean} [seriesScope.hoverAnimation]
  27421. * @param {Object} [seriesScope.cursorStyle]
  27422. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  27423. * @param {string} [seriesScope.symbolInnerColor]
  27424. * @param {Object} [seriesScope.fadeIn=false]
  27425. */
  27426. symbolProto.updateData = function (data, idx, seriesScope) {
  27427. this.silent = false;
  27428. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  27429. var seriesModel = data.hostModel;
  27430. var symbolSize = getSymbolSize(data, idx);
  27431. var isInit = symbolType !== this._symbolType;
  27432. if (isInit) {
  27433. this._createSymbol(symbolType, data, idx, symbolSize);
  27434. }
  27435. else {
  27436. var symbolPath = this.childAt(0);
  27437. symbolPath.silent = false;
  27438. updateProps(symbolPath, {
  27439. scale: getScale(symbolSize)
  27440. }, seriesModel, idx);
  27441. }
  27442. this._updateCommon(data, idx, symbolSize, seriesScope);
  27443. if (isInit) {
  27444. var symbolPath = this.childAt(0);
  27445. var fadeIn = seriesScope && seriesScope.fadeIn;
  27446. var target = {scale: symbolPath.scale.slice()};
  27447. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  27448. symbolPath.scale = [0, 0];
  27449. fadeIn && (symbolPath.style.opacity = 0);
  27450. initProps(symbolPath, target, seriesModel, idx);
  27451. }
  27452. this._seriesModel = seriesModel;
  27453. };
  27454. // Update common properties
  27455. var normalStyleAccessPath = ['itemStyle'];
  27456. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  27457. var normalLabelAccessPath = ['label'];
  27458. var emphasisLabelAccessPath = ['emphasis', 'label'];
  27459. /**
  27460. * @param {module:echarts/data/List} data
  27461. * @param {number} idx
  27462. * @param {Array.<number>} symbolSize
  27463. * @param {Object} [seriesScope]
  27464. */
  27465. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  27466. var symbolPath = this.childAt(0);
  27467. var seriesModel = data.hostModel;
  27468. var color = data.getItemVisual(idx, 'color');
  27469. // Reset style
  27470. if (symbolPath.type !== 'image') {
  27471. symbolPath.useStyle({
  27472. strokeNoScale: true
  27473. });
  27474. }
  27475. var itemStyle = seriesScope && seriesScope.itemStyle;
  27476. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  27477. var symbolRotate = seriesScope && seriesScope.symbolRotate;
  27478. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  27479. var labelModel = seriesScope && seriesScope.labelModel;
  27480. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  27481. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  27482. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  27483. if (!seriesScope || data.hasItemOption) {
  27484. var itemModel = (seriesScope && seriesScope.itemModel)
  27485. ? seriesScope.itemModel : data.getItemModel(idx);
  27486. // Color must be excluded.
  27487. // Because symbol provide setColor individually to set fill and stroke
  27488. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  27489. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  27490. symbolRotate = itemModel.getShallow('symbolRotate');
  27491. symbolOffset = itemModel.getShallow('symbolOffset');
  27492. labelModel = itemModel.getModel(normalLabelAccessPath);
  27493. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  27494. hoverAnimation = itemModel.getShallow('hoverAnimation');
  27495. cursorStyle = itemModel.getShallow('cursor');
  27496. }
  27497. else {
  27498. hoverItemStyle = extend({}, hoverItemStyle);
  27499. }
  27500. var elStyle = symbolPath.style;
  27501. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  27502. if (symbolOffset) {
  27503. symbolPath.attr('position', [
  27504. parsePercent$1(symbolOffset[0], symbolSize[0]),
  27505. parsePercent$1(symbolOffset[1], symbolSize[1])
  27506. ]);
  27507. }
  27508. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  27509. // PENDING setColor before setStyle!!!
  27510. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  27511. symbolPath.setStyle(itemStyle);
  27512. var opacity = data.getItemVisual(idx, 'opacity');
  27513. if (opacity != null) {
  27514. elStyle.opacity = opacity;
  27515. }
  27516. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  27517. setLabelStyle(
  27518. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  27519. {
  27520. labelFetcher: seriesModel,
  27521. labelDataIndex: idx,
  27522. defaultText: getLabelDefaultText,
  27523. isRectText: true,
  27524. autoColor: color
  27525. }
  27526. );
  27527. // Do not execute util needed.
  27528. function getLabelDefaultText(idx, opt) {
  27529. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  27530. }
  27531. symbolPath.off('mouseover')
  27532. .off('mouseout')
  27533. .off('emphasis')
  27534. .off('normal');
  27535. symbolPath.hoverStyle = hoverItemStyle;
  27536. // FIXME
  27537. // Do not use symbol.trigger('emphasis'), but use symbol.highlight() instead.
  27538. setHoverStyle(symbolPath);
  27539. var scale = getScale(symbolSize);
  27540. if (hoverAnimation && seriesModel.isAnimationEnabled()) {
  27541. var onEmphasis = function() {
  27542. // Do not support this hover animation util some scenario required.
  27543. // Animation can only be supported in hover layer when using `el.incremetal`.
  27544. if (this.incremental) {
  27545. return;
  27546. }
  27547. var ratio = scale[1] / scale[0];
  27548. this.animateTo({
  27549. scale: [
  27550. Math.max(scale[0] * 1.1, scale[0] + 3),
  27551. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  27552. ]
  27553. }, 400, 'elasticOut');
  27554. };
  27555. var onNormal = function() {
  27556. if (this.incremental) {
  27557. return;
  27558. }
  27559. this.animateTo({
  27560. scale: scale
  27561. }, 400, 'elasticOut');
  27562. };
  27563. symbolPath.on('mouseover', onEmphasis)
  27564. .on('mouseout', onNormal)
  27565. .on('emphasis', onEmphasis)
  27566. .on('normal', onNormal);
  27567. }
  27568. };
  27569. /**
  27570. * @param {Function} cb
  27571. * @param {Object} [opt]
  27572. * @param {Object} [opt.keepLabel=true]
  27573. */
  27574. symbolProto.fadeOut = function (cb, opt) {
  27575. var symbolPath = this.childAt(0);
  27576. // Avoid mistaken hover when fading out
  27577. this.silent = symbolPath.silent = true;
  27578. // Not show text when animating
  27579. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  27580. updateProps(
  27581. symbolPath,
  27582. {
  27583. style: {opacity: 0},
  27584. scale: [0, 0]
  27585. },
  27586. this._seriesModel,
  27587. this.dataIndex,
  27588. cb
  27589. );
  27590. };
  27591. inherits(SymbolClz$1, Group);
  27592. /**
  27593. * @module echarts/chart/helper/SymbolDraw
  27594. */
  27595. /**
  27596. * @constructor
  27597. * @alias module:echarts/chart/helper/SymbolDraw
  27598. * @param {module:zrender/graphic/Group} [symbolCtor]
  27599. */
  27600. function SymbolDraw(symbolCtor) {
  27601. this.group = new Group();
  27602. this._symbolCtor = symbolCtor || SymbolClz$1;
  27603. }
  27604. var symbolDrawProto = SymbolDraw.prototype;
  27605. function symbolNeedsDraw(data, point, idx, opt) {
  27606. return point && !isNaN(point[0]) && !isNaN(point[1])
  27607. && !(opt.isIgnore && opt.isIgnore(idx))
  27608. // We do not set clipShape on group, because it will
  27609. // cut part of the symbol element shape.
  27610. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1]))
  27611. && data.getItemVisual(idx, 'symbol') !== 'none';
  27612. }
  27613. /**
  27614. * Update symbols draw by new data
  27615. * @param {module:echarts/data/List} data
  27616. * @param {Object} [opt] Or isIgnore
  27617. * @param {Function} [opt.isIgnore]
  27618. * @param {Object} [opt.clipShape]
  27619. */
  27620. symbolDrawProto.updateData = function (data, opt) {
  27621. opt = normalizeUpdateOpt(opt);
  27622. var group = this.group;
  27623. var seriesModel = data.hostModel;
  27624. var oldData = this._data;
  27625. var SymbolCtor = this._symbolCtor;
  27626. var seriesScope = makeSeriesScope(data);
  27627. // There is no oldLineData only when first rendering or switching from
  27628. // stream mode to normal mode, where previous elements should be removed.
  27629. if (!oldData) {
  27630. group.removeAll();
  27631. }
  27632. data.diff(oldData)
  27633. .add(function (newIdx) {
  27634. var point = data.getItemLayout(newIdx);
  27635. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  27636. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  27637. symbolEl.attr('position', point);
  27638. data.setItemGraphicEl(newIdx, symbolEl);
  27639. group.add(symbolEl);
  27640. }
  27641. })
  27642. .update(function (newIdx, oldIdx) {
  27643. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  27644. var point = data.getItemLayout(newIdx);
  27645. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  27646. group.remove(symbolEl);
  27647. return;
  27648. }
  27649. if (!symbolEl) {
  27650. symbolEl = new SymbolCtor(data, newIdx);
  27651. symbolEl.attr('position', point);
  27652. }
  27653. else {
  27654. symbolEl.updateData(data, newIdx, seriesScope);
  27655. updateProps(symbolEl, {
  27656. position: point
  27657. }, seriesModel);
  27658. }
  27659. // Add back
  27660. group.add(symbolEl);
  27661. data.setItemGraphicEl(newIdx, symbolEl);
  27662. })
  27663. .remove(function (oldIdx) {
  27664. var el = oldData.getItemGraphicEl(oldIdx);
  27665. el && el.fadeOut(function () {
  27666. group.remove(el);
  27667. });
  27668. })
  27669. .execute();
  27670. this._data = data;
  27671. };
  27672. symbolDrawProto.isPersistent = function () {
  27673. return true;
  27674. };
  27675. symbolDrawProto.updateLayout = function () {
  27676. var data = this._data;
  27677. if (data) {
  27678. // Not use animation
  27679. data.eachItemGraphicEl(function (el, idx) {
  27680. var point = data.getItemLayout(idx);
  27681. el.attr('position', point);
  27682. });
  27683. }
  27684. };
  27685. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  27686. this._seriesScope = makeSeriesScope(data);
  27687. this._data = null;
  27688. this.group.removeAll();
  27689. };
  27690. /**
  27691. * Update symbols draw by new data
  27692. * @param {module:echarts/data/List} data
  27693. * @param {Object} [opt] Or isIgnore
  27694. * @param {Function} [opt.isIgnore]
  27695. * @param {Object} [opt.clipShape]
  27696. */
  27697. symbolDrawProto.incrementalUpdate = function (taskParams, data, opt) {
  27698. opt = normalizeUpdateOpt(opt);
  27699. function updateIncrementalAndHover(el) {
  27700. if (!el.isGroup) {
  27701. el.incremental = el.useHoverLayer = true;
  27702. }
  27703. }
  27704. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  27705. var point = data.getItemLayout(idx);
  27706. if (symbolNeedsDraw(data, point, idx, opt)) {
  27707. var el = new this._symbolCtor(data, idx, this._seriesScope);
  27708. el.traverse(updateIncrementalAndHover);
  27709. el.attr('position', point);
  27710. this.group.add(el);
  27711. data.setItemGraphicEl(idx, el);
  27712. }
  27713. }
  27714. };
  27715. function normalizeUpdateOpt(opt) {
  27716. if (opt != null && !isObject$1(opt)) {
  27717. opt = {isIgnore: opt};
  27718. }
  27719. return opt || {};
  27720. }
  27721. symbolDrawProto.remove = function (enableAnimation) {
  27722. var group = this.group;
  27723. var data = this._data;
  27724. // Incremental model do not have this._data.
  27725. if (data && enableAnimation) {
  27726. data.eachItemGraphicEl(function (el) {
  27727. el.fadeOut(function () {
  27728. group.remove(el);
  27729. });
  27730. });
  27731. }
  27732. else {
  27733. group.removeAll();
  27734. }
  27735. };
  27736. function makeSeriesScope(data) {
  27737. var seriesModel = data.hostModel;
  27738. return {
  27739. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  27740. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  27741. symbolRotate: seriesModel.get('symbolRotate'),
  27742. symbolOffset: seriesModel.get('symbolOffset'),
  27743. hoverAnimation: seriesModel.get('hoverAnimation'),
  27744. labelModel: seriesModel.getModel('label'),
  27745. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  27746. cursorStyle: seriesModel.get('cursor')
  27747. };
  27748. }
  27749. /**
  27750. * @param {Object} coordSys
  27751. * @param {module:echarts/data/List} data
  27752. * @param {string} valueOrigin lineSeries.option.areaStyle.origin
  27753. */
  27754. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  27755. var baseAxis = coordSys.getBaseAxis();
  27756. var valueAxis = coordSys.getOtherAxis(baseAxis);
  27757. var valueStart = getValueStart(valueAxis, valueOrigin);
  27758. var baseAxisDim = baseAxis.dim;
  27759. var valueAxisDim = valueAxis.dim;
  27760. var valueDim = data.mapDimension(valueAxisDim);
  27761. var baseDim = data.mapDimension(baseAxisDim);
  27762. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  27763. var stacked = isDimensionStacked(data, valueDim, baseDim);
  27764. var dataDimsForPoint = map(coordSys.dimensions, function (coordDim) {
  27765. return data.mapDimension(coordDim);
  27766. });
  27767. return {
  27768. dataDimsForPoint: dataDimsForPoint,
  27769. valueStart: valueStart,
  27770. valueAxisDim: valueAxisDim,
  27771. baseAxisDim: baseAxisDim,
  27772. stacked: stacked,
  27773. valueDim: valueDim,
  27774. baseDim: baseDim,
  27775. baseDataOffset: baseDataOffset,
  27776. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  27777. };
  27778. }
  27779. function getValueStart(valueAxis, valueOrigin) {
  27780. var valueStart = 0;
  27781. var extent = valueAxis.scale.getExtent();
  27782. if (valueOrigin === 'start') {
  27783. valueStart = extent[0];
  27784. }
  27785. else if (valueOrigin === 'end') {
  27786. valueStart = extent[1];
  27787. }
  27788. // auto
  27789. else {
  27790. // Both positive
  27791. if (extent[0] > 0) {
  27792. valueStart = extent[0];
  27793. }
  27794. // Both negative
  27795. else if (extent[1] < 0) {
  27796. valueStart = extent[1];
  27797. }
  27798. // If is one positive, and one negative, onZero shall be true
  27799. }
  27800. return valueStart;
  27801. }
  27802. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  27803. var value = NaN;
  27804. if (dataCoordInfo.stacked) {
  27805. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  27806. }
  27807. if (isNaN(value)) {
  27808. value = dataCoordInfo.valueStart;
  27809. }
  27810. var baseDataOffset = dataCoordInfo.baseDataOffset;
  27811. var stackedData = [];
  27812. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  27813. stackedData[1 - baseDataOffset] = value;
  27814. return coordSys.dataToPoint(stackedData);
  27815. }
  27816. // var arrayDiff = require('zrender/src/core/arrayDiff');
  27817. // 'zrender/src/core/arrayDiff' has been used before, but it did
  27818. // not do well in performance when roam with fixed dataZoom window.
  27819. // function convertToIntId(newIdList, oldIdList) {
  27820. // // Generate int id instead of string id.
  27821. // // Compare string maybe slow in score function of arrDiff
  27822. // // Assume id in idList are all unique
  27823. // var idIndicesMap = {};
  27824. // var idx = 0;
  27825. // for (var i = 0; i < newIdList.length; i++) {
  27826. // idIndicesMap[newIdList[i]] = idx;
  27827. // newIdList[i] = idx++;
  27828. // }
  27829. // for (var i = 0; i < oldIdList.length; i++) {
  27830. // var oldId = oldIdList[i];
  27831. // // Same with newIdList
  27832. // if (idIndicesMap[oldId]) {
  27833. // oldIdList[i] = idIndicesMap[oldId];
  27834. // }
  27835. // else {
  27836. // oldIdList[i] = idx++;
  27837. // }
  27838. // }
  27839. // }
  27840. function diffData(oldData, newData) {
  27841. var diffResult = [];
  27842. newData.diff(oldData)
  27843. .add(function (idx) {
  27844. diffResult.push({cmd: '+', idx: idx});
  27845. })
  27846. .update(function (newIdx, oldIdx) {
  27847. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  27848. })
  27849. .remove(function (idx) {
  27850. diffResult.push({cmd: '-', idx: idx});
  27851. })
  27852. .execute();
  27853. return diffResult;
  27854. }
  27855. var lineAnimationDiff = function (
  27856. oldData, newData,
  27857. oldStackedOnPoints, newStackedOnPoints,
  27858. oldCoordSys, newCoordSys,
  27859. oldValueOrigin, newValueOrigin
  27860. ) {
  27861. var diff = diffData(oldData, newData);
  27862. // var newIdList = newData.mapArray(newData.getId);
  27863. // var oldIdList = oldData.mapArray(oldData.getId);
  27864. // convertToIntId(newIdList, oldIdList);
  27865. // // FIXME One data ?
  27866. // diff = arrayDiff(oldIdList, newIdList);
  27867. var currPoints = [];
  27868. var nextPoints = [];
  27869. // Points for stacking base line
  27870. var currStackedPoints = [];
  27871. var nextStackedPoints = [];
  27872. var status = [];
  27873. var sortedIndices = [];
  27874. var rawIndices = [];
  27875. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  27876. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  27877. for (var i = 0; i < diff.length; i++) {
  27878. var diffItem = diff[i];
  27879. var pointAdded = true;
  27880. // FIXME, animation is not so perfect when dataZoom window moves fast
  27881. // Which is in case remvoing or add more than one data in the tail or head
  27882. switch (diffItem.cmd) {
  27883. case '=':
  27884. var currentPt = oldData.getItemLayout(diffItem.idx);
  27885. var nextPt = newData.getItemLayout(diffItem.idx1);
  27886. // If previous data is NaN, use next point directly
  27887. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  27888. currentPt = nextPt.slice();
  27889. }
  27890. currPoints.push(currentPt);
  27891. nextPoints.push(nextPt);
  27892. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  27893. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  27894. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  27895. break;
  27896. case '+':
  27897. var idx = diffItem.idx;
  27898. currPoints.push(
  27899. oldCoordSys.dataToPoint([
  27900. newData.get(newDataOldCoordInfo.dataDimsForPoint[0], idx),
  27901. newData.get(newDataOldCoordInfo.dataDimsForPoint[1], idx)
  27902. ])
  27903. );
  27904. nextPoints.push(newData.getItemLayout(idx).slice());
  27905. currStackedPoints.push(
  27906. getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, idx)
  27907. );
  27908. nextStackedPoints.push(newStackedOnPoints[idx]);
  27909. rawIndices.push(newData.getRawIndex(idx));
  27910. break;
  27911. case '-':
  27912. var idx = diffItem.idx;
  27913. var rawIndex = oldData.getRawIndex(idx);
  27914. // Data is replaced. In the case of dynamic data queue
  27915. // FIXME FIXME FIXME
  27916. if (rawIndex !== idx) {
  27917. currPoints.push(oldData.getItemLayout(idx));
  27918. nextPoints.push(newCoordSys.dataToPoint([
  27919. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[0], idx),
  27920. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[1], idx)
  27921. ]));
  27922. currStackedPoints.push(oldStackedOnPoints[idx]);
  27923. nextStackedPoints.push(
  27924. getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, idx)
  27925. );
  27926. rawIndices.push(rawIndex);
  27927. }
  27928. else {
  27929. pointAdded = false;
  27930. }
  27931. }
  27932. // Original indices
  27933. if (pointAdded) {
  27934. status.push(diffItem);
  27935. sortedIndices.push(sortedIndices.length);
  27936. }
  27937. }
  27938. // Diff result may be crossed if all items are changed
  27939. // Sort by data index
  27940. sortedIndices.sort(function (a, b) {
  27941. return rawIndices[a] - rawIndices[b];
  27942. });
  27943. var sortedCurrPoints = [];
  27944. var sortedNextPoints = [];
  27945. var sortedCurrStackedPoints = [];
  27946. var sortedNextStackedPoints = [];
  27947. var sortedStatus = [];
  27948. for (var i = 0; i < sortedIndices.length; i++) {
  27949. var idx = sortedIndices[i];
  27950. sortedCurrPoints[i] = currPoints[idx];
  27951. sortedNextPoints[i] = nextPoints[idx];
  27952. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  27953. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  27954. sortedStatus[i] = status[idx];
  27955. }
  27956. return {
  27957. current: sortedCurrPoints,
  27958. next: sortedNextPoints,
  27959. stackedOnCurrent: sortedCurrStackedPoints,
  27960. stackedOnNext: sortedNextStackedPoints,
  27961. status: sortedStatus
  27962. };
  27963. };
  27964. // Poly path support NaN point
  27965. var vec2Min = min;
  27966. var vec2Max = max;
  27967. var scaleAndAdd$1 = scaleAndAdd;
  27968. var v2Copy = copy;
  27969. // Temporary variable
  27970. var v = [];
  27971. var cp0 = [];
  27972. var cp1 = [];
  27973. function isPointNull(p) {
  27974. return isNaN(p[0]) || isNaN(p[1]);
  27975. }
  27976. function drawSegment(
  27977. ctx, points, start, segLen, allLen,
  27978. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  27979. ) {
  27980. if (smoothMonotone == null) {
  27981. if (isMono(points, 'x')) {
  27982. return drawMono(ctx, points, start, segLen, allLen,
  27983. dir, smoothMin, smoothMax, smooth, 'x', connectNulls);
  27984. }
  27985. else if (isMono(points, 'y')) {
  27986. return drawMono(ctx, points, start, segLen, allLen,
  27987. dir, smoothMin, smoothMax, smooth, 'y', connectNulls);
  27988. }
  27989. else {
  27990. return drawNonMono.apply(this, arguments);
  27991. }
  27992. }
  27993. else if (smoothMonotone !== 'none' && isMono(points, smoothMonotone)) {
  27994. return drawMono.apply(this, arguments);
  27995. }
  27996. else {
  27997. return drawNonMono.apply(this, arguments);
  27998. }
  27999. }
  28000. /**
  28001. * Check if points is in monotone.
  28002. *
  28003. * @param {number[][]} points Array of points which is in [x, y] form
  28004. * @param {string} smoothMonotone 'x', 'y', or 'none', stating for which
  28005. * dimension that is checking.
  28006. * If is 'none', `drawNonMono` should be
  28007. * called.
  28008. * If is undefined, either being monotone
  28009. * in 'x' or 'y' will call `drawMono`.
  28010. */
  28011. function isMono(points, smoothMonotone) {
  28012. if (points.length <= 1) {
  28013. return true;
  28014. }
  28015. var dim = smoothMonotone === 'x' ? 0 : 1;
  28016. var last = points[0][dim];
  28017. var lastDiff = 0;
  28018. for (var i = 1; i < points.length; ++i) {
  28019. var diff = points[i][dim] - last;
  28020. if (!isNaN(diff) && !isNaN(lastDiff)
  28021. && diff !== 0 && lastDiff !== 0
  28022. && ((diff >= 0) !== (lastDiff >= 0))
  28023. ) {
  28024. return false;
  28025. }
  28026. if (!isNaN(diff) && diff !== 0) {
  28027. lastDiff = diff;
  28028. last = points[i][dim];
  28029. }
  28030. }
  28031. return true;
  28032. }
  28033. /**
  28034. * Draw smoothed line in monotone, in which only vertical or horizontal bezier
  28035. * control points will be used. This should be used when points are monotone
  28036. * either in x or y dimension.
  28037. */
  28038. function drawMono(
  28039. ctx, points, start, segLen, allLen,
  28040. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  28041. ) {
  28042. var prevIdx = 0;
  28043. var idx = start;
  28044. for (var k = 0; k < segLen; k++) {
  28045. var p = points[idx];
  28046. if (idx >= allLen || idx < 0) {
  28047. break;
  28048. }
  28049. if (isPointNull(p)) {
  28050. if (connectNulls) {
  28051. idx += dir;
  28052. continue;
  28053. }
  28054. break;
  28055. }
  28056. if (idx === start) {
  28057. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  28058. }
  28059. else {
  28060. if (smooth > 0) {
  28061. var prevP = points[prevIdx];
  28062. var dim = smoothMonotone === 'y' ? 1 : 0;
  28063. // Length of control point to p, either in x or y, but not both
  28064. var ctrlLen = (p[dim] - prevP[dim]) * smooth;
  28065. v2Copy(cp0, prevP);
  28066. cp0[dim] = prevP[dim] + ctrlLen;
  28067. v2Copy(cp1, p);
  28068. cp1[dim] = p[dim] - ctrlLen;
  28069. ctx.bezierCurveTo(
  28070. cp0[0], cp0[1],
  28071. cp1[0], cp1[1],
  28072. p[0], p[1]
  28073. );
  28074. }
  28075. else {
  28076. ctx.lineTo(p[0], p[1]);
  28077. }
  28078. }
  28079. prevIdx = idx;
  28080. idx += dir;
  28081. }
  28082. return k;
  28083. }
  28084. /**
  28085. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  28086. * situations. This should be used when points are non-monotone neither in x or
  28087. * y dimension.
  28088. */
  28089. function drawNonMono(
  28090. ctx, points, start, segLen, allLen,
  28091. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  28092. ) {
  28093. var prevIdx = 0;
  28094. var idx = start;
  28095. for (var k = 0; k < segLen; k++) {
  28096. var p = points[idx];
  28097. if (idx >= allLen || idx < 0) {
  28098. break;
  28099. }
  28100. if (isPointNull(p)) {
  28101. if (connectNulls) {
  28102. idx += dir;
  28103. continue;
  28104. }
  28105. break;
  28106. }
  28107. if (idx === start) {
  28108. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  28109. v2Copy(cp0, p);
  28110. }
  28111. else {
  28112. if (smooth > 0) {
  28113. var nextIdx = idx + dir;
  28114. var nextP = points[nextIdx];
  28115. if (connectNulls) {
  28116. // Find next point not null
  28117. while (nextP && isPointNull(points[nextIdx])) {
  28118. nextIdx += dir;
  28119. nextP = points[nextIdx];
  28120. }
  28121. }
  28122. var ratioNextSeg = 0.5;
  28123. var prevP = points[prevIdx];
  28124. var nextP = points[nextIdx];
  28125. // Last point
  28126. if (!nextP || isPointNull(nextP)) {
  28127. v2Copy(cp1, p);
  28128. }
  28129. else {
  28130. // If next data is null in not connect case
  28131. if (isPointNull(nextP) && !connectNulls) {
  28132. nextP = p;
  28133. }
  28134. sub(v, nextP, prevP);
  28135. var lenPrevSeg;
  28136. var lenNextSeg;
  28137. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  28138. var dim = smoothMonotone === 'x' ? 0 : 1;
  28139. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  28140. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  28141. }
  28142. else {
  28143. lenPrevSeg = dist(p, prevP);
  28144. lenNextSeg = dist(p, nextP);
  28145. }
  28146. // Use ratio of seg length
  28147. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  28148. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  28149. }
  28150. // Smooth constraint
  28151. vec2Min(cp0, cp0, smoothMax);
  28152. vec2Max(cp0, cp0, smoothMin);
  28153. vec2Min(cp1, cp1, smoothMax);
  28154. vec2Max(cp1, cp1, smoothMin);
  28155. ctx.bezierCurveTo(
  28156. cp0[0], cp0[1],
  28157. cp1[0], cp1[1],
  28158. p[0], p[1]
  28159. );
  28160. // cp0 of next segment
  28161. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  28162. }
  28163. else {
  28164. ctx.lineTo(p[0], p[1]);
  28165. }
  28166. }
  28167. prevIdx = idx;
  28168. idx += dir;
  28169. }
  28170. return k;
  28171. }
  28172. function getBoundingBox(points, smoothConstraint) {
  28173. var ptMin = [Infinity, Infinity];
  28174. var ptMax = [-Infinity, -Infinity];
  28175. if (smoothConstraint) {
  28176. for (var i = 0; i < points.length; i++) {
  28177. var pt = points[i];
  28178. if (pt[0] < ptMin[0]) { ptMin[0] = pt[0]; }
  28179. if (pt[1] < ptMin[1]) { ptMin[1] = pt[1]; }
  28180. if (pt[0] > ptMax[0]) { ptMax[0] = pt[0]; }
  28181. if (pt[1] > ptMax[1]) { ptMax[1] = pt[1]; }
  28182. }
  28183. }
  28184. return {
  28185. min: smoothConstraint ? ptMin : ptMax,
  28186. max: smoothConstraint ? ptMax : ptMin
  28187. };
  28188. }
  28189. var Polyline$1 = Path.extend({
  28190. type: 'ec-polyline',
  28191. shape: {
  28192. points: [],
  28193. smooth: 0,
  28194. smoothConstraint: true,
  28195. smoothMonotone: null,
  28196. connectNulls: false
  28197. },
  28198. style: {
  28199. fill: null,
  28200. stroke: '#000'
  28201. },
  28202. brush: fixClipWithShadow(Path.prototype.brush),
  28203. buildPath: function (ctx, shape) {
  28204. var points = shape.points;
  28205. var i = 0;
  28206. var len$$1 = points.length;
  28207. var result = getBoundingBox(points, shape.smoothConstraint);
  28208. if (shape.connectNulls) {
  28209. // Must remove first and last null values avoid draw error in polygon
  28210. for (; len$$1 > 0; len$$1--) {
  28211. if (!isPointNull(points[len$$1 - 1])) {
  28212. break;
  28213. }
  28214. }
  28215. for (; i < len$$1; i++) {
  28216. if (!isPointNull(points[i])) {
  28217. break;
  28218. }
  28219. }
  28220. }
  28221. while (i < len$$1) {
  28222. i += drawSegment(
  28223. ctx, points, i, len$$1, len$$1,
  28224. 1, result.min, result.max, shape.smooth,
  28225. shape.smoothMonotone, shape.connectNulls
  28226. ) + 1;
  28227. }
  28228. }
  28229. });
  28230. var Polygon$1 = Path.extend({
  28231. type: 'ec-polygon',
  28232. shape: {
  28233. points: [],
  28234. // Offset between stacked base points and points
  28235. stackedOnPoints: [],
  28236. smooth: 0,
  28237. stackedOnSmooth: 0,
  28238. smoothConstraint: true,
  28239. smoothMonotone: null,
  28240. connectNulls: false
  28241. },
  28242. brush: fixClipWithShadow(Path.prototype.brush),
  28243. buildPath: function (ctx, shape) {
  28244. var points = shape.points;
  28245. var stackedOnPoints = shape.stackedOnPoints;
  28246. var i = 0;
  28247. var len$$1 = points.length;
  28248. var smoothMonotone = shape.smoothMonotone;
  28249. var bbox = getBoundingBox(points, shape.smoothConstraint);
  28250. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  28251. if (shape.connectNulls) {
  28252. // Must remove first and last null values avoid draw error in polygon
  28253. for (; len$$1 > 0; len$$1--) {
  28254. if (!isPointNull(points[len$$1 - 1])) {
  28255. break;
  28256. }
  28257. }
  28258. for (; i < len$$1; i++) {
  28259. if (!isPointNull(points[i])) {
  28260. break;
  28261. }
  28262. }
  28263. }
  28264. while (i < len$$1) {
  28265. var k = drawSegment(
  28266. ctx, points, i, len$$1, len$$1,
  28267. 1, bbox.min, bbox.max, shape.smooth,
  28268. smoothMonotone, shape.connectNulls
  28269. );
  28270. drawSegment(
  28271. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  28272. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  28273. smoothMonotone, shape.connectNulls
  28274. );
  28275. i += k + 1;
  28276. ctx.closePath();
  28277. }
  28278. }
  28279. });
  28280. // FIXME step not support polar
  28281. function isPointsSame(points1, points2) {
  28282. if (points1.length !== points2.length) {
  28283. return;
  28284. }
  28285. for (var i = 0; i < points1.length; i++) {
  28286. var p1 = points1[i];
  28287. var p2 = points2[i];
  28288. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  28289. return;
  28290. }
  28291. }
  28292. return true;
  28293. }
  28294. function getSmooth(smooth) {
  28295. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.5 : 0);
  28296. }
  28297. function getAxisExtentWithGap(axis) {
  28298. var extent = axis.getGlobalExtent();
  28299. if (axis.onBand) {
  28300. // Remove extra 1px to avoid line miter in clipped edge
  28301. var halfBandWidth = axis.getBandWidth() / 2 - 1;
  28302. var dir = extent[1] > extent[0] ? 1 : -1;
  28303. extent[0] += dir * halfBandWidth;
  28304. extent[1] -= dir * halfBandWidth;
  28305. }
  28306. return extent;
  28307. }
  28308. /**
  28309. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  28310. * @param {module:echarts/data/List} data
  28311. * @param {Object} dataCoordInfo
  28312. * @param {Array.<Array.<number>>} points
  28313. */
  28314. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  28315. if (!dataCoordInfo.valueDim) {
  28316. return [];
  28317. }
  28318. var points = [];
  28319. for (var idx = 0, len = data.count(); idx < len; idx++) {
  28320. points.push(getStackedOnPoint(dataCoordInfo, coordSys, data, idx));
  28321. }
  28322. return points;
  28323. }
  28324. function createGridClipShape(cartesian, hasAnimation, seriesModel) {
  28325. var xExtent = getAxisExtentWithGap(cartesian.getAxis('x'));
  28326. var yExtent = getAxisExtentWithGap(cartesian.getAxis('y'));
  28327. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  28328. var x = Math.min(xExtent[0], xExtent[1]);
  28329. var y = Math.min(yExtent[0], yExtent[1]);
  28330. var width = Math.max(xExtent[0], xExtent[1]) - x;
  28331. var height = Math.max(yExtent[0], yExtent[1]) - y;
  28332. var lineWidth = seriesModel.get('lineStyle.width') || 2;
  28333. // Expand clip shape to avoid clipping when line value exceeds axis
  28334. var expandSize = seriesModel.get('clipOverflow') ? lineWidth / 2 : Math.max(width, height);
  28335. if (isHorizontal) {
  28336. y -= expandSize;
  28337. height += expandSize * 2;
  28338. }
  28339. else {
  28340. x -= expandSize;
  28341. width += expandSize * 2;
  28342. }
  28343. var clipPath = new Rect({
  28344. shape: {
  28345. x: x,
  28346. y: y,
  28347. width: width,
  28348. height: height
  28349. }
  28350. });
  28351. if (hasAnimation) {
  28352. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  28353. initProps(clipPath, {
  28354. shape: {
  28355. width: width,
  28356. height: height
  28357. }
  28358. }, seriesModel);
  28359. }
  28360. return clipPath;
  28361. }
  28362. function createPolarClipShape(polar, hasAnimation, seriesModel) {
  28363. var angleAxis = polar.getAngleAxis();
  28364. var radiusAxis = polar.getRadiusAxis();
  28365. var radiusExtent = radiusAxis.getExtent();
  28366. var angleExtent = angleAxis.getExtent();
  28367. var RADIAN = Math.PI / 180;
  28368. var clipPath = new Sector({
  28369. shape: {
  28370. cx: polar.cx,
  28371. cy: polar.cy,
  28372. r0: radiusExtent[0],
  28373. r: radiusExtent[1],
  28374. startAngle: -angleExtent[0] * RADIAN,
  28375. endAngle: -angleExtent[1] * RADIAN,
  28376. clockwise: angleAxis.inverse
  28377. }
  28378. });
  28379. if (hasAnimation) {
  28380. clipPath.shape.endAngle = -angleExtent[0] * RADIAN;
  28381. initProps(clipPath, {
  28382. shape: {
  28383. endAngle: -angleExtent[1] * RADIAN
  28384. }
  28385. }, seriesModel);
  28386. }
  28387. return clipPath;
  28388. }
  28389. function createClipShape(coordSys, hasAnimation, seriesModel) {
  28390. return coordSys.type === 'polar'
  28391. ? createPolarClipShape(coordSys, hasAnimation, seriesModel)
  28392. : createGridClipShape(coordSys, hasAnimation, seriesModel);
  28393. }
  28394. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  28395. var baseAxis = coordSys.getBaseAxis();
  28396. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  28397. var stepPoints = [];
  28398. for (var i = 0; i < points.length - 1; i++) {
  28399. var nextPt = points[i + 1];
  28400. var pt = points[i];
  28401. stepPoints.push(pt);
  28402. var stepPt = [];
  28403. switch (stepTurnAt) {
  28404. case 'end':
  28405. stepPt[baseIndex] = nextPt[baseIndex];
  28406. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  28407. // default is start
  28408. stepPoints.push(stepPt);
  28409. break;
  28410. case 'middle':
  28411. // default is start
  28412. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  28413. var stepPt2 = [];
  28414. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  28415. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  28416. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  28417. stepPoints.push(stepPt);
  28418. stepPoints.push(stepPt2);
  28419. break;
  28420. default:
  28421. stepPt[baseIndex] = pt[baseIndex];
  28422. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  28423. // default is start
  28424. stepPoints.push(stepPt);
  28425. }
  28426. }
  28427. // Last points
  28428. points[i] && stepPoints.push(points[i]);
  28429. return stepPoints;
  28430. }
  28431. function getVisualGradient(data, coordSys) {
  28432. var visualMetaList = data.getVisual('visualMeta');
  28433. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  28434. // When data.count() is 0, gradient range can not be calculated.
  28435. return;
  28436. }
  28437. if (coordSys.type !== 'cartesian2d') {
  28438. if (__DEV__) {
  28439. console.warn('Visual map on line style is only supported on cartesian2d.');
  28440. }
  28441. return;
  28442. }
  28443. var coordDim;
  28444. var visualMeta;
  28445. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  28446. var dimIndex = visualMetaList[i].dimension;
  28447. var dimName = data.dimensions[dimIndex];
  28448. var dimInfo = data.getDimensionInfo(dimName);
  28449. coordDim = dimInfo && dimInfo.coordDim;
  28450. // Can only be x or y
  28451. if (coordDim === 'x' || coordDim === 'y') {
  28452. visualMeta = visualMetaList[i];
  28453. break;
  28454. }
  28455. }
  28456. if (!visualMeta) {
  28457. if (__DEV__) {
  28458. console.warn('Visual map on line style only support x or y dimension.');
  28459. }
  28460. return;
  28461. }
  28462. // If the area to be rendered is bigger than area defined by LinearGradient,
  28463. // the canvas spec prescribes that the color of the first stop and the last
  28464. // stop should be used. But if two stops are added at offset 0, in effect
  28465. // browsers use the color of the second stop to render area outside
  28466. // LinearGradient. So we can only infinitesimally extend area defined in
  28467. // LinearGradient to render `outerColors`.
  28468. var axis = coordSys.getAxis(coordDim);
  28469. // dataToCoor mapping may not be linear, but must be monotonic.
  28470. var colorStops = map(visualMeta.stops, function (stop) {
  28471. return {
  28472. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  28473. color: stop.color
  28474. };
  28475. });
  28476. var stopLen = colorStops.length;
  28477. var outerColors = visualMeta.outerColors.slice();
  28478. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  28479. colorStops.reverse();
  28480. outerColors.reverse();
  28481. }
  28482. var tinyExtent = 10; // Arbitrary value: 10px
  28483. var minCoord = colorStops[0].coord - tinyExtent;
  28484. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  28485. var coordSpan = maxCoord - minCoord;
  28486. if (coordSpan < 1e-3) {
  28487. return 'transparent';
  28488. }
  28489. each$1(colorStops, function (stop) {
  28490. stop.offset = (stop.coord - minCoord) / coordSpan;
  28491. });
  28492. colorStops.push({
  28493. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  28494. color: outerColors[1] || 'transparent'
  28495. });
  28496. colorStops.unshift({ // notice colorStops.length have been changed.
  28497. offset: stopLen ? colorStops[0].offset : 0.5,
  28498. color: outerColors[0] || 'transparent'
  28499. });
  28500. // zrUtil.each(colorStops, function (colorStop) {
  28501. // // Make sure each offset has rounded px to avoid not sharp edge
  28502. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  28503. // });
  28504. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  28505. gradient[coordDim] = minCoord;
  28506. gradient[coordDim + '2'] = maxCoord;
  28507. return gradient;
  28508. }
  28509. Chart.extend({
  28510. type: 'line',
  28511. init: function () {
  28512. var lineGroup = new Group();
  28513. var symbolDraw = new SymbolDraw();
  28514. this.group.add(symbolDraw.group);
  28515. this._symbolDraw = symbolDraw;
  28516. this._lineGroup = lineGroup;
  28517. },
  28518. render: function (seriesModel, ecModel, api) {
  28519. var coordSys = seriesModel.coordinateSystem;
  28520. var group = this.group;
  28521. var data = seriesModel.getData();
  28522. var lineStyleModel = seriesModel.getModel('lineStyle');
  28523. var areaStyleModel = seriesModel.getModel('areaStyle');
  28524. var points = data.mapArray(data.getItemLayout);
  28525. var isCoordSysPolar = coordSys.type === 'polar';
  28526. var prevCoordSys = this._coordSys;
  28527. var symbolDraw = this._symbolDraw;
  28528. var polyline = this._polyline;
  28529. var polygon = this._polygon;
  28530. var lineGroup = this._lineGroup;
  28531. var hasAnimation = seriesModel.get('animation');
  28532. var isAreaChart = !areaStyleModel.isEmpty();
  28533. var valueOrigin = areaStyleModel.get('origin');
  28534. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  28535. var stackedOnPoints = getStackedOnPoints(coordSys, data, dataCoordInfo);
  28536. var showSymbol = seriesModel.get('showSymbol');
  28537. var isSymbolIgnore = showSymbol && !isCoordSysPolar && !seriesModel.get('showAllSymbol')
  28538. && this._getSymbolIgnoreFunc(data, coordSys);
  28539. // Remove temporary symbols
  28540. var oldData = this._data;
  28541. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  28542. if (el.__temp) {
  28543. group.remove(el);
  28544. oldData.setItemGraphicEl(idx, null);
  28545. }
  28546. });
  28547. // Remove previous created symbols if showSymbol changed to false
  28548. if (!showSymbol) {
  28549. symbolDraw.remove();
  28550. }
  28551. group.add(lineGroup);
  28552. // FIXME step not support polar
  28553. var step = !isCoordSysPolar && seriesModel.get('step');
  28554. // Initialization animation or coordinate system changed
  28555. if (
  28556. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  28557. ) {
  28558. showSymbol && symbolDraw.updateData(data, {
  28559. isIgnore: isSymbolIgnore,
  28560. clipShape: createClipShape(coordSys, false, seriesModel)
  28561. });
  28562. if (step) {
  28563. // TODO If stacked series is not step
  28564. points = turnPointsIntoStep(points, coordSys, step);
  28565. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  28566. }
  28567. polyline = this._newPolyline(points, coordSys, hasAnimation);
  28568. if (isAreaChart) {
  28569. polygon = this._newPolygon(
  28570. points, stackedOnPoints,
  28571. coordSys, hasAnimation
  28572. );
  28573. }
  28574. lineGroup.setClipPath(createClipShape(coordSys, true, seriesModel));
  28575. }
  28576. else {
  28577. if (isAreaChart && !polygon) {
  28578. // If areaStyle is added
  28579. polygon = this._newPolygon(
  28580. points, stackedOnPoints,
  28581. coordSys, hasAnimation
  28582. );
  28583. }
  28584. else if (polygon && !isAreaChart) {
  28585. // If areaStyle is removed
  28586. lineGroup.remove(polygon);
  28587. polygon = this._polygon = null;
  28588. }
  28589. var coordSysClipShape = createClipShape(coordSys, false, seriesModel);
  28590. // Update clipPath
  28591. lineGroup.setClipPath(coordSysClipShape);
  28592. // Always update, or it is wrong in the case turning on legend
  28593. // because points are not changed
  28594. showSymbol && symbolDraw.updateData(data, {
  28595. isIgnore: isSymbolIgnore,
  28596. clipShape: coordSysClipShape
  28597. });
  28598. // Stop symbol animation and sync with line points
  28599. // FIXME performance?
  28600. data.eachItemGraphicEl(function (el) {
  28601. el.stopAnimation(true);
  28602. });
  28603. // In the case data zoom triggerred refreshing frequently
  28604. // Data may not change if line has a category axis. So it should animate nothing
  28605. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  28606. || !isPointsSame(this._points, points)
  28607. ) {
  28608. if (hasAnimation) {
  28609. this._updateAnimation(
  28610. data, stackedOnPoints, coordSys, api, step, valueOrigin
  28611. );
  28612. }
  28613. else {
  28614. // Not do it in update with animation
  28615. if (step) {
  28616. // TODO If stacked series is not step
  28617. points = turnPointsIntoStep(points, coordSys, step);
  28618. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  28619. }
  28620. polyline.setShape({
  28621. points: points
  28622. });
  28623. polygon && polygon.setShape({
  28624. points: points,
  28625. stackedOnPoints: stackedOnPoints
  28626. });
  28627. }
  28628. }
  28629. }
  28630. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  28631. polyline.useStyle(defaults(
  28632. // Use color in lineStyle first
  28633. lineStyleModel.getLineStyle(),
  28634. {
  28635. fill: 'none',
  28636. stroke: visualColor,
  28637. lineJoin: 'bevel'
  28638. }
  28639. ));
  28640. var smooth = seriesModel.get('smooth');
  28641. smooth = getSmooth(seriesModel.get('smooth'));
  28642. polyline.setShape({
  28643. smooth: smooth,
  28644. smoothMonotone: seriesModel.get('smoothMonotone'),
  28645. connectNulls: seriesModel.get('connectNulls')
  28646. });
  28647. if (polygon) {
  28648. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  28649. var stackedOnSmooth = 0;
  28650. polygon.useStyle(defaults(
  28651. areaStyleModel.getAreaStyle(),
  28652. {
  28653. fill: visualColor,
  28654. opacity: 0.7,
  28655. lineJoin: 'bevel'
  28656. }
  28657. ));
  28658. if (stackedOnSeries) {
  28659. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  28660. }
  28661. polygon.setShape({
  28662. smooth: smooth,
  28663. stackedOnSmooth: stackedOnSmooth,
  28664. smoothMonotone: seriesModel.get('smoothMonotone'),
  28665. connectNulls: seriesModel.get('connectNulls')
  28666. });
  28667. }
  28668. this._data = data;
  28669. // Save the coordinate system for transition animation when data changed
  28670. this._coordSys = coordSys;
  28671. this._stackedOnPoints = stackedOnPoints;
  28672. this._points = points;
  28673. this._step = step;
  28674. this._valueOrigin = valueOrigin;
  28675. },
  28676. dispose: function () {},
  28677. highlight: function (seriesModel, ecModel, api, payload) {
  28678. var data = seriesModel.getData();
  28679. var dataIndex = queryDataIndex(data, payload);
  28680. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  28681. var symbol = data.getItemGraphicEl(dataIndex);
  28682. if (!symbol) {
  28683. // Create a temporary symbol if it is not exists
  28684. var pt = data.getItemLayout(dataIndex);
  28685. if (!pt) {
  28686. // Null data
  28687. return;
  28688. }
  28689. symbol = new SymbolClz$1(data, dataIndex);
  28690. symbol.position = pt;
  28691. symbol.setZ(
  28692. seriesModel.get('zlevel'),
  28693. seriesModel.get('z')
  28694. );
  28695. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  28696. symbol.__temp = true;
  28697. data.setItemGraphicEl(dataIndex, symbol);
  28698. // Stop scale animation
  28699. symbol.stopSymbolAnimation(true);
  28700. this.group.add(symbol);
  28701. }
  28702. symbol.highlight();
  28703. }
  28704. else {
  28705. // Highlight whole series
  28706. Chart.prototype.highlight.call(
  28707. this, seriesModel, ecModel, api, payload
  28708. );
  28709. }
  28710. },
  28711. downplay: function (seriesModel, ecModel, api, payload) {
  28712. var data = seriesModel.getData();
  28713. var dataIndex = queryDataIndex(data, payload);
  28714. if (dataIndex != null && dataIndex >= 0) {
  28715. var symbol = data.getItemGraphicEl(dataIndex);
  28716. if (symbol) {
  28717. if (symbol.__temp) {
  28718. data.setItemGraphicEl(dataIndex, null);
  28719. this.group.remove(symbol);
  28720. }
  28721. else {
  28722. symbol.downplay();
  28723. }
  28724. }
  28725. }
  28726. else {
  28727. // FIXME
  28728. // can not downplay completely.
  28729. // Downplay whole series
  28730. Chart.prototype.downplay.call(
  28731. this, seriesModel, ecModel, api, payload
  28732. );
  28733. }
  28734. },
  28735. /**
  28736. * @param {module:zrender/container/Group} group
  28737. * @param {Array.<Array.<number>>} points
  28738. * @private
  28739. */
  28740. _newPolyline: function (points) {
  28741. var polyline = this._polyline;
  28742. // Remove previous created polyline
  28743. if (polyline) {
  28744. this._lineGroup.remove(polyline);
  28745. }
  28746. polyline = new Polyline$1({
  28747. shape: {
  28748. points: points
  28749. },
  28750. silent: true,
  28751. z2: 10
  28752. });
  28753. this._lineGroup.add(polyline);
  28754. this._polyline = polyline;
  28755. return polyline;
  28756. },
  28757. /**
  28758. * @param {module:zrender/container/Group} group
  28759. * @param {Array.<Array.<number>>} stackedOnPoints
  28760. * @param {Array.<Array.<number>>} points
  28761. * @private
  28762. */
  28763. _newPolygon: function (points, stackedOnPoints) {
  28764. var polygon = this._polygon;
  28765. // Remove previous created polygon
  28766. if (polygon) {
  28767. this._lineGroup.remove(polygon);
  28768. }
  28769. polygon = new Polygon$1({
  28770. shape: {
  28771. points: points,
  28772. stackedOnPoints: stackedOnPoints
  28773. },
  28774. silent: true
  28775. });
  28776. this._lineGroup.add(polygon);
  28777. this._polygon = polygon;
  28778. return polygon;
  28779. },
  28780. /**
  28781. * @private
  28782. */
  28783. _getSymbolIgnoreFunc: function (data, coordSys) {
  28784. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  28785. // `getLabelInterval` is provided by echarts/component/axis
  28786. if (categoryAxis && categoryAxis.isLabelIgnored) {
  28787. return bind(categoryAxis.isLabelIgnored, categoryAxis);
  28788. }
  28789. },
  28790. /**
  28791. * @private
  28792. */
  28793. // FIXME Two value axis
  28794. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  28795. var polyline = this._polyline;
  28796. var polygon = this._polygon;
  28797. var seriesModel = data.hostModel;
  28798. var diff = lineAnimationDiff(
  28799. this._data, data,
  28800. this._stackedOnPoints, stackedOnPoints,
  28801. this._coordSys, coordSys,
  28802. this._valueOrigin, valueOrigin
  28803. );
  28804. var current = diff.current;
  28805. var stackedOnCurrent = diff.stackedOnCurrent;
  28806. var next = diff.next;
  28807. var stackedOnNext = diff.stackedOnNext;
  28808. if (step) {
  28809. // TODO If stacked series is not step
  28810. current = turnPointsIntoStep(diff.current, coordSys, step);
  28811. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  28812. next = turnPointsIntoStep(diff.next, coordSys, step);
  28813. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  28814. }
  28815. // `diff.current` is subset of `current` (which should be ensured by
  28816. // turnPointsIntoStep), so points in `__points` can be updated when
  28817. // points in `current` are update during animation.
  28818. polyline.shape.__points = diff.current;
  28819. polyline.shape.points = current;
  28820. updateProps(polyline, {
  28821. shape: {
  28822. points: next
  28823. }
  28824. }, seriesModel);
  28825. if (polygon) {
  28826. polygon.setShape({
  28827. points: current,
  28828. stackedOnPoints: stackedOnCurrent
  28829. });
  28830. updateProps(polygon, {
  28831. shape: {
  28832. points: next,
  28833. stackedOnPoints: stackedOnNext
  28834. }
  28835. }, seriesModel);
  28836. }
  28837. var updatedDataInfo = [];
  28838. var diffStatus = diff.status;
  28839. for (var i = 0; i < diffStatus.length; i++) {
  28840. var cmd = diffStatus[i].cmd;
  28841. if (cmd === '=') {
  28842. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  28843. if (el) {
  28844. updatedDataInfo.push({
  28845. el: el,
  28846. ptIdx: i // Index of points
  28847. });
  28848. }
  28849. }
  28850. }
  28851. if (polyline.animators && polyline.animators.length) {
  28852. polyline.animators[0].during(function () {
  28853. for (var i = 0; i < updatedDataInfo.length; i++) {
  28854. var el = updatedDataInfo[i].el;
  28855. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  28856. }
  28857. });
  28858. }
  28859. },
  28860. remove: function (ecModel) {
  28861. var group = this.group;
  28862. var oldData = this._data;
  28863. this._lineGroup.removeAll();
  28864. this._symbolDraw.remove(true);
  28865. // Remove temporary created elements when highlighting
  28866. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  28867. if (el.__temp) {
  28868. group.remove(el);
  28869. oldData.setItemGraphicEl(idx, null);
  28870. }
  28871. });
  28872. this._polyline =
  28873. this._polygon =
  28874. this._coordSys =
  28875. this._points =
  28876. this._stackedOnPoints =
  28877. this._data = null;
  28878. }
  28879. });
  28880. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  28881. // Encoding visual for all series include which is filtered for legend drawing
  28882. return {
  28883. seriesType: seriesType,
  28884. performRawSeries: true,
  28885. reset: function (seriesModel, ecModel, api) {
  28886. var data = seriesModel.getData();
  28887. var symbolType = seriesModel.get('symbol') || defaultSymbolType;
  28888. var symbolSize = seriesModel.get('symbolSize');
  28889. data.setVisual({
  28890. legendSymbol: legendSymbol || symbolType,
  28891. symbol: symbolType,
  28892. symbolSize: symbolSize
  28893. });
  28894. // Only visible series has each data be visual encoded
  28895. if (ecModel.isSeriesFiltered(seriesModel)) {
  28896. return;
  28897. }
  28898. var hasCallback = typeof symbolSize === 'function';
  28899. function dataEach(data, idx) {
  28900. if (typeof symbolSize === 'function') {
  28901. var rawValue = seriesModel.getRawValue(idx);
  28902. // FIXME
  28903. var params = seriesModel.getDataParams(idx);
  28904. data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  28905. }
  28906. if (data.hasItemOption) {
  28907. var itemModel = data.getItemModel(idx);
  28908. var itemSymbolType = itemModel.getShallow('symbol', true);
  28909. var itemSymbolSize = itemModel.getShallow('symbolSize', true);
  28910. // If has item symbol
  28911. if (itemSymbolType != null) {
  28912. data.setItemVisual(idx, 'symbol', itemSymbolType);
  28913. }
  28914. if (itemSymbolSize != null) {
  28915. // PENDING Transform symbolSize ?
  28916. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  28917. }
  28918. }
  28919. }
  28920. return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null };
  28921. }
  28922. };
  28923. };
  28924. var pointsLayout = function (seriesType) {
  28925. return {
  28926. seriesType: seriesType,
  28927. plan: createRenderPlanner(),
  28928. reset: function (seriesModel) {
  28929. var data = seriesModel.getData();
  28930. var coordSys = seriesModel.coordinateSystem;
  28931. var pipelineContext = seriesModel.pipelineContext;
  28932. var isLargeRender = pipelineContext.large;
  28933. if (!coordSys) {
  28934. return;
  28935. }
  28936. var dims = map(coordSys.dimensions, function (dim) {
  28937. return data.mapDimension(dim);
  28938. }).slice(0, 2);
  28939. var dimLen = dims.length;
  28940. if (isDimensionStacked(data, dims[0], dims[1])) {
  28941. dims[0] = data.getCalculationInfo('stackResultDimension');
  28942. }
  28943. if (isDimensionStacked(data, dims[1], dims[0])) {
  28944. dims[1] = data.getCalculationInfo('stackResultDimension');
  28945. }
  28946. function progress(params, data) {
  28947. var segCount = params.end - params.start;
  28948. var points = isLargeRender && new Float32Array(segCount * dimLen);
  28949. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  28950. var point;
  28951. if (dimLen === 1) {
  28952. var x = data.get(dims[0], i, true);
  28953. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  28954. }
  28955. else {
  28956. var x = tmpIn[0] = data.get(dims[0], i, true);
  28957. var y = tmpIn[1] = data.get(dims[1], i, true);
  28958. // Also {Array.<number>}, not undefined to avoid if...else... statement
  28959. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  28960. }
  28961. if (isLargeRender) {
  28962. points[offset++] = point ? point[0] : NaN;
  28963. points[offset++] = point ? point[1] : NaN;
  28964. }
  28965. else {
  28966. data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]);
  28967. }
  28968. }
  28969. isLargeRender && data.setLayout('symbolPoints', points);
  28970. }
  28971. return dimLen && {progress: progress};
  28972. }
  28973. };
  28974. };
  28975. var samplers = {
  28976. average: function (frame) {
  28977. var sum = 0;
  28978. var count = 0;
  28979. for (var i = 0; i < frame.length; i++) {
  28980. if (!isNaN(frame[i])) {
  28981. sum += frame[i];
  28982. count++;
  28983. }
  28984. }
  28985. // Return NaN if count is 0
  28986. return count === 0 ? NaN : sum / count;
  28987. },
  28988. sum: function (frame) {
  28989. var sum = 0;
  28990. for (var i = 0; i < frame.length; i++) {
  28991. // Ignore NaN
  28992. sum += frame[i] || 0;
  28993. }
  28994. return sum;
  28995. },
  28996. max: function (frame) {
  28997. var max = -Infinity;
  28998. for (var i = 0; i < frame.length; i++) {
  28999. frame[i] > max && (max = frame[i]);
  29000. }
  29001. return max;
  29002. },
  29003. min: function (frame) {
  29004. var min = Infinity;
  29005. for (var i = 0; i < frame.length; i++) {
  29006. frame[i] < min && (min = frame[i]);
  29007. }
  29008. return min;
  29009. },
  29010. // TODO
  29011. // Median
  29012. nearest: function (frame) {
  29013. return frame[0];
  29014. }
  29015. };
  29016. var indexSampler = function (frame, value) {
  29017. return Math.round(frame.length / 2);
  29018. };
  29019. var dataSample = function (seriesType) {
  29020. return {
  29021. seriesType: seriesType,
  29022. reset: function (seriesModel, ecModel, api) {
  29023. var data = seriesModel.getData();
  29024. var sampling = seriesModel.get('sampling');
  29025. var coordSys = seriesModel.coordinateSystem;
  29026. // Only cartesian2d support down sampling
  29027. if (coordSys.type === 'cartesian2d' && sampling) {
  29028. var baseAxis = coordSys.getBaseAxis();
  29029. var valueAxis = coordSys.getOtherAxis(baseAxis);
  29030. var extent = baseAxis.getExtent();
  29031. // Coordinste system has been resized
  29032. var size = extent[1] - extent[0];
  29033. var rate = Math.round(data.count() / size);
  29034. if (rate > 1) {
  29035. var sampler;
  29036. if (typeof sampling === 'string') {
  29037. sampler = samplers[sampling];
  29038. }
  29039. else if (typeof sampling === 'function') {
  29040. sampler = sampling;
  29041. }
  29042. if (sampler) {
  29043. seriesModel.setData(data.downSample(
  29044. valueAxis.dim, 1 / rate, sampler, indexSampler
  29045. ));
  29046. }
  29047. }
  29048. }
  29049. }
  29050. };
  29051. };
  29052. /**
  29053. * Cartesian coordinate system
  29054. * @module echarts/coord/Cartesian
  29055. *
  29056. */
  29057. function dimAxisMapper(dim) {
  29058. return this._axes[dim];
  29059. }
  29060. /**
  29061. * @alias module:echarts/coord/Cartesian
  29062. * @constructor
  29063. */
  29064. var Cartesian = function (name) {
  29065. this._axes = {};
  29066. this._dimList = [];
  29067. /**
  29068. * @type {string}
  29069. */
  29070. this.name = name || '';
  29071. };
  29072. Cartesian.prototype = {
  29073. constructor: Cartesian,
  29074. type: 'cartesian',
  29075. /**
  29076. * Get axis
  29077. * @param {number|string} dim
  29078. * @return {module:echarts/coord/Cartesian~Axis}
  29079. */
  29080. getAxis: function (dim) {
  29081. return this._axes[dim];
  29082. },
  29083. /**
  29084. * Get axes list
  29085. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  29086. */
  29087. getAxes: function () {
  29088. return map(this._dimList, dimAxisMapper, this);
  29089. },
  29090. /**
  29091. * Get axes list by given scale type
  29092. */
  29093. getAxesByScale: function (scaleType) {
  29094. scaleType = scaleType.toLowerCase();
  29095. return filter(
  29096. this.getAxes(),
  29097. function (axis) {
  29098. return axis.scale.type === scaleType;
  29099. }
  29100. );
  29101. },
  29102. /**
  29103. * Add axis
  29104. * @param {module:echarts/coord/Cartesian.Axis}
  29105. */
  29106. addAxis: function (axis) {
  29107. var dim = axis.dim;
  29108. this._axes[dim] = axis;
  29109. this._dimList.push(dim);
  29110. },
  29111. /**
  29112. * Convert data to coord in nd space
  29113. * @param {Array.<number>|Object.<string, number>} val
  29114. * @return {Array.<number>|Object.<string, number>}
  29115. */
  29116. dataToCoord: function (val) {
  29117. return this._dataCoordConvert(val, 'dataToCoord');
  29118. },
  29119. /**
  29120. * Convert coord in nd space to data
  29121. * @param {Array.<number>|Object.<string, number>} val
  29122. * @return {Array.<number>|Object.<string, number>}
  29123. */
  29124. coordToData: function (val) {
  29125. return this._dataCoordConvert(val, 'coordToData');
  29126. },
  29127. _dataCoordConvert: function (input, method) {
  29128. var dimList = this._dimList;
  29129. var output = input instanceof Array ? [] : {};
  29130. for (var i = 0; i < dimList.length; i++) {
  29131. var dim = dimList[i];
  29132. var axis = this._axes[dim];
  29133. output[dim] = axis[method](input[dim]);
  29134. }
  29135. return output;
  29136. }
  29137. };
  29138. function Cartesian2D(name) {
  29139. Cartesian.call(this, name);
  29140. }
  29141. Cartesian2D.prototype = {
  29142. constructor: Cartesian2D,
  29143. type: 'cartesian2d',
  29144. /**
  29145. * @type {Array.<string>}
  29146. * @readOnly
  29147. */
  29148. dimensions: ['x', 'y'],
  29149. /**
  29150. * Base axis will be used on stacking.
  29151. *
  29152. * @return {module:echarts/coord/cartesian/Axis2D}
  29153. */
  29154. getBaseAxis: function () {
  29155. return this.getAxesByScale('ordinal')[0]
  29156. || this.getAxesByScale('time')[0]
  29157. || this.getAxis('x');
  29158. },
  29159. /**
  29160. * If contain point
  29161. * @param {Array.<number>} point
  29162. * @return {boolean}
  29163. */
  29164. containPoint: function (point) {
  29165. var axisX = this.getAxis('x');
  29166. var axisY = this.getAxis('y');
  29167. return axisX.contain(axisX.toLocalCoord(point[0]))
  29168. && axisY.contain(axisY.toLocalCoord(point[1]));
  29169. },
  29170. /**
  29171. * If contain data
  29172. * @param {Array.<number>} data
  29173. * @return {boolean}
  29174. */
  29175. containData: function (data) {
  29176. return this.getAxis('x').containData(data[0])
  29177. && this.getAxis('y').containData(data[1]);
  29178. },
  29179. /**
  29180. * @param {Array.<number>} data
  29181. * @param {Array.<number>} out
  29182. * @return {Array.<number>}
  29183. */
  29184. dataToPoint: function (data, reserved, out) {
  29185. var xAxis = this.getAxis('x');
  29186. var yAxis = this.getAxis('y');
  29187. out = out || [];
  29188. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  29189. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  29190. return out;
  29191. },
  29192. /**
  29193. * @param {Array.<number>} data
  29194. * @param {Array.<number>} out
  29195. * @return {Array.<number>}
  29196. */
  29197. clampData: function (data, out) {
  29198. var xAxisExtent = this.getAxis('x').scale.getExtent();
  29199. var yAxisExtent = this.getAxis('y').scale.getExtent();
  29200. out = out || [];
  29201. out[0] = Math.min(
  29202. Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), data[0]),
  29203. Math.max(xAxisExtent[0], xAxisExtent[1])
  29204. );
  29205. out[1] = Math.min(
  29206. Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), data[1]),
  29207. Math.max(yAxisExtent[0], yAxisExtent[1])
  29208. );
  29209. return out;
  29210. },
  29211. /**
  29212. * @param {Array.<number>} point
  29213. * @param {Array.<number>} out
  29214. * @return {Array.<number>}
  29215. */
  29216. pointToData: function (point, out) {
  29217. var xAxis = this.getAxis('x');
  29218. var yAxis = this.getAxis('y');
  29219. out = out || [];
  29220. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  29221. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  29222. return out;
  29223. },
  29224. /**
  29225. * Get other axis
  29226. * @param {module:echarts/coord/cartesian/Axis2D} axis
  29227. */
  29228. getOtherAxis: function (axis) {
  29229. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  29230. }
  29231. };
  29232. inherits(Cartesian2D, Cartesian);
  29233. /**
  29234. * Extend axis 2d
  29235. * @constructor module:echarts/coord/cartesian/Axis2D
  29236. * @extends {module:echarts/coord/cartesian/Axis}
  29237. * @param {string} dim
  29238. * @param {*} scale
  29239. * @param {Array.<number>} coordExtent
  29240. * @param {string} axisType
  29241. * @param {string} position
  29242. */
  29243. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  29244. Axis.call(this, dim, scale, coordExtent);
  29245. /**
  29246. * Axis type
  29247. * - 'category'
  29248. * - 'value'
  29249. * - 'time'
  29250. * - 'log'
  29251. * @type {string}
  29252. */
  29253. this.type = axisType || 'value';
  29254. /**
  29255. * Axis position
  29256. * - 'top'
  29257. * - 'bottom'
  29258. * - 'left'
  29259. * - 'right'
  29260. */
  29261. this.position = position || 'bottom';
  29262. };
  29263. Axis2D.prototype = {
  29264. constructor: Axis2D,
  29265. /**
  29266. * Index of axis, can be used as key
  29267. */
  29268. index: 0,
  29269. /**
  29270. * If axis is on the zero position of the other axis
  29271. * @type {boolean}
  29272. */
  29273. onZero: false,
  29274. /**
  29275. * Axis model
  29276. * @param {module:echarts/coord/cartesian/AxisModel}
  29277. */
  29278. model: null,
  29279. isHorizontal: function () {
  29280. var position = this.position;
  29281. return position === 'top' || position === 'bottom';
  29282. },
  29283. /**
  29284. * Each item cooresponds to this.getExtent(), which
  29285. * means globalExtent[0] may greater than globalExtent[1],
  29286. * unless `asc` is input.
  29287. *
  29288. * @param {boolean} [asc]
  29289. * @return {Array.<number>}
  29290. */
  29291. getGlobalExtent: function (asc) {
  29292. var ret = this.getExtent();
  29293. ret[0] = this.toGlobalCoord(ret[0]);
  29294. ret[1] = this.toGlobalCoord(ret[1]);
  29295. asc && ret[0] > ret[1] && ret.reverse();
  29296. return ret;
  29297. },
  29298. getOtherAxis: function () {
  29299. this.grid.getOtherAxis();
  29300. },
  29301. /**
  29302. * If label is ignored.
  29303. * Automatically used when axis is category and label can not be all shown
  29304. * @param {number} idx
  29305. * @return {boolean}
  29306. */
  29307. isLabelIgnored: function (idx) {
  29308. if (this.type === 'category') {
  29309. var labelInterval = this.getLabelInterval();
  29310. return ((typeof labelInterval === 'function')
  29311. && !labelInterval(idx, this.scale.getLabel(idx)))
  29312. || idx % (labelInterval + 1);
  29313. }
  29314. },
  29315. /**
  29316. * @override
  29317. */
  29318. pointToData: function (point, clamp) {
  29319. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  29320. },
  29321. /**
  29322. * Transform global coord to local coord,
  29323. * i.e. var localCoord = axis.toLocalCoord(80);
  29324. * designate by module:echarts/coord/cartesian/Grid.
  29325. * @type {Function}
  29326. */
  29327. toLocalCoord: null,
  29328. /**
  29329. * Transform global coord to local coord,
  29330. * i.e. var globalCoord = axis.toLocalCoord(40);
  29331. * designate by module:echarts/coord/cartesian/Grid.
  29332. * @type {Function}
  29333. */
  29334. toGlobalCoord: null
  29335. };
  29336. inherits(Axis2D, Axis);
  29337. var defaultOption = {
  29338. show: true,
  29339. zlevel: 0, // 一级层叠
  29340. z: 0, // 二级层叠
  29341. // 反向坐标轴
  29342. inverse: false,
  29343. // 坐标轴名字,默认为空
  29344. name: '',
  29345. // 坐标轴名字位置,支持'start' | 'middle' | 'end'
  29346. nameLocation: 'end',
  29347. // 坐标轴名字旋转,degree。
  29348. nameRotate: null, // Adapt to axis rotate, when nameLocation is 'middle'.
  29349. nameTruncate: {
  29350. maxWidth: null,
  29351. ellipsis: '...',
  29352. placeholder: '.'
  29353. },
  29354. // 坐标轴文字样式,默认取全局样式
  29355. nameTextStyle: {},
  29356. // 文字与轴线距离
  29357. nameGap: 15,
  29358. silent: false, // Default false to support tooltip.
  29359. triggerEvent: false, // Default false to avoid legacy user event listener fail.
  29360. tooltip: {
  29361. show: false
  29362. },
  29363. axisPointer: {},
  29364. // 坐标轴线
  29365. axisLine: {
  29366. // 默认显示,属性show控制显示与否
  29367. show: true,
  29368. onZero: true,
  29369. onZeroAxisIndex: null,
  29370. // 属性lineStyle控制线条样式
  29371. lineStyle: {
  29372. color: '#333',
  29373. width: 1,
  29374. type: 'solid'
  29375. },
  29376. // 坐标轴两端的箭头
  29377. symbol: ['none', 'none'],
  29378. symbolSize: [10, 15]
  29379. },
  29380. // 坐标轴小标记
  29381. axisTick: {
  29382. // 属性show控制显示与否,默认显示
  29383. show: true,
  29384. // 控制小标记是否在grid里
  29385. inside: false,
  29386. // 属性length控制线长
  29387. length: 5,
  29388. // 属性lineStyle控制线条样式
  29389. lineStyle: {
  29390. width: 1
  29391. }
  29392. },
  29393. // 坐标轴文本标签,详见axis.axisLabel
  29394. axisLabel: {
  29395. show: true,
  29396. // 控制文本标签是否在grid里
  29397. inside: false,
  29398. rotate: 0,
  29399. showMinLabel: null, // true | false | null (auto)
  29400. showMaxLabel: null, // true | false | null (auto)
  29401. margin: 8,
  29402. // formatter: null,
  29403. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  29404. fontSize: 12
  29405. },
  29406. // 分隔线
  29407. splitLine: {
  29408. // 默认显示,属性show控制显示与否
  29409. show: true,
  29410. // 属性lineStyle(详见lineStyle)控制线条样式
  29411. lineStyle: {
  29412. color: ['#ccc'],
  29413. width: 1,
  29414. type: 'solid'
  29415. }
  29416. },
  29417. // 分隔区域
  29418. splitArea: {
  29419. // 默认不显示,属性show控制显示与否
  29420. show: false,
  29421. // 属性areaStyle(详见areaStyle)控制区域样式
  29422. areaStyle: {
  29423. color: ['rgba(250,250,250,0.3)','rgba(200,200,200,0.3)']
  29424. }
  29425. }
  29426. };
  29427. var axisDefault = {};
  29428. axisDefault.categoryAxis = merge({
  29429. // 类目起始和结束两端空白策略
  29430. boundaryGap: true,
  29431. // Set false to faster category collection.
  29432. // Only usefull in the case like: category is
  29433. // ['2012-01-01', '2012-01-02', ...], where the input
  29434. // data has been ensured not duplicate and is large data.
  29435. // null means "auto":
  29436. // if axis.data provided, do not deduplication,
  29437. // else do deduplication.
  29438. deduplication: null,
  29439. // splitArea: {
  29440. // show: false
  29441. // },
  29442. splitLine: {
  29443. show: false
  29444. },
  29445. // 坐标轴小标记
  29446. axisTick: {
  29447. // If tick is align with label when boundaryGap is true
  29448. alignWithLabel: false,
  29449. interval: 'auto'
  29450. },
  29451. // 坐标轴文本标签,详见axis.axisLabel
  29452. axisLabel: {
  29453. interval: 'auto'
  29454. }
  29455. }, defaultOption);
  29456. axisDefault.valueAxis = merge({
  29457. // 数值起始和结束两端空白策略
  29458. boundaryGap: [0, 0],
  29459. // TODO
  29460. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  29461. // 最小值, 设置成 'dataMin' 则从数据中计算最小值
  29462. // min: null,
  29463. // 最大值,设置成 'dataMax' 则从数据中计算最大值
  29464. // max: null,
  29465. // Readonly prop, specifies start value of the range when using data zoom.
  29466. // rangeStart: null
  29467. // Readonly prop, specifies end value of the range when using data zoom.
  29468. // rangeEnd: null
  29469. // 脱离0值比例,放大聚焦到最终_min,_max区间
  29470. // scale: false,
  29471. // 分割段数,默认为5
  29472. splitNumber: 5
  29473. // Minimum interval
  29474. // minInterval: null
  29475. // maxInterval: null
  29476. }, defaultOption);
  29477. // FIXME
  29478. axisDefault.timeAxis = defaults({
  29479. scale: true,
  29480. min: 'dataMin',
  29481. max: 'dataMax'
  29482. }, axisDefault.valueAxis);
  29483. axisDefault.logAxis = defaults({
  29484. scale: true,
  29485. logBase: 10
  29486. }, axisDefault.valueAxis);
  29487. // FIXME axisType is fixed ?
  29488. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  29489. /**
  29490. * Generate sub axis model class
  29491. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  29492. * @param {module:echarts/model/Component} BaseAxisModelClass
  29493. * @param {Function} axisTypeDefaulter
  29494. * @param {Object} [extraDefaultOption]
  29495. */
  29496. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  29497. each$1(AXIS_TYPES, function (axisType) {
  29498. BaseAxisModelClass.extend({
  29499. /**
  29500. * @readOnly
  29501. */
  29502. type: axisName + 'Axis.' + axisType,
  29503. mergeDefaultAndTheme: function (option, ecModel) {
  29504. var layoutMode = this.layoutMode;
  29505. var inputPositionParams = layoutMode
  29506. ? getLayoutParams(option) : {};
  29507. var themeModel = ecModel.getTheme();
  29508. merge(option, themeModel.get(axisType + 'Axis'));
  29509. merge(option, this.getDefaultOption());
  29510. option.type = axisTypeDefaulter(axisName, option);
  29511. if (layoutMode) {
  29512. mergeLayoutParam(option, inputPositionParams, layoutMode);
  29513. }
  29514. },
  29515. /**
  29516. * @override
  29517. */
  29518. optionUpdated: function () {
  29519. var thisOption = this.option;
  29520. if (thisOption.type === 'category') {
  29521. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  29522. }
  29523. },
  29524. /**
  29525. * Should not be called before all of 'getInitailData' finished.
  29526. * Because categories are collected during initializing data.
  29527. */
  29528. getCategories: function () {
  29529. // FIXME
  29530. // warning if called before all of 'getInitailData' finished.
  29531. if (this.option.type === 'category') {
  29532. return this.__ordinalMeta.categories;
  29533. }
  29534. },
  29535. getOrdinalMeta: function () {
  29536. return this.__ordinalMeta;
  29537. },
  29538. defaultOption: mergeAll(
  29539. [
  29540. {},
  29541. axisDefault[axisType + 'Axis'],
  29542. extraDefaultOption
  29543. ],
  29544. true
  29545. )
  29546. });
  29547. });
  29548. ComponentModel.registerSubTypeDefaulter(
  29549. axisName + 'Axis',
  29550. curry(axisTypeDefaulter, axisName)
  29551. );
  29552. };
  29553. var AxisModel = ComponentModel.extend({
  29554. type: 'cartesian2dAxis',
  29555. /**
  29556. * @type {module:echarts/coord/cartesian/Axis2D}
  29557. */
  29558. axis: null,
  29559. /**
  29560. * @override
  29561. */
  29562. init: function () {
  29563. AxisModel.superApply(this, 'init', arguments);
  29564. this.resetRange();
  29565. },
  29566. /**
  29567. * @override
  29568. */
  29569. mergeOption: function () {
  29570. AxisModel.superApply(this, 'mergeOption', arguments);
  29571. this.resetRange();
  29572. },
  29573. /**
  29574. * @override
  29575. */
  29576. restoreData: function () {
  29577. AxisModel.superApply(this, 'restoreData', arguments);
  29578. this.resetRange();
  29579. },
  29580. /**
  29581. * @override
  29582. * @return {module:echarts/model/Component}
  29583. */
  29584. getCoordSysModel: function () {
  29585. return this.ecModel.queryComponents({
  29586. mainType: 'grid',
  29587. index: this.option.gridIndex,
  29588. id: this.option.gridId
  29589. })[0];
  29590. }
  29591. });
  29592. function getAxisType(axisDim, option) {
  29593. // Default axis with data is category axis
  29594. return option.type || (option.data ? 'category' : 'value');
  29595. }
  29596. merge(AxisModel.prototype, axisModelCommonMixin);
  29597. var extraOption = {
  29598. // gridIndex: 0,
  29599. // gridId: '',
  29600. // Offset is for multiple axis on the same position
  29601. offset: 0
  29602. };
  29603. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  29604. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  29605. // Grid 是在有直角坐标系的时候必须要存在的
  29606. // 所以这里也要被 Cartesian2D 依赖
  29607. ComponentModel.extend({
  29608. type: 'grid',
  29609. dependencies: ['xAxis', 'yAxis'],
  29610. layoutMode: 'box',
  29611. /**
  29612. * @type {module:echarts/coord/cartesian/Grid}
  29613. */
  29614. coordinateSystem: null,
  29615. defaultOption: {
  29616. show: false,
  29617. zlevel: 0,
  29618. z: 0,
  29619. left: '10%',
  29620. top: 60,
  29621. right: '10%',
  29622. bottom: 60,
  29623. // If grid size contain label
  29624. containLabel: false,
  29625. // width: {totalWidth} - left - right,
  29626. // height: {totalHeight} - top - bottom,
  29627. backgroundColor: 'rgba(0,0,0,0)',
  29628. borderWidth: 1,
  29629. borderColor: '#ccc'
  29630. }
  29631. });
  29632. /**
  29633. * Grid is a region which contains at most 4 cartesian systems
  29634. *
  29635. * TODO Default cartesian
  29636. */
  29637. // Depends on GridModel, AxisModel, which performs preprocess.
  29638. var each$6 = each$1;
  29639. var ifAxisCrossZero$1 = ifAxisCrossZero;
  29640. var niceScaleExtent$1 = niceScaleExtent;
  29641. /**
  29642. * Check if the axis is used in the specified grid
  29643. * @inner
  29644. */
  29645. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  29646. return axisModel.getCoordSysModel() === gridModel;
  29647. }
  29648. function rotateTextRect(textRect, rotate) {
  29649. var rotateRadians = rotate * Math.PI / 180;
  29650. var boundingBox = textRect.plain();
  29651. var beforeWidth = boundingBox.width;
  29652. var beforeHeight = boundingBox.height;
  29653. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  29654. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  29655. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  29656. return rotatedRect;
  29657. }
  29658. function getLabelUnionRect(axis) {
  29659. var axisModel = axis.model;
  29660. var labels = axisModel.get('axisLabel.show') ? axisModel.getFormattedLabels() : [];
  29661. var axisLabelModel = axisModel.getModel('axisLabel');
  29662. var rect;
  29663. var step = 1;
  29664. var labelCount = labels.length;
  29665. if (labelCount > 40) {
  29666. // Simple optimization for large amount of labels
  29667. step = Math.ceil(labelCount / 40);
  29668. }
  29669. for (var i = 0; i < labelCount; i += step) {
  29670. if (!axis.isLabelIgnored(i)) {
  29671. var unrotatedSingleRect = axisLabelModel.getTextRect(labels[i]);
  29672. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  29673. rect ? rect.union(singleRect) : (rect = singleRect);
  29674. }
  29675. }
  29676. return rect;
  29677. }
  29678. function Grid(gridModel, ecModel, api) {
  29679. /**
  29680. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  29681. * @private
  29682. */
  29683. this._coordsMap = {};
  29684. /**
  29685. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  29686. * @private
  29687. */
  29688. this._coordsList = [];
  29689. /**
  29690. * @type {Object.<string, module:echarts/coord/cartesian/Axis2D>}
  29691. * @private
  29692. */
  29693. this._axesMap = {};
  29694. /**
  29695. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  29696. * @private
  29697. */
  29698. this._axesList = [];
  29699. this._initCartesian(gridModel, ecModel, api);
  29700. this.model = gridModel;
  29701. }
  29702. var gridProto = Grid.prototype;
  29703. gridProto.type = 'grid';
  29704. gridProto.axisPointerEnabled = true;
  29705. gridProto.getRect = function () {
  29706. return this._rect;
  29707. };
  29708. gridProto.update = function (ecModel, api) {
  29709. var axesMap = this._axesMap;
  29710. this._updateScale(ecModel, this.model);
  29711. each$6(axesMap.x, function (xAxis) {
  29712. niceScaleExtent$1(xAxis.scale, xAxis.model);
  29713. });
  29714. each$6(axesMap.y, function (yAxis) {
  29715. niceScaleExtent$1(yAxis.scale, yAxis.model);
  29716. });
  29717. each$6(axesMap.x, function (xAxis) {
  29718. fixAxisOnZero(axesMap, 'y', xAxis);
  29719. });
  29720. each$6(axesMap.y, function (yAxis) {
  29721. fixAxisOnZero(axesMap, 'x', yAxis);
  29722. });
  29723. // Resize again if containLabel is enabled
  29724. // FIXME It may cause getting wrong grid size in data processing stage
  29725. this.resize(this.model, api);
  29726. };
  29727. function fixAxisOnZero(axesMap, otherAxisDim, axis) {
  29728. // onZero can not be enabled in these two situations:
  29729. // 1. When any other axis is a category axis.
  29730. // 2. When no axis is cross 0 point.
  29731. var axes = axesMap[otherAxisDim];
  29732. if (!axis.onZero) {
  29733. return;
  29734. }
  29735. var onZeroAxisIndex = axis.onZeroAxisIndex;
  29736. // If target axis is specified.
  29737. if (onZeroAxisIndex != null) {
  29738. var otherAxis = axes[onZeroAxisIndex];
  29739. if (otherAxis && canNotOnZeroToAxis(otherAxis)) {
  29740. axis.onZero = false;
  29741. }
  29742. return;
  29743. }
  29744. for (var idx in axes) {
  29745. if (axes.hasOwnProperty(idx)) {
  29746. var otherAxis = axes[idx];
  29747. if (otherAxis && !canNotOnZeroToAxis(otherAxis)) {
  29748. onZeroAxisIndex = +idx;
  29749. break;
  29750. }
  29751. }
  29752. }
  29753. if (onZeroAxisIndex == null) {
  29754. axis.onZero = false;
  29755. }
  29756. axis.onZeroAxisIndex = onZeroAxisIndex;
  29757. }
  29758. function canNotOnZeroToAxis(axis) {
  29759. return axis.type === 'category' || axis.type === 'time' || !ifAxisCrossZero$1(axis);
  29760. }
  29761. /**
  29762. * Resize the grid
  29763. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  29764. * @param {module:echarts/ExtensionAPI} api
  29765. */
  29766. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  29767. var gridRect = getLayoutRect(
  29768. gridModel.getBoxLayoutParams(), {
  29769. width: api.getWidth(),
  29770. height: api.getHeight()
  29771. });
  29772. this._rect = gridRect;
  29773. var axesList = this._axesList;
  29774. adjustAxes();
  29775. // Minus label size
  29776. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  29777. each$6(axesList, function (axis) {
  29778. if (!axis.model.get('axisLabel.inside')) {
  29779. var labelUnionRect = getLabelUnionRect(axis);
  29780. if (labelUnionRect) {
  29781. var dim = axis.isHorizontal() ? 'height' : 'width';
  29782. var margin = axis.model.get('axisLabel.margin');
  29783. gridRect[dim] -= labelUnionRect[dim] + margin;
  29784. if (axis.position === 'top') {
  29785. gridRect.y += labelUnionRect.height + margin;
  29786. }
  29787. else if (axis.position === 'left') {
  29788. gridRect.x += labelUnionRect.width + margin;
  29789. }
  29790. }
  29791. }
  29792. });
  29793. adjustAxes();
  29794. }
  29795. function adjustAxes() {
  29796. each$6(axesList, function (axis) {
  29797. var isHorizontal = axis.isHorizontal();
  29798. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  29799. var idx = axis.inverse ? 1 : 0;
  29800. axis.setExtent(extent[idx], extent[1 - idx]);
  29801. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  29802. });
  29803. }
  29804. };
  29805. /**
  29806. * @param {string} axisType
  29807. * @param {number} [axisIndex]
  29808. */
  29809. gridProto.getAxis = function (axisType, axisIndex) {
  29810. var axesMapOnDim = this._axesMap[axisType];
  29811. if (axesMapOnDim != null) {
  29812. if (axisIndex == null) {
  29813. // Find first axis
  29814. for (var name in axesMapOnDim) {
  29815. if (axesMapOnDim.hasOwnProperty(name)) {
  29816. return axesMapOnDim[name];
  29817. }
  29818. }
  29819. }
  29820. return axesMapOnDim[axisIndex];
  29821. }
  29822. };
  29823. /**
  29824. * @return {Array.<module:echarts/coord/Axis>}
  29825. */
  29826. gridProto.getAxes = function () {
  29827. return this._axesList.slice();
  29828. };
  29829. /**
  29830. * Usage:
  29831. * grid.getCartesian(xAxisIndex, yAxisIndex);
  29832. * grid.getCartesian(xAxisIndex);
  29833. * grid.getCartesian(null, yAxisIndex);
  29834. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  29835. *
  29836. * @param {number|Object} [xAxisIndex]
  29837. * @param {number} [yAxisIndex]
  29838. */
  29839. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  29840. if (xAxisIndex != null && yAxisIndex != null) {
  29841. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  29842. return this._coordsMap[key];
  29843. }
  29844. if (isObject$1(xAxisIndex)) {
  29845. yAxisIndex = xAxisIndex.yAxisIndex;
  29846. xAxisIndex = xAxisIndex.xAxisIndex;
  29847. }
  29848. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  29849. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  29850. if (coordList[i].getAxis('x').index === xAxisIndex
  29851. || coordList[i].getAxis('y').index === yAxisIndex
  29852. ) {
  29853. return coordList[i];
  29854. }
  29855. }
  29856. };
  29857. gridProto.getCartesians = function () {
  29858. return this._coordsList.slice();
  29859. };
  29860. /**
  29861. * @implements
  29862. * see {module:echarts/CoodinateSystem}
  29863. */
  29864. gridProto.convertToPixel = function (ecModel, finder, value) {
  29865. var target = this._findConvertTarget(ecModel, finder);
  29866. return target.cartesian
  29867. ? target.cartesian.dataToPoint(value)
  29868. : target.axis
  29869. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  29870. : null;
  29871. };
  29872. /**
  29873. * @implements
  29874. * see {module:echarts/CoodinateSystem}
  29875. */
  29876. gridProto.convertFromPixel = function (ecModel, finder, value) {
  29877. var target = this._findConvertTarget(ecModel, finder);
  29878. return target.cartesian
  29879. ? target.cartesian.pointToData(value)
  29880. : target.axis
  29881. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  29882. : null;
  29883. };
  29884. /**
  29885. * @inner
  29886. */
  29887. gridProto._findConvertTarget = function (ecModel, finder) {
  29888. var seriesModel = finder.seriesModel;
  29889. var xAxisModel = finder.xAxisModel
  29890. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  29891. var yAxisModel = finder.yAxisModel
  29892. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  29893. var gridModel = finder.gridModel;
  29894. var coordsList = this._coordsList;
  29895. var cartesian;
  29896. var axis;
  29897. if (seriesModel) {
  29898. cartesian = seriesModel.coordinateSystem;
  29899. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  29900. }
  29901. else if (xAxisModel && yAxisModel) {
  29902. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  29903. }
  29904. else if (xAxisModel) {
  29905. axis = this.getAxis('x', xAxisModel.componentIndex);
  29906. }
  29907. else if (yAxisModel) {
  29908. axis = this.getAxis('y', yAxisModel.componentIndex);
  29909. }
  29910. // Lowest priority.
  29911. else if (gridModel) {
  29912. var grid = gridModel.coordinateSystem;
  29913. if (grid === this) {
  29914. cartesian = this._coordsList[0];
  29915. }
  29916. }
  29917. return {cartesian: cartesian, axis: axis};
  29918. };
  29919. /**
  29920. * @implements
  29921. * see {module:echarts/CoodinateSystem}
  29922. */
  29923. gridProto.containPoint = function (point) {
  29924. var coord = this._coordsList[0];
  29925. if (coord) {
  29926. return coord.containPoint(point);
  29927. }
  29928. };
  29929. /**
  29930. * Initialize cartesian coordinate systems
  29931. * @private
  29932. */
  29933. gridProto._initCartesian = function (gridModel, ecModel, api) {
  29934. var axisPositionUsed = {
  29935. left: false,
  29936. right: false,
  29937. top: false,
  29938. bottom: false
  29939. };
  29940. var axesMap = {
  29941. x: {},
  29942. y: {}
  29943. };
  29944. var axesCount = {
  29945. x: 0,
  29946. y: 0
  29947. };
  29948. /// Create axis
  29949. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  29950. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  29951. if (!axesCount.x || !axesCount.y) {
  29952. // Roll back when there no either x or y axis
  29953. this._axesMap = {};
  29954. this._axesList = [];
  29955. return;
  29956. }
  29957. this._axesMap = axesMap;
  29958. /// Create cartesian2d
  29959. each$6(axesMap.x, function (xAxis, xAxisIndex) {
  29960. each$6(axesMap.y, function (yAxis, yAxisIndex) {
  29961. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  29962. var cartesian = new Cartesian2D(key);
  29963. cartesian.grid = this;
  29964. cartesian.model = gridModel;
  29965. this._coordsMap[key] = cartesian;
  29966. this._coordsList.push(cartesian);
  29967. cartesian.addAxis(xAxis);
  29968. cartesian.addAxis(yAxis);
  29969. }, this);
  29970. }, this);
  29971. function createAxisCreator(axisType) {
  29972. return function (axisModel, idx) {
  29973. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  29974. return;
  29975. }
  29976. var axisPosition = axisModel.get('position');
  29977. if (axisType === 'x') {
  29978. // Fix position
  29979. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  29980. // Default bottom of X
  29981. axisPosition = 'bottom';
  29982. if (axisPositionUsed[axisPosition]) {
  29983. axisPosition = axisPosition === 'top' ? 'bottom' : 'top';
  29984. }
  29985. }
  29986. }
  29987. else {
  29988. // Fix position
  29989. if (axisPosition !== 'left' && axisPosition !== 'right') {
  29990. // Default left of Y
  29991. axisPosition = 'left';
  29992. if (axisPositionUsed[axisPosition]) {
  29993. axisPosition = axisPosition === 'left' ? 'right' : 'left';
  29994. }
  29995. }
  29996. }
  29997. axisPositionUsed[axisPosition] = true;
  29998. var axis = new Axis2D(
  29999. axisType, createScaleByModel(axisModel),
  30000. [0, 0],
  30001. axisModel.get('type'),
  30002. axisPosition
  30003. );
  30004. var isCategory = axis.type === 'category';
  30005. axis.onBand = isCategory && axisModel.get('boundaryGap');
  30006. axis.inverse = axisModel.get('inverse');
  30007. axis.onZero = axisModel.get('axisLine.onZero');
  30008. axis.onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  30009. // Inject axis into axisModel
  30010. axisModel.axis = axis;
  30011. // Inject axisModel into axis
  30012. axis.model = axisModel;
  30013. // Inject grid info axis
  30014. axis.grid = this;
  30015. // Index of axis, can be used as key
  30016. axis.index = idx;
  30017. this._axesList.push(axis);
  30018. axesMap[axisType][idx] = axis;
  30019. axesCount[axisType]++;
  30020. };
  30021. }
  30022. };
  30023. /**
  30024. * Update cartesian properties from series
  30025. * @param {module:echarts/model/Option} option
  30026. * @private
  30027. */
  30028. gridProto._updateScale = function (ecModel, gridModel) {
  30029. // Reset scale
  30030. each$1(this._axesList, function (axis) {
  30031. axis.scale.setExtent(Infinity, -Infinity);
  30032. });
  30033. ecModel.eachSeries(function (seriesModel) {
  30034. if (isCartesian2D(seriesModel)) {
  30035. var axesModels = findAxesModels(seriesModel, ecModel);
  30036. var xAxisModel = axesModels[0];
  30037. var yAxisModel = axesModels[1];
  30038. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  30039. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  30040. ) {
  30041. return;
  30042. }
  30043. var cartesian = this.getCartesian(
  30044. xAxisModel.componentIndex, yAxisModel.componentIndex
  30045. );
  30046. var data = seriesModel.getData();
  30047. var xAxis = cartesian.getAxis('x');
  30048. var yAxis = cartesian.getAxis('y');
  30049. if (data.type === 'list') {
  30050. unionExtent(data, xAxis, seriesModel);
  30051. unionExtent(data, yAxis, seriesModel);
  30052. }
  30053. }
  30054. }, this);
  30055. function unionExtent(data, axis, seriesModel) {
  30056. each$6(data.mapDimension(axis.dim, true), function (dim) {
  30057. axis.scale.unionExtentFromData(data, dim);
  30058. });
  30059. }
  30060. };
  30061. /**
  30062. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  30063. * @return {Object} {baseAxes: [], otherAxes: []}
  30064. */
  30065. gridProto.getTooltipAxes = function (dim) {
  30066. var baseAxes = [];
  30067. var otherAxes = [];
  30068. each$6(this.getCartesians(), function (cartesian) {
  30069. var baseAxis = (dim != null && dim !== 'auto')
  30070. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  30071. var otherAxis = cartesian.getOtherAxis(baseAxis);
  30072. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  30073. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  30074. });
  30075. return {baseAxes: baseAxes, otherAxes: otherAxes};
  30076. };
  30077. /**
  30078. * @inner
  30079. */
  30080. function updateAxisTransform(axis, coordBase) {
  30081. var axisExtent = axis.getExtent();
  30082. var axisExtentSum = axisExtent[0] + axisExtent[1];
  30083. // Fast transform
  30084. axis.toGlobalCoord = axis.dim === 'x'
  30085. ? function (coord) {
  30086. return coord + coordBase;
  30087. }
  30088. : function (coord) {
  30089. return axisExtentSum - coord + coordBase;
  30090. };
  30091. axis.toLocalCoord = axis.dim === 'x'
  30092. ? function (coord) {
  30093. return coord - coordBase;
  30094. }
  30095. : function (coord) {
  30096. return axisExtentSum - coord + coordBase;
  30097. };
  30098. }
  30099. var axesTypes = ['xAxis', 'yAxis'];
  30100. /**
  30101. * @inner
  30102. */
  30103. function findAxesModels(seriesModel, ecModel) {
  30104. return map(axesTypes, function (axisType) {
  30105. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  30106. if (__DEV__) {
  30107. if (!axisModel) {
  30108. throw new Error(axisType + ' "' + retrieve(
  30109. seriesModel.get(axisType + 'Index'),
  30110. seriesModel.get(axisType + 'Id'),
  30111. 0
  30112. ) + '" not found');
  30113. }
  30114. }
  30115. return axisModel;
  30116. });
  30117. }
  30118. /**
  30119. * @inner
  30120. */
  30121. function isCartesian2D(seriesModel) {
  30122. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  30123. }
  30124. Grid.create = function (ecModel, api) {
  30125. var grids = [];
  30126. ecModel.eachComponent('grid', function (gridModel, idx) {
  30127. var grid = new Grid(gridModel, ecModel, api);
  30128. grid.name = 'grid_' + idx;
  30129. // dataSampling requires axis extent, so resize
  30130. // should be performed in create stage.
  30131. grid.resize(gridModel, api, true);
  30132. gridModel.coordinateSystem = grid;
  30133. grids.push(grid);
  30134. });
  30135. // Inject the coordinateSystems into seriesModel
  30136. ecModel.eachSeries(function (seriesModel) {
  30137. if (!isCartesian2D(seriesModel)) {
  30138. return;
  30139. }
  30140. var axesModels = findAxesModels(seriesModel, ecModel);
  30141. var xAxisModel = axesModels[0];
  30142. var yAxisModel = axesModels[1];
  30143. var gridModel = xAxisModel.getCoordSysModel();
  30144. if (__DEV__) {
  30145. if (!gridModel) {
  30146. throw new Error(
  30147. 'Grid "' + retrieve(
  30148. xAxisModel.get('gridIndex'),
  30149. xAxisModel.get('gridId'),
  30150. 0
  30151. ) + '" not found'
  30152. );
  30153. }
  30154. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  30155. throw new Error('xAxis and yAxis must use the same grid');
  30156. }
  30157. }
  30158. var grid = gridModel.coordinateSystem;
  30159. seriesModel.coordinateSystem = grid.getCartesian(
  30160. xAxisModel.componentIndex, yAxisModel.componentIndex
  30161. );
  30162. });
  30163. return grids;
  30164. };
  30165. // For deciding which dimensions to use when creating list data
  30166. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  30167. CoordinateSystemManager.register('cartesian2d', Grid);
  30168. var PI$2 = Math.PI;
  30169. function makeAxisEventDataBase(axisModel) {
  30170. var eventData = {
  30171. componentType: axisModel.mainType
  30172. };
  30173. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  30174. return eventData;
  30175. }
  30176. /**
  30177. * A final axis is translated and rotated from a "standard axis".
  30178. * So opt.position and opt.rotation is required.
  30179. *
  30180. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  30181. * for example: (0, 0) ------------> (0, 50)
  30182. *
  30183. * nameDirection or tickDirection or labelDirection is 1 means tick
  30184. * or label is below the standard axis, whereas is -1 means above
  30185. * the standard axis. labelOffset means offset between label and axis,
  30186. * which is useful when 'onZero', where axisLabel is in the grid and
  30187. * label in outside grid.
  30188. *
  30189. * Tips: like always,
  30190. * positive rotation represents anticlockwise, and negative rotation
  30191. * represents clockwise.
  30192. * The direction of position coordinate is the same as the direction
  30193. * of screen coordinate.
  30194. *
  30195. * Do not need to consider axis 'inverse', which is auto processed by
  30196. * axis extent.
  30197. *
  30198. * @param {module:zrender/container/Group} group
  30199. * @param {Object} axisModel
  30200. * @param {Object} opt Standard axis parameters.
  30201. * @param {Array.<number>} opt.position [x, y]
  30202. * @param {number} opt.rotation by radian
  30203. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  30204. * @param {number} [opt.tickDirection=1] 1 or -1
  30205. * @param {number} [opt.labelDirection=1] 1 or -1
  30206. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  30207. * @param {string} [opt.axisLabelShow] default get from axisModel.
  30208. * @param {string} [opt.axisName] default get from axisModel.
  30209. * @param {number} [opt.axisNameAvailableWidth]
  30210. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  30211. * @param {number} [opt.labelInterval] Default label interval when label
  30212. * interval from model is null or 'auto'.
  30213. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  30214. * @param {number} [opt.nameTruncateMaxWidth]
  30215. */
  30216. var AxisBuilder = function (axisModel, opt) {
  30217. /**
  30218. * @readOnly
  30219. */
  30220. this.opt = opt;
  30221. /**
  30222. * @readOnly
  30223. */
  30224. this.axisModel = axisModel;
  30225. // Default value
  30226. defaults(
  30227. opt,
  30228. {
  30229. labelOffset: 0,
  30230. nameDirection: 1,
  30231. tickDirection: 1,
  30232. labelDirection: 1,
  30233. silent: true
  30234. }
  30235. );
  30236. /**
  30237. * @readOnly
  30238. */
  30239. this.group = new Group();
  30240. // FIXME Not use a seperate text group?
  30241. var dumbGroup = new Group({
  30242. position: opt.position.slice(),
  30243. rotation: opt.rotation
  30244. });
  30245. // this.group.add(dumbGroup);
  30246. // this._dumbGroup = dumbGroup;
  30247. dumbGroup.updateTransform();
  30248. this._transform = dumbGroup.transform;
  30249. this._dumbGroup = dumbGroup;
  30250. };
  30251. AxisBuilder.prototype = {
  30252. constructor: AxisBuilder,
  30253. hasBuilder: function (name) {
  30254. return !!builders[name];
  30255. },
  30256. add: function (name) {
  30257. builders[name].call(this);
  30258. },
  30259. getGroup: function () {
  30260. return this.group;
  30261. }
  30262. };
  30263. var builders = {
  30264. /**
  30265. * @private
  30266. */
  30267. axisLine: function () {
  30268. var opt = this.opt;
  30269. var axisModel = this.axisModel;
  30270. if (!axisModel.get('axisLine.show')) {
  30271. return;
  30272. }
  30273. var extent = this.axisModel.axis.getExtent();
  30274. var matrix = this._transform;
  30275. var pt1 = [extent[0], 0];
  30276. var pt2 = [extent[1], 0];
  30277. if (matrix) {
  30278. applyTransform(pt1, pt1, matrix);
  30279. applyTransform(pt2, pt2, matrix);
  30280. }
  30281. var lineStyle = extend(
  30282. {
  30283. lineCap: 'round'
  30284. },
  30285. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  30286. );
  30287. this.group.add(new Line(subPixelOptimizeLine({
  30288. // Id for animation
  30289. anid: 'line',
  30290. shape: {
  30291. x1: pt1[0],
  30292. y1: pt1[1],
  30293. x2: pt2[0],
  30294. y2: pt2[1]
  30295. },
  30296. style: lineStyle,
  30297. strokeContainThreshold: opt.strokeContainThreshold || 5,
  30298. silent: true,
  30299. z2: 1
  30300. })));
  30301. var arrows = axisModel.get('axisLine.symbol');
  30302. var arrowSize = axisModel.get('axisLine.symbolSize');
  30303. var arrowOffset = axisModel.get('axisLine.symbolOffset') || 0;
  30304. if (typeof arrowOffset === 'number') {
  30305. arrowOffset = [arrowOffset, arrowOffset];
  30306. }
  30307. if (arrows != null) {
  30308. if (typeof arrows === 'string') {
  30309. // Use the same arrow for start and end point
  30310. arrows = [arrows, arrows];
  30311. }
  30312. if (typeof arrowSize === 'string'
  30313. || typeof arrowSize === 'number'
  30314. ) {
  30315. // Use the same size for width and height
  30316. arrowSize = [arrowSize, arrowSize];
  30317. }
  30318. var symbolWidth = arrowSize[0];
  30319. var symbolHeight = arrowSize[1];
  30320. each$1([{
  30321. rotate: opt.rotation + Math.PI / 2,
  30322. offset: arrowOffset[0],
  30323. r: 0
  30324. }, {
  30325. rotate: opt.rotation - Math.PI / 2,
  30326. offset: arrowOffset[1],
  30327. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0])
  30328. + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  30329. }], function (point, index) {
  30330. if (arrows[index] !== 'none' && arrows[index] != null) {
  30331. var symbol = createSymbol(
  30332. arrows[index],
  30333. -symbolWidth / 2,
  30334. -symbolHeight / 2,
  30335. symbolWidth,
  30336. symbolHeight,
  30337. lineStyle.stroke,
  30338. true
  30339. );
  30340. // Calculate arrow position with offset
  30341. var r = point.r + point.offset;
  30342. var pos = [
  30343. pt1[0] + r * Math.cos(opt.rotation),
  30344. pt1[1] - r * Math.sin(opt.rotation)
  30345. ];
  30346. symbol.attr({
  30347. rotation: point.rotate,
  30348. position: pos,
  30349. silent: true
  30350. });
  30351. this.group.add(symbol);
  30352. }
  30353. }, this);
  30354. }
  30355. },
  30356. /**
  30357. * @private
  30358. */
  30359. axisTickLabel: function () {
  30360. var axisModel = this.axisModel;
  30361. var opt = this.opt;
  30362. var tickEls = buildAxisTick(this, axisModel, opt);
  30363. var labelEls = buildAxisLabel(this, axisModel, opt);
  30364. fixMinMaxLabelShow(axisModel, labelEls, tickEls);
  30365. },
  30366. /**
  30367. * @private
  30368. */
  30369. axisName: function () {
  30370. var opt = this.opt;
  30371. var axisModel = this.axisModel;
  30372. var name = retrieve(opt.axisName, axisModel.get('name'));
  30373. if (!name) {
  30374. return;
  30375. }
  30376. var nameLocation = axisModel.get('nameLocation');
  30377. var nameDirection = opt.nameDirection;
  30378. var textStyleModel = axisModel.getModel('nameTextStyle');
  30379. var gap = axisModel.get('nameGap') || 0;
  30380. var extent = this.axisModel.axis.getExtent();
  30381. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  30382. var pos = [
  30383. nameLocation === 'start'
  30384. ? extent[0] - gapSignal * gap
  30385. : nameLocation === 'end'
  30386. ? extent[1] + gapSignal * gap
  30387. : (extent[0] + extent[1]) / 2, // 'middle'
  30388. // Reuse labelOffset.
  30389. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  30390. ];
  30391. var labelLayout;
  30392. var nameRotation = axisModel.get('nameRotate');
  30393. if (nameRotation != null) {
  30394. nameRotation = nameRotation * PI$2 / 180; // To radian.
  30395. }
  30396. var axisNameAvailableWidth;
  30397. if (isNameLocationCenter(nameLocation)) {
  30398. labelLayout = innerTextLayout(
  30399. opt.rotation,
  30400. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  30401. nameDirection
  30402. );
  30403. }
  30404. else {
  30405. labelLayout = endTextLayout(
  30406. opt, nameLocation, nameRotation || 0, extent
  30407. );
  30408. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  30409. if (axisNameAvailableWidth != null) {
  30410. axisNameAvailableWidth = Math.abs(
  30411. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  30412. );
  30413. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  30414. }
  30415. }
  30416. var textFont = textStyleModel.getFont();
  30417. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  30418. var ellipsis = truncateOpt.ellipsis;
  30419. var maxWidth = retrieve(
  30420. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  30421. );
  30422. // FIXME
  30423. // truncate rich text? (consider performance)
  30424. var truncatedText = (ellipsis != null && maxWidth != null)
  30425. ? truncateText$1(
  30426. name, maxWidth, textFont, ellipsis,
  30427. {minChar: 2, placeholder: truncateOpt.placeholder}
  30428. )
  30429. : name;
  30430. var tooltipOpt = axisModel.get('tooltip', true);
  30431. var mainType = axisModel.mainType;
  30432. var formatterParams = {
  30433. componentType: mainType,
  30434. name: name,
  30435. $vars: ['name']
  30436. };
  30437. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  30438. var textEl = new Text({
  30439. // Id for animation
  30440. anid: 'name',
  30441. __fullText: name,
  30442. __truncatedText: truncatedText,
  30443. position: pos,
  30444. rotation: labelLayout.rotation,
  30445. silent: isSilent(axisModel),
  30446. z2: 1,
  30447. tooltip: (tooltipOpt && tooltipOpt.show)
  30448. ? extend({
  30449. content: name,
  30450. formatter: function () {
  30451. return name;
  30452. },
  30453. formatterParams: formatterParams
  30454. }, tooltipOpt)
  30455. : null
  30456. });
  30457. setTextStyle(textEl.style, textStyleModel, {
  30458. text: truncatedText,
  30459. textFont: textFont,
  30460. textFill: textStyleModel.getTextColor()
  30461. || axisModel.get('axisLine.lineStyle.color'),
  30462. textAlign: labelLayout.textAlign,
  30463. textVerticalAlign: labelLayout.textVerticalAlign
  30464. });
  30465. if (axisModel.get('triggerEvent')) {
  30466. textEl.eventData = makeAxisEventDataBase(axisModel);
  30467. textEl.eventData.targetType = 'axisName';
  30468. textEl.eventData.name = name;
  30469. }
  30470. // FIXME
  30471. this._dumbGroup.add(textEl);
  30472. textEl.updateTransform();
  30473. this.group.add(textEl);
  30474. textEl.decomposeTransform();
  30475. }
  30476. };
  30477. /**
  30478. * @public
  30479. * @static
  30480. * @param {Object} opt
  30481. * @param {number} axisRotation in radian
  30482. * @param {number} textRotation in radian
  30483. * @param {number} direction
  30484. * @return {Object} {
  30485. * rotation, // according to axis
  30486. * textAlign,
  30487. * textVerticalAlign
  30488. * }
  30489. */
  30490. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  30491. var rotationDiff = remRadian(textRotation - axisRotation);
  30492. var textAlign;
  30493. var textVerticalAlign;
  30494. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  30495. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  30496. textAlign = 'center';
  30497. }
  30498. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  30499. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  30500. textAlign = 'center';
  30501. }
  30502. else {
  30503. textVerticalAlign = 'middle';
  30504. if (rotationDiff > 0 && rotationDiff < PI$2) {
  30505. textAlign = direction > 0 ? 'right' : 'left';
  30506. }
  30507. else {
  30508. textAlign = direction > 0 ? 'left' : 'right';
  30509. }
  30510. }
  30511. return {
  30512. rotation: rotationDiff,
  30513. textAlign: textAlign,
  30514. textVerticalAlign: textVerticalAlign
  30515. };
  30516. };
  30517. function endTextLayout(opt, textPosition, textRotate, extent) {
  30518. var rotationDiff = remRadian(textRotate - opt.rotation);
  30519. var textAlign;
  30520. var textVerticalAlign;
  30521. var inverse = extent[0] > extent[1];
  30522. var onLeft = (textPosition === 'start' && !inverse)
  30523. || (textPosition !== 'start' && inverse);
  30524. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  30525. textVerticalAlign = onLeft ? 'bottom' : 'top';
  30526. textAlign = 'center';
  30527. }
  30528. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  30529. textVerticalAlign = onLeft ? 'top' : 'bottom';
  30530. textAlign = 'center';
  30531. }
  30532. else {
  30533. textVerticalAlign = 'middle';
  30534. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  30535. textAlign = onLeft ? 'left' : 'right';
  30536. }
  30537. else {
  30538. textAlign = onLeft ? 'right' : 'left';
  30539. }
  30540. }
  30541. return {
  30542. rotation: rotationDiff,
  30543. textAlign: textAlign,
  30544. textVerticalAlign: textVerticalAlign
  30545. };
  30546. }
  30547. function isSilent(axisModel) {
  30548. var tooltipOpt = axisModel.get('tooltip');
  30549. return axisModel.get('silent')
  30550. // Consider mouse cursor, add these restrictions.
  30551. || !(
  30552. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  30553. );
  30554. }
  30555. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  30556. // If min or max are user set, we need to check
  30557. // If the tick on min(max) are overlap on their neighbour tick
  30558. // If they are overlapped, we need to hide the min(max) tick label
  30559. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  30560. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  30561. // FIXME
  30562. // Have not consider onBand yet, where tick els is more than label els.
  30563. labelEls = labelEls || [];
  30564. tickEls = tickEls || [];
  30565. var firstLabel = labelEls[0];
  30566. var nextLabel = labelEls[1];
  30567. var lastLabel = labelEls[labelEls.length - 1];
  30568. var prevLabel = labelEls[labelEls.length - 2];
  30569. var firstTick = tickEls[0];
  30570. var nextTick = tickEls[1];
  30571. var lastTick = tickEls[tickEls.length - 1];
  30572. var prevTick = tickEls[tickEls.length - 2];
  30573. if (showMinLabel === false) {
  30574. ignoreEl(firstLabel);
  30575. ignoreEl(firstTick);
  30576. }
  30577. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  30578. if (showMinLabel) {
  30579. ignoreEl(nextLabel);
  30580. ignoreEl(nextTick);
  30581. }
  30582. else {
  30583. ignoreEl(firstLabel);
  30584. ignoreEl(firstTick);
  30585. }
  30586. }
  30587. if (showMaxLabel === false) {
  30588. ignoreEl(lastLabel);
  30589. ignoreEl(lastTick);
  30590. }
  30591. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  30592. if (showMaxLabel) {
  30593. ignoreEl(prevLabel);
  30594. ignoreEl(prevTick);
  30595. }
  30596. else {
  30597. ignoreEl(lastLabel);
  30598. ignoreEl(lastTick);
  30599. }
  30600. }
  30601. }
  30602. function ignoreEl(el) {
  30603. el && (el.ignore = true);
  30604. }
  30605. function isTwoLabelOverlapped(current, next, labelLayout) {
  30606. // current and next has the same rotation.
  30607. var firstRect = current && current.getBoundingRect().clone();
  30608. var nextRect = next && next.getBoundingRect().clone();
  30609. if (!firstRect || !nextRect) {
  30610. return;
  30611. }
  30612. // When checking intersect of two rotated labels, we use mRotationBack
  30613. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  30614. var mRotationBack = identity([]);
  30615. rotate(mRotationBack, mRotationBack, -current.rotation);
  30616. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  30617. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  30618. return firstRect.intersect(nextRect);
  30619. }
  30620. function isNameLocationCenter(nameLocation) {
  30621. return nameLocation === 'middle' || nameLocation === 'center';
  30622. }
  30623. /**
  30624. * @static
  30625. */
  30626. var ifIgnoreOnTick$1 = AxisBuilder.ifIgnoreOnTick = function (
  30627. axis,
  30628. i,
  30629. interval,
  30630. ticksCnt,
  30631. showMinLabel,
  30632. showMaxLabel
  30633. ) {
  30634. if (i === 0 && showMinLabel || i === ticksCnt - 1 && showMaxLabel) {
  30635. return false;
  30636. }
  30637. // FIXME
  30638. // Have not consider label overlap (if label is too long) yet.
  30639. var rawTick;
  30640. var scale$$1 = axis.scale;
  30641. return scale$$1.type === 'ordinal'
  30642. && (
  30643. typeof interval === 'function'
  30644. ? (
  30645. rawTick = scale$$1.getTicks()[i],
  30646. !interval(rawTick, scale$$1.getLabel(rawTick))
  30647. )
  30648. : i % (interval + 1)
  30649. );
  30650. };
  30651. /**
  30652. * @static
  30653. */
  30654. var getInterval$1 = AxisBuilder.getInterval = function (model, labelInterval) {
  30655. var interval = model.get('interval');
  30656. if (interval == null || interval == 'auto') {
  30657. interval = labelInterval;
  30658. }
  30659. return interval;
  30660. };
  30661. function buildAxisTick(axisBuilder, axisModel, opt) {
  30662. var axis = axisModel.axis;
  30663. if (!axisModel.get('axisTick.show') || axis.scale.isBlank()) {
  30664. return;
  30665. }
  30666. var tickModel = axisModel.getModel('axisTick');
  30667. var lineStyleModel = tickModel.getModel('lineStyle');
  30668. var tickLen = tickModel.get('length');
  30669. var tickInterval = getInterval$1(tickModel, opt.labelInterval);
  30670. var ticksCoords = axis.getTicksCoords(tickModel.get('alignWithLabel'));
  30671. // FIXME
  30672. // Corresponds to ticksCoords ?
  30673. var ticks = axis.scale.getTicks();
  30674. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  30675. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  30676. var pt1 = [];
  30677. var pt2 = [];
  30678. var matrix = axisBuilder._transform;
  30679. var tickEls = [];
  30680. var ticksCnt = ticksCoords.length;
  30681. for (var i = 0; i < ticksCnt; i++) {
  30682. // Only ordinal scale support tick interval
  30683. if (ifIgnoreOnTick$1(
  30684. axis, i, tickInterval, ticksCnt,
  30685. showMinLabel, showMaxLabel
  30686. )) {
  30687. continue;
  30688. }
  30689. var tickCoord = ticksCoords[i];
  30690. pt1[0] = tickCoord;
  30691. pt1[1] = 0;
  30692. pt2[0] = tickCoord;
  30693. pt2[1] = opt.tickDirection * tickLen;
  30694. if (matrix) {
  30695. applyTransform(pt1, pt1, matrix);
  30696. applyTransform(pt2, pt2, matrix);
  30697. }
  30698. // Tick line, Not use group transform to have better line draw
  30699. var tickEl = new Line(subPixelOptimizeLine({
  30700. // Id for animation
  30701. anid: 'tick_' + ticks[i],
  30702. shape: {
  30703. x1: pt1[0],
  30704. y1: pt1[1],
  30705. x2: pt2[0],
  30706. y2: pt2[1]
  30707. },
  30708. style: defaults(
  30709. lineStyleModel.getLineStyle(),
  30710. {
  30711. stroke: axisModel.get('axisLine.lineStyle.color')
  30712. }
  30713. ),
  30714. z2: 2,
  30715. silent: true
  30716. }));
  30717. axisBuilder.group.add(tickEl);
  30718. tickEls.push(tickEl);
  30719. }
  30720. return tickEls;
  30721. }
  30722. function buildAxisLabel(axisBuilder, axisModel, opt) {
  30723. var axis = axisModel.axis;
  30724. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  30725. if (!show || axis.scale.isBlank()) {
  30726. return;
  30727. }
  30728. var labelModel = axisModel.getModel('axisLabel');
  30729. var labelMargin = labelModel.get('margin');
  30730. var ticks = axis.scale.getTicks();
  30731. var labels = axisModel.getFormattedLabels();
  30732. // Special label rotate.
  30733. var labelRotation = (
  30734. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  30735. ) * PI$2 / 180;
  30736. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  30737. var categoryData = axisModel.getCategories();
  30738. var labelEls = [];
  30739. var silent = isSilent(axisModel);
  30740. var triggerEvent = axisModel.get('triggerEvent');
  30741. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  30742. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  30743. each$1(ticks, function (tickVal, index) {
  30744. if (ifIgnoreOnTick$1(
  30745. axis, index, opt.labelInterval, ticks.length,
  30746. showMinLabel, showMaxLabel
  30747. )) {
  30748. return;
  30749. }
  30750. var itemLabelModel = labelModel;
  30751. if (categoryData && categoryData[tickVal] && categoryData[tickVal].textStyle) {
  30752. itemLabelModel = new Model(
  30753. categoryData[tickVal].textStyle, labelModel, axisModel.ecModel
  30754. );
  30755. }
  30756. var textColor = itemLabelModel.getTextColor()
  30757. || axisModel.get('axisLine.lineStyle.color');
  30758. var tickCoord = axis.dataToCoord(tickVal);
  30759. var pos = [
  30760. tickCoord,
  30761. opt.labelOffset + opt.labelDirection * labelMargin
  30762. ];
  30763. var labelStr = axis.scale.getLabel(tickVal);
  30764. var textEl = new Text({
  30765. // Id for animation
  30766. anid: 'label_' + tickVal,
  30767. position: pos,
  30768. rotation: labelLayout.rotation,
  30769. silent: silent,
  30770. z2: 10
  30771. });
  30772. setTextStyle(textEl.style, itemLabelModel, {
  30773. text: labels[index],
  30774. textAlign: itemLabelModel.getShallow('align', true)
  30775. || labelLayout.textAlign,
  30776. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  30777. || itemLabelModel.getShallow('baseline', true)
  30778. || labelLayout.textVerticalAlign,
  30779. textFill: typeof textColor === 'function'
  30780. ? textColor(
  30781. // (1) In category axis with data zoom, tick is not the original
  30782. // index of axis.data. So tick should not be exposed to user
  30783. // in category axis.
  30784. // (2) Compatible with previous version, which always returns labelStr.
  30785. // But in interval scale labelStr is like '223,445', which maked
  30786. // user repalce ','. So we modify it to return original val but remain
  30787. // it as 'string' to avoid error in replacing.
  30788. axis.type === 'category' ? labelStr : axis.type === 'value' ? tickVal + '' : tickVal,
  30789. index
  30790. )
  30791. : textColor
  30792. });
  30793. // Pack data for mouse event
  30794. if (triggerEvent) {
  30795. textEl.eventData = makeAxisEventDataBase(axisModel);
  30796. textEl.eventData.targetType = 'axisLabel';
  30797. textEl.eventData.value = labelStr;
  30798. }
  30799. // FIXME
  30800. axisBuilder._dumbGroup.add(textEl);
  30801. textEl.updateTransform();
  30802. labelEls.push(textEl);
  30803. axisBuilder.group.add(textEl);
  30804. textEl.decomposeTransform();
  30805. });
  30806. return labelEls;
  30807. }
  30808. var each$7 = each$1;
  30809. var curry$1 = curry;
  30810. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  30811. // allAxesInfo should be updated when setOption performed.
  30812. function collect(ecModel, api) {
  30813. var result = {
  30814. /**
  30815. * key: makeKey(axis.model)
  30816. * value: {
  30817. * axis,
  30818. * coordSys,
  30819. * axisPointerModel,
  30820. * triggerTooltip,
  30821. * involveSeries,
  30822. * snap,
  30823. * seriesModels,
  30824. * seriesDataCount
  30825. * }
  30826. */
  30827. axesInfo: {},
  30828. seriesInvolved: false,
  30829. /**
  30830. * key: makeKey(coordSys.model)
  30831. * value: Object: key makeKey(axis.model), value: axisInfo
  30832. */
  30833. coordSysAxesInfo: {},
  30834. coordSysMap: {}
  30835. };
  30836. collectAxesInfo(result, ecModel, api);
  30837. // Check seriesInvolved for performance, in case too many series in some chart.
  30838. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  30839. return result;
  30840. }
  30841. function collectAxesInfo(result, ecModel, api) {
  30842. var globalTooltipModel = ecModel.getComponent('tooltip');
  30843. var globalAxisPointerModel = ecModel.getComponent('axisPointer');
  30844. // links can only be set on global.
  30845. var linksOption = globalAxisPointerModel.get('link', true) || [];
  30846. var linkGroups = [];
  30847. // Collect axes info.
  30848. each$7(api.getCoordinateSystems(), function (coordSys) {
  30849. // Some coordinate system do not support axes, like geo.
  30850. if (!coordSys.axisPointerEnabled) {
  30851. return;
  30852. }
  30853. var coordSysKey = makeKey(coordSys.model);
  30854. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  30855. result.coordSysMap[coordSysKey] = coordSys;
  30856. // Set tooltip (like 'cross') is a convienent way to show axisPointer
  30857. // for user. So we enable seting tooltip on coordSys model.
  30858. var coordSysModel = coordSys.model;
  30859. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  30860. each$7(coordSys.getAxes(), curry$1(saveTooltipAxisInfo, false, null));
  30861. // If axis tooltip used, choose tooltip axis for each coordSys.
  30862. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  30863. if (coordSys.getTooltipAxes
  30864. && globalTooltipModel
  30865. // If tooltip.showContent is set as false, tooltip will not
  30866. // show but axisPointer will show as normal.
  30867. && baseTooltipModel.get('show')
  30868. ) {
  30869. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  30870. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  30871. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  30872. var cross = baseTooltipModel.get('axisPointer.type') === 'cross';
  30873. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get('axisPointer.axis'));
  30874. if (triggerAxis || cross) {
  30875. each$7(tooltipAxes.baseAxes, curry$1(
  30876. saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis
  30877. ));
  30878. }
  30879. if (cross) {
  30880. each$7(tooltipAxes.otherAxes, curry$1(saveTooltipAxisInfo, 'cross', false));
  30881. }
  30882. }
  30883. // fromTooltip: true | false | 'cross'
  30884. // triggerTooltip: true | false | null
  30885. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  30886. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  30887. var axisPointerShow = axisPointerModel.get('show');
  30888. if (!axisPointerShow || (
  30889. axisPointerShow === 'auto'
  30890. && !fromTooltip
  30891. && !isHandleTrigger(axisPointerModel)
  30892. )) {
  30893. return;
  30894. }
  30895. if (triggerTooltip == null) {
  30896. triggerTooltip = axisPointerModel.get('triggerTooltip');
  30897. }
  30898. axisPointerModel = fromTooltip
  30899. ? makeAxisPointerModel(
  30900. axis, baseTooltipModel, globalAxisPointerModel, ecModel,
  30901. fromTooltip, triggerTooltip
  30902. )
  30903. : axisPointerModel;
  30904. var snap = axisPointerModel.get('snap');
  30905. var key = makeKey(axis.model);
  30906. var involveSeries = triggerTooltip || snap || axis.type === 'category';
  30907. // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  30908. var axisInfo = result.axesInfo[key] = {
  30909. key: key,
  30910. axis: axis,
  30911. coordSys: coordSys,
  30912. axisPointerModel: axisPointerModel,
  30913. triggerTooltip: triggerTooltip,
  30914. involveSeries: involveSeries,
  30915. snap: snap,
  30916. useHandle: isHandleTrigger(axisPointerModel),
  30917. seriesModels: []
  30918. };
  30919. axesInfoInCoordSys[key] = axisInfo;
  30920. result.seriesInvolved |= involveSeries;
  30921. var groupIndex = getLinkGroupIndex(linksOption, axis);
  30922. if (groupIndex != null) {
  30923. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {axesInfo: {}});
  30924. linkGroup.axesInfo[key] = axisInfo;
  30925. linkGroup.mapper = linksOption[groupIndex].mapper;
  30926. axisInfo.linkGroup = linkGroup;
  30927. }
  30928. }
  30929. });
  30930. }
  30931. function makeAxisPointerModel(
  30932. axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip
  30933. ) {
  30934. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  30935. var volatileOption = {};
  30936. each$7(
  30937. [
  30938. 'type', 'snap', 'lineStyle', 'shadowStyle', 'label',
  30939. 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'
  30940. ],
  30941. function (field) {
  30942. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  30943. }
  30944. );
  30945. // category axis do not auto snap, otherwise some tick that do not
  30946. // has value can not be hovered. value/time/log axis default snap if
  30947. // triggered from tooltip and trigger tooltip.
  30948. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip;
  30949. // Compatibel with previous behavior, tooltip axis do not show label by default.
  30950. // Only these properties can be overrided from tooltip to axisPointer.
  30951. if (tooltipAxisPointerModel.get('type') === 'cross') {
  30952. volatileOption.type = 'line';
  30953. }
  30954. var labelOption = volatileOption.label || (volatileOption.label = {});
  30955. // Follow the convention, do not show label when triggered by tooltip by default.
  30956. labelOption.show == null && (labelOption.show = false);
  30957. if (fromTooltip === 'cross') {
  30958. // When 'cross', both axes show labels.
  30959. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get('label.show');
  30960. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true;
  30961. // If triggerTooltip, this is a base axis, which should better not use cross style
  30962. // (cross style is dashed by default)
  30963. if (!triggerTooltip) {
  30964. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  30965. crossStyle && defaults(labelOption, crossStyle.textStyle);
  30966. }
  30967. }
  30968. return axis.model.getModel(
  30969. 'axisPointer',
  30970. new Model(volatileOption, globalAxisPointerModel, ecModel)
  30971. );
  30972. }
  30973. function collectSeriesInfo(result, ecModel) {
  30974. // Prepare data for axis trigger
  30975. ecModel.eachSeries(function (seriesModel) {
  30976. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  30977. var coordSys = seriesModel.coordinateSystem;
  30978. var seriesTooltipTrigger = seriesModel.get('tooltip.trigger', true);
  30979. var seriesTooltipShow = seriesModel.get('tooltip.show', true);
  30980. if (!coordSys
  30981. || seriesTooltipTrigger === 'none'
  30982. || seriesTooltipTrigger === false
  30983. || seriesTooltipTrigger === 'item'
  30984. || seriesTooltipShow === false
  30985. || seriesModel.get('axisPointer.show', true) === false
  30986. ) {
  30987. return;
  30988. }
  30989. each$7(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  30990. var axis = axisInfo.axis;
  30991. if (coordSys.getAxis(axis.dim) === axis) {
  30992. axisInfo.seriesModels.push(seriesModel);
  30993. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  30994. axisInfo.seriesDataCount += seriesModel.getData().count();
  30995. }
  30996. });
  30997. }, this);
  30998. }
  30999. /**
  31000. * For example:
  31001. * {
  31002. * axisPointer: {
  31003. * links: [{
  31004. * xAxisIndex: [2, 4],
  31005. * yAxisIndex: 'all'
  31006. * }, {
  31007. * xAxisId: ['a5', 'a7'],
  31008. * xAxisName: 'xxx'
  31009. * }]
  31010. * }
  31011. * }
  31012. */
  31013. function getLinkGroupIndex(linksOption, axis) {
  31014. var axisModel = axis.model;
  31015. var dim = axis.dim;
  31016. for (var i = 0; i < linksOption.length; i++) {
  31017. var linkOption = linksOption[i] || {};
  31018. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id)
  31019. || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex)
  31020. || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)
  31021. ) {
  31022. return i;
  31023. }
  31024. }
  31025. }
  31026. function checkPropInLink(linkPropValue, axisPropValue) {
  31027. return linkPropValue === 'all'
  31028. || (isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0)
  31029. || linkPropValue === axisPropValue;
  31030. }
  31031. function fixValue(axisModel) {
  31032. var axisInfo = getAxisInfo(axisModel);
  31033. if (!axisInfo) {
  31034. return;
  31035. }
  31036. var axisPointerModel = axisInfo.axisPointerModel;
  31037. var scale = axisInfo.axis.scale;
  31038. var option = axisPointerModel.option;
  31039. var status = axisPointerModel.get('status');
  31040. var value = axisPointerModel.get('value');
  31041. // Parse init value for category and time axis.
  31042. if (value != null) {
  31043. value = scale.parse(value);
  31044. }
  31045. var useHandle = isHandleTrigger(axisPointerModel);
  31046. // If `handle` used, `axisPointer` will always be displayed, so value
  31047. // and status should be initialized.
  31048. if (status == null) {
  31049. option.status = useHandle ? 'show' : 'hide';
  31050. }
  31051. var extent = scale.getExtent().slice();
  31052. extent[0] > extent[1] && extent.reverse();
  31053. if (// Pick a value on axis when initializing.
  31054. value == null
  31055. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  31056. // where we should re-pick a value to keep `handle` displaying normally.
  31057. || value > extent[1]
  31058. ) {
  31059. // Make handle displayed on the end of the axis when init, which looks better.
  31060. value = extent[1];
  31061. }
  31062. if (value < extent[0]) {
  31063. value = extent[0];
  31064. }
  31065. option.value = value;
  31066. if (useHandle) {
  31067. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  31068. }
  31069. }
  31070. function getAxisInfo(axisModel) {
  31071. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  31072. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  31073. }
  31074. function getAxisPointerModel(axisModel) {
  31075. var axisInfo = getAxisInfo(axisModel);
  31076. return axisInfo && axisInfo.axisPointerModel;
  31077. }
  31078. function isHandleTrigger(axisPointerModel) {
  31079. return !!axisPointerModel.get('handle.show');
  31080. }
  31081. /**
  31082. * @param {module:echarts/model/Model} model
  31083. * @return {string} unique key
  31084. */
  31085. function makeKey(model) {
  31086. return model.type + '||' + model.id;
  31087. }
  31088. /**
  31089. * Base class of AxisView.
  31090. */
  31091. var AxisView = extendComponentView({
  31092. type: 'axis',
  31093. /**
  31094. * @private
  31095. */
  31096. _axisPointer: null,
  31097. /**
  31098. * @protected
  31099. * @type {string}
  31100. */
  31101. axisPointerClass: null,
  31102. /**
  31103. * @override
  31104. */
  31105. render: function (axisModel, ecModel, api, payload) {
  31106. // FIXME
  31107. // This process should proformed after coordinate systems updated
  31108. // (axis scale updated), and should be performed each time update.
  31109. // So put it here temporarily, although it is not appropriate to
  31110. // put a model-writing procedure in `view`.
  31111. this.axisPointerClass && fixValue(axisModel);
  31112. AxisView.superApply(this, 'render', arguments);
  31113. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  31114. },
  31115. /**
  31116. * Action handler.
  31117. * @public
  31118. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  31119. * @param {module:echarts/model/Global} ecModel
  31120. * @param {module:echarts/ExtensionAPI} api
  31121. * @param {Object} payload
  31122. */
  31123. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  31124. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  31125. },
  31126. /**
  31127. * @override
  31128. */
  31129. remove: function (ecModel, api) {
  31130. var axisPointer = this._axisPointer;
  31131. axisPointer && axisPointer.remove(api);
  31132. AxisView.superApply(this, 'remove', arguments);
  31133. },
  31134. /**
  31135. * @override
  31136. */
  31137. dispose: function (ecModel, api) {
  31138. disposeAxisPointer(this, api);
  31139. AxisView.superApply(this, 'dispose', arguments);
  31140. }
  31141. });
  31142. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  31143. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  31144. if (!Clazz) {
  31145. return;
  31146. }
  31147. var axisPointerModel = getAxisPointerModel(axisModel);
  31148. axisPointerModel
  31149. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  31150. .render(axisModel, axisPointerModel, api, forceRender)
  31151. : disposeAxisPointer(axisView, api);
  31152. }
  31153. function disposeAxisPointer(axisView, ecModel, api) {
  31154. var axisPointer = axisView._axisPointer;
  31155. axisPointer && axisPointer.dispose(ecModel, api);
  31156. axisView._axisPointer = null;
  31157. }
  31158. var axisPointerClazz = [];
  31159. AxisView.registerAxisPointerClass = function (type, clazz) {
  31160. if (__DEV__) {
  31161. if (axisPointerClazz[type]) {
  31162. throw new Error('axisPointer ' + type + ' exists');
  31163. }
  31164. }
  31165. axisPointerClazz[type] = clazz;
  31166. };
  31167. AxisView.getAxisPointerClass = function (type) {
  31168. return type && axisPointerClazz[type];
  31169. };
  31170. /**
  31171. * @param {Object} opt {labelInside}
  31172. * @return {Object} {
  31173. * position, rotation, labelDirection, labelOffset,
  31174. * tickDirection, labelRotate, labelInterval, z2
  31175. * }
  31176. */
  31177. function layout$1(gridModel, axisModel, opt) {
  31178. opt = opt || {};
  31179. var grid = gridModel.coordinateSystem;
  31180. var axis = axisModel.axis;
  31181. var layout = {};
  31182. var rawAxisPosition = axis.position;
  31183. var axisPosition = axis.onZero ? 'onZero' : rawAxisPosition;
  31184. var axisDim = axis.dim;
  31185. var rect = grid.getRect();
  31186. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  31187. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  31188. var axisOffset = axisModel.get('offset') || 0;
  31189. var posBound = axisDim === 'x'
  31190. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  31191. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  31192. if (axis.onZero) {
  31193. var otherAxis = grid.getAxis(axisDim === 'x' ? 'y' : 'x', axis.onZeroAxisIndex);
  31194. var onZeroCoord = otherAxis.toGlobalCoord(otherAxis.dataToCoord(0));
  31195. posBound[idx['onZero']] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  31196. }
  31197. // Axis position
  31198. layout.position = [
  31199. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  31200. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  31201. ];
  31202. // Axis rotation
  31203. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  31204. // Tick and label direction, x y is axisDim
  31205. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  31206. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  31207. layout.labelOffset = axis.onZero ? posBound[idx[rawAxisPosition]] - posBound[idx['onZero']] : 0;
  31208. if (axisModel.get('axisTick.inside')) {
  31209. layout.tickDirection = -layout.tickDirection;
  31210. }
  31211. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  31212. layout.labelDirection = -layout.labelDirection;
  31213. }
  31214. // Special label rotation
  31215. var labelRotate = axisModel.get('axisLabel.rotate');
  31216. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  31217. // label interval when auto mode.
  31218. layout.labelInterval = axis.getLabelInterval();
  31219. // Over splitLine and splitArea
  31220. layout.z2 = 1;
  31221. return layout;
  31222. }
  31223. var ifIgnoreOnTick = AxisBuilder.ifIgnoreOnTick;
  31224. var getInterval = AxisBuilder.getInterval;
  31225. var axisBuilderAttrs = [
  31226. 'axisLine', 'axisTickLabel', 'axisName'
  31227. ];
  31228. var selfBuilderAttrs = [
  31229. 'splitArea', 'splitLine'
  31230. ];
  31231. // function getAlignWithLabel(model, axisModel) {
  31232. // var alignWithLabel = model.get('alignWithLabel');
  31233. // if (alignWithLabel === 'auto') {
  31234. // alignWithLabel = axisModel.get('axisTick.alignWithLabel');
  31235. // }
  31236. // return alignWithLabel;
  31237. // }
  31238. var CartesianAxisView = AxisView.extend({
  31239. type: 'cartesianAxis',
  31240. axisPointerClass: 'CartesianAxisPointer',
  31241. /**
  31242. * @override
  31243. */
  31244. render: function (axisModel, ecModel, api, payload) {
  31245. this.group.removeAll();
  31246. var oldAxisGroup = this._axisGroup;
  31247. this._axisGroup = new Group();
  31248. this.group.add(this._axisGroup);
  31249. if (!axisModel.get('show')) {
  31250. return;
  31251. }
  31252. var gridModel = axisModel.getCoordSysModel();
  31253. var layout = layout$1(gridModel, axisModel);
  31254. var axisBuilder = new AxisBuilder(axisModel, layout);
  31255. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  31256. this._axisGroup.add(axisBuilder.getGroup());
  31257. each$1(selfBuilderAttrs, function (name) {
  31258. if (axisModel.get(name + '.show')) {
  31259. this['_' + name](axisModel, gridModel, layout.labelInterval);
  31260. }
  31261. }, this);
  31262. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  31263. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  31264. },
  31265. /**
  31266. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  31267. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  31268. * @param {number|Function} labelInterval
  31269. * @private
  31270. */
  31271. _splitLine: function (axisModel, gridModel, labelInterval) {
  31272. var axis = axisModel.axis;
  31273. if (axis.scale.isBlank()) {
  31274. return;
  31275. }
  31276. var splitLineModel = axisModel.getModel('splitLine');
  31277. var lineStyleModel = splitLineModel.getModel('lineStyle');
  31278. var lineColors = lineStyleModel.get('color');
  31279. var lineInterval = getInterval(splitLineModel, labelInterval);
  31280. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  31281. var gridRect = gridModel.coordinateSystem.getRect();
  31282. var isHorizontal = axis.isHorizontal();
  31283. var lineCount = 0;
  31284. var ticksCoords = axis.getTicksCoords(
  31285. // splitLineModel.get('alignWithLabel')
  31286. );
  31287. var ticks = axis.scale.getTicks();
  31288. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  31289. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  31290. var p1 = [];
  31291. var p2 = [];
  31292. // Simple optimization
  31293. // Batching the lines if color are the same
  31294. var lineStyle = lineStyleModel.getLineStyle();
  31295. for (var i = 0; i < ticksCoords.length; i++) {
  31296. if (ifIgnoreOnTick(
  31297. axis, i, lineInterval, ticksCoords.length,
  31298. showMinLabel, showMaxLabel
  31299. )) {
  31300. continue;
  31301. }
  31302. var tickCoord = axis.toGlobalCoord(ticksCoords[i]);
  31303. if (isHorizontal) {
  31304. p1[0] = tickCoord;
  31305. p1[1] = gridRect.y;
  31306. p2[0] = tickCoord;
  31307. p2[1] = gridRect.y + gridRect.height;
  31308. }
  31309. else {
  31310. p1[0] = gridRect.x;
  31311. p1[1] = tickCoord;
  31312. p2[0] = gridRect.x + gridRect.width;
  31313. p2[1] = tickCoord;
  31314. }
  31315. var colorIndex = (lineCount++) % lineColors.length;
  31316. this._axisGroup.add(new Line(subPixelOptimizeLine({
  31317. anid: 'line_' + ticks[i],
  31318. shape: {
  31319. x1: p1[0],
  31320. y1: p1[1],
  31321. x2: p2[0],
  31322. y2: p2[1]
  31323. },
  31324. style: defaults({
  31325. stroke: lineColors[colorIndex]
  31326. }, lineStyle),
  31327. silent: true
  31328. })));
  31329. }
  31330. },
  31331. /**
  31332. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  31333. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  31334. * @param {number|Function} labelInterval
  31335. * @private
  31336. */
  31337. _splitArea: function (axisModel, gridModel, labelInterval) {
  31338. var axis = axisModel.axis;
  31339. if (axis.scale.isBlank()) {
  31340. return;
  31341. }
  31342. var splitAreaModel = axisModel.getModel('splitArea');
  31343. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  31344. var areaColors = areaStyleModel.get('color');
  31345. var gridRect = gridModel.coordinateSystem.getRect();
  31346. var ticksCoords = axis.getTicksCoords(
  31347. // splitAreaModel.get('alignWithLabel')
  31348. );
  31349. var ticks = axis.scale.getTicks();
  31350. var prevX = axis.toGlobalCoord(ticksCoords[0]);
  31351. var prevY = axis.toGlobalCoord(ticksCoords[0]);
  31352. var count = 0;
  31353. var areaInterval = getInterval(splitAreaModel, labelInterval);
  31354. var areaStyle = areaStyleModel.getAreaStyle();
  31355. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  31356. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  31357. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  31358. for (var i = 1; i < ticksCoords.length; i++) {
  31359. if (ifIgnoreOnTick(
  31360. axis, i, areaInterval, ticksCoords.length,
  31361. showMinLabel, showMaxLabel
  31362. ) && (i < ticksCoords.length - 1)) {
  31363. continue;
  31364. }
  31365. var tickCoord = axis.toGlobalCoord(ticksCoords[i]);
  31366. var x;
  31367. var y;
  31368. var width;
  31369. var height;
  31370. if (axis.isHorizontal()) {
  31371. x = prevX;
  31372. y = gridRect.y;
  31373. width = tickCoord - x;
  31374. height = gridRect.height;
  31375. }
  31376. else {
  31377. x = gridRect.x;
  31378. y = prevY;
  31379. width = gridRect.width;
  31380. height = tickCoord - y;
  31381. }
  31382. var colorIndex = (count++) % areaColors.length;
  31383. this._axisGroup.add(new Rect({
  31384. anid: 'area_' + ticks[i],
  31385. shape: {
  31386. x: x,
  31387. y: y,
  31388. width: width,
  31389. height: height
  31390. },
  31391. style: defaults({
  31392. fill: areaColors[colorIndex]
  31393. }, areaStyle),
  31394. silent: true
  31395. }));
  31396. prevX = x + width;
  31397. prevY = y + height;
  31398. }
  31399. }
  31400. });
  31401. CartesianAxisView.extend({
  31402. type: 'xAxis'
  31403. });
  31404. CartesianAxisView.extend({
  31405. type: 'yAxis'
  31406. });
  31407. // Grid view
  31408. extendComponentView({
  31409. type: 'grid',
  31410. render: function (gridModel, ecModel) {
  31411. this.group.removeAll();
  31412. if (gridModel.get('show')) {
  31413. this.group.add(new Rect({
  31414. shape: gridModel.coordinateSystem.getRect(),
  31415. style: defaults({
  31416. fill: gridModel.get('backgroundColor')
  31417. }, gridModel.getItemStyle()),
  31418. silent: true,
  31419. z2: -1
  31420. }));
  31421. }
  31422. }
  31423. });
  31424. registerPreprocessor(function (option) {
  31425. // Only create grid when need
  31426. if (option.xAxis && option.yAxis && !option.grid) {
  31427. option.grid = {};
  31428. }
  31429. });
  31430. // In case developer forget to include grid component
  31431. registerVisual(visualSymbol('line', 'circle', 'line'));
  31432. registerLayout(pointsLayout('line'));
  31433. // Down sample after filter
  31434. registerProcessor(
  31435. PRIORITY.PROCESSOR.STATISTIC,
  31436. dataSample('line')
  31437. );
  31438. var BaseBarSeries = SeriesModel.extend({
  31439. type: 'series.__base_bar__',
  31440. getInitialData: function (option, ecModel) {
  31441. return createListFromArray(this.getSource(), this);
  31442. },
  31443. getMarkerPosition: function (value) {
  31444. var coordSys = this.coordinateSystem;
  31445. if (coordSys) {
  31446. // PENDING if clamp ?
  31447. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  31448. var data = this.getData();
  31449. var offset = data.getLayout('offset');
  31450. var size = data.getLayout('size');
  31451. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  31452. pt[offsetIndex] += offset + size / 2;
  31453. return pt;
  31454. }
  31455. return [NaN, NaN];
  31456. },
  31457. defaultOption: {
  31458. zlevel: 0, // 一级层叠
  31459. z: 2, // 二级层叠
  31460. coordinateSystem: 'cartesian2d',
  31461. legendHoverLink: true,
  31462. // stack: null
  31463. // Cartesian coordinate system
  31464. // xAxisIndex: 0,
  31465. // yAxisIndex: 0,
  31466. // 最小高度改为0
  31467. barMinHeight: 0,
  31468. // 最小角度为0,仅对极坐标系下的柱状图有效
  31469. barMinAngle: 0,
  31470. // cursor: null,
  31471. // barMaxWidth: null,
  31472. // 默认自适应
  31473. // barWidth: null,
  31474. // 柱间距离,默认为柱形宽度的30%,可设固定值
  31475. // barGap: '30%',
  31476. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  31477. // barCategoryGap: '20%',
  31478. // label: {
  31479. // show: false
  31480. // },
  31481. itemStyle: {},
  31482. emphasis: {}
  31483. }
  31484. });
  31485. BaseBarSeries.extend({
  31486. type: 'series.bar',
  31487. dependencies: ['grid', 'polar'],
  31488. brushSelector: 'rect'
  31489. });
  31490. function setLabel(
  31491. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  31492. ) {
  31493. var labelModel = itemModel.getModel('label');
  31494. var hoverLabelModel = itemModel.getModel('emphasis.label');
  31495. setLabelStyle(
  31496. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  31497. {
  31498. labelFetcher: seriesModel,
  31499. labelDataIndex: dataIndex,
  31500. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  31501. isRectText: true,
  31502. autoColor: color
  31503. }
  31504. );
  31505. fixPosition(normalStyle);
  31506. fixPosition(hoverStyle);
  31507. }
  31508. function fixPosition(style, labelPositionOutside) {
  31509. if (style.textPosition === 'outside') {
  31510. style.textPosition = labelPositionOutside;
  31511. }
  31512. }
  31513. var getBarItemStyle = makeStyleMapper(
  31514. [
  31515. ['fill', 'color'],
  31516. ['stroke', 'borderColor'],
  31517. ['lineWidth', 'borderWidth'],
  31518. // Compatitable with 2
  31519. ['stroke', 'barBorderColor'],
  31520. ['lineWidth', 'barBorderWidth'],
  31521. ['opacity'],
  31522. ['shadowBlur'],
  31523. ['shadowOffsetX'],
  31524. ['shadowOffsetY'],
  31525. ['shadowColor']
  31526. ]
  31527. );
  31528. var barItemStyle = {
  31529. getBarItemStyle: function (excludes) {
  31530. var style = getBarItemStyle(this, excludes);
  31531. if (this.getBorderLineDash) {
  31532. var lineDash = this.getBorderLineDash();
  31533. lineDash && (style.lineDash = lineDash);
  31534. }
  31535. return style;
  31536. }
  31537. };
  31538. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  31539. // FIXME
  31540. // Just for compatible with ec2.
  31541. extend(Model.prototype, barItemStyle);
  31542. extendChartView({
  31543. type: 'bar',
  31544. render: function (seriesModel, ecModel, api) {
  31545. var coordinateSystemType = seriesModel.get('coordinateSystem');
  31546. if (coordinateSystemType === 'cartesian2d'
  31547. || coordinateSystemType === 'polar'
  31548. ) {
  31549. this._render(seriesModel, ecModel, api);
  31550. }
  31551. else if (__DEV__) {
  31552. console.warn('Only cartesian2d and polar supported for bar.');
  31553. }
  31554. return this.group;
  31555. },
  31556. dispose: noop,
  31557. _render: function (seriesModel, ecModel, api) {
  31558. var group = this.group;
  31559. var data = seriesModel.getData();
  31560. var oldData = this._data;
  31561. var coord = seriesModel.coordinateSystem;
  31562. var baseAxis = coord.getBaseAxis();
  31563. var isHorizontalOrRadial;
  31564. if (coord.type === 'cartesian2d') {
  31565. isHorizontalOrRadial = baseAxis.isHorizontal();
  31566. }
  31567. else if (coord.type === 'polar') {
  31568. isHorizontalOrRadial = baseAxis.dim === 'angle';
  31569. }
  31570. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  31571. data.diff(oldData)
  31572. .add(function (dataIndex) {
  31573. if (!data.hasValue(dataIndex)) {
  31574. return;
  31575. }
  31576. var itemModel = data.getItemModel(dataIndex);
  31577. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  31578. var el = elementCreator[coord.type](
  31579. data, dataIndex, itemModel, layout, isHorizontalOrRadial, animationModel
  31580. );
  31581. data.setItemGraphicEl(dataIndex, el);
  31582. group.add(el);
  31583. updateStyle(
  31584. el, data, dataIndex, itemModel, layout,
  31585. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  31586. );
  31587. })
  31588. .update(function (newIndex, oldIndex) {
  31589. var el = oldData.getItemGraphicEl(oldIndex);
  31590. if (!data.hasValue(newIndex)) {
  31591. group.remove(el);
  31592. return;
  31593. }
  31594. var itemModel = data.getItemModel(newIndex);
  31595. var layout = getLayout[coord.type](data, newIndex, itemModel);
  31596. if (el) {
  31597. updateProps(el, {shape: layout}, animationModel, newIndex);
  31598. }
  31599. else {
  31600. el = elementCreator[coord.type](
  31601. data, newIndex, itemModel, layout, isHorizontalOrRadial, animationModel, true
  31602. );
  31603. }
  31604. data.setItemGraphicEl(newIndex, el);
  31605. // Add back
  31606. group.add(el);
  31607. updateStyle(
  31608. el, data, newIndex, itemModel, layout,
  31609. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  31610. );
  31611. })
  31612. .remove(function (dataIndex) {
  31613. var el = oldData.getItemGraphicEl(dataIndex);
  31614. if (coord.type === 'cartesian2d') {
  31615. el && removeRect(dataIndex, animationModel, el);
  31616. }
  31617. else {
  31618. el && removeSector(dataIndex, animationModel, el);
  31619. }
  31620. })
  31621. .execute();
  31622. this._data = data;
  31623. },
  31624. remove: function (ecModel, api) {
  31625. var group = this.group;
  31626. var data = this._data;
  31627. if (ecModel.get('animation')) {
  31628. if (data) {
  31629. data.eachItemGraphicEl(function (el) {
  31630. if (el.type === 'sector') {
  31631. removeSector(el.dataIndex, ecModel, el);
  31632. }
  31633. else {
  31634. removeRect(el.dataIndex, ecModel, el);
  31635. }
  31636. });
  31637. }
  31638. }
  31639. else {
  31640. group.removeAll();
  31641. }
  31642. }
  31643. });
  31644. var elementCreator = {
  31645. cartesian2d: function (
  31646. data, dataIndex, itemModel, layout, isHorizontal,
  31647. animationModel, isUpdate
  31648. ) {
  31649. var rect = new Rect({shape: extend({}, layout)});
  31650. // Animation
  31651. if (animationModel) {
  31652. var rectShape = rect.shape;
  31653. var animateProperty = isHorizontal ? 'height' : 'width';
  31654. var animateTarget = {};
  31655. rectShape[animateProperty] = 0;
  31656. animateTarget[animateProperty] = layout[animateProperty];
  31657. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  31658. shape: animateTarget
  31659. }, animationModel, dataIndex);
  31660. }
  31661. return rect;
  31662. },
  31663. polar: function (
  31664. data, dataIndex, itemModel, layout, isRadial,
  31665. animationModel, isUpdate
  31666. ) {
  31667. // Keep the same logic with bar in catesion: use end value to control
  31668. // direction. Notice that if clockwise is true (by default), the sector
  31669. // will always draw clockwisely, no matter whether endAngle is greater
  31670. // or less than startAngle.
  31671. var clockwise = layout.startAngle < layout.endAngle;
  31672. var sector = new Sector({
  31673. shape: defaults({clockwise: clockwise}, layout)
  31674. });
  31675. // Animation
  31676. if (animationModel) {
  31677. var sectorShape = sector.shape;
  31678. var animateProperty = isRadial ? 'r' : 'endAngle';
  31679. var animateTarget = {};
  31680. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  31681. animateTarget[animateProperty] = layout[animateProperty];
  31682. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  31683. shape: animateTarget
  31684. }, animationModel, dataIndex);
  31685. }
  31686. return sector;
  31687. }
  31688. };
  31689. function removeRect(dataIndex, animationModel, el) {
  31690. // Not show text when animating
  31691. el.style.text = null;
  31692. updateProps(el, {
  31693. shape: {
  31694. width: 0
  31695. }
  31696. }, animationModel, dataIndex, function () {
  31697. el.parent && el.parent.remove(el);
  31698. });
  31699. }
  31700. function removeSector(dataIndex, animationModel, el) {
  31701. // Not show text when animating
  31702. el.style.text = null;
  31703. updateProps(el, {
  31704. shape: {
  31705. r: el.shape.r0
  31706. }
  31707. }, animationModel, dataIndex, function () {
  31708. el.parent && el.parent.remove(el);
  31709. });
  31710. }
  31711. var getLayout = {
  31712. cartesian2d: function (data, dataIndex, itemModel) {
  31713. var layout = data.getItemLayout(dataIndex);
  31714. var fixedLineWidth = getLineWidth(itemModel, layout);
  31715. // fix layout with lineWidth
  31716. var signX = layout.width > 0 ? 1 : -1;
  31717. var signY = layout.height > 0 ? 1 : -1;
  31718. return {
  31719. x: layout.x + signX * fixedLineWidth / 2,
  31720. y: layout.y + signY * fixedLineWidth / 2,
  31721. width: layout.width - signX * fixedLineWidth,
  31722. height: layout.height - signY * fixedLineWidth
  31723. };
  31724. },
  31725. polar: function (data, dataIndex, itemModel) {
  31726. var layout = data.getItemLayout(dataIndex);
  31727. return {
  31728. cx: layout.cx,
  31729. cy: layout.cy,
  31730. r0: layout.r0,
  31731. r: layout.r,
  31732. startAngle: layout.startAngle,
  31733. endAngle: layout.endAngle
  31734. };
  31735. }
  31736. };
  31737. function updateStyle(
  31738. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  31739. ) {
  31740. var color = data.getItemVisual(dataIndex, 'color');
  31741. var opacity = data.getItemVisual(dataIndex, 'opacity');
  31742. var itemStyleModel = itemModel.getModel('itemStyle');
  31743. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  31744. if (!isPolar) {
  31745. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  31746. }
  31747. el.useStyle(defaults(
  31748. {
  31749. fill: color,
  31750. opacity: opacity
  31751. },
  31752. itemStyleModel.getBarItemStyle()
  31753. ));
  31754. var cursorStyle = itemModel.getShallow('cursor');
  31755. cursorStyle && el.attr('cursor', cursorStyle);
  31756. var labelPositionOutside = isHorizontal
  31757. ? (layout.height > 0 ? 'bottom' : 'top')
  31758. : (layout.width > 0 ? 'left' : 'right');
  31759. if (!isPolar) {
  31760. setLabel(
  31761. el.style, hoverStyle, itemModel, color,
  31762. seriesModel, dataIndex, labelPositionOutside
  31763. );
  31764. }
  31765. setHoverStyle(el, hoverStyle);
  31766. }
  31767. // In case width or height are too small.
  31768. function getLineWidth(itemModel, rawLayout) {
  31769. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  31770. return Math.min(lineWidth, Math.abs(rawLayout.width), Math.abs(rawLayout.height));
  31771. }
  31772. // In case developer forget to include grid component
  31773. registerLayout(curry(layout, 'bar'));
  31774. // Visual coding for legend
  31775. registerVisual(function (ecModel) {
  31776. ecModel.eachSeriesByType('bar', function (seriesModel) {
  31777. var data = seriesModel.getData();
  31778. data.setVisual('legendSymbol', 'roundRect');
  31779. });
  31780. });
  31781. /**
  31782. * [Usage]:
  31783. * (1)
  31784. * createListSimply(seriesModel, ['value']);
  31785. * (2)
  31786. * createListSimply(seriesModel, {
  31787. * coordDimensions: ['value'],
  31788. * dimensionsCount: 5
  31789. * });
  31790. *
  31791. * @param {module:echarts/model/Series} seriesModel
  31792. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  31793. * The options in opt, see `echarts/data/helper/createDimensions`
  31794. * @param {Array.<string>} [nameList]
  31795. * @return {module:echarts/data/List}
  31796. */
  31797. var createListSimply = function (seriesModel, opt, nameList) {
  31798. opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt);
  31799. var source = seriesModel.getSource();
  31800. var dimensionsInfo = createDimensions(source, opt);
  31801. var list = new List(dimensionsInfo, seriesModel);
  31802. list.initData(source, nameList);
  31803. return list;
  31804. };
  31805. /**
  31806. * Data selectable mixin for chart series.
  31807. * To eanble data select, option of series must have `selectedMode`.
  31808. * And each data item will use `selected` to toggle itself selected status
  31809. */
  31810. var dataSelectableMixin = {
  31811. /**
  31812. * @param {Array.<Object>} targetList [{name, value, selected}, ...]
  31813. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  31814. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  31815. */
  31816. updateSelectedMap: function (targetList) {
  31817. this._targetList = isArray(targetList) ? targetList.slice() : [];
  31818. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  31819. targetMap.set(target.name, target);
  31820. return targetMap;
  31821. }, createHashMap());
  31822. },
  31823. /**
  31824. * Either name or id should be passed as input here.
  31825. * If both of them are defined, id is used.
  31826. *
  31827. * @param {string|undefined} name name of data
  31828. * @param {number|undefined} id dataIndex of data
  31829. */
  31830. // PENGING If selectedMode is null ?
  31831. select: function (name, id) {
  31832. var target = id != null
  31833. ? this._targetList[id]
  31834. : this._selectTargetMap.get(name);
  31835. var selectedMode = this.get('selectedMode');
  31836. if (selectedMode === 'single') {
  31837. this._selectTargetMap.each(function (target) {
  31838. target.selected = false;
  31839. });
  31840. }
  31841. target && (target.selected = true);
  31842. },
  31843. /**
  31844. * Either name or id should be passed as input here.
  31845. * If both of them are defined, id is used.
  31846. *
  31847. * @param {string|undefined} name name of data
  31848. * @param {number|undefined} id dataIndex of data
  31849. */
  31850. unSelect: function (name, id) {
  31851. var target = id != null
  31852. ? this._targetList[id]
  31853. : this._selectTargetMap.get(name);
  31854. // var selectedMode = this.get('selectedMode');
  31855. // selectedMode !== 'single' && target && (target.selected = false);
  31856. target && (target.selected = false);
  31857. },
  31858. /**
  31859. * Either name or id should be passed as input here.
  31860. * If both of them are defined, id is used.
  31861. *
  31862. * @param {string|undefined} name name of data
  31863. * @param {number|undefined} id dataIndex of data
  31864. */
  31865. toggleSelected: function (name, id) {
  31866. var target = id != null
  31867. ? this._targetList[id]
  31868. : this._selectTargetMap.get(name);
  31869. if (target != null) {
  31870. this[target.selected ? 'unSelect' : 'select'](name, id);
  31871. return target.selected;
  31872. }
  31873. },
  31874. /**
  31875. * Either name or id should be passed as input here.
  31876. * If both of them are defined, id is used.
  31877. *
  31878. * @param {string|undefined} name name of data
  31879. * @param {number|undefined} id dataIndex of data
  31880. */
  31881. isSelected: function (name, id) {
  31882. var target = id != null
  31883. ? this._targetList[id]
  31884. : this._selectTargetMap.get(name);
  31885. return target && target.selected;
  31886. }
  31887. };
  31888. var PieSeries = extendSeriesModel({
  31889. type: 'series.pie',
  31890. // Overwrite
  31891. init: function (option) {
  31892. PieSeries.superApply(this, 'init', arguments);
  31893. // Enable legend selection for each data item
  31894. // Use a function instead of direct access because data reference may changed
  31895. this.legendDataProvider = function () {
  31896. return this.getRawData();
  31897. };
  31898. this.updateSelectedMap(this._createSelectableList());
  31899. this._defaultLabelLine(option);
  31900. },
  31901. // Overwrite
  31902. mergeOption: function (newOption) {
  31903. PieSeries.superCall(this, 'mergeOption', newOption);
  31904. this.updateSelectedMap(this._createSelectableList());
  31905. },
  31906. getInitialData: function (option, ecModel) {
  31907. return createListSimply(this, ['value']);
  31908. },
  31909. _createSelectableList: function () {
  31910. var data = this.getRawData();
  31911. var valueDim = data.mapDimension('value');
  31912. var targetList = [];
  31913. for (var i = 0, len = data.count(); i < len; i++) {
  31914. targetList.push({
  31915. name: data.getName(i),
  31916. value: data.get(valueDim, i),
  31917. selected: retrieveRawAttr(data, i, 'selected')
  31918. });
  31919. }
  31920. return targetList;
  31921. },
  31922. // Overwrite
  31923. getDataParams: function (dataIndex) {
  31924. var data = this.getData();
  31925. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  31926. // FIXME toFixed?
  31927. var valueList = [];
  31928. data.each(data.mapDimension('value'), function (value) {
  31929. valueList.push(value);
  31930. });
  31931. params.percent = getPercentWithPrecision(
  31932. valueList,
  31933. dataIndex,
  31934. data.hostModel.get('percentPrecision')
  31935. );
  31936. params.$vars.push('percent');
  31937. return params;
  31938. },
  31939. _defaultLabelLine: function (option) {
  31940. // Extend labelLine emphasis
  31941. defaultEmphasis(option, 'labelLine', ['show']);
  31942. var labelLineNormalOpt = option.labelLine;
  31943. var labelLineEmphasisOpt = option.emphasis.labelLine;
  31944. // Not show label line if `label.normal.show = false`
  31945. labelLineNormalOpt.show = labelLineNormalOpt.show
  31946. && option.label.show;
  31947. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  31948. && option.emphasis.label.show;
  31949. },
  31950. defaultOption: {
  31951. zlevel: 0,
  31952. z: 2,
  31953. legendHoverLink: true,
  31954. hoverAnimation: true,
  31955. // 默认全局居中
  31956. center: ['50%', '50%'],
  31957. radius: [0, '75%'],
  31958. // 默认顺时针
  31959. clockwise: true,
  31960. startAngle: 90,
  31961. // 最小角度改为0
  31962. minAngle: 0,
  31963. // 选中时扇区偏移量
  31964. selectedOffset: 10,
  31965. // 高亮扇区偏移量
  31966. hoverOffset: 10,
  31967. // If use strategy to avoid label overlapping
  31968. avoidLabelOverlap: true,
  31969. // 选择模式,默认关闭,可选single,multiple
  31970. // selectedMode: false,
  31971. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  31972. // roseType: null,
  31973. percentPrecision: 2,
  31974. // If still show when all data zero.
  31975. stillShowZeroSum: true,
  31976. // cursor: null,
  31977. label: {
  31978. // If rotate around circle
  31979. rotate: false,
  31980. show: true,
  31981. // 'outer', 'inside', 'center'
  31982. position: 'outer'
  31983. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  31984. // 默认使用全局文本样式,详见TEXTSTYLE
  31985. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  31986. },
  31987. // Enabled when label.normal.position is 'outer'
  31988. labelLine: {
  31989. show: true,
  31990. // 引导线两段中的第一段长度
  31991. length: 15,
  31992. // 引导线两段中的第二段长度
  31993. length2: 15,
  31994. smooth: false,
  31995. lineStyle: {
  31996. // color: 各异,
  31997. width: 1,
  31998. type: 'solid'
  31999. }
  32000. },
  32001. itemStyle: {
  32002. borderWidth: 1
  32003. },
  32004. // Animation type canbe expansion, scale
  32005. animationType: 'expansion',
  32006. animationEasing: 'cubicOut'
  32007. }
  32008. });
  32009. mixin(PieSeries, dataSelectableMixin);
  32010. /**
  32011. * @param {module:echarts/model/Series} seriesModel
  32012. * @param {boolean} hasAnimation
  32013. * @inner
  32014. */
  32015. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  32016. var data = seriesModel.getData();
  32017. var dataIndex = this.dataIndex;
  32018. var name = data.getName(dataIndex);
  32019. var selectedOffset = seriesModel.get('selectedOffset');
  32020. api.dispatchAction({
  32021. type: 'pieToggleSelect',
  32022. from: uid,
  32023. name: name,
  32024. seriesId: seriesModel.id
  32025. });
  32026. data.each(function (idx) {
  32027. toggleItemSelected(
  32028. data.getItemGraphicEl(idx),
  32029. data.getItemLayout(idx),
  32030. seriesModel.isSelected(data.getName(idx)),
  32031. selectedOffset,
  32032. hasAnimation
  32033. );
  32034. });
  32035. }
  32036. /**
  32037. * @param {module:zrender/graphic/Sector} el
  32038. * @param {Object} layout
  32039. * @param {boolean} isSelected
  32040. * @param {number} selectedOffset
  32041. * @param {boolean} hasAnimation
  32042. * @inner
  32043. */
  32044. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  32045. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  32046. var dx = Math.cos(midAngle);
  32047. var dy = Math.sin(midAngle);
  32048. var offset = isSelected ? selectedOffset : 0;
  32049. var position = [dx * offset, dy * offset];
  32050. hasAnimation
  32051. // animateTo will stop revious animation like update transition
  32052. ? el.animate()
  32053. .when(200, {
  32054. position: position
  32055. })
  32056. .start('bounceOut')
  32057. : el.attr('position', position);
  32058. }
  32059. /**
  32060. * Piece of pie including Sector, Label, LabelLine
  32061. * @constructor
  32062. * @extends {module:zrender/graphic/Group}
  32063. */
  32064. function PiePiece(data, idx) {
  32065. Group.call(this);
  32066. var sector = new Sector({
  32067. z2: 2
  32068. });
  32069. var polyline = new Polyline();
  32070. var text = new Text();
  32071. this.add(sector);
  32072. this.add(polyline);
  32073. this.add(text);
  32074. this.updateData(data, idx, true);
  32075. // Hover to change label and labelLine
  32076. function onEmphasis() {
  32077. polyline.ignore = polyline.hoverIgnore;
  32078. text.ignore = text.hoverIgnore;
  32079. }
  32080. function onNormal() {
  32081. polyline.ignore = polyline.normalIgnore;
  32082. text.ignore = text.normalIgnore;
  32083. }
  32084. this.on('emphasis', onEmphasis)
  32085. .on('normal', onNormal)
  32086. .on('mouseover', onEmphasis)
  32087. .on('mouseout', onNormal);
  32088. }
  32089. var piePieceProto = PiePiece.prototype;
  32090. piePieceProto.updateData = function (data, idx, firstCreate) {
  32091. var sector = this.childAt(0);
  32092. var seriesModel = data.hostModel;
  32093. var itemModel = data.getItemModel(idx);
  32094. var layout = data.getItemLayout(idx);
  32095. var sectorShape = extend({}, layout);
  32096. sectorShape.label = null;
  32097. if (firstCreate) {
  32098. sector.setShape(sectorShape);
  32099. var animationType = seriesModel.getShallow('animationType');
  32100. if (animationType === 'scale') {
  32101. sector.shape.r = layout.r0;
  32102. initProps(sector, {
  32103. shape: {
  32104. r: layout.r
  32105. }
  32106. }, seriesModel, idx);
  32107. }
  32108. // Expansion
  32109. else {
  32110. sector.shape.endAngle = layout.startAngle;
  32111. updateProps(sector, {
  32112. shape: {
  32113. endAngle: layout.endAngle
  32114. }
  32115. }, seriesModel, idx);
  32116. }
  32117. }
  32118. else {
  32119. updateProps(sector, {
  32120. shape: sectorShape
  32121. }, seriesModel, idx);
  32122. }
  32123. // Update common style
  32124. var visualColor = data.getItemVisual(idx, 'color');
  32125. sector.useStyle(
  32126. defaults(
  32127. {
  32128. lineJoin: 'bevel',
  32129. fill: visualColor
  32130. },
  32131. itemModel.getModel('itemStyle').getItemStyle()
  32132. )
  32133. );
  32134. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  32135. var cursorStyle = itemModel.getShallow('cursor');
  32136. cursorStyle && sector.attr('cursor', cursorStyle);
  32137. // Toggle selected
  32138. toggleItemSelected(
  32139. this,
  32140. data.getItemLayout(idx),
  32141. seriesModel.isSelected(null, idx),
  32142. seriesModel.get('selectedOffset'),
  32143. seriesModel.get('animation')
  32144. );
  32145. function onEmphasis() {
  32146. // Sector may has animation of updating data. Force to move to the last frame
  32147. // Or it may stopped on the wrong shape
  32148. sector.stopAnimation(true);
  32149. sector.animateTo({
  32150. shape: {
  32151. r: layout.r + seriesModel.get('hoverOffset')
  32152. }
  32153. }, 300, 'elasticOut');
  32154. }
  32155. function onNormal() {
  32156. sector.stopAnimation(true);
  32157. sector.animateTo({
  32158. shape: {
  32159. r: layout.r
  32160. }
  32161. }, 300, 'elasticOut');
  32162. }
  32163. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  32164. if (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled()) {
  32165. sector
  32166. .on('mouseover', onEmphasis)
  32167. .on('mouseout', onNormal)
  32168. .on('emphasis', onEmphasis)
  32169. .on('normal', onNormal);
  32170. }
  32171. this._updateLabel(data, idx);
  32172. setHoverStyle(this);
  32173. };
  32174. piePieceProto._updateLabel = function (data, idx) {
  32175. var labelLine = this.childAt(1);
  32176. var labelText = this.childAt(2);
  32177. var seriesModel = data.hostModel;
  32178. var itemModel = data.getItemModel(idx);
  32179. var layout = data.getItemLayout(idx);
  32180. var labelLayout = layout.label;
  32181. var visualColor = data.getItemVisual(idx, 'color');
  32182. updateProps(labelLine, {
  32183. shape: {
  32184. points: labelLayout.linePoints || [
  32185. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  32186. ]
  32187. }
  32188. }, seriesModel, idx);
  32189. updateProps(labelText, {
  32190. style: {
  32191. x: labelLayout.x,
  32192. y: labelLayout.y
  32193. }
  32194. }, seriesModel, idx);
  32195. labelText.attr({
  32196. rotation: labelLayout.rotation,
  32197. origin: [labelLayout.x, labelLayout.y],
  32198. z2: 10
  32199. });
  32200. var labelModel = itemModel.getModel('label');
  32201. var labelHoverModel = itemModel.getModel('emphasis.label');
  32202. var labelLineModel = itemModel.getModel('labelLine');
  32203. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  32204. var visualColor = data.getItemVisual(idx, 'color');
  32205. setLabelStyle(
  32206. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  32207. {
  32208. labelFetcher: data.hostModel,
  32209. labelDataIndex: idx,
  32210. defaultText: data.getName(idx),
  32211. autoColor: visualColor,
  32212. useInsideStyle: !!labelLayout.inside
  32213. },
  32214. {
  32215. textAlign: labelLayout.textAlign,
  32216. textVerticalAlign: labelLayout.verticalAlign,
  32217. opacity: data.getItemVisual(idx, 'opacity')
  32218. }
  32219. );
  32220. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  32221. labelText.hoverIgnore = !labelHoverModel.get('show');
  32222. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  32223. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  32224. // Default use item visual color
  32225. labelLine.setStyle({
  32226. stroke: visualColor,
  32227. opacity: data.getItemVisual(idx, 'opacity')
  32228. });
  32229. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  32230. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  32231. var smooth = labelLineModel.get('smooth');
  32232. if (smooth && smooth === true) {
  32233. smooth = 0.4;
  32234. }
  32235. labelLine.setShape({
  32236. smooth: smooth
  32237. });
  32238. };
  32239. inherits(PiePiece, Group);
  32240. // Pie view
  32241. var PieView = Chart.extend({
  32242. type: 'pie',
  32243. init: function () {
  32244. var sectorGroup = new Group();
  32245. this._sectorGroup = sectorGroup;
  32246. },
  32247. render: function (seriesModel, ecModel, api, payload) {
  32248. if (payload && (payload.from === this.uid)) {
  32249. return;
  32250. }
  32251. var data = seriesModel.getData();
  32252. var oldData = this._data;
  32253. var group = this.group;
  32254. var hasAnimation = ecModel.get('animation');
  32255. var isFirstRender = !oldData;
  32256. var animationType = seriesModel.get('animationType');
  32257. var onSectorClick = curry(
  32258. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  32259. );
  32260. var selectedMode = seriesModel.get('selectedMode');
  32261. data.diff(oldData)
  32262. .add(function (idx) {
  32263. var piePiece = new PiePiece(data, idx);
  32264. // Default expansion animation
  32265. if (isFirstRender && animationType !== 'scale') {
  32266. piePiece.eachChild(function (child) {
  32267. child.stopAnimation(true);
  32268. });
  32269. }
  32270. selectedMode && piePiece.on('click', onSectorClick);
  32271. data.setItemGraphicEl(idx, piePiece);
  32272. group.add(piePiece);
  32273. })
  32274. .update(function (newIdx, oldIdx) {
  32275. var piePiece = oldData.getItemGraphicEl(oldIdx);
  32276. piePiece.updateData(data, newIdx);
  32277. piePiece.off('click');
  32278. selectedMode && piePiece.on('click', onSectorClick);
  32279. group.add(piePiece);
  32280. data.setItemGraphicEl(newIdx, piePiece);
  32281. })
  32282. .remove(function (idx) {
  32283. var piePiece = oldData.getItemGraphicEl(idx);
  32284. group.remove(piePiece);
  32285. })
  32286. .execute();
  32287. if (
  32288. hasAnimation && isFirstRender && data.count() > 0
  32289. // Default expansion animation
  32290. && animationType !== 'scale'
  32291. ) {
  32292. var shape = data.getItemLayout(0);
  32293. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  32294. var removeClipPath = bind(group.removeClipPath, group);
  32295. group.setClipPath(this._createClipPath(
  32296. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel
  32297. ));
  32298. }
  32299. this._data = data;
  32300. },
  32301. dispose: function () {},
  32302. _createClipPath: function (
  32303. cx, cy, r, startAngle, clockwise, cb, seriesModel
  32304. ) {
  32305. var clipPath = new Sector({
  32306. shape: {
  32307. cx: cx,
  32308. cy: cy,
  32309. r0: 0,
  32310. r: r,
  32311. startAngle: startAngle,
  32312. endAngle: startAngle,
  32313. clockwise: clockwise
  32314. }
  32315. });
  32316. initProps(clipPath, {
  32317. shape: {
  32318. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  32319. }
  32320. }, seriesModel, cb);
  32321. return clipPath;
  32322. },
  32323. /**
  32324. * @implement
  32325. */
  32326. containPoint: function (point, seriesModel) {
  32327. var data = seriesModel.getData();
  32328. var itemLayout = data.getItemLayout(0);
  32329. if (itemLayout) {
  32330. var dx = point[0] - itemLayout.cx;
  32331. var dy = point[1] - itemLayout.cy;
  32332. var radius = Math.sqrt(dx * dx + dy * dy);
  32333. return radius <= itemLayout.r && radius >= itemLayout.r0;
  32334. }
  32335. }
  32336. });
  32337. var createDataSelectAction = function (seriesType, actionInfos) {
  32338. each$1(actionInfos, function (actionInfo) {
  32339. actionInfo.update = 'updateView';
  32340. /**
  32341. * @payload
  32342. * @property {string} seriesName
  32343. * @property {string} name
  32344. */
  32345. registerAction(actionInfo, function (payload, ecModel) {
  32346. var selected = {};
  32347. ecModel.eachComponent(
  32348. {mainType: 'series', subType: seriesType, query: payload},
  32349. function (seriesModel) {
  32350. if (seriesModel[actionInfo.method]) {
  32351. seriesModel[actionInfo.method](
  32352. payload.name,
  32353. payload.dataIndex
  32354. );
  32355. }
  32356. var data = seriesModel.getData();
  32357. // Create selected map
  32358. data.each(function (idx) {
  32359. var name = data.getName(idx);
  32360. selected[name] = seriesModel.isSelected(name)
  32361. || false;
  32362. });
  32363. }
  32364. );
  32365. return {
  32366. name: payload.name,
  32367. selected: selected
  32368. };
  32369. });
  32370. });
  32371. };
  32372. // Pick color from palette for each data item.
  32373. // Applicable for charts that require applying color palette
  32374. // in data level (like pie, funnel, chord).
  32375. var dataColor = function (seriesType) {
  32376. return {
  32377. getTargetSeries: function (ecModel) {
  32378. // Pie and funnel may use diferrent scope
  32379. var paletteScope = {};
  32380. var seiresModelMap = createHashMap();
  32381. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  32382. seriesModel.__paletteScope = paletteScope;
  32383. seiresModelMap.set(seriesModel.uid, seriesModel);
  32384. });
  32385. return seiresModelMap;
  32386. },
  32387. reset: function (seriesModel, ecModel) {
  32388. var dataAll = seriesModel.getRawData();
  32389. var idxMap = {};
  32390. var data = seriesModel.getData();
  32391. data.each(function (idx) {
  32392. var rawIdx = data.getRawIndex(idx);
  32393. idxMap[rawIdx] = idx;
  32394. });
  32395. dataAll.each(function (rawIdx) {
  32396. var filteredIdx = idxMap[rawIdx];
  32397. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  32398. var singleDataColor = filteredIdx != null
  32399. && data.getItemVisual(filteredIdx, 'color', true);
  32400. if (!singleDataColor) {
  32401. // FIXME Performance
  32402. var itemModel = dataAll.getItemModel(rawIdx);
  32403. var color = itemModel.get('itemStyle.color')
  32404. || seriesModel.getColorFromPalette(
  32405. dataAll.getName(rawIdx) || (rawIdx + ''), seriesModel.__paletteScope,
  32406. dataAll.count()
  32407. );
  32408. // Legend may use the visual info in data before processed
  32409. dataAll.setItemVisual(rawIdx, 'color', color);
  32410. // Data is not filtered
  32411. if (filteredIdx != null) {
  32412. data.setItemVisual(filteredIdx, 'color', color);
  32413. }
  32414. }
  32415. else {
  32416. // Set data all color for legend
  32417. dataAll.setItemVisual(rawIdx, 'color', singleDataColor);
  32418. }
  32419. });
  32420. }
  32421. };
  32422. };
  32423. // FIXME emphasis label position is not same with normal label position
  32424. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight) {
  32425. list.sort(function (a, b) {
  32426. return a.y - b.y;
  32427. });
  32428. // 压
  32429. function shiftDown(start, end, delta, dir) {
  32430. for (var j = start; j < end; j++) {
  32431. list[j].y += delta;
  32432. if (j > start
  32433. && j + 1 < end
  32434. && list[j + 1].y > list[j].y + list[j].height
  32435. ) {
  32436. shiftUp(j, delta / 2);
  32437. return;
  32438. }
  32439. }
  32440. shiftUp(end - 1, delta / 2);
  32441. }
  32442. // 弹
  32443. function shiftUp(end, delta) {
  32444. for (var j = end; j >= 0; j--) {
  32445. list[j].y -= delta;
  32446. if (j > 0
  32447. && list[j].y > list[j - 1].y + list[j - 1].height
  32448. ) {
  32449. break;
  32450. }
  32451. }
  32452. }
  32453. function changeX(list, isDownList, cx, cy, r, dir) {
  32454. var lastDeltaX = dir > 0
  32455. ? isDownList // 右侧
  32456. ? Number.MAX_VALUE // 下
  32457. : 0 // 上
  32458. : isDownList // 左侧
  32459. ? Number.MAX_VALUE // 下
  32460. : 0; // 上
  32461. for (var i = 0, l = list.length; i < l; i++) {
  32462. // Not change x for center label
  32463. if (list[i].position === 'center') {
  32464. continue;
  32465. }
  32466. var deltaY = Math.abs(list[i].y - cy);
  32467. var length = list[i].len;
  32468. var length2 = list[i].len2;
  32469. var deltaX = (deltaY < r + length)
  32470. ? Math.sqrt(
  32471. (r + length + length2) * (r + length + length2)
  32472. - deltaY * deltaY
  32473. )
  32474. : Math.abs(list[i].x - cx);
  32475. if (isDownList && deltaX >= lastDeltaX) {
  32476. // 右下,左下
  32477. deltaX = lastDeltaX - 10;
  32478. }
  32479. if (!isDownList && deltaX <= lastDeltaX) {
  32480. // 右上,左上
  32481. deltaX = lastDeltaX + 10;
  32482. }
  32483. list[i].x = cx + deltaX * dir;
  32484. lastDeltaX = deltaX;
  32485. }
  32486. }
  32487. var lastY = 0;
  32488. var delta;
  32489. var len = list.length;
  32490. var upList = [];
  32491. var downList = [];
  32492. for (var i = 0; i < len; i++) {
  32493. delta = list[i].y - lastY;
  32494. if (delta < 0) {
  32495. shiftDown(i, len, -delta, dir);
  32496. }
  32497. lastY = list[i].y + list[i].height;
  32498. }
  32499. if (viewHeight - lastY < 0) {
  32500. shiftUp(len - 1, lastY - viewHeight);
  32501. }
  32502. for (var i = 0; i < len; i++) {
  32503. if (list[i].y >= cy) {
  32504. downList.push(list[i]);
  32505. }
  32506. else {
  32507. upList.push(list[i]);
  32508. }
  32509. }
  32510. changeX(upList, false, cx, cy, r, dir);
  32511. changeX(downList, true, cx, cy, r, dir);
  32512. }
  32513. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight) {
  32514. var leftList = [];
  32515. var rightList = [];
  32516. for (var i = 0; i < labelLayoutList.length; i++) {
  32517. if (labelLayoutList[i].x < cx) {
  32518. leftList.push(labelLayoutList[i]);
  32519. }
  32520. else {
  32521. rightList.push(labelLayoutList[i]);
  32522. }
  32523. }
  32524. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight);
  32525. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight);
  32526. for (var i = 0; i < labelLayoutList.length; i++) {
  32527. var linePoints = labelLayoutList[i].linePoints;
  32528. if (linePoints) {
  32529. var dist = linePoints[1][0] - linePoints[2][0];
  32530. if (labelLayoutList[i].x < cx) {
  32531. linePoints[2][0] = labelLayoutList[i].x + 3;
  32532. }
  32533. else {
  32534. linePoints[2][0] = labelLayoutList[i].x - 3;
  32535. }
  32536. linePoints[1][1] = linePoints[2][1] = labelLayoutList[i].y;
  32537. linePoints[1][0] = linePoints[2][0] + dist;
  32538. }
  32539. }
  32540. }
  32541. var labelLayout = function (seriesModel, r, viewWidth, viewHeight) {
  32542. var data = seriesModel.getData();
  32543. var labelLayoutList = [];
  32544. var cx;
  32545. var cy;
  32546. var hasLabelRotate = false;
  32547. data.each(function (idx) {
  32548. var layout = data.getItemLayout(idx);
  32549. var itemModel = data.getItemModel(idx);
  32550. var labelModel = itemModel.getModel('label');
  32551. // Use position in normal or emphasis
  32552. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  32553. var labelLineModel = itemModel.getModel('labelLine');
  32554. var labelLineLen = labelLineModel.get('length');
  32555. var labelLineLen2 = labelLineModel.get('length2');
  32556. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  32557. var dx = Math.cos(midAngle);
  32558. var dy = Math.sin(midAngle);
  32559. var textX;
  32560. var textY;
  32561. var linePoints;
  32562. var textAlign;
  32563. cx = layout.cx;
  32564. cy = layout.cy;
  32565. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  32566. if (labelPosition === 'center') {
  32567. textX = layout.cx;
  32568. textY = layout.cy;
  32569. textAlign = 'center';
  32570. }
  32571. else {
  32572. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  32573. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  32574. textX = x1 + dx * 3;
  32575. textY = y1 + dy * 3;
  32576. if (!isLabelInside) {
  32577. // For roseType
  32578. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  32579. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  32580. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  32581. var y3 = y2;
  32582. textX = x3 + (dx < 0 ? -5 : 5);
  32583. textY = y3;
  32584. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  32585. }
  32586. textAlign = isLabelInside ? 'center' : (dx > 0 ? 'left' : 'right');
  32587. }
  32588. var font = labelModel.getFont();
  32589. var labelRotate = labelModel.get('rotate')
  32590. ? (dx < 0 ? -midAngle + Math.PI : -midAngle) : 0;
  32591. var text = seriesModel.getFormattedLabel(idx, 'normal')
  32592. || data.getName(idx);
  32593. var textRect = getBoundingRect(
  32594. text, font, textAlign, 'top'
  32595. );
  32596. hasLabelRotate = !!labelRotate;
  32597. layout.label = {
  32598. x: textX,
  32599. y: textY,
  32600. position: labelPosition,
  32601. height: textRect.height,
  32602. len: labelLineLen,
  32603. len2: labelLineLen2,
  32604. linePoints: linePoints,
  32605. textAlign: textAlign,
  32606. verticalAlign: 'middle',
  32607. rotation: labelRotate,
  32608. inside: isLabelInside
  32609. };
  32610. // Not layout the inside label
  32611. if (!isLabelInside) {
  32612. labelLayoutList.push(layout.label);
  32613. }
  32614. });
  32615. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  32616. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight);
  32617. }
  32618. };
  32619. var PI2$4 = Math.PI * 2;
  32620. var RADIAN = Math.PI / 180;
  32621. var pieLayout = function (seriesType, ecModel, api, payload) {
  32622. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  32623. var data = seriesModel.getData();
  32624. var valueDim = data.mapDimension('value');
  32625. var center = seriesModel.get('center');
  32626. var radius = seriesModel.get('radius');
  32627. if (!isArray(radius)) {
  32628. radius = [0, radius];
  32629. }
  32630. if (!isArray(center)) {
  32631. center = [center, center];
  32632. }
  32633. var width = api.getWidth();
  32634. var height = api.getHeight();
  32635. var size = Math.min(width, height);
  32636. var cx = parsePercent$1(center[0], width);
  32637. var cy = parsePercent$1(center[1], height);
  32638. var r0 = parsePercent$1(radius[0], size / 2);
  32639. var r = parsePercent$1(radius[1], size / 2);
  32640. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  32641. var minAngle = seriesModel.get('minAngle') * RADIAN;
  32642. var validDataCount = 0;
  32643. data.each(valueDim, function (value) {
  32644. !isNaN(value) && validDataCount++;
  32645. });
  32646. var sum = data.getSum(valueDim);
  32647. // Sum may be 0
  32648. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  32649. var clockwise = seriesModel.get('clockwise');
  32650. var roseType = seriesModel.get('roseType');
  32651. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  32652. // [0...max]
  32653. var extent = data.getDataExtent(valueDim);
  32654. extent[0] = 0;
  32655. // In the case some sector angle is smaller than minAngle
  32656. var restAngle = PI2$4;
  32657. var valueSumLargerThanMinAngle = 0;
  32658. var currentAngle = startAngle;
  32659. var dir = clockwise ? 1 : -1;
  32660. data.each(valueDim, function (value, idx) {
  32661. var angle;
  32662. if (isNaN(value)) {
  32663. data.setItemLayout(idx, {
  32664. angle: NaN,
  32665. startAngle: NaN,
  32666. endAngle: NaN,
  32667. clockwise: clockwise,
  32668. cx: cx,
  32669. cy: cy,
  32670. r0: r0,
  32671. r: roseType
  32672. ? NaN
  32673. : r
  32674. });
  32675. return;
  32676. }
  32677. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  32678. if (roseType !== 'area') {
  32679. angle = (sum === 0 && stillShowZeroSum)
  32680. ? unitRadian : (value * unitRadian);
  32681. }
  32682. else {
  32683. angle = PI2$4 / validDataCount;
  32684. }
  32685. if (angle < minAngle) {
  32686. angle = minAngle;
  32687. restAngle -= minAngle;
  32688. }
  32689. else {
  32690. valueSumLargerThanMinAngle += value;
  32691. }
  32692. var endAngle = currentAngle + dir * angle;
  32693. data.setItemLayout(idx, {
  32694. angle: angle,
  32695. startAngle: currentAngle,
  32696. endAngle: endAngle,
  32697. clockwise: clockwise,
  32698. cx: cx,
  32699. cy: cy,
  32700. r0: r0,
  32701. r: roseType
  32702. ? linearMap(value, extent, [r0, r])
  32703. : r
  32704. });
  32705. currentAngle = endAngle;
  32706. });
  32707. // Some sector is constrained by minAngle
  32708. // Rest sectors needs recalculate angle
  32709. if (restAngle < PI2$4 && validDataCount) {
  32710. // Average the angle if rest angle is not enough after all angles is
  32711. // Constrained by minAngle
  32712. if (restAngle <= 1e-3) {
  32713. var angle = PI2$4 / validDataCount;
  32714. data.each(valueDim, function (value, idx) {
  32715. if (!isNaN(value)) {
  32716. var layout = data.getItemLayout(idx);
  32717. layout.angle = angle;
  32718. layout.startAngle = startAngle + dir * idx * angle;
  32719. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  32720. }
  32721. });
  32722. }
  32723. else {
  32724. unitRadian = restAngle / valueSumLargerThanMinAngle;
  32725. currentAngle = startAngle;
  32726. data.each(valueDim, function (value, idx) {
  32727. if (!isNaN(value)) {
  32728. var layout = data.getItemLayout(idx);
  32729. var angle = layout.angle === minAngle
  32730. ? minAngle : value * unitRadian;
  32731. layout.startAngle = currentAngle;
  32732. layout.endAngle = currentAngle + dir * angle;
  32733. currentAngle += dir * angle;
  32734. }
  32735. });
  32736. }
  32737. }
  32738. labelLayout(seriesModel, r, width, height);
  32739. });
  32740. };
  32741. var dataFilter = function (seriesType) {
  32742. return {
  32743. seriesType: seriesType,
  32744. reset: function (seriesModel, ecModel) {
  32745. var legendModels = ecModel.findComponents({
  32746. mainType: 'legend'
  32747. });
  32748. if (!legendModels || !legendModels.length) {
  32749. return;
  32750. }
  32751. var data = seriesModel.getData();
  32752. data.filterSelf(function (idx) {
  32753. var name = data.getName(idx);
  32754. // If in any legend component the status is not selected.
  32755. for (var i = 0; i < legendModels.length; i++) {
  32756. if (!legendModels[i].isSelected(name)) {
  32757. return false;
  32758. }
  32759. }
  32760. return true;
  32761. });
  32762. }
  32763. };
  32764. };
  32765. createDataSelectAction('pie', [{
  32766. type: 'pieToggleSelect',
  32767. event: 'pieselectchanged',
  32768. method: 'toggleSelected'
  32769. }, {
  32770. type: 'pieSelect',
  32771. event: 'pieselected',
  32772. method: 'select'
  32773. }, {
  32774. type: 'pieUnSelect',
  32775. event: 'pieunselected',
  32776. method: 'unSelect'
  32777. }]);
  32778. registerVisual(dataColor('pie'));
  32779. registerLayout(curry(pieLayout, 'pie'));
  32780. registerProcessor(dataFilter('pie'));
  32781. SeriesModel.extend({
  32782. type: 'series.scatter',
  32783. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  32784. getInitialData: function (option, ecModel) {
  32785. return createListFromArray(this.getSource(), this);
  32786. },
  32787. brushSelector: 'point',
  32788. getProgressive: function () {
  32789. var progressive = this.option.progressive;
  32790. if (progressive == null) {
  32791. // PENDING
  32792. return this.option.large ? 5e3 : this.get('progressive');
  32793. }
  32794. return progressive;
  32795. },
  32796. getProgressiveThreshold: function () {
  32797. var progressiveThreshold = this.option.progressiveThreshold;
  32798. if (progressiveThreshold == null) {
  32799. // PENDING
  32800. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  32801. }
  32802. return progressiveThreshold;
  32803. },
  32804. defaultOption: {
  32805. coordinateSystem: 'cartesian2d',
  32806. zlevel: 0,
  32807. z: 2,
  32808. legendHoverLink: true,
  32809. hoverAnimation: true,
  32810. // Cartesian coordinate system
  32811. // xAxisIndex: 0,
  32812. // yAxisIndex: 0,
  32813. // Polar coordinate system
  32814. // polarIndex: 0,
  32815. // Geo coordinate system
  32816. // geoIndex: 0,
  32817. // symbol: null, // 图形类型
  32818. symbolSize: 10, // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  32819. // symbolRotate: null, // 图形旋转控制
  32820. large: false,
  32821. // Available when large is true
  32822. largeThreshold: 2000,
  32823. // cursor: null,
  32824. // label: {
  32825. // show: false
  32826. // distance: 5,
  32827. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  32828. // position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
  32829. // 'inside'|'left'|'right'|'top'|'bottom'
  32830. // 默认使用全局文本样式,详见TEXTSTYLE
  32831. // },
  32832. itemStyle: {
  32833. opacity: 0.8
  32834. // color: 各异
  32835. },
  32836. progressive: null
  32837. }
  32838. });
  32839. // TODO Batch by color
  32840. var BOOST_SIZE_THRESHOLD = 4;
  32841. var LargeSymbolPath = extendShape({
  32842. shape: {
  32843. points: null
  32844. },
  32845. symbolProxy: null,
  32846. buildPath: function (path, shape) {
  32847. var points = shape.points;
  32848. var size = shape.size;
  32849. var symbolProxy = this.symbolProxy;
  32850. var symbolProxyShape = symbolProxy.shape;
  32851. var ctx = path.getContext ? path.getContext() : path;
  32852. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  32853. // Do draw in afterBrush.
  32854. if (canBoost) {
  32855. return;
  32856. }
  32857. for (var i = 0; i < points.length;) {
  32858. var x = points[i++];
  32859. var y = points[i++];
  32860. if (isNaN(x) || isNaN(y)) {
  32861. continue;
  32862. }
  32863. symbolProxyShape.x = x - size[0] / 2;
  32864. symbolProxyShape.y = y - size[1] / 2;
  32865. symbolProxyShape.width = size[0];
  32866. symbolProxyShape.height = size[1];
  32867. symbolProxy.buildPath(path, symbolProxyShape, true);
  32868. }
  32869. },
  32870. afterBrush: function (ctx) {
  32871. var shape = this.shape;
  32872. var points = shape.points;
  32873. var size = shape.size;
  32874. var canBoost = size[0] < BOOST_SIZE_THRESHOLD;
  32875. if (!canBoost) {
  32876. return;
  32877. }
  32878. this.setTransform(ctx);
  32879. // PENDING If style or other canvas status changed?
  32880. for (var i = 0; i < points.length;) {
  32881. var x = points[i++];
  32882. var y = points[i++];
  32883. if (isNaN(x) || isNaN(y)) {
  32884. continue;
  32885. }
  32886. // fillRect is faster than building a rect path and draw.
  32887. // And it support light globalCompositeOperation.
  32888. ctx.fillRect(
  32889. x - size[0] / 2, y - size[1] / 2,
  32890. size[0], size[1]
  32891. );
  32892. }
  32893. this.restoreTransform(ctx);
  32894. },
  32895. findDataIndex: function (x, y) {
  32896. // TODO ???
  32897. // Consider transform
  32898. var shape = this.shape;
  32899. var points = shape.points;
  32900. var size = shape.size;
  32901. var w = Math.max(size[0], 4);
  32902. var h = Math.max(size[1], 4);
  32903. // Not consider transform
  32904. // Treat each element as a rect
  32905. // top down traverse
  32906. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  32907. var i = idx * 2;
  32908. var x0 = points[i] - w / 2;
  32909. var y0 = points[i + 1] - h / 2;
  32910. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  32911. return idx;
  32912. }
  32913. }
  32914. return -1;
  32915. }
  32916. });
  32917. function LargeSymbolDraw() {
  32918. this.group = new Group();
  32919. }
  32920. var largeSymbolProto = LargeSymbolDraw.prototype;
  32921. largeSymbolProto.isPersistent = function () {
  32922. return !this._incremental;
  32923. };
  32924. /**
  32925. * Update symbols draw by new data
  32926. * @param {module:echarts/data/List} data
  32927. */
  32928. largeSymbolProto.updateData = function (data) {
  32929. this.group.removeAll();
  32930. var symbolEl = new LargeSymbolPath({
  32931. rectHover: true,
  32932. cursor: 'default'
  32933. });
  32934. symbolEl.setShape({
  32935. points: data.getLayout('symbolPoints')
  32936. });
  32937. this._setCommon(symbolEl, data);
  32938. this.group.add(symbolEl);
  32939. this._incremental = null;
  32940. };
  32941. largeSymbolProto.updateLayout = function (data) {
  32942. if (this._incremental) {
  32943. return;
  32944. }
  32945. var points = data.getLayout('symbolPoints');
  32946. this.group.eachChild(function (child) {
  32947. if (child.startIndex != null) {
  32948. var len = (child.endIndex - child.startIndex) * 2;
  32949. var byteOffset = child.startIndex * 4 * 2;
  32950. points = new Float32Array(points.buffer, byteOffset, len);
  32951. }
  32952. child.setShape('points', points);
  32953. });
  32954. };
  32955. largeSymbolProto.incrementalPrepareUpdate = function (data) {
  32956. this.group.removeAll();
  32957. this._clearIncremental();
  32958. // Only use incremental displayables when data amount is larger than 2 million.
  32959. // PENDING Incremental data?
  32960. if (data.count() > 2e6) {
  32961. if (!this._incremental) {
  32962. this._incremental = new IncrementalDisplayble({
  32963. silent: true
  32964. });
  32965. }
  32966. this.group.add(this._incremental);
  32967. }
  32968. else {
  32969. this._incremental = null;
  32970. }
  32971. };
  32972. largeSymbolProto.incrementalUpdate = function (taskParams, data) {
  32973. var symbolEl;
  32974. if (this._incremental) {
  32975. symbolEl = new LargeSymbolPath();
  32976. this._incremental.addDisplayable(symbolEl, true);
  32977. }
  32978. else {
  32979. symbolEl = new LargeSymbolPath({
  32980. rectHover: true,
  32981. cursor: 'default',
  32982. startIndex: taskParams.start,
  32983. endIndex: taskParams.end
  32984. });
  32985. symbolEl.incremental = true;
  32986. this.group.add(symbolEl);
  32987. }
  32988. symbolEl.setShape({
  32989. points: data.getLayout('symbolPoints')
  32990. });
  32991. this._setCommon(symbolEl, data, !!this._incremental);
  32992. };
  32993. largeSymbolProto._setCommon = function (symbolEl, data, isIncremental) {
  32994. var hostModel = data.hostModel;
  32995. // TODO
  32996. // if (data.hasItemVisual.symbolSize) {
  32997. // // TODO typed array?
  32998. // symbolEl.setShape('sizes', data.mapArray(
  32999. // function (idx) {
  33000. // var size = data.getItemVisual(idx, 'symbolSize');
  33001. // return (size instanceof Array) ? size : [size, size];
  33002. // }
  33003. // ));
  33004. // }
  33005. // else {
  33006. var size = data.getVisual('symbolSize');
  33007. symbolEl.setShape('size', (size instanceof Array) ? size : [size, size]);
  33008. // }
  33009. // Create symbolProxy to build path for each data
  33010. symbolEl.symbolProxy = createSymbol(
  33011. data.getVisual('symbol'), 0, 0, 0, 0
  33012. );
  33013. // Use symbolProxy setColor method
  33014. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  33015. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  33016. symbolEl.useStyle(
  33017. // Draw shadow when doing fillRect is extremely slow.
  33018. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color'])
  33019. );
  33020. var visualColor = data.getVisual('color');
  33021. if (visualColor) {
  33022. symbolEl.setColor(visualColor);
  33023. }
  33024. if (!isIncremental) {
  33025. // Enable tooltip
  33026. // PENDING May have performance issue when path is extremely large
  33027. symbolEl.seriesIndex = hostModel.seriesIndex;
  33028. symbolEl.on('mousemove', function (e) {
  33029. symbolEl.dataIndex = null;
  33030. var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY);
  33031. if (dataIndex >= 0) {
  33032. // Provide dataIndex for tooltip
  33033. symbolEl.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  33034. }
  33035. });
  33036. }
  33037. };
  33038. largeSymbolProto.remove = function () {
  33039. this._clearIncremental();
  33040. this._incremental = null;
  33041. this.group.removeAll();
  33042. };
  33043. largeSymbolProto._clearIncremental = function () {
  33044. var incremental = this._incremental;
  33045. if (incremental) {
  33046. incremental.clearDisplaybles();
  33047. }
  33048. };
  33049. extendChartView({
  33050. type: 'scatter',
  33051. render: function (seriesModel, ecModel, api) {
  33052. var data = seriesModel.getData();
  33053. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  33054. symbolDraw.updateData(data);
  33055. this._finished = true;
  33056. },
  33057. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  33058. var data = seriesModel.getData();
  33059. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  33060. symbolDraw.incrementalPrepareUpdate(data);
  33061. this._finished = false;
  33062. },
  33063. incrementalRender: function (taskParams, seriesModel, ecModel) {
  33064. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData());
  33065. this._finished = taskParams.end === seriesModel.getData().count();
  33066. },
  33067. updateTransform: function (seriesModel, ecModel, api) {
  33068. var data = seriesModel.getData();
  33069. // Must mark group dirty and make sure the incremental layer will be cleared
  33070. // PENDING
  33071. this.group.dirty();
  33072. if (!this._finished || data.count() > 1e4 || !this._symbolDraw.isPersistent()) {
  33073. return {
  33074. update: true
  33075. };
  33076. }
  33077. else {
  33078. var res = pointsLayout().reset(seriesModel);
  33079. if (res.progress) {
  33080. res.progress({ start: 0, end: data.count() }, data);
  33081. }
  33082. this._symbolDraw.updateLayout(data);
  33083. }
  33084. },
  33085. _updateSymbolDraw: function (data, seriesModel) {
  33086. var symbolDraw = this._symbolDraw;
  33087. var pipelineContext = seriesModel.pipelineContext;
  33088. var isLargeDraw = pipelineContext.large;
  33089. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  33090. symbolDraw && symbolDraw.remove();
  33091. symbolDraw = this._symbolDraw = isLargeDraw
  33092. ? new LargeSymbolDraw()
  33093. : new SymbolDraw();
  33094. this._isLargeDraw = isLargeDraw;
  33095. this.group.removeAll();
  33096. }
  33097. this.group.add(symbolDraw.group);
  33098. return symbolDraw;
  33099. },
  33100. remove: function (ecModel, api) {
  33101. this._symbolDraw && this._symbolDraw.remove(true);
  33102. this._symbolDraw = null;
  33103. },
  33104. dispose: function () {}
  33105. });
  33106. // import * as zrUtil from 'zrender/src/core/util';
  33107. // In case developer forget to include grid component
  33108. registerVisual(visualSymbol('scatter', 'circle'));
  33109. registerLayout(pointsLayout('scatter'));
  33110. // echarts.registerProcessor(function (ecModel, api) {
  33111. // ecModel.eachSeriesByType('scatter', function (seriesModel) {
  33112. // var data = seriesModel.getData();
  33113. // var coordSys = seriesModel.coordinateSystem;
  33114. // if (coordSys.type !== 'geo') {
  33115. // return;
  33116. // }
  33117. // var startPt = coordSys.pointToData([0, 0]);
  33118. // var endPt = coordSys.pointToData([api.getWidth(), api.getHeight()]);
  33119. // var dims = zrUtil.map(coordSys.dimensions, function (dim) {
  33120. // return data.mapDimension(dim);
  33121. // });
  33122. // var range = {};
  33123. // range[dims[0]] = [Math.min(startPt[0], endPt[0]), Math.max(startPt[0], endPt[0])];
  33124. // range[dims[1]] = [Math.min(startPt[1], endPt[1]), Math.max(startPt[1], endPt[1])];
  33125. // data.selectRange(range);
  33126. // });
  33127. // });
  33128. // -------------
  33129. // Preprocessor
  33130. // -------------
  33131. registerPreprocessor(function (option) {
  33132. var graphicOption = option.graphic;
  33133. // Convert
  33134. // {graphic: [{left: 10, type: 'circle'}, ...]}
  33135. // or
  33136. // {graphic: {left: 10, type: 'circle'}}
  33137. // to
  33138. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  33139. if (isArray(graphicOption)) {
  33140. if (!graphicOption[0] || !graphicOption[0].elements) {
  33141. option.graphic = [{elements: graphicOption}];
  33142. }
  33143. else {
  33144. // Only one graphic instance can be instantiated. (We dont
  33145. // want that too many views are created in echarts._viewMap)
  33146. option.graphic = [option.graphic[0]];
  33147. }
  33148. }
  33149. else if (graphicOption && !graphicOption.elements) {
  33150. option.graphic = [{elements: [graphicOption]}];
  33151. }
  33152. });
  33153. // ------
  33154. // Model
  33155. // ------
  33156. var GraphicModel = extendComponentModel({
  33157. type: 'graphic',
  33158. defaultOption: {
  33159. // Extra properties for each elements:
  33160. //
  33161. // left/right/top/bottom: (like 12, '22%', 'center', default undefined)
  33162. // If left/rigth is set, shape.x/shape.cx/position will not be used.
  33163. // If top/bottom is set, shape.y/shape.cy/position will not be used.
  33164. // This mechanism is useful when you want to position a group/element
  33165. // against the right side or the center of this container.
  33166. //
  33167. // width/height: (can only be pixel value, default 0)
  33168. // Only be used to specify contianer(group) size, if needed. And
  33169. // can not be percentage value (like '33%'). See the reason in the
  33170. // layout algorithm below.
  33171. //
  33172. // bounding: (enum: 'all' (default) | 'raw')
  33173. // Specify how to calculate boundingRect when locating.
  33174. // 'all': Get uioned and transformed boundingRect
  33175. // from both itself and its descendants.
  33176. // This mode simplies confining a group of elements in the bounding
  33177. // of their ancester container (e.g., using 'right: 0').
  33178. // 'raw': Only use the boundingRect of itself and before transformed.
  33179. // This mode is similar to css behavior, which is useful when you
  33180. // want an element to be able to overflow its container. (Consider
  33181. // a rotated circle needs to be located in a corner.)
  33182. // Note: elements is always behind its ancestors in this elements array.
  33183. elements: [],
  33184. parentId: null
  33185. },
  33186. /**
  33187. * Save el options for the sake of the performance (only update modified graphics).
  33188. * The order is the same as those in option. (ancesters -> descendants)
  33189. *
  33190. * @private
  33191. * @type {Array.<Object>}
  33192. */
  33193. _elOptionsToUpdate: null,
  33194. /**
  33195. * @override
  33196. */
  33197. mergeOption: function (option) {
  33198. // Prevent default merge to elements
  33199. var elements = this.option.elements;
  33200. this.option.elements = null;
  33201. GraphicModel.superApply(this, 'mergeOption', arguments);
  33202. this.option.elements = elements;
  33203. },
  33204. /**
  33205. * @override
  33206. */
  33207. optionUpdated: function (newOption, isInit) {
  33208. var thisOption = this.option;
  33209. var newList = (isInit ? thisOption : newOption).elements;
  33210. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  33211. var flattenedList = [];
  33212. this._flatten(newList, flattenedList);
  33213. var mappingResult = mappingToExists(existList, flattenedList);
  33214. makeIdAndName(mappingResult);
  33215. // Clear elOptionsToUpdate
  33216. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  33217. each$1(mappingResult, function (resultItem, index) {
  33218. var newElOption = resultItem.option;
  33219. if (__DEV__) {
  33220. assert$1(
  33221. isObject$1(newElOption) || resultItem.exist,
  33222. 'Empty graphic option definition'
  33223. );
  33224. }
  33225. if (!newElOption) {
  33226. return;
  33227. }
  33228. elOptionsToUpdate.push(newElOption);
  33229. setKeyInfoToNewElOption(resultItem, newElOption);
  33230. mergeNewElOptionToExist(existList, index, newElOption);
  33231. setLayoutInfoToExist(existList[index], newElOption);
  33232. }, this);
  33233. // Clean
  33234. for (var i = existList.length - 1; i >= 0; i--) {
  33235. if (existList[i] == null) {
  33236. existList.splice(i, 1);
  33237. }
  33238. else {
  33239. // $action should be volatile, otherwise option gotten from
  33240. // `getOption` will contain unexpected $action.
  33241. delete existList[i].$action;
  33242. }
  33243. }
  33244. },
  33245. /**
  33246. * Convert
  33247. * [{
  33248. * type: 'group',
  33249. * id: 'xx',
  33250. * children: [{type: 'circle'}, {type: 'polygon'}]
  33251. * }]
  33252. * to
  33253. * [
  33254. * {type: 'group', id: 'xx'},
  33255. * {type: 'circle', parentId: 'xx'},
  33256. * {type: 'polygon', parentId: 'xx'}
  33257. * ]
  33258. *
  33259. * @private
  33260. * @param {Array.<Object>} optionList option list
  33261. * @param {Array.<Object>} result result of flatten
  33262. * @param {Object} parentOption parent option
  33263. */
  33264. _flatten: function (optionList, result, parentOption) {
  33265. each$1(optionList, function (option) {
  33266. if (!option) {
  33267. return;
  33268. }
  33269. if (parentOption) {
  33270. option.parentOption = parentOption;
  33271. }
  33272. result.push(option);
  33273. var children = option.children;
  33274. if (option.type === 'group' && children) {
  33275. this._flatten(children, result, option);
  33276. }
  33277. // Deleting for JSON output, and for not affecting group creation.
  33278. delete option.children;
  33279. }, this);
  33280. },
  33281. // FIXME
  33282. // Pass to view using payload? setOption has a payload?
  33283. useElOptionsToUpdate: function () {
  33284. var els = this._elOptionsToUpdate;
  33285. // Clear to avoid render duplicately when zooming.
  33286. this._elOptionsToUpdate = null;
  33287. return els;
  33288. }
  33289. });
  33290. // -----
  33291. // View
  33292. // -----
  33293. extendComponentView({
  33294. type: 'graphic',
  33295. /**
  33296. * @override
  33297. */
  33298. init: function (ecModel, api) {
  33299. /**
  33300. * @private
  33301. * @type {module:zrender/core/util.HashMap}
  33302. */
  33303. this._elMap = createHashMap();
  33304. /**
  33305. * @private
  33306. * @type {module:echarts/graphic/GraphicModel}
  33307. */
  33308. this._lastGraphicModel;
  33309. },
  33310. /**
  33311. * @override
  33312. */
  33313. render: function (graphicModel, ecModel, api) {
  33314. // Having leveraged between use cases and algorithm complexity, a very
  33315. // simple layout mechanism is used:
  33316. // The size(width/height) can be determined by itself or its parent (not
  33317. // implemented yet), but can not by its children. (Top-down travel)
  33318. // The location(x/y) can be determined by the bounding rect of itself
  33319. // (can including its descendants or not) and the size of its parent.
  33320. // (Bottom-up travel)
  33321. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  33322. // view will be reused.
  33323. if (graphicModel !== this._lastGraphicModel) {
  33324. this._clear();
  33325. }
  33326. this._lastGraphicModel = graphicModel;
  33327. this._updateElements(graphicModel, api);
  33328. this._relocate(graphicModel, api);
  33329. },
  33330. /**
  33331. * Update graphic elements.
  33332. *
  33333. * @private
  33334. * @param {Object} graphicModel graphic model
  33335. * @param {module:echarts/ExtensionAPI} api extension API
  33336. */
  33337. _updateElements: function (graphicModel, api) {
  33338. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  33339. if (!elOptionsToUpdate) {
  33340. return;
  33341. }
  33342. var elMap = this._elMap;
  33343. var rootGroup = this.group;
  33344. // Top-down tranverse to assign graphic settings to each elements.
  33345. each$1(elOptionsToUpdate, function (elOption) {
  33346. var $action = elOption.$action;
  33347. var id = elOption.id;
  33348. var existEl = elMap.get(id);
  33349. var parentId = elOption.parentId;
  33350. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  33351. if (elOption.type === 'text') {
  33352. var elOptionStyle = elOption.style;
  33353. // In top/bottom mode, textVerticalAlign should not be used, which cause
  33354. // inaccurately locating.
  33355. if (elOption.hv && elOption.hv[1]) {
  33356. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = null;
  33357. }
  33358. // Compatible with previous setting: both support fill and textFill,
  33359. // stroke and textStroke.
  33360. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  33361. elOptionStyle.textFill = elOptionStyle.fill
  33362. );
  33363. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  33364. elOptionStyle.textStroke = elOptionStyle.stroke
  33365. );
  33366. }
  33367. // Remove unnecessary props to avoid potential problems.
  33368. var elOptionCleaned = getCleanedElOption(elOption);
  33369. // For simple, do not support parent change, otherwise reorder is needed.
  33370. if (__DEV__) {
  33371. existEl && assert$1(
  33372. targetElParent === existEl.parent,
  33373. 'Changing parent is not supported.'
  33374. );
  33375. }
  33376. if (!$action || $action === 'merge') {
  33377. existEl
  33378. ? existEl.attr(elOptionCleaned)
  33379. : createEl(id, targetElParent, elOptionCleaned, elMap);
  33380. }
  33381. else if ($action === 'replace') {
  33382. removeEl(existEl, elMap);
  33383. createEl(id, targetElParent, elOptionCleaned, elMap);
  33384. }
  33385. else if ($action === 'remove') {
  33386. removeEl(existEl, elMap);
  33387. }
  33388. var el = elMap.get(id);
  33389. if (el) {
  33390. el.__ecGraphicWidth = elOption.width;
  33391. el.__ecGraphicHeight = elOption.height;
  33392. }
  33393. });
  33394. },
  33395. /**
  33396. * Locate graphic elements.
  33397. *
  33398. * @private
  33399. * @param {Object} graphicModel graphic model
  33400. * @param {module:echarts/ExtensionAPI} api extension API
  33401. */
  33402. _relocate: function (graphicModel, api) {
  33403. var elOptions = graphicModel.option.elements;
  33404. var rootGroup = this.group;
  33405. var elMap = this._elMap;
  33406. // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  33407. for (var i = elOptions.length - 1; i >= 0; i--) {
  33408. var elOption = elOptions[i];
  33409. var el = elMap.get(elOption.id);
  33410. if (!el) {
  33411. continue;
  33412. }
  33413. var parentEl = el.parent;
  33414. var containerInfo = parentEl === rootGroup
  33415. ? {
  33416. width: api.getWidth(),
  33417. height: api.getHeight()
  33418. }
  33419. : { // Like 'position:absolut' in css, default 0.
  33420. width: parentEl.__ecGraphicWidth || 0,
  33421. height: parentEl.__ecGraphicHeight || 0
  33422. };
  33423. positionElement(
  33424. el, elOption, containerInfo, null,
  33425. {hv: elOption.hv, boundingMode: elOption.bounding}
  33426. );
  33427. }
  33428. },
  33429. /**
  33430. * Clear all elements.
  33431. *
  33432. * @private
  33433. */
  33434. _clear: function () {
  33435. var elMap = this._elMap;
  33436. elMap.each(function (el) {
  33437. removeEl(el, elMap);
  33438. });
  33439. this._elMap = createHashMap();
  33440. },
  33441. /**
  33442. * @override
  33443. */
  33444. dispose: function () {
  33445. this._clear();
  33446. }
  33447. });
  33448. function createEl(id, targetElParent, elOption, elMap) {
  33449. var graphicType = elOption.type;
  33450. if (__DEV__) {
  33451. assert$1(graphicType, 'graphic type MUST be set');
  33452. }
  33453. var Clz = graphic[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];
  33454. if (__DEV__) {
  33455. assert$1(Clz, 'graphic type can not be found');
  33456. }
  33457. var el = new Clz(elOption);
  33458. targetElParent.add(el);
  33459. elMap.set(id, el);
  33460. el.__ecGraphicId = id;
  33461. }
  33462. function removeEl(existEl, elMap) {
  33463. var existElParent = existEl && existEl.parent;
  33464. if (existElParent) {
  33465. existEl.type === 'group' && existEl.traverse(function (el) {
  33466. removeEl(el, elMap);
  33467. });
  33468. elMap.removeKey(existEl.__ecGraphicId);
  33469. existElParent.remove(existEl);
  33470. }
  33471. }
  33472. // Remove unnecessary props to avoid potential problems.
  33473. function getCleanedElOption(elOption) {
  33474. elOption = extend({}, elOption);
  33475. each$1(
  33476. ['id', 'parentId', '$action', 'hv', 'bounding'].concat(LOCATION_PARAMS),
  33477. function (name) {
  33478. delete elOption[name];
  33479. }
  33480. );
  33481. return elOption;
  33482. }
  33483. function isSetLoc(obj, props) {
  33484. var isSet;
  33485. each$1(props, function (prop) {
  33486. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  33487. });
  33488. return isSet;
  33489. }
  33490. function setKeyInfoToNewElOption(resultItem, newElOption) {
  33491. var existElOption = resultItem.exist;
  33492. // Set id and type after id assigned.
  33493. newElOption.id = resultItem.keyInfo.id;
  33494. !newElOption.type && existElOption && (newElOption.type = existElOption.type);
  33495. // Set parent id if not specified
  33496. if (newElOption.parentId == null) {
  33497. var newElParentOption = newElOption.parentOption;
  33498. if (newElParentOption) {
  33499. newElOption.parentId = newElParentOption.id;
  33500. }
  33501. else if (existElOption) {
  33502. newElOption.parentId = existElOption.parentId;
  33503. }
  33504. }
  33505. // Clear
  33506. newElOption.parentOption = null;
  33507. }
  33508. function mergeNewElOptionToExist(existList, index, newElOption) {
  33509. // Update existing options, for `getOption` feature.
  33510. var newElOptCopy = extend({}, newElOption);
  33511. var existElOption = existList[index];
  33512. var $action = newElOption.$action || 'merge';
  33513. if ($action === 'merge') {
  33514. if (existElOption) {
  33515. if (__DEV__) {
  33516. var newType = newElOption.type;
  33517. assert$1(
  33518. !newType || existElOption.type === newType,
  33519. 'Please set $action: "replace" to change `type`'
  33520. );
  33521. }
  33522. // We can ensure that newElOptCopy and existElOption are not
  33523. // the same object, so `merge` will not change newElOptCopy.
  33524. merge(existElOption, newElOptCopy, true);
  33525. // Rigid body, use ignoreSize.
  33526. mergeLayoutParam(existElOption, newElOptCopy, {ignoreSize: true});
  33527. // Will be used in render.
  33528. copyLayoutParams(newElOption, existElOption);
  33529. }
  33530. else {
  33531. existList[index] = newElOptCopy;
  33532. }
  33533. }
  33534. else if ($action === 'replace') {
  33535. existList[index] = newElOptCopy;
  33536. }
  33537. else if ($action === 'remove') {
  33538. // null will be cleaned later.
  33539. existElOption && (existList[index] = null);
  33540. }
  33541. }
  33542. function setLayoutInfoToExist(existItem, newElOption) {
  33543. if (!existItem) {
  33544. return;
  33545. }
  33546. existItem.hv = newElOption.hv = [
  33547. // Rigid body, dont care `width`.
  33548. isSetLoc(newElOption, ['left', 'right']),
  33549. // Rigid body, dont care `height`.
  33550. isSetLoc(newElOption, ['top', 'bottom'])
  33551. ];
  33552. // Give default group size. Otherwise layout error may occur.
  33553. if (existItem.type === 'group') {
  33554. existItem.width == null && (existItem.width = newElOption.width = 0);
  33555. existItem.height == null && (existItem.height = newElOption.height = 0);
  33556. }
  33557. }
  33558. /**
  33559. * @param {Object} finder contains {seriesIndex, dataIndex, dataIndexInside}
  33560. * @param {module:echarts/model/Global} ecModel
  33561. * @return {Object} {point: [x, y], el: ...} point Will not be null.
  33562. */
  33563. var findPointFromSeries = function (finder, ecModel) {
  33564. var point = [];
  33565. var seriesIndex = finder.seriesIndex;
  33566. var seriesModel;
  33567. if (seriesIndex == null || !(
  33568. seriesModel = ecModel.getSeriesByIndex(seriesIndex)
  33569. )) {
  33570. return {point: []};
  33571. }
  33572. var data = seriesModel.getData();
  33573. var dataIndex = queryDataIndex(data, finder);
  33574. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  33575. return {point: []};
  33576. }
  33577. var el = data.getItemGraphicEl(dataIndex);
  33578. var coordSys = seriesModel.coordinateSystem;
  33579. if (seriesModel.getTooltipPosition) {
  33580. point = seriesModel.getTooltipPosition(dataIndex) || [];
  33581. }
  33582. else if (coordSys && coordSys.dataToPoint) {
  33583. point = coordSys.dataToPoint(
  33584. data.getValues(
  33585. map(coordSys.dimensions, function (dim) {
  33586. return data.mapDimension(dim);
  33587. }), dataIndex, true
  33588. )
  33589. ) || [];
  33590. }
  33591. else if (el) {
  33592. // Use graphic bounding rect
  33593. var rect = el.getBoundingRect().clone();
  33594. rect.applyTransform(el.transform);
  33595. point = [
  33596. rect.x + rect.width / 2,
  33597. rect.y + rect.height / 2
  33598. ];
  33599. }
  33600. return {point: point, el: el};
  33601. };
  33602. var each$8 = each$1;
  33603. var curry$2 = curry;
  33604. var inner$6 = makeInner();
  33605. /**
  33606. * Basic logic: check all axis, if they do not demand show/highlight,
  33607. * then hide/downplay them.
  33608. *
  33609. * @param {Object} coordSysAxesInfo
  33610. * @param {Object} payload
  33611. * @param {string} [payload.currTrigger] 'click' | 'mousemove' | 'leave'
  33612. * @param {Array.<number>} [payload.x] x and y, which are mandatory, specify a point to
  33613. * trigger axisPointer and tooltip.
  33614. * @param {Array.<number>} [payload.y] x and y, which are mandatory, specify a point to
  33615. * trigger axisPointer and tooltip.
  33616. * @param {Object} [payload.seriesIndex] finder, optional, restrict target axes.
  33617. * @param {Object} [payload.dataIndex] finder, restrict target axes.
  33618. * @param {Object} [payload.axesInfo] finder, restrict target axes.
  33619. * [{
  33620. * axisDim: 'x'|'y'|'angle'|...,
  33621. * axisIndex: ...,
  33622. * value: ...
  33623. * }, ...]
  33624. * @param {Function} [payload.dispatchAction]
  33625. * @param {Object} [payload.tooltipOption]
  33626. * @param {Object|Array.<number>|Function} [payload.position] Tooltip position,
  33627. * which can be specified in dispatchAction
  33628. * @param {module:echarts/model/Global} ecModel
  33629. * @param {module:echarts/ExtensionAPI} api
  33630. * @return {Object} content of event obj for echarts.connect.
  33631. */
  33632. var axisTrigger = function (payload, ecModel, api) {
  33633. var currTrigger = payload.currTrigger;
  33634. var point = [payload.x, payload.y];
  33635. var finder = payload;
  33636. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  33637. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  33638. // Pending
  33639. // See #6121. But we are not able to reproduce it yet.
  33640. if (!coordSysAxesInfo) {
  33641. return;
  33642. }
  33643. if (illegalPoint(point)) {
  33644. // Used in the default behavior of `connection`: use the sample seriesIndex
  33645. // and dataIndex. And also used in the tooltipView trigger.
  33646. point = findPointFromSeries({
  33647. seriesIndex: finder.seriesIndex,
  33648. // Do not use dataIndexInside from other ec instance.
  33649. // FIXME: auto detect it?
  33650. dataIndex: finder.dataIndex
  33651. }, ecModel).point;
  33652. }
  33653. var isIllegalPoint = illegalPoint(point);
  33654. // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  33655. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  33656. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  33657. // and dataIndex.
  33658. var inputAxesInfo = finder.axesInfo;
  33659. var axesInfo = coordSysAxesInfo.axesInfo;
  33660. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  33661. var outputFinder = {};
  33662. var showValueMap = {};
  33663. var dataByCoordSys = {list: [], map: {}};
  33664. var updaters = {
  33665. showPointer: curry$2(showPointer, showValueMap),
  33666. showTooltip: curry$2(showTooltip, dataByCoordSys)
  33667. };
  33668. // Process for triggered axes.
  33669. each$8(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  33670. // If a point given, it must be contained by the coordinate system.
  33671. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  33672. each$8(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  33673. var axis = axisInfo.axis;
  33674. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo);
  33675. // If no inputAxesInfo, no axis is restricted.
  33676. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  33677. var val = inputAxisInfo && inputAxisInfo.value;
  33678. if (val == null && !isIllegalPoint) {
  33679. val = axis.pointToData(point);
  33680. }
  33681. val != null && processOnAxis(axisInfo, val, updaters, false, outputFinder);
  33682. }
  33683. });
  33684. });
  33685. // Process for linked axes.
  33686. var linkTriggers = {};
  33687. each$8(axesInfo, function (tarAxisInfo, tarKey) {
  33688. var linkGroup = tarAxisInfo.linkGroup;
  33689. // If axis has been triggered in the previous stage, it should not be triggered by link.
  33690. if (linkGroup && !showValueMap[tarKey]) {
  33691. each$8(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  33692. var srcValItem = showValueMap[srcKey];
  33693. // If srcValItem exist, source axis is triggered, so link to target axis.
  33694. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  33695. var val = srcValItem.value;
  33696. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(
  33697. val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo)
  33698. )));
  33699. linkTriggers[tarAxisInfo.key] = val;
  33700. }
  33701. });
  33702. }
  33703. });
  33704. each$8(linkTriggers, function (val, tarKey) {
  33705. processOnAxis(axesInfo[tarKey], val, updaters, true, outputFinder);
  33706. });
  33707. updateModelActually(showValueMap, axesInfo, outputFinder);
  33708. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  33709. dispatchHighDownActually(axesInfo, dispatchAction, api);
  33710. return outputFinder;
  33711. };
  33712. function processOnAxis(axisInfo, newValue, updaters, dontSnap, outputFinder) {
  33713. var axis = axisInfo.axis;
  33714. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  33715. return;
  33716. }
  33717. if (!axisInfo.involveSeries) {
  33718. updaters.showPointer(axisInfo, newValue);
  33719. return;
  33720. }
  33721. // Heavy calculation. So put it after axis.containData checking.
  33722. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  33723. var payloadBatch = payloadInfo.payloadBatch;
  33724. var snapToValue = payloadInfo.snapToValue;
  33725. // Fill content of event obj for echarts.connect.
  33726. // By defualt use the first involved series data as a sample to connect.
  33727. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  33728. extend(outputFinder, payloadBatch[0]);
  33729. }
  33730. // If no linkSource input, this process is for collecting link
  33731. // target, where snap should not be accepted.
  33732. if (!dontSnap && axisInfo.snap) {
  33733. if (axis.containData(snapToValue) && snapToValue != null) {
  33734. newValue = snapToValue;
  33735. }
  33736. }
  33737. updaters.showPointer(axisInfo, newValue, payloadBatch, outputFinder);
  33738. // Tooltip should always be snapToValue, otherwise there will be
  33739. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  33740. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  33741. }
  33742. function buildPayloadsBySeries(value, axisInfo) {
  33743. var axis = axisInfo.axis;
  33744. var dim = axis.dim;
  33745. var snapToValue = value;
  33746. var payloadBatch = [];
  33747. var minDist = Number.MAX_VALUE;
  33748. var minDiff = -1;
  33749. each$8(axisInfo.seriesModels, function (series, idx) {
  33750. var dataDim = series.getData().mapDimension(dim, true);
  33751. var seriesNestestValue;
  33752. var dataIndices;
  33753. if (series.getAxisTooltipData) {
  33754. var result = series.getAxisTooltipData(dataDim, value, axis);
  33755. dataIndices = result.dataIndices;
  33756. seriesNestestValue = result.nestestValue;
  33757. }
  33758. else {
  33759. dataIndices = series.getData().indicesOfNearest(
  33760. dataDim[0],
  33761. value,
  33762. // Add a threshold to avoid find the wrong dataIndex
  33763. // when data length is not same.
  33764. // false,
  33765. axis.type === 'category' ? 0.5 : null
  33766. );
  33767. if (!dataIndices.length) {
  33768. return;
  33769. }
  33770. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  33771. }
  33772. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  33773. return;
  33774. }
  33775. var diff = value - seriesNestestValue;
  33776. var dist = Math.abs(diff);
  33777. // Consider category case
  33778. if (dist <= minDist) {
  33779. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  33780. minDist = dist;
  33781. minDiff = diff;
  33782. snapToValue = seriesNestestValue;
  33783. payloadBatch.length = 0;
  33784. }
  33785. each$8(dataIndices, function (dataIndex) {
  33786. payloadBatch.push({
  33787. seriesIndex: series.seriesIndex,
  33788. dataIndexInside: dataIndex,
  33789. dataIndex: series.getData().getRawIndex(dataIndex)
  33790. });
  33791. });
  33792. }
  33793. });
  33794. return {
  33795. payloadBatch: payloadBatch,
  33796. snapToValue: snapToValue
  33797. };
  33798. }
  33799. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  33800. showValueMap[axisInfo.key] = {value: value, payloadBatch: payloadBatch};
  33801. }
  33802. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  33803. var payloadBatch = payloadInfo.payloadBatch;
  33804. var axis = axisInfo.axis;
  33805. var axisModel = axis.model;
  33806. var axisPointerModel = axisInfo.axisPointerModel;
  33807. // If no data, do not create anything in dataByCoordSys,
  33808. // whose length will be used to judge whether dispatch action.
  33809. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  33810. return;
  33811. }
  33812. var coordSysModel = axisInfo.coordSys.model;
  33813. var coordSysKey = makeKey(coordSysModel);
  33814. var coordSysItem = dataByCoordSys.map[coordSysKey];
  33815. if (!coordSysItem) {
  33816. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  33817. coordSysId: coordSysModel.id,
  33818. coordSysIndex: coordSysModel.componentIndex,
  33819. coordSysType: coordSysModel.type,
  33820. coordSysMainType: coordSysModel.mainType,
  33821. dataByAxis: []
  33822. };
  33823. dataByCoordSys.list.push(coordSysItem);
  33824. }
  33825. coordSysItem.dataByAxis.push({
  33826. axisDim: axis.dim,
  33827. axisIndex: axisModel.componentIndex,
  33828. axisType: axisModel.type,
  33829. axisId: axisModel.id,
  33830. value: value,
  33831. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  33832. // depends that all models have been updated. So it should not be performed
  33833. // here. Considering axisPointerModel used here is volatile, which is hard
  33834. // to be retrieve in TooltipView, we prepare parameters here.
  33835. valueLabelOpt: {
  33836. precision: axisPointerModel.get('label.precision'),
  33837. formatter: axisPointerModel.get('label.formatter')
  33838. },
  33839. seriesDataIndices: payloadBatch.slice()
  33840. });
  33841. }
  33842. function updateModelActually(showValueMap, axesInfo, outputFinder) {
  33843. var outputAxesInfo = outputFinder.axesInfo = [];
  33844. // Basic logic: If no 'show' required, 'hide' this axisPointer.
  33845. each$8(axesInfo, function (axisInfo, key) {
  33846. var option = axisInfo.axisPointerModel.option;
  33847. var valItem = showValueMap[key];
  33848. if (valItem) {
  33849. !axisInfo.useHandle && (option.status = 'show');
  33850. option.value = valItem.value;
  33851. // For label formatter param and highlight.
  33852. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  33853. }
  33854. // When always show (e.g., handle used), remain
  33855. // original value and status.
  33856. else {
  33857. // If hide, value still need to be set, consider
  33858. // click legend to toggle axis blank.
  33859. !axisInfo.useHandle && (option.status = 'hide');
  33860. }
  33861. // If status is 'hide', should be no info in payload.
  33862. option.status === 'show' && outputAxesInfo.push({
  33863. axisDim: axisInfo.axis.dim,
  33864. axisIndex: axisInfo.axis.model.componentIndex,
  33865. value: option.value
  33866. });
  33867. });
  33868. }
  33869. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  33870. // Basic logic: If no showTip required, hideTip will be dispatched.
  33871. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  33872. dispatchAction({type: 'hideTip'});
  33873. return;
  33874. }
  33875. // In most case only one axis (or event one series is used). It is
  33876. // convinient to fetch payload.seriesIndex and payload.dataIndex
  33877. // dirtectly. So put the first seriesIndex and dataIndex of the first
  33878. // axis on the payload.
  33879. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  33880. dispatchAction({
  33881. type: 'showTip',
  33882. escapeConnect: true,
  33883. x: point[0],
  33884. y: point[1],
  33885. tooltipOption: payload.tooltipOption,
  33886. position: payload.position,
  33887. dataIndexInside: sampleItem.dataIndexInside,
  33888. dataIndex: sampleItem.dataIndex,
  33889. seriesIndex: sampleItem.seriesIndex,
  33890. dataByCoordSys: dataByCoordSys.list
  33891. });
  33892. }
  33893. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  33894. // FIXME
  33895. // highlight status modification shoule be a stage of main process?
  33896. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  33897. var zr = api.getZr();
  33898. var highDownKey = 'axisPointerLastHighlights';
  33899. var lastHighlights = inner$6(zr)[highDownKey] || {};
  33900. var newHighlights = inner$6(zr)[highDownKey] = {};
  33901. // Update highlight/downplay status according to axisPointer model.
  33902. // Build hash map and remove duplicate incidentally.
  33903. each$8(axesInfo, function (axisInfo, key) {
  33904. var option = axisInfo.axisPointerModel.option;
  33905. option.status === 'show' && each$8(option.seriesDataIndices, function (batchItem) {
  33906. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  33907. newHighlights[key] = batchItem;
  33908. });
  33909. });
  33910. // Diff.
  33911. var toHighlight = [];
  33912. var toDownplay = [];
  33913. each$1(lastHighlights, function (batchItem, key) {
  33914. !newHighlights[key] && toDownplay.push(batchItem);
  33915. });
  33916. each$1(newHighlights, function (batchItem, key) {
  33917. !lastHighlights[key] && toHighlight.push(batchItem);
  33918. });
  33919. toDownplay.length && api.dispatchAction({
  33920. type: 'downplay', escapeConnect: true, batch: toDownplay
  33921. });
  33922. toHighlight.length && api.dispatchAction({
  33923. type: 'highlight', escapeConnect: true, batch: toHighlight
  33924. });
  33925. }
  33926. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  33927. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  33928. var inputAxisInfo = inputAxesInfo[i];
  33929. if (axisInfo.axis.dim === inputAxisInfo.axisDim
  33930. && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex
  33931. ) {
  33932. return inputAxisInfo;
  33933. }
  33934. }
  33935. }
  33936. function makeMapperParam(axisInfo) {
  33937. var axisModel = axisInfo.axis.model;
  33938. var item = {};
  33939. var dim = item.axisDim = axisInfo.axis.dim;
  33940. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  33941. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  33942. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  33943. return item;
  33944. }
  33945. function illegalPoint(point) {
  33946. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  33947. }
  33948. var AxisPointerModel = extendComponentModel({
  33949. type: 'axisPointer',
  33950. coordSysAxesInfo: null,
  33951. defaultOption: {
  33952. // 'auto' means that show when triggered by tooltip or handle.
  33953. show: 'auto',
  33954. // 'click' | 'mousemove' | 'none'
  33955. triggerOn: null, // set default in AxisPonterView.js
  33956. zlevel: 0,
  33957. z: 50,
  33958. type: 'line',
  33959. // axispointer triggered by tootip determine snap automatically,
  33960. // see `modelHelper`.
  33961. snap: false,
  33962. triggerTooltip: true,
  33963. value: null,
  33964. status: null, // Init value depends on whether handle is used.
  33965. // [group0, group1, ...]
  33966. // Each group can be: {
  33967. // mapper: function () {},
  33968. // singleTooltip: 'multiple', // 'multiple' or 'single'
  33969. // xAxisId: ...,
  33970. // yAxisName: ...,
  33971. // angleAxisIndex: ...
  33972. // }
  33973. // mapper: can be ignored.
  33974. // input: {axisInfo, value}
  33975. // output: {axisInfo, value}
  33976. link: [],
  33977. // Do not set 'auto' here, otherwise global animation: false
  33978. // will not effect at this axispointer.
  33979. animation: null,
  33980. animationDurationUpdate: 200,
  33981. lineStyle: {
  33982. color: '#aaa',
  33983. width: 1,
  33984. type: 'solid'
  33985. },
  33986. shadowStyle: {
  33987. color: 'rgba(150,150,150,0.3)'
  33988. },
  33989. label: {
  33990. show: true,
  33991. formatter: null, // string | Function
  33992. precision: 'auto', // Or a number like 0, 1, 2 ...
  33993. margin: 3,
  33994. color: '#fff',
  33995. padding: [5, 7, 5, 7],
  33996. backgroundColor: 'auto', // default: axis line color
  33997. borderColor: null,
  33998. borderWidth: 0,
  33999. shadowBlur: 3,
  34000. shadowColor: '#aaa'
  34001. // Considering applicability, common style should
  34002. // better not have shadowOffset.
  34003. // shadowOffsetX: 0,
  34004. // shadowOffsetY: 2
  34005. },
  34006. handle: {
  34007. show: false,
  34008. 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
  34009. size: 45,
  34010. // handle margin is from symbol center to axis, which is stable when circular move.
  34011. margin: 50,
  34012. // color: '#1b8bbd'
  34013. // color: '#2f4554'
  34014. color: '#333',
  34015. shadowBlur: 3,
  34016. shadowColor: '#aaa',
  34017. shadowOffsetX: 0,
  34018. shadowOffsetY: 2,
  34019. // For mobile performance
  34020. throttle: 40
  34021. }
  34022. }
  34023. });
  34024. var inner$7 = makeInner();
  34025. var each$9 = each$1;
  34026. /**
  34027. * @param {string} key
  34028. * @param {module:echarts/ExtensionAPI} api
  34029. * @param {Function} handler
  34030. * param: {string} currTrigger
  34031. * param: {Array.<number>} point
  34032. */
  34033. function register(key, api, handler) {
  34034. if (env$1.node) {
  34035. return;
  34036. }
  34037. var zr = api.getZr();
  34038. inner$7(zr).records || (inner$7(zr).records = {});
  34039. initGlobalListeners(zr, api);
  34040. var record = inner$7(zr).records[key] || (inner$7(zr).records[key] = {});
  34041. record.handler = handler;
  34042. }
  34043. function initGlobalListeners(zr, api) {
  34044. if (inner$7(zr).initialized) {
  34045. return;
  34046. }
  34047. inner$7(zr).initialized = true;
  34048. useHandler('click', curry(doEnter, 'click'));
  34049. useHandler('mousemove', curry(doEnter, 'mousemove'));
  34050. // useHandler('mouseout', onLeave);
  34051. useHandler('globalout', onLeave);
  34052. function useHandler(eventType, cb) {
  34053. zr.on(eventType, function (e) {
  34054. var dis = makeDispatchAction(api);
  34055. each$9(inner$7(zr).records, function (record) {
  34056. record && cb(record, e, dis.dispatchAction);
  34057. });
  34058. dispatchTooltipFinally(dis.pendings, api);
  34059. });
  34060. }
  34061. }
  34062. function dispatchTooltipFinally(pendings, api) {
  34063. var showLen = pendings.showTip.length;
  34064. var hideLen = pendings.hideTip.length;
  34065. var actuallyPayload;
  34066. if (showLen) {
  34067. actuallyPayload = pendings.showTip[showLen - 1];
  34068. }
  34069. else if (hideLen) {
  34070. actuallyPayload = pendings.hideTip[hideLen - 1];
  34071. }
  34072. if (actuallyPayload) {
  34073. actuallyPayload.dispatchAction = null;
  34074. api.dispatchAction(actuallyPayload);
  34075. }
  34076. }
  34077. function onLeave(record, e, dispatchAction) {
  34078. record.handler('leave', null, dispatchAction);
  34079. }
  34080. function doEnter(currTrigger, record, e, dispatchAction) {
  34081. record.handler(currTrigger, e, dispatchAction);
  34082. }
  34083. function makeDispatchAction(api) {
  34084. var pendings = {
  34085. showTip: [],
  34086. hideTip: []
  34087. };
  34088. // FIXME
  34089. // better approach?
  34090. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  34091. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  34092. // So we have to add "final stage" to merge those dispatched actions.
  34093. var dispatchAction = function (payload) {
  34094. var pendingList = pendings[payload.type];
  34095. if (pendingList) {
  34096. pendingList.push(payload);
  34097. }
  34098. else {
  34099. payload.dispatchAction = dispatchAction;
  34100. api.dispatchAction(payload);
  34101. }
  34102. };
  34103. return {
  34104. dispatchAction: dispatchAction,
  34105. pendings: pendings
  34106. };
  34107. }
  34108. /**
  34109. * @param {string} key
  34110. * @param {module:echarts/ExtensionAPI} api
  34111. */
  34112. function unregister(key, api) {
  34113. if (env$1.node) {
  34114. return;
  34115. }
  34116. var zr = api.getZr();
  34117. var record = (inner$7(zr).records || {})[key];
  34118. if (record) {
  34119. inner$7(zr).records[key] = null;
  34120. }
  34121. }
  34122. var AxisPointerView = extendComponentView({
  34123. type: 'axisPointer',
  34124. render: function (globalAxisPointerModel, ecModel, api) {
  34125. var globalTooltipModel = ecModel.getComponent('tooltip');
  34126. var triggerOn = globalAxisPointerModel.get('triggerOn')
  34127. || (globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click');
  34128. // Register global listener in AxisPointerView to enable
  34129. // AxisPointerView to be independent to Tooltip.
  34130. register(
  34131. 'axisPointer',
  34132. api,
  34133. function (currTrigger, e, dispatchAction) {
  34134. // If 'none', it is not controlled by mouse totally.
  34135. if (triggerOn !== 'none'
  34136. && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)
  34137. ) {
  34138. dispatchAction({
  34139. type: 'updateAxisPointer',
  34140. currTrigger: currTrigger,
  34141. x: e && e.offsetX,
  34142. y: e && e.offsetY
  34143. });
  34144. }
  34145. }
  34146. );
  34147. },
  34148. /**
  34149. * @override
  34150. */
  34151. remove: function (ecModel, api) {
  34152. unregister(api.getZr(), 'axisPointer');
  34153. AxisPointerView.superApply(this._model, 'remove', arguments);
  34154. },
  34155. /**
  34156. * @override
  34157. */
  34158. dispose: function (ecModel, api) {
  34159. unregister('axisPointer', api);
  34160. AxisPointerView.superApply(this._model, 'dispose', arguments);
  34161. }
  34162. });
  34163. var inner$8 = makeInner();
  34164. var clone$4 = clone;
  34165. var bind$1 = bind;
  34166. /**
  34167. * Base axis pointer class in 2D.
  34168. * Implemenents {module:echarts/component/axis/IAxisPointer}.
  34169. */
  34170. function BaseAxisPointer () {
  34171. }
  34172. BaseAxisPointer.prototype = {
  34173. /**
  34174. * @private
  34175. */
  34176. _group: null,
  34177. /**
  34178. * @private
  34179. */
  34180. _lastGraphicKey: null,
  34181. /**
  34182. * @private
  34183. */
  34184. _handle: null,
  34185. /**
  34186. * @private
  34187. */
  34188. _dragging: false,
  34189. /**
  34190. * @private
  34191. */
  34192. _lastValue: null,
  34193. /**
  34194. * @private
  34195. */
  34196. _lastStatus: null,
  34197. /**
  34198. * @private
  34199. */
  34200. _payloadInfo: null,
  34201. /**
  34202. * In px, arbitrary value. Do not set too small,
  34203. * no animation is ok for most cases.
  34204. * @protected
  34205. */
  34206. animationThreshold: 15,
  34207. /**
  34208. * @implement
  34209. */
  34210. render: function (axisModel, axisPointerModel, api, forceRender) {
  34211. var value = axisPointerModel.get('value');
  34212. var status = axisPointerModel.get('status');
  34213. // Bind them to `this`, not in closure, otherwise they will not
  34214. // be replaced when user calling setOption in not merge mode.
  34215. this._axisModel = axisModel;
  34216. this._axisPointerModel = axisPointerModel;
  34217. this._api = api;
  34218. // Optimize: `render` will be called repeatly during mouse move.
  34219. // So it is power consuming if performing `render` each time,
  34220. // especially on mobile device.
  34221. if (!forceRender
  34222. && this._lastValue === value
  34223. && this._lastStatus === status
  34224. ) {
  34225. return;
  34226. }
  34227. this._lastValue = value;
  34228. this._lastStatus = status;
  34229. var group = this._group;
  34230. var handle = this._handle;
  34231. if (!status || status === 'hide') {
  34232. // Do not clear here, for animation better.
  34233. group && group.hide();
  34234. handle && handle.hide();
  34235. return;
  34236. }
  34237. group && group.show();
  34238. handle && handle.show();
  34239. // Otherwise status is 'show'
  34240. var elOption = {};
  34241. this.makeElOption(elOption, value, axisModel, axisPointerModel, api);
  34242. // Enable change axis pointer type.
  34243. var graphicKey = elOption.graphicKey;
  34244. if (graphicKey !== this._lastGraphicKey) {
  34245. this.clear(api);
  34246. }
  34247. this._lastGraphicKey = graphicKey;
  34248. var moveAnimation = this._moveAnimation =
  34249. this.determineAnimation(axisModel, axisPointerModel);
  34250. if (!group) {
  34251. group = this._group = new Group();
  34252. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  34253. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  34254. api.getZr().add(group);
  34255. }
  34256. else {
  34257. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  34258. this.updatePointerEl(group, elOption, doUpdateProps, axisPointerModel);
  34259. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  34260. }
  34261. updateMandatoryProps(group, axisPointerModel, true);
  34262. this._renderHandle(value);
  34263. },
  34264. /**
  34265. * @implement
  34266. */
  34267. remove: function (api) {
  34268. this.clear(api);
  34269. },
  34270. /**
  34271. * @implement
  34272. */
  34273. dispose: function (api) {
  34274. this.clear(api);
  34275. },
  34276. /**
  34277. * @protected
  34278. */
  34279. determineAnimation: function (axisModel, axisPointerModel) {
  34280. var animation = axisPointerModel.get('animation');
  34281. var axis = axisModel.axis;
  34282. var isCategoryAxis = axis.type === 'category';
  34283. var useSnap = axisPointerModel.get('snap');
  34284. // Value axis without snap always do not snap.
  34285. if (!useSnap && !isCategoryAxis) {
  34286. return false;
  34287. }
  34288. if (animation === 'auto' || animation == null) {
  34289. var animationThreshold = this.animationThreshold;
  34290. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  34291. return true;
  34292. }
  34293. // It is important to auto animation when snap used. Consider if there is
  34294. // a dataZoom, animation will be disabled when too many points exist, while
  34295. // it will be enabled for better visual effect when little points exist.
  34296. if (useSnap) {
  34297. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  34298. var axisExtent = axis.getExtent();
  34299. // Approximate band width
  34300. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  34301. }
  34302. return false;
  34303. }
  34304. return animation === true;
  34305. },
  34306. /**
  34307. * add {pointer, label, graphicKey} to elOption
  34308. * @protected
  34309. */
  34310. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  34311. // Shoule be implemenented by sub-class.
  34312. },
  34313. /**
  34314. * @protected
  34315. */
  34316. createPointerEl: function (group, elOption, axisModel, axisPointerModel) {
  34317. var pointerOption = elOption.pointer;
  34318. if (pointerOption) {
  34319. var pointerEl = inner$8(group).pointerEl = new graphic[pointerOption.type](
  34320. clone$4(elOption.pointer)
  34321. );
  34322. group.add(pointerEl);
  34323. }
  34324. },
  34325. /**
  34326. * @protected
  34327. */
  34328. createLabelEl: function (group, elOption, axisModel, axisPointerModel) {
  34329. if (elOption.label) {
  34330. var labelEl = inner$8(group).labelEl = new Rect(
  34331. clone$4(elOption.label)
  34332. );
  34333. group.add(labelEl);
  34334. updateLabelShowHide(labelEl, axisPointerModel);
  34335. }
  34336. },
  34337. /**
  34338. * @protected
  34339. */
  34340. updatePointerEl: function (group, elOption, updateProps$$1) {
  34341. var pointerEl = inner$8(group).pointerEl;
  34342. if (pointerEl) {
  34343. pointerEl.setStyle(elOption.pointer.style);
  34344. updateProps$$1(pointerEl, {shape: elOption.pointer.shape});
  34345. }
  34346. },
  34347. /**
  34348. * @protected
  34349. */
  34350. updateLabelEl: function (group, elOption, updateProps$$1, axisPointerModel) {
  34351. var labelEl = inner$8(group).labelEl;
  34352. if (labelEl) {
  34353. labelEl.setStyle(elOption.label.style);
  34354. updateProps$$1(labelEl, {
  34355. // Consider text length change in vertical axis, animation should
  34356. // be used on shape, otherwise the effect will be weird.
  34357. shape: elOption.label.shape,
  34358. position: elOption.label.position
  34359. });
  34360. updateLabelShowHide(labelEl, axisPointerModel);
  34361. }
  34362. },
  34363. /**
  34364. * @private
  34365. */
  34366. _renderHandle: function (value) {
  34367. if (this._dragging || !this.updateHandleTransform) {
  34368. return;
  34369. }
  34370. var axisPointerModel = this._axisPointerModel;
  34371. var zr = this._api.getZr();
  34372. var handle = this._handle;
  34373. var handleModel = axisPointerModel.getModel('handle');
  34374. var status = axisPointerModel.get('status');
  34375. if (!handleModel.get('show') || !status || status === 'hide') {
  34376. handle && zr.remove(handle);
  34377. this._handle = null;
  34378. return;
  34379. }
  34380. var isInit;
  34381. if (!this._handle) {
  34382. isInit = true;
  34383. handle = this._handle = createIcon(
  34384. handleModel.get('icon'),
  34385. {
  34386. cursor: 'move',
  34387. draggable: true,
  34388. onmousemove: function (e) {
  34389. // Fot mobile devicem, prevent screen slider on the button.
  34390. stop(e.event);
  34391. },
  34392. onmousedown: bind$1(this._onHandleDragMove, this, 0, 0),
  34393. drift: bind$1(this._onHandleDragMove, this),
  34394. ondragend: bind$1(this._onHandleDragEnd, this)
  34395. }
  34396. );
  34397. zr.add(handle);
  34398. }
  34399. updateMandatoryProps(handle, axisPointerModel, false);
  34400. // update style
  34401. var includeStyles = [
  34402. 'color', 'borderColor', 'borderWidth', 'opacity',
  34403. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'
  34404. ];
  34405. handle.setStyle(handleModel.getItemStyle(null, includeStyles));
  34406. // update position
  34407. var handleSize = handleModel.get('size');
  34408. if (!isArray(handleSize)) {
  34409. handleSize = [handleSize, handleSize];
  34410. }
  34411. handle.attr('scale', [handleSize[0] / 2, handleSize[1] / 2]);
  34412. createOrUpdate(
  34413. this,
  34414. '_doDispatchAxisPointer',
  34415. handleModel.get('throttle') || 0,
  34416. 'fixRate'
  34417. );
  34418. this._moveHandleToValue(value, isInit);
  34419. },
  34420. /**
  34421. * @private
  34422. */
  34423. _moveHandleToValue: function (value, isInit) {
  34424. updateProps$1(
  34425. this._axisPointerModel,
  34426. !isInit && this._moveAnimation,
  34427. this._handle,
  34428. getHandleTransProps(this.getHandleTransform(
  34429. value, this._axisModel, this._axisPointerModel
  34430. ))
  34431. );
  34432. },
  34433. /**
  34434. * @private
  34435. */
  34436. _onHandleDragMove: function (dx, dy) {
  34437. var handle = this._handle;
  34438. if (!handle) {
  34439. return;
  34440. }
  34441. this._dragging = true;
  34442. // Persistent for throttle.
  34443. var trans = this.updateHandleTransform(
  34444. getHandleTransProps(handle),
  34445. [dx, dy],
  34446. this._axisModel,
  34447. this._axisPointerModel
  34448. );
  34449. this._payloadInfo = trans;
  34450. handle.stopAnimation();
  34451. handle.attr(getHandleTransProps(trans));
  34452. inner$8(handle).lastProp = null;
  34453. this._doDispatchAxisPointer();
  34454. },
  34455. /**
  34456. * Throttled method.
  34457. * @private
  34458. */
  34459. _doDispatchAxisPointer: function () {
  34460. var handle = this._handle;
  34461. if (!handle) {
  34462. return;
  34463. }
  34464. var payloadInfo = this._payloadInfo;
  34465. var axisModel = this._axisModel;
  34466. this._api.dispatchAction({
  34467. type: 'updateAxisPointer',
  34468. x: payloadInfo.cursorPoint[0],
  34469. y: payloadInfo.cursorPoint[1],
  34470. tooltipOption: payloadInfo.tooltipOption,
  34471. axesInfo: [{
  34472. axisDim: axisModel.axis.dim,
  34473. axisIndex: axisModel.componentIndex
  34474. }]
  34475. });
  34476. },
  34477. /**
  34478. * @private
  34479. */
  34480. _onHandleDragEnd: function (moveAnimation) {
  34481. this._dragging = false;
  34482. var handle = this._handle;
  34483. if (!handle) {
  34484. return;
  34485. }
  34486. var value = this._axisPointerModel.get('value');
  34487. // Consider snap or categroy axis, handle may be not consistent with
  34488. // axisPointer. So move handle to align the exact value position when
  34489. // drag ended.
  34490. this._moveHandleToValue(value);
  34491. // For the effect: tooltip will be shown when finger holding on handle
  34492. // button, and will be hidden after finger left handle button.
  34493. this._api.dispatchAction({
  34494. type: 'hideTip'
  34495. });
  34496. },
  34497. /**
  34498. * Should be implemenented by sub-class if support `handle`.
  34499. * @protected
  34500. * @param {number} value
  34501. * @param {module:echarts/model/Model} axisModel
  34502. * @param {module:echarts/model/Model} axisPointerModel
  34503. * @return {Object} {position: [x, y], rotation: 0}
  34504. */
  34505. getHandleTransform: null,
  34506. /**
  34507. * * Should be implemenented by sub-class if support `handle`.
  34508. * @protected
  34509. * @param {Object} transform {position, rotation}
  34510. * @param {Array.<number>} delta [dx, dy]
  34511. * @param {module:echarts/model/Model} axisModel
  34512. * @param {module:echarts/model/Model} axisPointerModel
  34513. * @return {Object} {position: [x, y], rotation: 0, cursorPoint: [x, y]}
  34514. */
  34515. updateHandleTransform: null,
  34516. /**
  34517. * @private
  34518. */
  34519. clear: function (api) {
  34520. this._lastValue = null;
  34521. this._lastStatus = null;
  34522. var zr = api.getZr();
  34523. var group = this._group;
  34524. var handle = this._handle;
  34525. if (zr && group) {
  34526. this._lastGraphicKey = null;
  34527. group && zr.remove(group);
  34528. handle && zr.remove(handle);
  34529. this._group = null;
  34530. this._handle = null;
  34531. this._payloadInfo = null;
  34532. }
  34533. },
  34534. /**
  34535. * @protected
  34536. */
  34537. doClear: function () {
  34538. // Implemented by sub-class if necessary.
  34539. },
  34540. /**
  34541. * @protected
  34542. * @param {Array.<number>} xy
  34543. * @param {Array.<number>} wh
  34544. * @param {number} [xDimIndex=0] or 1
  34545. */
  34546. buildLabel: function (xy, wh, xDimIndex) {
  34547. xDimIndex = xDimIndex || 0;
  34548. return {
  34549. x: xy[xDimIndex],
  34550. y: xy[1 - xDimIndex],
  34551. width: wh[xDimIndex],
  34552. height: wh[1 - xDimIndex]
  34553. };
  34554. }
  34555. };
  34556. BaseAxisPointer.prototype.constructor = BaseAxisPointer;
  34557. function updateProps$1(animationModel, moveAnimation, el, props) {
  34558. // Animation optimize.
  34559. if (!propsEqual(inner$8(el).lastProp, props)) {
  34560. inner$8(el).lastProp = props;
  34561. moveAnimation
  34562. ? updateProps(el, props, animationModel)
  34563. : (el.stopAnimation(), el.attr(props));
  34564. }
  34565. }
  34566. function propsEqual(lastProps, newProps) {
  34567. if (isObject$1(lastProps) && isObject$1(newProps)) {
  34568. var equals = true;
  34569. each$1(newProps, function (item, key) {
  34570. equals = equals && propsEqual(lastProps[key], item);
  34571. });
  34572. return !!equals;
  34573. }
  34574. else {
  34575. return lastProps === newProps;
  34576. }
  34577. }
  34578. function updateLabelShowHide(labelEl, axisPointerModel) {
  34579. labelEl[axisPointerModel.get('label.show') ? 'show' : 'hide']();
  34580. }
  34581. function getHandleTransProps(trans) {
  34582. return {
  34583. position: trans.position.slice(),
  34584. rotation: trans.rotation || 0
  34585. };
  34586. }
  34587. function updateMandatoryProps(group, axisPointerModel, silent) {
  34588. var z = axisPointerModel.get('z');
  34589. var zlevel = axisPointerModel.get('zlevel');
  34590. group && group.traverse(function (el) {
  34591. if (el.type !== 'group') {
  34592. z != null && (el.z = z);
  34593. zlevel != null && (el.zlevel = zlevel);
  34594. el.silent = silent;
  34595. }
  34596. });
  34597. }
  34598. enableClassExtend(BaseAxisPointer);
  34599. /**
  34600. * @param {module:echarts/model/Model} axisPointerModel
  34601. */
  34602. function buildElStyle(axisPointerModel) {
  34603. var axisPointerType = axisPointerModel.get('type');
  34604. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  34605. var style;
  34606. if (axisPointerType === 'line') {
  34607. style = styleModel.getLineStyle();
  34608. style.fill = null;
  34609. }
  34610. else if (axisPointerType === 'shadow') {
  34611. style = styleModel.getAreaStyle();
  34612. style.stroke = null;
  34613. }
  34614. return style;
  34615. }
  34616. /**
  34617. * @param {Function} labelPos {align, verticalAlign, position}
  34618. */
  34619. function buildLabelElOption(
  34620. elOption, axisModel, axisPointerModel, api, labelPos
  34621. ) {
  34622. var value = axisPointerModel.get('value');
  34623. var text = getValueLabel(
  34624. value, axisModel.axis, axisModel.ecModel,
  34625. axisPointerModel.get('seriesDataIndices'),
  34626. {
  34627. precision: axisPointerModel.get('label.precision'),
  34628. formatter: axisPointerModel.get('label.formatter')
  34629. }
  34630. );
  34631. var labelModel = axisPointerModel.getModel('label');
  34632. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  34633. var font = labelModel.getFont();
  34634. var textRect = getBoundingRect(text, font);
  34635. var position = labelPos.position;
  34636. var width = textRect.width + paddings[1] + paddings[3];
  34637. var height = textRect.height + paddings[0] + paddings[2];
  34638. // Adjust by align.
  34639. var align = labelPos.align;
  34640. align === 'right' && (position[0] -= width);
  34641. align === 'center' && (position[0] -= width / 2);
  34642. var verticalAlign = labelPos.verticalAlign;
  34643. verticalAlign === 'bottom' && (position[1] -= height);
  34644. verticalAlign === 'middle' && (position[1] -= height / 2);
  34645. // Not overflow ec container
  34646. confineInContainer(position, width, height, api);
  34647. var bgColor = labelModel.get('backgroundColor');
  34648. if (!bgColor || bgColor === 'auto') {
  34649. bgColor = axisModel.get('axisLine.lineStyle.color');
  34650. }
  34651. elOption.label = {
  34652. shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  34653. position: position.slice(),
  34654. // TODO: rich
  34655. style: {
  34656. text: text,
  34657. textFont: font,
  34658. textFill: labelModel.getTextColor(),
  34659. textPosition: 'inside',
  34660. fill: bgColor,
  34661. stroke: labelModel.get('borderColor') || 'transparent',
  34662. lineWidth: labelModel.get('borderWidth') || 0,
  34663. shadowBlur: labelModel.get('shadowBlur'),
  34664. shadowColor: labelModel.get('shadowColor'),
  34665. shadowOffsetX: labelModel.get('shadowOffsetX'),
  34666. shadowOffsetY: labelModel.get('shadowOffsetY')
  34667. },
  34668. // Lable should be over axisPointer.
  34669. z2: 10
  34670. };
  34671. }
  34672. // Do not overflow ec container
  34673. function confineInContainer(position, width, height, api) {
  34674. var viewWidth = api.getWidth();
  34675. var viewHeight = api.getHeight();
  34676. position[0] = Math.min(position[0] + width, viewWidth) - width;
  34677. position[1] = Math.min(position[1] + height, viewHeight) - height;
  34678. position[0] = Math.max(position[0], 0);
  34679. position[1] = Math.max(position[1], 0);
  34680. }
  34681. /**
  34682. * @param {number} value
  34683. * @param {module:echarts/coord/Axis} axis
  34684. * @param {module:echarts/model/Global} ecModel
  34685. * @param {Object} opt
  34686. * @param {Array.<Object>} seriesDataIndices
  34687. * @param {number|string} opt.precision 'auto' or a number
  34688. * @param {string|Function} opt.formatter label formatter
  34689. */
  34690. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  34691. var text = axis.scale.getLabel(
  34692. // If `precision` is set, width can be fixed (like '12.00500'), which
  34693. // helps to debounce when when moving label.
  34694. value, {precision: opt.precision}
  34695. );
  34696. var formatter = opt.formatter;
  34697. if (formatter) {
  34698. var params = {
  34699. value: getAxisRawValue(axis, value),
  34700. seriesData: []
  34701. };
  34702. each$1(seriesDataIndices, function (idxItem) {
  34703. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  34704. var dataIndex = idxItem.dataIndexInside;
  34705. var dataParams = series && series.getDataParams(dataIndex);
  34706. dataParams && params.seriesData.push(dataParams);
  34707. });
  34708. if (isString(formatter)) {
  34709. text = formatter.replace('{value}', text);
  34710. }
  34711. else if (isFunction$1(formatter)) {
  34712. text = formatter(params);
  34713. }
  34714. }
  34715. return text;
  34716. }
  34717. /**
  34718. * @param {module:echarts/coord/Axis} axis
  34719. * @param {number} value
  34720. * @param {Object} layoutInfo {
  34721. * rotation, position, labelOffset, labelDirection, labelMargin
  34722. * }
  34723. */
  34724. function getTransformedPosition (axis, value, layoutInfo) {
  34725. var transform = create$1();
  34726. rotate(transform, transform, layoutInfo.rotation);
  34727. translate(transform, transform, layoutInfo.position);
  34728. return applyTransform$1([
  34729. axis.dataToCoord(value),
  34730. (layoutInfo.labelOffset || 0)
  34731. + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)
  34732. ], transform);
  34733. }
  34734. function buildCartesianSingleLabelElOption(
  34735. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  34736. ) {
  34737. var textLayout = AxisBuilder.innerTextLayout(
  34738. layoutInfo.rotation, 0, layoutInfo.labelDirection
  34739. );
  34740. layoutInfo.labelMargin = axisPointerModel.get('label.margin');
  34741. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  34742. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  34743. align: textLayout.textAlign,
  34744. verticalAlign: textLayout.textVerticalAlign
  34745. });
  34746. }
  34747. /**
  34748. * @param {Array.<number>} p1
  34749. * @param {Array.<number>} p2
  34750. * @param {number} [xDimIndex=0] or 1
  34751. */
  34752. function makeLineShape(p1, p2, xDimIndex) {
  34753. xDimIndex = xDimIndex || 0;
  34754. return {
  34755. x1: p1[xDimIndex],
  34756. y1: p1[1 - xDimIndex],
  34757. x2: p2[xDimIndex],
  34758. y2: p2[1 - xDimIndex]
  34759. };
  34760. }
  34761. /**
  34762. * @param {Array.<number>} xy
  34763. * @param {Array.<number>} wh
  34764. * @param {number} [xDimIndex=0] or 1
  34765. */
  34766. function makeRectShape(xy, wh, xDimIndex) {
  34767. xDimIndex = xDimIndex || 0;
  34768. return {
  34769. x: xy[xDimIndex],
  34770. y: xy[1 - xDimIndex],
  34771. width: wh[xDimIndex],
  34772. height: wh[1 - xDimIndex]
  34773. };
  34774. }
  34775. var CartesianAxisPointer = BaseAxisPointer.extend({
  34776. /**
  34777. * @override
  34778. */
  34779. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  34780. var axis = axisModel.axis;
  34781. var grid = axis.grid;
  34782. var axisPointerType = axisPointerModel.get('type');
  34783. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  34784. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  34785. if (axisPointerType && axisPointerType !== 'none') {
  34786. var elStyle = buildElStyle(axisPointerModel);
  34787. var pointerOption = pointerShapeBuilder[axisPointerType](
  34788. axis, pixelValue, otherExtent, elStyle
  34789. );
  34790. pointerOption.style = elStyle;
  34791. elOption.graphicKey = pointerOption.type;
  34792. elOption.pointer = pointerOption;
  34793. }
  34794. var layoutInfo = layout$1(grid.model, axisModel);
  34795. buildCartesianSingleLabelElOption(
  34796. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  34797. );
  34798. },
  34799. /**
  34800. * @override
  34801. */
  34802. getHandleTransform: function (value, axisModel, axisPointerModel) {
  34803. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  34804. labelInside: false
  34805. });
  34806. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  34807. return {
  34808. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  34809. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  34810. };
  34811. },
  34812. /**
  34813. * @override
  34814. */
  34815. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  34816. var axis = axisModel.axis;
  34817. var grid = axis.grid;
  34818. var axisExtent = axis.getGlobalExtent(true);
  34819. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  34820. var dimIndex = axis.dim === 'x' ? 0 : 1;
  34821. var currPosition = transform.position;
  34822. currPosition[dimIndex] += delta[dimIndex];
  34823. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  34824. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  34825. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  34826. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  34827. cursorPoint[dimIndex] = currPosition[dimIndex];
  34828. // Make tooltip do not overlap axisPointer and in the middle of the grid.
  34829. var tooltipOptions = [{verticalAlign: 'middle'}, {align: 'center'}];
  34830. return {
  34831. position: currPosition,
  34832. rotation: transform.rotation,
  34833. cursorPoint: cursorPoint,
  34834. tooltipOption: tooltipOptions[dimIndex]
  34835. };
  34836. }
  34837. });
  34838. function getCartesian(grid, axis) {
  34839. var opt = {};
  34840. opt[axis.dim + 'AxisIndex'] = axis.index;
  34841. return grid.getCartesian(opt);
  34842. }
  34843. var pointerShapeBuilder = {
  34844. line: function (axis, pixelValue, otherExtent, elStyle) {
  34845. var targetShape = makeLineShape(
  34846. [pixelValue, otherExtent[0]],
  34847. [pixelValue, otherExtent[1]],
  34848. getAxisDimIndex(axis)
  34849. );
  34850. subPixelOptimizeLine({
  34851. shape: targetShape,
  34852. style: elStyle
  34853. });
  34854. return {
  34855. type: 'Line',
  34856. shape: targetShape
  34857. };
  34858. },
  34859. shadow: function (axis, pixelValue, otherExtent, elStyle) {
  34860. var bandWidth = axis.getBandWidth();
  34861. var span = otherExtent[1] - otherExtent[0];
  34862. return {
  34863. type: 'Rect',
  34864. shape: makeRectShape(
  34865. [pixelValue - bandWidth / 2, otherExtent[0]],
  34866. [bandWidth, span],
  34867. getAxisDimIndex(axis)
  34868. )
  34869. };
  34870. }
  34871. };
  34872. function getAxisDimIndex(axis) {
  34873. return axis.dim === 'x' ? 0 : 1;
  34874. }
  34875. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  34876. // CartesianAxisPointer is not supposed to be required here. But consider
  34877. // echarts.simple.js and online build tooltip, which only require gridSimple,
  34878. // CartesianAxisPointer should be able to required somewhere.
  34879. registerPreprocessor(function (option) {
  34880. // Always has a global axisPointerModel for default setting.
  34881. if (option) {
  34882. (!option.axisPointer || option.axisPointer.length === 0)
  34883. && (option.axisPointer = {});
  34884. var link = option.axisPointer.link;
  34885. // Normalize to array to avoid object mergin. But if link
  34886. // is not set, remain null/undefined, otherwise it will
  34887. // override existent link setting.
  34888. if (link && !isArray(link)) {
  34889. option.axisPointer.link = [link];
  34890. }
  34891. }
  34892. });
  34893. // This process should proformed after coordinate systems created
  34894. // and series data processed. So put it on statistic processing stage.
  34895. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  34896. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  34897. // allAxesInfo should be updated when setOption performed.
  34898. ecModel.getComponent('axisPointer').coordSysAxesInfo
  34899. = collect(ecModel, api);
  34900. });
  34901. // Broadcast to all views.
  34902. registerAction({
  34903. type: 'updateAxisPointer',
  34904. event: 'updateAxisPointer',
  34905. update: ':updateAxisPointer'
  34906. }, axisTrigger);
  34907. extendComponentModel({
  34908. type: 'tooltip',
  34909. dependencies: ['axisPointer'],
  34910. defaultOption: {
  34911. zlevel: 0,
  34912. z: 8,
  34913. show: true,
  34914. // tooltip主体内容
  34915. showContent: true,
  34916. // 'trigger' only works on coordinate system.
  34917. // 'item' | 'axis' | 'none'
  34918. trigger: 'item',
  34919. // 'click' | 'mousemove' | 'none'
  34920. triggerOn: 'mousemove|click',
  34921. alwaysShowContent: false,
  34922. displayMode: 'single', // 'single' | 'multipleByCoordSys'
  34923. // 位置 {Array} | {Function}
  34924. // position: null
  34925. // Consider triggered from axisPointer handle, verticalAlign should be 'middle'
  34926. // align: null,
  34927. // verticalAlign: null,
  34928. // 是否约束 content 在 viewRect 中。默认 false 是为了兼容以前版本。
  34929. confine: false,
  34930. // 内容格式器:{string}(Template) ¦ {Function}
  34931. // formatter: null
  34932. showDelay: 0,
  34933. // 隐藏延迟,单位ms
  34934. hideDelay: 100,
  34935. // 动画变换时间,单位s
  34936. transitionDuration: 0.4,
  34937. enterable: false,
  34938. // 提示背景颜色,默认为透明度为0.7的黑色
  34939. backgroundColor: 'rgba(50,50,50,0.7)',
  34940. // 提示边框颜色
  34941. borderColor: '#333',
  34942. // 提示边框圆角,单位px,默认为4
  34943. borderRadius: 4,
  34944. // 提示边框线宽,单位px,默认为0(无边框)
  34945. borderWidth: 0,
  34946. // 提示内边距,单位px,默认各方向内边距为5,
  34947. // 接受数组分别设定上右下左边距,同css
  34948. padding: 5,
  34949. // Extra css text
  34950. extraCssText: '',
  34951. // 坐标轴指示器,坐标轴触发有效
  34952. axisPointer: {
  34953. // 默认为直线
  34954. // 可选为:'line' | 'shadow' | 'cross'
  34955. type: 'line',
  34956. // type 为 line 的时候有效,指定 tooltip line 所在的轴,可选
  34957. // 可选 'x' | 'y' | 'angle' | 'radius' | 'auto'
  34958. // 默认 'auto',会选择类型为 category 的轴,对于双数值轴,笛卡尔坐标系会默认选择 x 轴
  34959. // 极坐标系会默认选择 angle 轴
  34960. axis: 'auto',
  34961. animation: 'auto',
  34962. animationDurationUpdate: 200,
  34963. animationEasingUpdate: 'exponentialOut',
  34964. crossStyle: {
  34965. color: '#999',
  34966. width: 1,
  34967. type: 'dashed',
  34968. // TODO formatter
  34969. textStyle: {}
  34970. }
  34971. // lineStyle and shadowStyle should not be specified here,
  34972. // otherwise it will always override those styles on option.axisPointer.
  34973. },
  34974. textStyle: {
  34975. color: '#fff',
  34976. fontSize: 14
  34977. }
  34978. }
  34979. });
  34980. var each$11 = each$1;
  34981. var toCamelCase$1 = toCamelCase;
  34982. var vendors = ['', '-webkit-', '-moz-', '-o-'];
  34983. var gCssText = 'position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;';
  34984. /**
  34985. * @param {number} duration
  34986. * @return {string}
  34987. * @inner
  34988. */
  34989. function assembleTransition(duration) {
  34990. var transitionCurve = 'cubic-bezier(0.23, 1, 0.32, 1)';
  34991. var transitionText = 'left ' + duration + 's ' + transitionCurve + ','
  34992. + 'top ' + duration + 's ' + transitionCurve;
  34993. return map(vendors, function (vendorPrefix) {
  34994. return vendorPrefix + 'transition:' + transitionText;
  34995. }).join(';');
  34996. }
  34997. /**
  34998. * @param {Object} textStyle
  34999. * @return {string}
  35000. * @inner
  35001. */
  35002. function assembleFont(textStyleModel) {
  35003. var cssText = [];
  35004. var fontSize = textStyleModel.get('fontSize');
  35005. var color = textStyleModel.getTextColor();
  35006. color && cssText.push('color:' + color);
  35007. cssText.push('font:' + textStyleModel.getFont());
  35008. fontSize &&
  35009. cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  35010. each$11(['decoration', 'align'], function (name) {
  35011. var val = textStyleModel.get(name);
  35012. val && cssText.push('text-' + name + ':' + val);
  35013. });
  35014. return cssText.join(';');
  35015. }
  35016. /**
  35017. * @param {Object} tooltipModel
  35018. * @return {string}
  35019. * @inner
  35020. */
  35021. function assembleCssText(tooltipModel) {
  35022. var cssText = [];
  35023. var transitionDuration = tooltipModel.get('transitionDuration');
  35024. var backgroundColor = tooltipModel.get('backgroundColor');
  35025. var textStyleModel = tooltipModel.getModel('textStyle');
  35026. var padding = tooltipModel.get('padding');
  35027. // Animation transition. Do not animate when transitionDuration is 0.
  35028. transitionDuration &&
  35029. cssText.push(assembleTransition(transitionDuration));
  35030. if (backgroundColor) {
  35031. if (env$1.canvasSupported) {
  35032. cssText.push('background-Color:' + backgroundColor);
  35033. }
  35034. else {
  35035. // for ie
  35036. cssText.push(
  35037. 'background-Color:#' + toHex(backgroundColor)
  35038. );
  35039. cssText.push('filter:alpha(opacity=70)');
  35040. }
  35041. }
  35042. // Border style
  35043. each$11(['width', 'color', 'radius'], function (name) {
  35044. var borderName = 'border-' + name;
  35045. var camelCase = toCamelCase$1(borderName);
  35046. var val = tooltipModel.get(camelCase);
  35047. val != null &&
  35048. cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  35049. });
  35050. // Text style
  35051. cssText.push(assembleFont(textStyleModel));
  35052. // Padding
  35053. if (padding != null) {
  35054. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  35055. }
  35056. return cssText.join(';') + ';';
  35057. }
  35058. /**
  35059. * @alias module:echarts/component/tooltip/TooltipContent
  35060. * @constructor
  35061. */
  35062. function TooltipContent(container, api) {
  35063. if (env$1.wxa) {
  35064. return null;
  35065. }
  35066. var el = document.createElement('div');
  35067. var zr = this._zr = api.getZr();
  35068. this.el = el;
  35069. this._x = api.getWidth() / 2;
  35070. this._y = api.getHeight() / 2;
  35071. container.appendChild(el);
  35072. this._container = container;
  35073. this._show = false;
  35074. /**
  35075. * @private
  35076. */
  35077. this._hideTimeout;
  35078. var self = this;
  35079. el.onmouseenter = function () {
  35080. // clear the timeout in hideLater and keep showing tooltip
  35081. if (self._enterable) {
  35082. clearTimeout(self._hideTimeout);
  35083. self._show = true;
  35084. }
  35085. self._inContent = true;
  35086. };
  35087. el.onmousemove = function (e) {
  35088. e = e || window.event;
  35089. if (!self._enterable) {
  35090. // Try trigger zrender event to avoid mouse
  35091. // in and out shape too frequently
  35092. var handler = zr.handler;
  35093. normalizeEvent(container, e, true);
  35094. handler.dispatch('mousemove', e);
  35095. }
  35096. };
  35097. el.onmouseleave = function () {
  35098. if (self._enterable) {
  35099. if (self._show) {
  35100. self.hideLater(self._hideDelay);
  35101. }
  35102. }
  35103. self._inContent = false;
  35104. };
  35105. }
  35106. TooltipContent.prototype = {
  35107. constructor: TooltipContent,
  35108. /**
  35109. * @private
  35110. * @type {boolean}
  35111. */
  35112. _enterable: true,
  35113. /**
  35114. * Update when tooltip is rendered
  35115. */
  35116. update: function () {
  35117. // FIXME
  35118. // Move this logic to ec main?
  35119. var container = this._container;
  35120. var stl = container.currentStyle
  35121. || document.defaultView.getComputedStyle(container);
  35122. var domStyle = container.style;
  35123. if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
  35124. domStyle.position = 'relative';
  35125. }
  35126. // Hide the tooltip
  35127. // PENDING
  35128. // this.hide();
  35129. },
  35130. show: function (tooltipModel) {
  35131. clearTimeout(this._hideTimeout);
  35132. var el = this.el;
  35133. el.style.cssText = gCssText + assembleCssText(tooltipModel)
  35134. // http://stackoverflow.com/questions/21125587/css3-transition-not-working-in-chrome-anymore
  35135. + ';left:' + this._x + 'px;top:' + this._y + 'px;'
  35136. + (tooltipModel.get('extraCssText') || '');
  35137. el.style.display = el.innerHTML ? 'block' : 'none';
  35138. this._show = true;
  35139. },
  35140. setContent: function (content) {
  35141. this.el.innerHTML = content == null ? '' : content;
  35142. },
  35143. setEnterable: function (enterable) {
  35144. this._enterable = enterable;
  35145. },
  35146. getSize: function () {
  35147. var el = this.el;
  35148. return [el.clientWidth, el.clientHeight];
  35149. },
  35150. moveTo: function (x, y) {
  35151. // xy should be based on canvas root. But tooltipContent is
  35152. // the sibling of canvas root. So padding of ec container
  35153. // should be considered here.
  35154. var zr = this._zr;
  35155. var viewportRootOffset;
  35156. if (zr && zr.painter && (viewportRootOffset = zr.painter.getViewportRootOffset())) {
  35157. x += viewportRootOffset.offsetLeft;
  35158. y += viewportRootOffset.offsetTop;
  35159. }
  35160. var style = this.el.style;
  35161. style.left = x + 'px';
  35162. style.top = y + 'px';
  35163. this._x = x;
  35164. this._y = y;
  35165. },
  35166. hide: function () {
  35167. this.el.style.display = 'none';
  35168. this._show = false;
  35169. },
  35170. hideLater: function (time) {
  35171. if (this._show && !(this._inContent && this._enterable)) {
  35172. if (time) {
  35173. this._hideDelay = time;
  35174. // Set show false to avoid invoke hideLater mutiple times
  35175. this._show = false;
  35176. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  35177. }
  35178. else {
  35179. this.hide();
  35180. }
  35181. }
  35182. },
  35183. isShow: function () {
  35184. return this._show;
  35185. }
  35186. };
  35187. var bind$2 = bind;
  35188. var each$10 = each$1;
  35189. var parsePercent$2 = parsePercent$1;
  35190. var proxyRect = new Rect({
  35191. shape: {x: -1, y: -1, width: 2, height: 2}
  35192. });
  35193. extendComponentView({
  35194. type: 'tooltip',
  35195. init: function (ecModel, api) {
  35196. if (env$1.node) {
  35197. return;
  35198. }
  35199. var tooltipContent = new TooltipContent(api.getDom(), api);
  35200. this._tooltipContent = tooltipContent;
  35201. },
  35202. render: function (tooltipModel, ecModel, api) {
  35203. if (env$1.node || env$1.wxa) {
  35204. return;
  35205. }
  35206. // Reset
  35207. this.group.removeAll();
  35208. /**
  35209. * @private
  35210. * @type {module:echarts/component/tooltip/TooltipModel}
  35211. */
  35212. this._tooltipModel = tooltipModel;
  35213. /**
  35214. * @private
  35215. * @type {module:echarts/model/Global}
  35216. */
  35217. this._ecModel = ecModel;
  35218. /**
  35219. * @private
  35220. * @type {module:echarts/ExtensionAPI}
  35221. */
  35222. this._api = api;
  35223. /**
  35224. * Should be cleaned when render.
  35225. * @private
  35226. * @type {Array.<Array.<Object>>}
  35227. */
  35228. this._lastDataByCoordSys = null;
  35229. /**
  35230. * @private
  35231. * @type {boolean}
  35232. */
  35233. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  35234. var tooltipContent = this._tooltipContent;
  35235. tooltipContent.update();
  35236. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  35237. this._initGlobalListener();
  35238. this._keepShow();
  35239. },
  35240. _initGlobalListener: function () {
  35241. var tooltipModel = this._tooltipModel;
  35242. var triggerOn = tooltipModel.get('triggerOn');
  35243. register(
  35244. 'itemTooltip',
  35245. this._api,
  35246. bind$2(function (currTrigger, e, dispatchAction) {
  35247. // If 'none', it is not controlled by mouse totally.
  35248. if (triggerOn !== 'none') {
  35249. if (triggerOn.indexOf(currTrigger) >= 0) {
  35250. this._tryShow(e, dispatchAction);
  35251. }
  35252. else if (currTrigger === 'leave') {
  35253. this._hide(dispatchAction);
  35254. }
  35255. }
  35256. }, this)
  35257. );
  35258. },
  35259. _keepShow: function () {
  35260. var tooltipModel = this._tooltipModel;
  35261. var ecModel = this._ecModel;
  35262. var api = this._api;
  35263. // Try to keep the tooltip show when refreshing
  35264. if (this._lastX != null
  35265. && this._lastY != null
  35266. // When user is willing to control tooltip totally using API,
  35267. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  35268. // which is not expected.
  35269. && tooltipModel.get('triggerOn') !== 'none'
  35270. ) {
  35271. var self = this;
  35272. clearTimeout(this._refreshUpdateTimeout);
  35273. this._refreshUpdateTimeout = setTimeout(function () {
  35274. // Show tip next tick after other charts are rendered
  35275. // In case highlight action has wrong result
  35276. // FIXME
  35277. self.manuallyShowTip(tooltipModel, ecModel, api, {
  35278. x: self._lastX,
  35279. y: self._lastY
  35280. });
  35281. });
  35282. }
  35283. },
  35284. /**
  35285. * Show tip manually by
  35286. * dispatchAction({
  35287. * type: 'showTip',
  35288. * x: 10,
  35289. * y: 10
  35290. * });
  35291. * Or
  35292. * dispatchAction({
  35293. * type: 'showTip',
  35294. * seriesIndex: 0,
  35295. * dataIndex or dataIndexInside or name
  35296. * });
  35297. *
  35298. * TODO Batch
  35299. */
  35300. manuallyShowTip: function (tooltipModel, ecModel, api, payload) {
  35301. if (payload.from === this.uid || env$1.node) {
  35302. return;
  35303. }
  35304. var dispatchAction = makeDispatchAction$1(payload, api);
  35305. // Reset ticket
  35306. this._ticket = '';
  35307. // When triggered from axisPointer.
  35308. var dataByCoordSys = payload.dataByCoordSys;
  35309. if (payload.tooltip && payload.x != null && payload.y != null) {
  35310. var el = proxyRect;
  35311. el.position = [payload.x, payload.y];
  35312. el.update();
  35313. el.tooltip = payload.tooltip;
  35314. // Manually show tooltip while view is not using zrender elements.
  35315. this._tryShow({
  35316. offsetX: payload.x,
  35317. offsetY: payload.y,
  35318. target: el
  35319. }, dispatchAction);
  35320. }
  35321. else if (dataByCoordSys) {
  35322. this._tryShow({
  35323. offsetX: payload.x,
  35324. offsetY: payload.y,
  35325. position: payload.position,
  35326. event: {},
  35327. dataByCoordSys: payload.dataByCoordSys,
  35328. tooltipOption: payload.tooltipOption
  35329. }, dispatchAction);
  35330. }
  35331. else if (payload.seriesIndex != null) {
  35332. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  35333. return;
  35334. }
  35335. var pointInfo = findPointFromSeries(payload, ecModel);
  35336. var cx = pointInfo.point[0];
  35337. var cy = pointInfo.point[1];
  35338. if (cx != null && cy != null) {
  35339. this._tryShow({
  35340. offsetX: cx,
  35341. offsetY: cy,
  35342. position: payload.position,
  35343. target: pointInfo.el,
  35344. event: {}
  35345. }, dispatchAction);
  35346. }
  35347. }
  35348. else if (payload.x != null && payload.y != null) {
  35349. // FIXME
  35350. // should wrap dispatchAction like `axisPointer/globalListener` ?
  35351. api.dispatchAction({
  35352. type: 'updateAxisPointer',
  35353. x: payload.x,
  35354. y: payload.y
  35355. });
  35356. this._tryShow({
  35357. offsetX: payload.x,
  35358. offsetY: payload.y,
  35359. position: payload.position,
  35360. target: api.getZr().findHover(payload.x, payload.y).target,
  35361. event: {}
  35362. }, dispatchAction);
  35363. }
  35364. },
  35365. manuallyHideTip: function (tooltipModel, ecModel, api, payload) {
  35366. var tooltipContent = this._tooltipContent;
  35367. if (!this._alwaysShowContent && this._tooltipModel) {
  35368. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  35369. }
  35370. this._lastX = this._lastY = null;
  35371. if (payload.from !== this.uid) {
  35372. this._hide(makeDispatchAction$1(payload, api));
  35373. }
  35374. },
  35375. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  35376. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  35377. // and tooltip.
  35378. _manuallyAxisShowTip: function (tooltipModel, ecModel, api, payload) {
  35379. var seriesIndex = payload.seriesIndex;
  35380. var dataIndex = payload.dataIndex;
  35381. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  35382. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  35383. return;
  35384. }
  35385. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  35386. if (!seriesModel) {
  35387. return;
  35388. }
  35389. var data = seriesModel.getData();
  35390. var tooltipModel = buildTooltipModel([
  35391. data.getItemModel(dataIndex),
  35392. seriesModel,
  35393. (seriesModel.coordinateSystem || {}).model,
  35394. tooltipModel
  35395. ]);
  35396. if (tooltipModel.get('trigger') !== 'axis') {
  35397. return;
  35398. }
  35399. api.dispatchAction({
  35400. type: 'updateAxisPointer',
  35401. seriesIndex: seriesIndex,
  35402. dataIndex: dataIndex,
  35403. position: payload.position
  35404. });
  35405. return true;
  35406. },
  35407. _tryShow: function (e, dispatchAction) {
  35408. var el = e.target;
  35409. var tooltipModel = this._tooltipModel;
  35410. if (!tooltipModel) {
  35411. return;
  35412. }
  35413. // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  35414. this._lastX = e.offsetX;
  35415. this._lastY = e.offsetY;
  35416. var dataByCoordSys = e.dataByCoordSys;
  35417. if (dataByCoordSys && dataByCoordSys.length) {
  35418. this._showAxisTooltip(dataByCoordSys, e);
  35419. }
  35420. // Always show item tooltip if mouse is on the element with dataIndex
  35421. else if (el && el.dataIndex != null) {
  35422. this._lastDataByCoordSys = null;
  35423. this._showSeriesItemTooltip(e, el, dispatchAction);
  35424. }
  35425. // Tooltip provided directly. Like legend.
  35426. else if (el && el.tooltip) {
  35427. this._lastDataByCoordSys = null;
  35428. this._showComponentItemTooltip(e, el, dispatchAction);
  35429. }
  35430. else {
  35431. this._lastDataByCoordSys = null;
  35432. this._hide(dispatchAction);
  35433. }
  35434. },
  35435. _showOrMove: function (tooltipModel, cb) {
  35436. // showDelay is used in this case: tooltip.enterable is set
  35437. // as true. User intent to move mouse into tooltip and click
  35438. // something. `showDelay` makes it easyer to enter the content
  35439. // but tooltip do not move immediately.
  35440. var delay = tooltipModel.get('showDelay');
  35441. cb = bind(cb, this);
  35442. clearTimeout(this._showTimout);
  35443. delay > 0
  35444. ? (this._showTimout = setTimeout(cb, delay))
  35445. : cb();
  35446. },
  35447. _showAxisTooltip: function (dataByCoordSys, e) {
  35448. var ecModel = this._ecModel;
  35449. var globalTooltipModel = this._tooltipModel;
  35450. var point = [e.offsetX, e.offsetY];
  35451. var singleDefaultHTML = [];
  35452. var singleParamsList = [];
  35453. var singleTooltipModel = buildTooltipModel([
  35454. e.tooltipOption,
  35455. globalTooltipModel
  35456. ]);
  35457. each$10(dataByCoordSys, function (itemCoordSys) {
  35458. // var coordParamList = [];
  35459. // var coordDefaultHTML = [];
  35460. // var coordTooltipModel = buildTooltipModel([
  35461. // e.tooltipOption,
  35462. // itemCoordSys.tooltipOption,
  35463. // ecModel.getComponent(itemCoordSys.coordSysMainType, itemCoordSys.coordSysIndex),
  35464. // globalTooltipModel
  35465. // ]);
  35466. // var displayMode = coordTooltipModel.get('displayMode');
  35467. // var paramsList = displayMode === 'single' ? singleParamsList : [];
  35468. each$10(itemCoordSys.dataByAxis, function (item) {
  35469. var axisModel = ecModel.getComponent(item.axisDim + 'Axis', item.axisIndex);
  35470. var axisValue = item.value;
  35471. var seriesDefaultHTML = [];
  35472. if (!axisModel || axisValue == null) {
  35473. return;
  35474. }
  35475. var valueLabel = getValueLabel(
  35476. axisValue, axisModel.axis, ecModel,
  35477. item.seriesDataIndices,
  35478. item.valueLabelOpt
  35479. );
  35480. each$1(item.seriesDataIndices, function (idxItem) {
  35481. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  35482. var dataIndex = idxItem.dataIndexInside;
  35483. var dataParams = series && series.getDataParams(dataIndex);
  35484. dataParams.axisDim = item.axisDim;
  35485. dataParams.axisIndex = item.axisIndex;
  35486. dataParams.axisType = item.axisType;
  35487. dataParams.axisId = item.axisId;
  35488. dataParams.axisValue = getAxisRawValue(axisModel.axis, axisValue);
  35489. dataParams.axisValueLabel = valueLabel;
  35490. if (dataParams) {
  35491. singleParamsList.push(dataParams);
  35492. seriesDefaultHTML.push(series.formatTooltip(dataIndex, true));
  35493. }
  35494. });
  35495. // Default tooltip content
  35496. // FIXME
  35497. // (1) shold be the first data which has name?
  35498. // (2) themeRiver, firstDataIndex is array, and first line is unnecessary.
  35499. var firstLine = valueLabel;
  35500. singleDefaultHTML.push(
  35501. (firstLine ? encodeHTML(firstLine) + '<br />' : '')
  35502. + seriesDefaultHTML.join('<br />')
  35503. );
  35504. });
  35505. }, this);
  35506. // In most case, the second axis is shown upper than the first one.
  35507. singleDefaultHTML.reverse();
  35508. singleDefaultHTML = singleDefaultHTML.join('<br /><br />');
  35509. var positionExpr = e.position;
  35510. this._showOrMove(singleTooltipModel, function () {
  35511. if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
  35512. this._updatePosition(
  35513. singleTooltipModel,
  35514. positionExpr,
  35515. point[0], point[1],
  35516. this._tooltipContent,
  35517. singleParamsList
  35518. );
  35519. }
  35520. else {
  35521. this._showTooltipContent(
  35522. singleTooltipModel, singleDefaultHTML, singleParamsList, Math.random(),
  35523. point[0], point[1], positionExpr
  35524. );
  35525. }
  35526. });
  35527. // Do not trigger events here, because this branch only be entered
  35528. // from dispatchAction.
  35529. },
  35530. _showSeriesItemTooltip: function (e, el, dispatchAction) {
  35531. var ecModel = this._ecModel;
  35532. // Use dataModel in element if possible
  35533. // Used when mouseover on a element like markPoint or edge
  35534. // In which case, the data is not main data in series.
  35535. var seriesIndex = el.seriesIndex;
  35536. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  35537. // For example, graph link.
  35538. var dataModel = el.dataModel || seriesModel;
  35539. var dataIndex = el.dataIndex;
  35540. var dataType = el.dataType;
  35541. var data = dataModel.getData();
  35542. var tooltipModel = buildTooltipModel([
  35543. data.getItemModel(dataIndex),
  35544. dataModel,
  35545. seriesModel && (seriesModel.coordinateSystem || {}).model,
  35546. this._tooltipModel
  35547. ]);
  35548. var tooltipTrigger = tooltipModel.get('trigger');
  35549. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  35550. return;
  35551. }
  35552. var params = dataModel.getDataParams(dataIndex, dataType);
  35553. var defaultHtml = dataModel.formatTooltip(dataIndex, false, dataType);
  35554. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  35555. this._showOrMove(tooltipModel, function () {
  35556. this._showTooltipContent(
  35557. tooltipModel, defaultHtml, params, asyncTicket,
  35558. e.offsetX, e.offsetY, e.position, e.target
  35559. );
  35560. });
  35561. // FIXME
  35562. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  35563. dispatchAction({
  35564. type: 'showTip',
  35565. dataIndexInside: dataIndex,
  35566. dataIndex: data.getRawIndex(dataIndex),
  35567. seriesIndex: seriesIndex,
  35568. from: this.uid
  35569. });
  35570. },
  35571. _showComponentItemTooltip: function (e, el, dispatchAction) {
  35572. var tooltipOpt = el.tooltip;
  35573. if (typeof tooltipOpt === 'string') {
  35574. var content = tooltipOpt;
  35575. tooltipOpt = {
  35576. content: content,
  35577. // Fixed formatter
  35578. formatter: content
  35579. };
  35580. }
  35581. var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
  35582. var defaultHtml = subTooltipModel.get('content');
  35583. var asyncTicket = Math.random();
  35584. // Do not check whether `trigger` is 'none' here, because `trigger`
  35585. // only works on cooridinate system. In fact, we have not found case
  35586. // that requires setting `trigger` nothing on component yet.
  35587. this._showOrMove(subTooltipModel, function () {
  35588. this._showTooltipContent(
  35589. subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {},
  35590. asyncTicket, e.offsetX, e.offsetY, e.position, el
  35591. );
  35592. });
  35593. // If not dispatch showTip, tip may be hide triggered by axis.
  35594. dispatchAction({
  35595. type: 'showTip',
  35596. from: this.uid
  35597. });
  35598. },
  35599. _showTooltipContent: function (
  35600. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el
  35601. ) {
  35602. // Reset ticket
  35603. this._ticket = '';
  35604. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  35605. return;
  35606. }
  35607. var tooltipContent = this._tooltipContent;
  35608. var formatter = tooltipModel.get('formatter');
  35609. positionExpr = positionExpr || tooltipModel.get('position');
  35610. var html = defaultHtml;
  35611. if (formatter && typeof formatter === 'string') {
  35612. html = formatTpl(formatter, params, true);
  35613. }
  35614. else if (typeof formatter === 'function') {
  35615. var callback = bind$2(function (cbTicket, html) {
  35616. if (cbTicket === this._ticket) {
  35617. tooltipContent.setContent(html);
  35618. this._updatePosition(
  35619. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  35620. );
  35621. }
  35622. }, this);
  35623. this._ticket = asyncTicket;
  35624. html = formatter(params, asyncTicket, callback);
  35625. }
  35626. tooltipContent.setContent(html);
  35627. tooltipContent.show(tooltipModel);
  35628. this._updatePosition(
  35629. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  35630. );
  35631. },
  35632. /**
  35633. * @param {string|Function|Array.<number>|Object} positionExpr
  35634. * @param {number} x Mouse x
  35635. * @param {number} y Mouse y
  35636. * @param {boolean} confine Whether confine tooltip content in view rect.
  35637. * @param {Object|<Array.<Object>} params
  35638. * @param {module:zrender/Element} el target element
  35639. * @param {module:echarts/ExtensionAPI} api
  35640. * @return {Array.<number>}
  35641. */
  35642. _updatePosition: function (tooltipModel, positionExpr, x, y, content, params, el) {
  35643. var viewWidth = this._api.getWidth();
  35644. var viewHeight = this._api.getHeight();
  35645. positionExpr = positionExpr || tooltipModel.get('position');
  35646. var contentSize = content.getSize();
  35647. var align = tooltipModel.get('align');
  35648. var vAlign = tooltipModel.get('verticalAlign');
  35649. var rect = el && el.getBoundingRect().clone();
  35650. el && rect.applyTransform(el.transform);
  35651. if (typeof positionExpr === 'function') {
  35652. // Callback of position can be an array or a string specify the position
  35653. positionExpr = positionExpr([x, y], params, content.el, rect, {
  35654. viewSize: [viewWidth, viewHeight],
  35655. contentSize: contentSize.slice()
  35656. });
  35657. }
  35658. if (isArray(positionExpr)) {
  35659. x = parsePercent$2(positionExpr[0], viewWidth);
  35660. y = parsePercent$2(positionExpr[1], viewHeight);
  35661. }
  35662. else if (isObject$1(positionExpr)) {
  35663. positionExpr.width = contentSize[0];
  35664. positionExpr.height = contentSize[1];
  35665. var layoutRect = getLayoutRect(
  35666. positionExpr, {width: viewWidth, height: viewHeight}
  35667. );
  35668. x = layoutRect.x;
  35669. y = layoutRect.y;
  35670. align = null;
  35671. // When positionExpr is left/top/right/bottom,
  35672. // align and verticalAlign will not work.
  35673. vAlign = null;
  35674. }
  35675. // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  35676. else if (typeof positionExpr === 'string' && el) {
  35677. var pos = calcTooltipPosition(
  35678. positionExpr, rect, contentSize
  35679. );
  35680. x = pos[0];
  35681. y = pos[1];
  35682. }
  35683. else {
  35684. var pos = refixTooltipPosition(
  35685. x, y, content.el, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20
  35686. );
  35687. x = pos[0];
  35688. y = pos[1];
  35689. }
  35690. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  35691. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  35692. if (tooltipModel.get('confine')) {
  35693. var pos = confineTooltipPosition(
  35694. x, y, content.el, viewWidth, viewHeight
  35695. );
  35696. x = pos[0];
  35697. y = pos[1];
  35698. }
  35699. content.moveTo(x, y);
  35700. },
  35701. // FIXME
  35702. // Should we remove this but leave this to user?
  35703. _updateContentNotChangedOnAxis: function (dataByCoordSys) {
  35704. var lastCoordSys = this._lastDataByCoordSys;
  35705. var contentNotChanged = !!lastCoordSys
  35706. && lastCoordSys.length === dataByCoordSys.length;
  35707. contentNotChanged && each$10(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  35708. var lastDataByAxis = lastItemCoordSys.dataByAxis || {};
  35709. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  35710. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  35711. contentNotChanged &= lastDataByAxis.length === thisDataByAxis.length;
  35712. contentNotChanged && each$10(lastDataByAxis, function (lastItem, indexAxis) {
  35713. var thisItem = thisDataByAxis[indexAxis] || {};
  35714. var lastIndices = lastItem.seriesDataIndices || [];
  35715. var newIndices = thisItem.seriesDataIndices || [];
  35716. contentNotChanged &=
  35717. lastItem.value === thisItem.value
  35718. && lastItem.axisType === thisItem.axisType
  35719. && lastItem.axisId === thisItem.axisId
  35720. && lastIndices.length === newIndices.length;
  35721. contentNotChanged && each$10(lastIndices, function (lastIdxItem, j) {
  35722. var newIdxItem = newIndices[j];
  35723. contentNotChanged &=
  35724. lastIdxItem.seriesIndex === newIdxItem.seriesIndex
  35725. && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  35726. });
  35727. });
  35728. });
  35729. this._lastDataByCoordSys = dataByCoordSys;
  35730. return !!contentNotChanged;
  35731. },
  35732. _hide: function (dispatchAction) {
  35733. // Do not directly hideLater here, because this behavior may be prevented
  35734. // in dispatchAction when showTip is dispatched.
  35735. // FIXME
  35736. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  35737. this._lastDataByCoordSys = null;
  35738. dispatchAction({
  35739. type: 'hideTip',
  35740. from: this.uid
  35741. });
  35742. },
  35743. dispose: function (ecModel, api) {
  35744. if (env$1.node) {
  35745. return;
  35746. }
  35747. this._tooltipContent.hide();
  35748. unregister('itemTooltip', api);
  35749. }
  35750. });
  35751. /**
  35752. * @param {Array.<Object|module:echarts/model/Model>} modelCascade
  35753. * From top to bottom. (the last one should be globalTooltipModel);
  35754. */
  35755. function buildTooltipModel(modelCascade) {
  35756. var resultModel = modelCascade.pop();
  35757. while (modelCascade.length) {
  35758. var tooltipOpt = modelCascade.pop();
  35759. if (tooltipOpt) {
  35760. if (Model.isInstance(tooltipOpt)) {
  35761. tooltipOpt = tooltipOpt.get('tooltip', true);
  35762. }
  35763. // In each data item tooltip can be simply write:
  35764. // {
  35765. // value: 10,
  35766. // tooltip: 'Something you need to know'
  35767. // }
  35768. if (typeof tooltipOpt === 'string') {
  35769. tooltipOpt = {formatter: tooltipOpt};
  35770. }
  35771. resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
  35772. }
  35773. }
  35774. return resultModel;
  35775. }
  35776. function makeDispatchAction$1(payload, api) {
  35777. return payload.dispatchAction || bind(api.dispatchAction, api);
  35778. }
  35779. function refixTooltipPosition(x, y, el, viewWidth, viewHeight, gapH, gapV) {
  35780. var size = getOuterSize(el);
  35781. var width = size.width;
  35782. var height = size.height;
  35783. if (gapH != null) {
  35784. if (x + width + gapH > viewWidth) {
  35785. x -= width + gapH;
  35786. }
  35787. else {
  35788. x += gapH;
  35789. }
  35790. }
  35791. if (gapV != null) {
  35792. if (y + height + gapV > viewHeight) {
  35793. y -= height + gapV;
  35794. }
  35795. else {
  35796. y += gapV;
  35797. }
  35798. }
  35799. return [x, y];
  35800. }
  35801. function confineTooltipPosition(x, y, el, viewWidth, viewHeight) {
  35802. var size = getOuterSize(el);
  35803. var width = size.width;
  35804. var height = size.height;
  35805. x = Math.min(x + width, viewWidth) - width;
  35806. y = Math.min(y + height, viewHeight) - height;
  35807. x = Math.max(x, 0);
  35808. y = Math.max(y, 0);
  35809. return [x, y];
  35810. }
  35811. function getOuterSize(el) {
  35812. var width = el.clientWidth;
  35813. var height = el.clientHeight;
  35814. // Consider browser compatibility.
  35815. // IE8 does not support getComputedStyle.
  35816. if (document.defaultView && document.defaultView.getComputedStyle) {
  35817. var stl = document.defaultView.getComputedStyle(el);
  35818. if (stl) {
  35819. width += parseInt(stl.paddingLeft, 10) + parseInt(stl.paddingRight, 10)
  35820. + parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10);
  35821. height += parseInt(stl.paddingTop, 10) + parseInt(stl.paddingBottom, 10)
  35822. + parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10);
  35823. }
  35824. }
  35825. return {width: width, height: height};
  35826. }
  35827. function calcTooltipPosition(position, rect, contentSize) {
  35828. var domWidth = contentSize[0];
  35829. var domHeight = contentSize[1];
  35830. var gap = 5;
  35831. var x = 0;
  35832. var y = 0;
  35833. var rectWidth = rect.width;
  35834. var rectHeight = rect.height;
  35835. switch (position) {
  35836. case 'inside':
  35837. x = rect.x + rectWidth / 2 - domWidth / 2;
  35838. y = rect.y + rectHeight / 2 - domHeight / 2;
  35839. break;
  35840. case 'top':
  35841. x = rect.x + rectWidth / 2 - domWidth / 2;
  35842. y = rect.y - domHeight - gap;
  35843. break;
  35844. case 'bottom':
  35845. x = rect.x + rectWidth / 2 - domWidth / 2;
  35846. y = rect.y + rectHeight + gap;
  35847. break;
  35848. case 'left':
  35849. x = rect.x - domWidth - gap;
  35850. y = rect.y + rectHeight / 2 - domHeight / 2;
  35851. break;
  35852. case 'right':
  35853. x = rect.x + rectWidth + gap;
  35854. y = rect.y + rectHeight / 2 - domHeight / 2;
  35855. }
  35856. return [x, y];
  35857. }
  35858. function isCenterAlign(align) {
  35859. return align === 'center' || align === 'middle';
  35860. }
  35861. // FIXME Better way to pack data in graphic element
  35862. /**
  35863. * @action
  35864. * @property {string} type
  35865. * @property {number} seriesIndex
  35866. * @property {number} dataIndex
  35867. * @property {number} [x]
  35868. * @property {number} [y]
  35869. */
  35870. registerAction(
  35871. {
  35872. type: 'showTip',
  35873. event: 'showTip',
  35874. update: 'tooltip:manuallyShowTip'
  35875. },
  35876. // noop
  35877. function () {}
  35878. );
  35879. registerAction(
  35880. {
  35881. type: 'hideTip',
  35882. event: 'hideTip',
  35883. update: 'tooltip:manuallyHideTip'
  35884. },
  35885. // noop
  35886. function () {}
  35887. );
  35888. var LegendModel = extendComponentModel({
  35889. type: 'legend.plain',
  35890. dependencies: ['series'],
  35891. layoutMode: {
  35892. type: 'box',
  35893. // legend.width/height are maxWidth/maxHeight actually,
  35894. // whereas realy width/height is calculated by its content.
  35895. // (Setting {left: 10, right: 10} does not make sense).
  35896. // So consider the case:
  35897. // `setOption({legend: {left: 10});`
  35898. // then `setOption({legend: {right: 10});`
  35899. // The previous `left` should be cleared by setting `ignoreSize`.
  35900. ignoreSize: true
  35901. },
  35902. init: function (option, parentModel, ecModel) {
  35903. this.mergeDefaultAndTheme(option, ecModel);
  35904. option.selected = option.selected || {};
  35905. },
  35906. mergeOption: function (option) {
  35907. LegendModel.superCall(this, 'mergeOption', option);
  35908. },
  35909. optionUpdated: function () {
  35910. this._updateData(this.ecModel);
  35911. var legendData = this._data;
  35912. // If selectedMode is single, try to select one
  35913. if (legendData[0] && this.get('selectedMode') === 'single') {
  35914. var hasSelected = false;
  35915. // If has any selected in option.selected
  35916. for (var i = 0; i < legendData.length; i++) {
  35917. var name = legendData[i].get('name');
  35918. if (this.isSelected(name)) {
  35919. // Force to unselect others
  35920. this.select(name);
  35921. hasSelected = true;
  35922. break;
  35923. }
  35924. }
  35925. // Try select the first if selectedMode is single
  35926. !hasSelected && this.select(legendData[0].get('name'));
  35927. }
  35928. },
  35929. _updateData: function (ecModel) {
  35930. var potentialData = [];
  35931. var availableNames = [];
  35932. ecModel.eachRawSeries(function (seriesModel) {
  35933. var seriesName = seriesModel.name;
  35934. availableNames.push(seriesName);
  35935. var isPotential;
  35936. if (seriesModel.legendDataProvider) {
  35937. var data = seriesModel.legendDataProvider();
  35938. var names = data.mapArray(data.getName);
  35939. if (!ecModel.isSeriesFiltered(seriesModel)) {
  35940. availableNames = availableNames.concat(names);
  35941. }
  35942. if (names.length) {
  35943. potentialData = potentialData.concat(names);
  35944. }
  35945. else {
  35946. isPotential = true;
  35947. }
  35948. }
  35949. else {
  35950. isPotential = true;
  35951. }
  35952. if (isPotential && isNameSpecified(seriesModel)) {
  35953. potentialData.push(seriesModel.name);
  35954. }
  35955. });
  35956. /**
  35957. * @type {Array.<string>}
  35958. * @private
  35959. */
  35960. this._availableNames = availableNames;
  35961. // If legend.data not specified in option, use availableNames as data,
  35962. // which is convinient for user preparing option.
  35963. var rawData = this.get('data') || potentialData;
  35964. var legendData = map(rawData, function (dataItem) {
  35965. // Can be string or number
  35966. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  35967. dataItem = {
  35968. name: dataItem
  35969. };
  35970. }
  35971. return new Model(dataItem, this, this.ecModel);
  35972. }, this);
  35973. /**
  35974. * @type {Array.<module:echarts/model/Model>}
  35975. * @private
  35976. */
  35977. this._data = legendData;
  35978. },
  35979. /**
  35980. * @return {Array.<module:echarts/model/Model>}
  35981. */
  35982. getData: function () {
  35983. return this._data;
  35984. },
  35985. /**
  35986. * @param {string} name
  35987. */
  35988. select: function (name) {
  35989. var selected = this.option.selected;
  35990. var selectedMode = this.get('selectedMode');
  35991. if (selectedMode === 'single') {
  35992. var data = this._data;
  35993. each$1(data, function (dataItem) {
  35994. selected[dataItem.get('name')] = false;
  35995. });
  35996. }
  35997. selected[name] = true;
  35998. },
  35999. /**
  36000. * @param {string} name
  36001. */
  36002. unSelect: function (name) {
  36003. if (this.get('selectedMode') !== 'single') {
  36004. this.option.selected[name] = false;
  36005. }
  36006. },
  36007. /**
  36008. * @param {string} name
  36009. */
  36010. toggleSelected: function (name) {
  36011. var selected = this.option.selected;
  36012. // Default is true
  36013. if (!selected.hasOwnProperty(name)) {
  36014. selected[name] = true;
  36015. }
  36016. this[selected[name] ? 'unSelect' : 'select'](name);
  36017. },
  36018. /**
  36019. * @param {string} name
  36020. */
  36021. isSelected: function (name) {
  36022. var selected = this.option.selected;
  36023. return !(selected.hasOwnProperty(name) && !selected[name])
  36024. && indexOf(this._availableNames, name) >= 0;
  36025. },
  36026. defaultOption: {
  36027. // 一级层叠
  36028. zlevel: 0,
  36029. // 二级层叠
  36030. z: 4,
  36031. show: true,
  36032. // 布局方式,默认为水平布局,可选为:
  36033. // 'horizontal' | 'vertical'
  36034. orient: 'horizontal',
  36035. left: 'center',
  36036. // right: 'center',
  36037. top: 0,
  36038. // bottom: null,
  36039. // 水平对齐
  36040. // 'auto' | 'left' | 'right'
  36041. // 默认为 'auto', 根据 x 的位置判断是左对齐还是右对齐
  36042. align: 'auto',
  36043. backgroundColor: 'rgba(0,0,0,0)',
  36044. // 图例边框颜色
  36045. borderColor: '#ccc',
  36046. borderRadius: 0,
  36047. // 图例边框线宽,单位px,默认为0(无边框)
  36048. borderWidth: 0,
  36049. // 图例内边距,单位px,默认各方向内边距为5,
  36050. // 接受数组分别设定上右下左边距,同css
  36051. padding: 5,
  36052. // 各个item之间的间隔,单位px,默认为10,
  36053. // 横向布局时为水平间隔,纵向布局时为纵向间隔
  36054. itemGap: 10,
  36055. // 图例图形宽度
  36056. itemWidth: 25,
  36057. // 图例图形高度
  36058. itemHeight: 14,
  36059. // 图例关闭时候的颜色
  36060. inactiveColor: '#ccc',
  36061. textStyle: {
  36062. // 图例文字颜色
  36063. color: '#333'
  36064. },
  36065. // formatter: '',
  36066. // 选择模式,默认开启图例开关
  36067. selectedMode: true,
  36068. // 配置默认选中状态,可配合LEGEND.SELECTED事件做动态数据载入
  36069. // selected: null,
  36070. // 图例内容(详见legend.data,数组中每一项代表一个item
  36071. // data: [],
  36072. // Tooltip 相关配置
  36073. tooltip: {
  36074. show: false
  36075. }
  36076. }
  36077. });
  36078. function legendSelectActionHandler(methodName, payload, ecModel) {
  36079. var selectedMap = {};
  36080. var isToggleSelect = methodName === 'toggleSelected';
  36081. var isSelected;
  36082. // Update all legend components
  36083. ecModel.eachComponent('legend', function (legendModel) {
  36084. if (isToggleSelect && isSelected != null) {
  36085. // Force other legend has same selected status
  36086. // Or the first is toggled to true and other are toggled to false
  36087. // In the case one legend has some item unSelected in option. And if other legend
  36088. // doesn't has the item, they will assume it is selected.
  36089. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  36090. }
  36091. else {
  36092. legendModel[methodName](payload.name);
  36093. isSelected = legendModel.isSelected(payload.name);
  36094. }
  36095. var legendData = legendModel.getData();
  36096. each$1(legendData, function (model) {
  36097. var name = model.get('name');
  36098. // Wrap element
  36099. if (name === '\n' || name === '') {
  36100. return;
  36101. }
  36102. var isItemSelected = legendModel.isSelected(name);
  36103. if (selectedMap.hasOwnProperty(name)) {
  36104. // Unselected if any legend is unselected
  36105. selectedMap[name] = selectedMap[name] && isItemSelected;
  36106. }
  36107. else {
  36108. selectedMap[name] = isItemSelected;
  36109. }
  36110. });
  36111. });
  36112. // Return the event explicitly
  36113. return {
  36114. name: payload.name,
  36115. selected: selectedMap
  36116. };
  36117. }
  36118. /**
  36119. * @event legendToggleSelect
  36120. * @type {Object}
  36121. * @property {string} type 'legendToggleSelect'
  36122. * @property {string} [from]
  36123. * @property {string} name Series name or data item name
  36124. */
  36125. registerAction(
  36126. 'legendToggleSelect', 'legendselectchanged',
  36127. curry(legendSelectActionHandler, 'toggleSelected')
  36128. );
  36129. /**
  36130. * @event legendSelect
  36131. * @type {Object}
  36132. * @property {string} type 'legendSelect'
  36133. * @property {string} name Series name or data item name
  36134. */
  36135. registerAction(
  36136. 'legendSelect', 'legendselected',
  36137. curry(legendSelectActionHandler, 'select')
  36138. );
  36139. /**
  36140. * @event legendUnSelect
  36141. * @type {Object}
  36142. * @property {string} type 'legendUnSelect'
  36143. * @property {string} name Series name or data item name
  36144. */
  36145. registerAction(
  36146. 'legendUnSelect', 'legendunselected',
  36147. curry(legendSelectActionHandler, 'unSelect')
  36148. );
  36149. /**
  36150. * Layout list like component.
  36151. * It will box layout each items in group of component and then position the whole group in the viewport
  36152. * @param {module:zrender/group/Group} group
  36153. * @param {module:echarts/model/Component} componentModel
  36154. * @param {module:echarts/ExtensionAPI}
  36155. */
  36156. function layout$2(group, componentModel, api) {
  36157. var boxLayoutParams = componentModel.getBoxLayoutParams();
  36158. var padding = componentModel.get('padding');
  36159. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  36160. var rect = getLayoutRect(
  36161. boxLayoutParams,
  36162. viewportSize,
  36163. padding
  36164. );
  36165. box(
  36166. componentModel.get('orient'),
  36167. group,
  36168. componentModel.get('itemGap'),
  36169. rect.width,
  36170. rect.height
  36171. );
  36172. positionElement(
  36173. group,
  36174. boxLayoutParams,
  36175. viewportSize,
  36176. padding
  36177. );
  36178. }
  36179. function makeBackground(rect, componentModel) {
  36180. var padding = normalizeCssArray$1(
  36181. componentModel.get('padding')
  36182. );
  36183. var style = componentModel.getItemStyle(['color', 'opacity']);
  36184. style.fill = componentModel.get('backgroundColor');
  36185. var rect = new Rect({
  36186. shape: {
  36187. x: rect.x - padding[3],
  36188. y: rect.y - padding[0],
  36189. width: rect.width + padding[1] + padding[3],
  36190. height: rect.height + padding[0] + padding[2],
  36191. r: componentModel.get('borderRadius')
  36192. },
  36193. style: style,
  36194. silent: true,
  36195. z2: -1
  36196. });
  36197. // FIXME
  36198. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  36199. // and background rect when setting like `left: 0`, `top: 0`.
  36200. // graphic.subPixelOptimizeRect(rect);
  36201. return rect;
  36202. }
  36203. var curry$3 = curry;
  36204. var each$12 = each$1;
  36205. var Group$2 = Group;
  36206. var LegendView = extendComponentView({
  36207. type: 'legend.plain',
  36208. newlineDisabled: false,
  36209. /**
  36210. * @override
  36211. */
  36212. init: function () {
  36213. /**
  36214. * @private
  36215. * @type {module:zrender/container/Group}
  36216. */
  36217. this.group.add(this._contentGroup = new Group$2());
  36218. /**
  36219. * @private
  36220. * @type {module:zrender/Element}
  36221. */
  36222. this._backgroundEl;
  36223. },
  36224. /**
  36225. * @protected
  36226. */
  36227. getContentGroup: function () {
  36228. return this._contentGroup;
  36229. },
  36230. /**
  36231. * @override
  36232. */
  36233. render: function (legendModel, ecModel, api) {
  36234. this.resetInner();
  36235. if (!legendModel.get('show', true)) {
  36236. return;
  36237. }
  36238. var itemAlign = legendModel.get('align');
  36239. if (!itemAlign || itemAlign === 'auto') {
  36240. itemAlign = (
  36241. legendModel.get('left') === 'right'
  36242. && legendModel.get('orient') === 'vertical'
  36243. ) ? 'right' : 'left';
  36244. }
  36245. this.renderInner(itemAlign, legendModel, ecModel, api);
  36246. // Perform layout.
  36247. var positionInfo = legendModel.getBoxLayoutParams();
  36248. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  36249. var padding = legendModel.get('padding');
  36250. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  36251. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize);
  36252. // Place mainGroup, based on the calculated `mainRect`.
  36253. var layoutRect = getLayoutRect(
  36254. defaults({width: mainRect.width, height: mainRect.height}, positionInfo),
  36255. viewportSize,
  36256. padding
  36257. );
  36258. this.group.attr('position', [layoutRect.x - mainRect.x, layoutRect.y - mainRect.y]);
  36259. // Render background after group is layout.
  36260. this.group.add(
  36261. this._backgroundEl = makeBackground(mainRect, legendModel)
  36262. );
  36263. },
  36264. /**
  36265. * @protected
  36266. */
  36267. resetInner: function () {
  36268. this.getContentGroup().removeAll();
  36269. this._backgroundEl && this.group.remove(this._backgroundEl);
  36270. },
  36271. /**
  36272. * @protected
  36273. */
  36274. renderInner: function (itemAlign, legendModel, ecModel, api) {
  36275. var contentGroup = this.getContentGroup();
  36276. var legendDrawnMap = createHashMap();
  36277. var selectMode = legendModel.get('selectedMode');
  36278. each$12(legendModel.getData(), function (itemModel, dataIndex) {
  36279. var name = itemModel.get('name');
  36280. // Use empty string or \n as a newline string
  36281. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  36282. contentGroup.add(new Group$2({
  36283. newline: true
  36284. }));
  36285. return;
  36286. }
  36287. var seriesModel = ecModel.getSeriesByName(name)[0];
  36288. if (legendDrawnMap.get(name)) {
  36289. // Have been drawed
  36290. return;
  36291. }
  36292. // Series legend
  36293. if (seriesModel) {
  36294. var data = seriesModel.getData();
  36295. var color = data.getVisual('color');
  36296. // If color is a callback function
  36297. if (typeof color === 'function') {
  36298. // Use the first data
  36299. color = color(seriesModel.getDataParams(0));
  36300. }
  36301. // Using rect symbol defaultly
  36302. var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
  36303. var symbolType = data.getVisual('symbol');
  36304. var itemGroup = this._createItem(
  36305. name, dataIndex, itemModel, legendModel,
  36306. legendSymbolType, symbolType,
  36307. itemAlign, color,
  36308. selectMode
  36309. );
  36310. itemGroup.on('click', curry$3(dispatchSelectAction, name, api))
  36311. .on('mouseover', curry$3(dispatchHighlightAction, seriesModel, null, api))
  36312. .on('mouseout', curry$3(dispatchDownplayAction, seriesModel, null, api));
  36313. legendDrawnMap.set(name, true);
  36314. }
  36315. else {
  36316. // Data legend of pie, funnel
  36317. ecModel.eachRawSeries(function (seriesModel) {
  36318. // In case multiple series has same data name
  36319. if (legendDrawnMap.get(name)) {
  36320. return;
  36321. }
  36322. if (seriesModel.legendDataProvider) {
  36323. var data = seriesModel.legendDataProvider();
  36324. var idx = data.indexOfName(name);
  36325. if (idx < 0) {
  36326. return;
  36327. }
  36328. var color = data.getItemVisual(idx, 'color');
  36329. var legendSymbolType = 'roundRect';
  36330. var itemGroup = this._createItem(
  36331. name, dataIndex, itemModel, legendModel,
  36332. legendSymbolType, null,
  36333. itemAlign, color,
  36334. selectMode
  36335. );
  36336. itemGroup.on('click', curry$3(dispatchSelectAction, name, api))
  36337. // FIXME Should not specify the series name
  36338. .on('mouseover', curry$3(dispatchHighlightAction, seriesModel, name, api))
  36339. .on('mouseout', curry$3(dispatchDownplayAction, seriesModel, name, api));
  36340. legendDrawnMap.set(name, true);
  36341. }
  36342. }, this);
  36343. }
  36344. if (__DEV__) {
  36345. if (!legendDrawnMap.get(name)) {
  36346. console.warn(name + ' series not exists. Legend data should be same with series name or data name.');
  36347. }
  36348. }
  36349. }, this);
  36350. },
  36351. _createItem: function (
  36352. name, dataIndex, itemModel, legendModel,
  36353. legendSymbolType, symbolType,
  36354. itemAlign, color, selectMode
  36355. ) {
  36356. var itemWidth = legendModel.get('itemWidth');
  36357. var itemHeight = legendModel.get('itemHeight');
  36358. var inactiveColor = legendModel.get('inactiveColor');
  36359. var isSelected = legendModel.isSelected(name);
  36360. var itemGroup = new Group$2();
  36361. var textStyleModel = itemModel.getModel('textStyle');
  36362. var itemIcon = itemModel.get('icon');
  36363. var tooltipModel = itemModel.getModel('tooltip');
  36364. var legendGlobalTooltipModel = tooltipModel.parentModel;
  36365. // Use user given icon first
  36366. legendSymbolType = itemIcon || legendSymbolType;
  36367. itemGroup.add(createSymbol(
  36368. legendSymbolType,
  36369. 0,
  36370. 0,
  36371. itemWidth,
  36372. itemHeight,
  36373. isSelected ? color : inactiveColor,
  36374. true
  36375. ));
  36376. // Compose symbols
  36377. // PENDING
  36378. if (!itemIcon && symbolType
  36379. // At least show one symbol, can't be all none
  36380. && ((symbolType !== legendSymbolType) || symbolType == 'none')
  36381. ) {
  36382. var size = itemHeight * 0.8;
  36383. if (symbolType === 'none') {
  36384. symbolType = 'circle';
  36385. }
  36386. // Put symbol in the center
  36387. itemGroup.add(createSymbol(
  36388. symbolType, (itemWidth - size) / 2, (itemHeight - size) / 2, size, size,
  36389. isSelected ? color : inactiveColor
  36390. ));
  36391. }
  36392. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  36393. var textAlign = itemAlign;
  36394. var formatter = legendModel.get('formatter');
  36395. var content = name;
  36396. if (typeof formatter === 'string' && formatter) {
  36397. content = formatter.replace('{name}', name != null ? name : '');
  36398. }
  36399. else if (typeof formatter === 'function') {
  36400. content = formatter(name);
  36401. }
  36402. itemGroup.add(new Text({
  36403. style: setTextStyle({}, textStyleModel, {
  36404. text: content,
  36405. x: textX,
  36406. y: itemHeight / 2,
  36407. textFill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  36408. textAlign: textAlign,
  36409. textVerticalAlign: 'middle'
  36410. })
  36411. }));
  36412. // Add a invisible rect to increase the area of mouse hover
  36413. var hitRect = new Rect({
  36414. shape: itemGroup.getBoundingRect(),
  36415. invisible: true,
  36416. tooltip: tooltipModel.get('show') ? extend({
  36417. content: name,
  36418. // Defaul formatter
  36419. formatter: legendGlobalTooltipModel.get('formatter', true) || function () {
  36420. return name;
  36421. },
  36422. formatterParams: {
  36423. componentType: 'legend',
  36424. legendIndex: legendModel.componentIndex,
  36425. name: name,
  36426. $vars: ['name']
  36427. }
  36428. }, tooltipModel.option) : null
  36429. });
  36430. itemGroup.add(hitRect);
  36431. itemGroup.eachChild(function (child) {
  36432. child.silent = true;
  36433. });
  36434. hitRect.silent = !selectMode;
  36435. this.getContentGroup().add(itemGroup);
  36436. setHoverStyle(itemGroup);
  36437. itemGroup.__legendDataIndex = dataIndex;
  36438. return itemGroup;
  36439. },
  36440. /**
  36441. * @protected
  36442. */
  36443. layoutInner: function (legendModel, itemAlign, maxSize) {
  36444. var contentGroup = this.getContentGroup();
  36445. // Place items in contentGroup.
  36446. box(
  36447. legendModel.get('orient'),
  36448. contentGroup,
  36449. legendModel.get('itemGap'),
  36450. maxSize.width,
  36451. maxSize.height
  36452. );
  36453. var contentRect = contentGroup.getBoundingRect();
  36454. contentGroup.attr('position', [-contentRect.x, -contentRect.y]);
  36455. return this.group.getBoundingRect();
  36456. }
  36457. });
  36458. function dispatchSelectAction(name, api) {
  36459. api.dispatchAction({
  36460. type: 'legendToggleSelect',
  36461. name: name
  36462. });
  36463. }
  36464. function dispatchHighlightAction(seriesModel, dataName, api) {
  36465. // If element hover will move to a hoverLayer.
  36466. var el = api.getZr().storage.getDisplayList()[0];
  36467. if (!(el && el.useHoverLayer)) {
  36468. seriesModel.get('legendHoverLink') && api.dispatchAction({
  36469. type: 'highlight',
  36470. seriesName: seriesModel.name,
  36471. name: dataName
  36472. });
  36473. }
  36474. }
  36475. function dispatchDownplayAction(seriesModel, dataName, api) {
  36476. // If element hover will move to a hoverLayer.
  36477. var el = api.getZr().storage.getDisplayList()[0];
  36478. if (!(el && el.useHoverLayer)) {
  36479. seriesModel.get('legendHoverLink') && api.dispatchAction({
  36480. type: 'downplay',
  36481. seriesName: seriesModel.name,
  36482. name: dataName
  36483. });
  36484. }
  36485. }
  36486. var legendFilter = function (ecModel) {
  36487. var legendModels = ecModel.findComponents({
  36488. mainType: 'legend'
  36489. });
  36490. if (legendModels && legendModels.length) {
  36491. ecModel.filterSeries(function (series) {
  36492. // If in any legend component the status is not selected.
  36493. // Because in legend series is assumed selected when it is not in the legend data.
  36494. for (var i = 0; i < legendModels.length; i++) {
  36495. if (!legendModels[i].isSelected(series.name)) {
  36496. return false;
  36497. }
  36498. }
  36499. return true;
  36500. });
  36501. }
  36502. };
  36503. // Do not contain scrollable legend, for sake of file size.
  36504. // Series Filter
  36505. registerProcessor(legendFilter);
  36506. ComponentModel.registerSubTypeDefaulter('legend', function () {
  36507. // Default 'plain' when no type specified.
  36508. return 'plain';
  36509. });
  36510. var ScrollableLegendModel = LegendModel.extend({
  36511. type: 'legend.scroll',
  36512. /**
  36513. * @param {number} scrollDataIndex
  36514. */
  36515. setScrollDataIndex: function (scrollDataIndex) {
  36516. this.option.scrollDataIndex = scrollDataIndex;
  36517. },
  36518. defaultOption: {
  36519. scrollDataIndex: 0,
  36520. pageButtonItemGap: 5,
  36521. pageButtonGap: null,
  36522. pageButtonPosition: 'end', // 'start' or 'end'
  36523. pageFormatter: '{current}/{total}', // If null/undefined, do not show page.
  36524. pageIcons: {
  36525. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  36526. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  36527. },
  36528. pageIconColor: '#2f4554',
  36529. pageIconInactiveColor: '#aaa',
  36530. pageIconSize: 15, // Can be [10, 3], which represents [width, height]
  36531. pageTextStyle: {
  36532. color: '#333'
  36533. },
  36534. animationDurationUpdate: 800
  36535. },
  36536. /**
  36537. * @override
  36538. */
  36539. init: function (option, parentModel, ecModel, extraOpt) {
  36540. var inputPositionParams = getLayoutParams(option);
  36541. ScrollableLegendModel.superCall(this, 'init', option, parentModel, ecModel, extraOpt);
  36542. mergeAndNormalizeLayoutParams(this, option, inputPositionParams);
  36543. },
  36544. /**
  36545. * @override
  36546. */
  36547. mergeOption: function (option, extraOpt) {
  36548. ScrollableLegendModel.superCall(this, 'mergeOption', option, extraOpt);
  36549. mergeAndNormalizeLayoutParams(this, this.option, option);
  36550. },
  36551. getOrient: function () {
  36552. return this.get('orient') === 'vertical'
  36553. ? {index: 1, name: 'vertical'}
  36554. : {index: 0, name: 'horizontal'};
  36555. }
  36556. });
  36557. // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  36558. function mergeAndNormalizeLayoutParams(legendModel, target, raw) {
  36559. var orient = legendModel.getOrient();
  36560. var ignoreSize = [1, 1];
  36561. ignoreSize[orient.index] = 0;
  36562. mergeLayoutParam(target, raw, {
  36563. type: 'box', ignoreSize: ignoreSize
  36564. });
  36565. }
  36566. /**
  36567. * Separate legend and scrollable legend to reduce package size.
  36568. */
  36569. var Group$3 = Group;
  36570. var WH = ['width', 'height'];
  36571. var XY = ['x', 'y'];
  36572. var ScrollableLegendView = LegendView.extend({
  36573. type: 'legend.scroll',
  36574. newlineDisabled: true,
  36575. init: function () {
  36576. ScrollableLegendView.superCall(this, 'init');
  36577. /**
  36578. * @private
  36579. * @type {number} For `scroll`.
  36580. */
  36581. this._currentIndex = 0;
  36582. /**
  36583. * @private
  36584. * @type {module:zrender/container/Group}
  36585. */
  36586. this.group.add(this._containerGroup = new Group$3());
  36587. this._containerGroup.add(this.getContentGroup());
  36588. /**
  36589. * @private
  36590. * @type {module:zrender/container/Group}
  36591. */
  36592. this.group.add(this._controllerGroup = new Group$3());
  36593. /**
  36594. *
  36595. * @private
  36596. */
  36597. this._showController;
  36598. },
  36599. /**
  36600. * @override
  36601. */
  36602. resetInner: function () {
  36603. ScrollableLegendView.superCall(this, 'resetInner');
  36604. this._controllerGroup.removeAll();
  36605. this._containerGroup.removeClipPath();
  36606. this._containerGroup.__rectSize = null;
  36607. },
  36608. /**
  36609. * @override
  36610. */
  36611. renderInner: function (itemAlign, legendModel, ecModel, api) {
  36612. var me = this;
  36613. // Render content items.
  36614. ScrollableLegendView.superCall(this, 'renderInner', itemAlign, legendModel, ecModel, api);
  36615. var controllerGroup = this._controllerGroup;
  36616. var pageIconSize = legendModel.get('pageIconSize', true);
  36617. if (!isArray(pageIconSize)) {
  36618. pageIconSize = [pageIconSize, pageIconSize];
  36619. }
  36620. createPageButton('pagePrev', 0);
  36621. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  36622. controllerGroup.add(new Text({
  36623. name: 'pageText',
  36624. style: {
  36625. textFill: pageTextStyleModel.getTextColor(),
  36626. font: pageTextStyleModel.getFont(),
  36627. textVerticalAlign: 'middle',
  36628. textAlign: 'center'
  36629. },
  36630. silent: true
  36631. }));
  36632. createPageButton('pageNext', 1);
  36633. function createPageButton(name, iconIdx) {
  36634. var pageDataIndexName = name + 'DataIndex';
  36635. var icon = createIcon(
  36636. legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx],
  36637. {
  36638. // Buttons will be created in each render, so we do not need
  36639. // to worry about avoiding using legendModel kept in scope.
  36640. onclick: bind(
  36641. me._pageGo, me, pageDataIndexName, legendModel, api
  36642. )
  36643. },
  36644. {
  36645. x: -pageIconSize[0] / 2,
  36646. y: -pageIconSize[1] / 2,
  36647. width: pageIconSize[0],
  36648. height: pageIconSize[1]
  36649. }
  36650. );
  36651. icon.name = name;
  36652. controllerGroup.add(icon);
  36653. }
  36654. },
  36655. /**
  36656. * @override
  36657. */
  36658. layoutInner: function (legendModel, itemAlign, maxSize) {
  36659. var contentGroup = this.getContentGroup();
  36660. var containerGroup = this._containerGroup;
  36661. var controllerGroup = this._controllerGroup;
  36662. var orientIdx = legendModel.getOrient().index;
  36663. var wh = WH[orientIdx];
  36664. var hw = WH[1 - orientIdx];
  36665. var yx = XY[1 - orientIdx];
  36666. // Place items in contentGroup.
  36667. box(
  36668. legendModel.get('orient'),
  36669. contentGroup,
  36670. legendModel.get('itemGap'),
  36671. !orientIdx ? null : maxSize.width,
  36672. orientIdx ? null : maxSize.height
  36673. );
  36674. box(
  36675. // Buttons in controller are layout always horizontally.
  36676. 'horizontal',
  36677. controllerGroup,
  36678. legendModel.get('pageButtonItemGap', true)
  36679. );
  36680. var contentRect = contentGroup.getBoundingRect();
  36681. var controllerRect = controllerGroup.getBoundingRect();
  36682. var showController = this._showController = contentRect[wh] > maxSize[wh];
  36683. var contentPos = [-contentRect.x, -contentRect.y];
  36684. // Remain contentPos when scroll animation perfroming.
  36685. contentPos[orientIdx] = contentGroup.position[orientIdx];
  36686. // Layout container group based on 0.
  36687. var containerPos = [0, 0];
  36688. var controllerPos = [-controllerRect.x, -controllerRect.y];
  36689. var pageButtonGap = retrieve2(
  36690. legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)
  36691. );
  36692. // Place containerGroup and controllerGroup and contentGroup.
  36693. if (showController) {
  36694. var pageButtonPosition = legendModel.get('pageButtonPosition', true);
  36695. // controller is on the right / bottom.
  36696. if (pageButtonPosition === 'end') {
  36697. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  36698. }
  36699. // controller is on the left / top.
  36700. else {
  36701. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  36702. }
  36703. }
  36704. // Always align controller to content as 'middle'.
  36705. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  36706. contentGroup.attr('position', contentPos);
  36707. containerGroup.attr('position', containerPos);
  36708. controllerGroup.attr('position', controllerPos);
  36709. // Calculate `mainRect` and set `clipPath`.
  36710. // mainRect should not be calculated by `this.group.getBoundingRect()`
  36711. // for sake of the overflow.
  36712. var mainRect = this.group.getBoundingRect();
  36713. var mainRect = {x: 0, y: 0};
  36714. // Consider content may be overflow (should be clipped).
  36715. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  36716. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]);
  36717. // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  36718. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  36719. containerGroup.__rectSize = maxSize[wh];
  36720. if (showController) {
  36721. var clipShape = {x: 0, y: 0};
  36722. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  36723. clipShape[hw] = mainRect[hw];
  36724. containerGroup.setClipPath(new Rect({shape: clipShape}));
  36725. // Consider content may be larger than container, container rect
  36726. // can not be obtained from `containerGroup.getBoundingRect()`.
  36727. containerGroup.__rectSize = clipShape[wh];
  36728. }
  36729. else {
  36730. // Do not remove or ignore controller. Keep them set as place holders.
  36731. controllerGroup.eachChild(function (child) {
  36732. child.attr({invisible: true, silent: true});
  36733. });
  36734. }
  36735. // Content translate animation.
  36736. var pageInfo = this._getPageInfo(legendModel);
  36737. pageInfo.pageIndex != null && updateProps(
  36738. contentGroup,
  36739. {position: pageInfo.contentPosition},
  36740. // When switch from "show controller" to "not show controller", view should be
  36741. // updated immediately without animation, otherwise causes weird efffect.
  36742. showController ? legendModel : false
  36743. );
  36744. this._updatePageInfoView(legendModel, pageInfo);
  36745. return mainRect;
  36746. },
  36747. _pageGo: function (to, legendModel, api) {
  36748. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  36749. scrollDataIndex != null && api.dispatchAction({
  36750. type: 'legendScroll',
  36751. scrollDataIndex: scrollDataIndex,
  36752. legendId: legendModel.id
  36753. });
  36754. },
  36755. _updatePageInfoView: function (legendModel, pageInfo) {
  36756. var controllerGroup = this._controllerGroup;
  36757. each$1(['pagePrev', 'pageNext'], function (name) {
  36758. var canJump = pageInfo[name + 'DataIndex'] != null;
  36759. var icon = controllerGroup.childOfName(name);
  36760. if (icon) {
  36761. icon.setStyle(
  36762. 'fill',
  36763. canJump
  36764. ? legendModel.get('pageIconColor', true)
  36765. : legendModel.get('pageIconInactiveColor', true)
  36766. );
  36767. icon.cursor = canJump ? 'pointer' : 'default';
  36768. }
  36769. });
  36770. var pageText = controllerGroup.childOfName('pageText');
  36771. var pageFormatter = legendModel.get('pageFormatter');
  36772. var pageIndex = pageInfo.pageIndex;
  36773. var current = pageIndex != null ? pageIndex + 1 : 0;
  36774. var total = pageInfo.pageCount;
  36775. pageText && pageFormatter && pageText.setStyle(
  36776. 'text',
  36777. isString(pageFormatter)
  36778. ? pageFormatter.replace('{current}', current).replace('{total}', total)
  36779. : pageFormatter({current: current, total: total})
  36780. );
  36781. },
  36782. /**
  36783. * @param {module:echarts/model/Model} legendModel
  36784. * @return {Object} {
  36785. * contentPosition: Array.<number>, null when data item not found.
  36786. * pageIndex: number, null when data item not found.
  36787. * pageCount: number, always be a number, can be 0.
  36788. * pagePrevDataIndex: number, null when no next page.
  36789. * pageNextDataIndex: number, null when no previous page.
  36790. * }
  36791. */
  36792. _getPageInfo: function (legendModel) {
  36793. // Align left or top by the current dataIndex.
  36794. var currDataIndex = legendModel.get('scrollDataIndex', true);
  36795. var contentGroup = this.getContentGroup();
  36796. var contentRect = contentGroup.getBoundingRect();
  36797. var containerRectSize = this._containerGroup.__rectSize;
  36798. var orientIdx = legendModel.getOrient().index;
  36799. var wh = WH[orientIdx];
  36800. var hw = WH[1 - orientIdx];
  36801. var xy = XY[orientIdx];
  36802. var contentPos = contentGroup.position.slice();
  36803. var pageIndex;
  36804. var pagePrevDataIndex;
  36805. var pageNextDataIndex;
  36806. var targetItemGroup;
  36807. if (this._showController) {
  36808. contentGroup.eachChild(function (child) {
  36809. if (child.__legendDataIndex === currDataIndex) {
  36810. targetItemGroup = child;
  36811. }
  36812. });
  36813. }
  36814. else {
  36815. targetItemGroup = contentGroup.childAt(0);
  36816. }
  36817. var pageCount = containerRectSize ? Math.ceil(contentRect[wh] / containerRectSize) : 0;
  36818. if (targetItemGroup) {
  36819. var itemRect = targetItemGroup.getBoundingRect();
  36820. var itemLoc = targetItemGroup.position[orientIdx] + itemRect[xy];
  36821. contentPos[orientIdx] = -itemLoc - contentRect[xy];
  36822. pageIndex = Math.floor(
  36823. pageCount * (itemLoc + itemRect[xy] + containerRectSize / 2) / contentRect[wh]
  36824. );
  36825. pageIndex = (contentRect[wh] && pageCount)
  36826. ? Math.max(0, Math.min(pageCount - 1, pageIndex))
  36827. : -1;
  36828. var winRect = {x: 0, y: 0};
  36829. winRect[wh] = containerRectSize;
  36830. winRect[hw] = contentRect[hw];
  36831. winRect[xy] = -contentPos[orientIdx] - contentRect[xy];
  36832. var startIdx;
  36833. var children = contentGroup.children();
  36834. contentGroup.eachChild(function (child, index) {
  36835. var itemRect = getItemRect(child);
  36836. if (itemRect.intersect(winRect)) {
  36837. startIdx == null && (startIdx = index);
  36838. // It is user-friendly that the last item shown in the
  36839. // current window is shown at the begining of next window.
  36840. pageNextDataIndex = child.__legendDataIndex;
  36841. }
  36842. // If the last item is shown entirely, no next page.
  36843. if (index === children.length - 1
  36844. && itemRect[xy] + itemRect[wh] <= winRect[xy] + winRect[wh]
  36845. ) {
  36846. pageNextDataIndex = null;
  36847. }
  36848. });
  36849. // Always align based on the left/top most item, so the left/top most
  36850. // item in the previous window is needed to be found here.
  36851. if (startIdx != null) {
  36852. var startItem = children[startIdx];
  36853. var startRect = getItemRect(startItem);
  36854. winRect[xy] = startRect[xy] + startRect[wh] - winRect[wh];
  36855. // If the first item is shown entirely, no previous page.
  36856. if (startIdx <= 0 && startRect[xy] >= winRect[xy]) {
  36857. pagePrevDataIndex = null;
  36858. }
  36859. else {
  36860. while (startIdx > 0 && getItemRect(children[startIdx - 1]).intersect(winRect)) {
  36861. startIdx--;
  36862. }
  36863. pagePrevDataIndex = children[startIdx].__legendDataIndex;
  36864. }
  36865. }
  36866. }
  36867. return {
  36868. contentPosition: contentPos,
  36869. pageIndex: pageIndex,
  36870. pageCount: pageCount,
  36871. pagePrevDataIndex: pagePrevDataIndex,
  36872. pageNextDataIndex: pageNextDataIndex
  36873. };
  36874. function getItemRect(el) {
  36875. var itemRect = el.getBoundingRect().clone();
  36876. itemRect[xy] += el.position[orientIdx];
  36877. return itemRect;
  36878. }
  36879. }
  36880. });
  36881. /**
  36882. * @event legendScroll
  36883. * @type {Object}
  36884. * @property {string} type 'legendScroll'
  36885. * @property {string} scrollDataIndex
  36886. */
  36887. registerAction(
  36888. 'legendScroll', 'legendscroll',
  36889. function (payload, ecModel) {
  36890. var scrollDataIndex = payload.scrollDataIndex;
  36891. scrollDataIndex != null && ecModel.eachComponent(
  36892. {mainType: 'legend', subType: 'scroll', query: payload},
  36893. function (legendModel) {
  36894. legendModel.setScrollDataIndex(scrollDataIndex);
  36895. }
  36896. );
  36897. }
  36898. );
  36899. /**
  36900. * Legend component entry file8
  36901. */
  36902. // Model
  36903. extendComponentModel({
  36904. type: 'title',
  36905. layoutMode: {type: 'box', ignoreSize: true},
  36906. defaultOption: {
  36907. // 一级层叠
  36908. zlevel: 0,
  36909. // 二级层叠
  36910. z: 6,
  36911. show: true,
  36912. text: '',
  36913. // 超链接跳转
  36914. // link: null,
  36915. // 仅支持self | blank
  36916. target: 'blank',
  36917. subtext: '',
  36918. // 超链接跳转
  36919. // sublink: null,
  36920. // 仅支持self | blank
  36921. subtarget: 'blank',
  36922. // 'center' ¦ 'left' ¦ 'right'
  36923. // ¦ {number}(x坐标,单位px)
  36924. left: 0,
  36925. // 'top' ¦ 'bottom' ¦ 'center'
  36926. // ¦ {number}(y坐标,单位px)
  36927. top: 0,
  36928. // 水平对齐
  36929. // 'auto' | 'left' | 'right' | 'center'
  36930. // 默认根据 left 的位置判断是左对齐还是右对齐
  36931. // textAlign: null
  36932. //
  36933. // 垂直对齐
  36934. // 'auto' | 'top' | 'bottom' | 'middle'
  36935. // 默认根据 top 位置判断是上对齐还是下对齐
  36936. // textBaseline: null
  36937. backgroundColor: 'rgba(0,0,0,0)',
  36938. // 标题边框颜色
  36939. borderColor: '#ccc',
  36940. // 标题边框线宽,单位px,默认为0(无边框)
  36941. borderWidth: 0,
  36942. // 标题内边距,单位px,默认各方向内边距为5,
  36943. // 接受数组分别设定上右下左边距,同css
  36944. padding: 5,
  36945. // 主副标题纵向间隔,单位px,默认为10,
  36946. itemGap: 10,
  36947. textStyle: {
  36948. fontSize: 18,
  36949. fontWeight: 'bolder',
  36950. color: '#333'
  36951. },
  36952. subtextStyle: {
  36953. color: '#aaa'
  36954. }
  36955. }
  36956. });
  36957. // View
  36958. extendComponentView({
  36959. type: 'title',
  36960. render: function (titleModel, ecModel, api) {
  36961. this.group.removeAll();
  36962. if (!titleModel.get('show')) {
  36963. return;
  36964. }
  36965. var group = this.group;
  36966. var textStyleModel = titleModel.getModel('textStyle');
  36967. var subtextStyleModel = titleModel.getModel('subtextStyle');
  36968. var textAlign = titleModel.get('textAlign');
  36969. var textBaseline = titleModel.get('textBaseline');
  36970. var textEl = new Text({
  36971. style: setTextStyle({}, textStyleModel, {
  36972. text: titleModel.get('text'),
  36973. textFill: textStyleModel.getTextColor()
  36974. }, {disableBox: true}),
  36975. z2: 10
  36976. });
  36977. var textRect = textEl.getBoundingRect();
  36978. var subText = titleModel.get('subtext');
  36979. var subTextEl = new Text({
  36980. style: setTextStyle({}, subtextStyleModel, {
  36981. text: subText,
  36982. textFill: subtextStyleModel.getTextColor(),
  36983. y: textRect.height + titleModel.get('itemGap'),
  36984. textVerticalAlign: 'top'
  36985. }, {disableBox: true}),
  36986. z2: 10
  36987. });
  36988. var link = titleModel.get('link');
  36989. var sublink = titleModel.get('sublink');
  36990. textEl.silent = !link;
  36991. subTextEl.silent = !sublink;
  36992. if (link) {
  36993. textEl.on('click', function () {
  36994. window.open(link, '_' + titleModel.get('target'));
  36995. });
  36996. }
  36997. if (sublink) {
  36998. subTextEl.on('click', function () {
  36999. window.open(sublink, '_' + titleModel.get('subtarget'));
  37000. });
  37001. }
  37002. group.add(textEl);
  37003. subText && group.add(subTextEl);
  37004. // If no subText, but add subTextEl, there will be an empty line.
  37005. var groupRect = group.getBoundingRect();
  37006. var layoutOption = titleModel.getBoxLayoutParams();
  37007. layoutOption.width = groupRect.width;
  37008. layoutOption.height = groupRect.height;
  37009. var layoutRect = getLayoutRect(
  37010. layoutOption, {
  37011. width: api.getWidth(),
  37012. height: api.getHeight()
  37013. }, titleModel.get('padding')
  37014. );
  37015. // Adjust text align based on position
  37016. if (!textAlign) {
  37017. // Align left if title is on the left. center and right is same
  37018. textAlign = titleModel.get('left') || titleModel.get('right');
  37019. if (textAlign === 'middle') {
  37020. textAlign = 'center';
  37021. }
  37022. // Adjust layout by text align
  37023. if (textAlign === 'right') {
  37024. layoutRect.x += layoutRect.width;
  37025. }
  37026. else if (textAlign === 'center') {
  37027. layoutRect.x += layoutRect.width / 2;
  37028. }
  37029. }
  37030. if (!textBaseline) {
  37031. textBaseline = titleModel.get('top') || titleModel.get('bottom');
  37032. if (textBaseline === 'center') {
  37033. textBaseline = 'middle';
  37034. }
  37035. if (textBaseline === 'bottom') {
  37036. layoutRect.y += layoutRect.height;
  37037. }
  37038. else if (textBaseline === 'middle') {
  37039. layoutRect.y += layoutRect.height / 2;
  37040. }
  37041. textBaseline = textBaseline || 'top';
  37042. }
  37043. group.attr('position', [layoutRect.x, layoutRect.y]);
  37044. var alignStyle = {
  37045. textAlign: textAlign,
  37046. textVerticalAlign: textBaseline
  37047. };
  37048. textEl.setStyle(alignStyle);
  37049. subTextEl.setStyle(alignStyle);
  37050. // Render background
  37051. // Get groupRect again because textAlign has been changed
  37052. groupRect = group.getBoundingRect();
  37053. var padding = layoutRect.margin;
  37054. var style = titleModel.getItemStyle(['color', 'opacity']);
  37055. style.fill = titleModel.get('backgroundColor');
  37056. var rect = new Rect({
  37057. shape: {
  37058. x: groupRect.x - padding[3],
  37059. y: groupRect.y - padding[0],
  37060. width: groupRect.width + padding[1] + padding[3],
  37061. height: groupRect.height + padding[0] + padding[2],
  37062. r: titleModel.get('borderRadius')
  37063. },
  37064. style: style,
  37065. silent: true
  37066. });
  37067. subPixelOptimizeRect(rect);
  37068. group.add(rect);
  37069. }
  37070. });
  37071. var addCommas$1 = addCommas;
  37072. var encodeHTML$1 = encodeHTML;
  37073. function fillLabel(opt) {
  37074. defaultEmphasis(opt, 'label', ['show']);
  37075. }
  37076. var MarkerModel = extendComponentModel({
  37077. type: 'marker',
  37078. dependencies: ['series', 'grid', 'polar', 'geo'],
  37079. /**
  37080. * @overrite
  37081. */
  37082. init: function (option, parentModel, ecModel, extraOpt) {
  37083. if (__DEV__) {
  37084. if (this.type === 'marker') {
  37085. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  37086. }
  37087. }
  37088. this.mergeDefaultAndTheme(option, ecModel);
  37089. this.mergeOption(option, ecModel, extraOpt.createdBySelf, true);
  37090. },
  37091. /**
  37092. * @return {boolean}
  37093. */
  37094. isAnimationEnabled: function () {
  37095. if (env$1.node) {
  37096. return false;
  37097. }
  37098. var hostSeries = this.__hostSeries;
  37099. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  37100. },
  37101. mergeOption: function (newOpt, ecModel, createdBySelf, isInit) {
  37102. var MarkerModel = this.constructor;
  37103. var modelPropName = this.mainType + 'Model';
  37104. if (!createdBySelf) {
  37105. ecModel.eachSeries(function (seriesModel) {
  37106. var markerOpt = seriesModel.get(this.mainType);
  37107. var markerModel = seriesModel[modelPropName];
  37108. if (!markerOpt || !markerOpt.data) {
  37109. seriesModel[modelPropName] = null;
  37110. return;
  37111. }
  37112. if (!markerModel) {
  37113. if (isInit) {
  37114. // Default label emphasis `position` and `show`
  37115. fillLabel(markerOpt);
  37116. }
  37117. each$1(markerOpt.data, function (item) {
  37118. // FIXME Overwrite fillLabel method ?
  37119. if (item instanceof Array) {
  37120. fillLabel(item[0]);
  37121. fillLabel(item[1]);
  37122. }
  37123. else {
  37124. fillLabel(item);
  37125. }
  37126. });
  37127. markerModel = new MarkerModel(
  37128. markerOpt, this, ecModel
  37129. );
  37130. extend(markerModel, {
  37131. mainType: this.mainType,
  37132. // Use the same series index and name
  37133. seriesIndex: seriesModel.seriesIndex,
  37134. name: seriesModel.name,
  37135. createdBySelf: true
  37136. });
  37137. markerModel.__hostSeries = seriesModel;
  37138. }
  37139. else {
  37140. markerModel.mergeOption(markerOpt, ecModel, true);
  37141. }
  37142. seriesModel[modelPropName] = markerModel;
  37143. }, this);
  37144. }
  37145. },
  37146. formatTooltip: function (dataIndex) {
  37147. var data = this.getData();
  37148. var value = this.getRawValue(dataIndex);
  37149. var formattedValue = isArray(value)
  37150. ? map(value, addCommas$1).join(', ') : addCommas$1(value);
  37151. var name = data.getName(dataIndex);
  37152. var html = encodeHTML$1(this.name);
  37153. if (value != null || name) {
  37154. html += '<br />';
  37155. }
  37156. if (name) {
  37157. html += encodeHTML$1(name);
  37158. if (value != null) {
  37159. html += ' : ';
  37160. }
  37161. }
  37162. if (value != null) {
  37163. html += encodeHTML$1(formattedValue);
  37164. }
  37165. return html;
  37166. },
  37167. getData: function () {
  37168. return this._data;
  37169. },
  37170. setData: function (data) {
  37171. this._data = data;
  37172. }
  37173. });
  37174. mixin(MarkerModel, dataFormatMixin);
  37175. MarkerModel.extend({
  37176. type: 'markPoint',
  37177. defaultOption: {
  37178. zlevel: 0,
  37179. z: 5,
  37180. symbol: 'pin',
  37181. symbolSize: 50,
  37182. //symbolRotate: 0,
  37183. //symbolOffset: [0, 0]
  37184. tooltip: {
  37185. trigger: 'item'
  37186. },
  37187. label: {
  37188. show: true,
  37189. position: 'inside'
  37190. },
  37191. itemStyle: {
  37192. borderWidth: 2
  37193. },
  37194. emphasis: {
  37195. label: {
  37196. show: true
  37197. }
  37198. }
  37199. }
  37200. });
  37201. var indexOf$1 = indexOf;
  37202. function hasXOrY(item) {
  37203. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  37204. }
  37205. function hasXAndY(item) {
  37206. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  37207. }
  37208. // Make it simple, do not visit all stacked value to count precision.
  37209. // function getPrecision(data, valueAxisDim, dataIndex) {
  37210. // var precision = -1;
  37211. // var stackedDim = data.mapDimension(valueAxisDim);
  37212. // do {
  37213. // precision = Math.max(
  37214. // numberUtil.getPrecision(data.get(stackedDim, dataIndex)),
  37215. // precision
  37216. // );
  37217. // var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  37218. // if (stackedOnSeries) {
  37219. // var byValue = data.get(data.getCalculationInfo('stackedByDimension'), dataIndex);
  37220. // data = stackedOnSeries.getData();
  37221. // dataIndex = data.indexOf(data.getCalculationInfo('stackedByDimension'), byValue);
  37222. // stackedDim = data.getCalculationInfo('stackedDimension');
  37223. // }
  37224. // else {
  37225. // data = null;
  37226. // }
  37227. // } while (data);
  37228. // return precision;
  37229. // }
  37230. function markerTypeCalculatorWithExtent(
  37231. mlType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex
  37232. ) {
  37233. var coordArr = [];
  37234. var stacked = isDimensionStacked(data, targetDataDim, otherDataDim);
  37235. var calcDataDim = stacked
  37236. ? data.getCalculationInfo('stackResultDimension')
  37237. : targetDataDim;
  37238. var value = numCalculate(data, calcDataDim, mlType);
  37239. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  37240. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  37241. coordArr[targetCoordIndex] = data.get(targetDataDim, dataIndex);
  37242. // Make it simple, do not visit all stacked value to count precision.
  37243. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  37244. precision = Math.min(precision, 20);
  37245. if (precision >= 0) {
  37246. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  37247. }
  37248. return coordArr;
  37249. }
  37250. var curry$4 = curry;
  37251. // TODO Specified percent
  37252. var markerTypeCalculator = {
  37253. /**
  37254. * @method
  37255. * @param {module:echarts/data/List} data
  37256. * @param {string} baseAxisDim
  37257. * @param {string} valueAxisDim
  37258. */
  37259. min: curry$4(markerTypeCalculatorWithExtent, 'min'),
  37260. /**
  37261. * @method
  37262. * @param {module:echarts/data/List} data
  37263. * @param {string} baseAxisDim
  37264. * @param {string} valueAxisDim
  37265. */
  37266. max: curry$4(markerTypeCalculatorWithExtent, 'max'),
  37267. /**
  37268. * @method
  37269. * @param {module:echarts/data/List} data
  37270. * @param {string} baseAxisDim
  37271. * @param {string} valueAxisDim
  37272. */
  37273. average: curry$4(markerTypeCalculatorWithExtent, 'average')
  37274. };
  37275. /**
  37276. * Transform markPoint data item to format used in List by do the following
  37277. * 1. Calculate statistic like `max`, `min`, `average`
  37278. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  37279. * @param {module:echarts/model/Series} seriesModel
  37280. * @param {module:echarts/coord/*} [coordSys]
  37281. * @param {Object} item
  37282. * @return {Object}
  37283. */
  37284. function dataTransform(seriesModel, item) {
  37285. var data = seriesModel.getData();
  37286. var coordSys = seriesModel.coordinateSystem;
  37287. // 1. If not specify the position with pixel directly
  37288. // 2. If `coord` is not a data array. Which uses `xAxis`,
  37289. // `yAxis` to specify the coord on each dimension
  37290. // parseFloat first because item.x and item.y can be percent string like '20%'
  37291. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  37292. var dims = coordSys.dimensions;
  37293. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  37294. // Clone the option
  37295. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  37296. item = clone(item);
  37297. if (item.type
  37298. && markerTypeCalculator[item.type]
  37299. && axisInfo.baseAxis && axisInfo.valueAxis
  37300. ) {
  37301. var otherCoordIndex = indexOf$1(dims, axisInfo.baseAxis.dim);
  37302. var targetCoordIndex = indexOf$1(dims, axisInfo.valueAxis.dim);
  37303. item.coord = markerTypeCalculator[item.type](
  37304. data, axisInfo.baseDataDim, axisInfo.valueDataDim,
  37305. otherCoordIndex, targetCoordIndex
  37306. );
  37307. // Force to use the value of calculated value.
  37308. item.value = item.coord[targetCoordIndex];
  37309. }
  37310. else {
  37311. // FIXME Only has one of xAxis and yAxis.
  37312. var coord = [
  37313. item.xAxis != null ? item.xAxis : item.radiusAxis,
  37314. item.yAxis != null ? item.yAxis : item.angleAxis
  37315. ];
  37316. // Each coord support max, min, average
  37317. for (var i = 0; i < 2; i++) {
  37318. if (markerTypeCalculator[coord[i]]) {
  37319. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  37320. }
  37321. }
  37322. item.coord = coord;
  37323. }
  37324. }
  37325. return item;
  37326. }
  37327. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  37328. var ret = {};
  37329. if (item.valueIndex != null || item.valueDim != null) {
  37330. ret.valueDataDim = item.valueIndex != null
  37331. ? data.getDimension(item.valueIndex) : item.valueDim;
  37332. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  37333. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  37334. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  37335. }
  37336. else {
  37337. ret.baseAxis = seriesModel.getBaseAxis();
  37338. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  37339. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  37340. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  37341. }
  37342. return ret;
  37343. }
  37344. function dataDimToCoordDim(seriesModel, dataDim) {
  37345. var data = seriesModel.getData();
  37346. var dimensions = data.dimensions;
  37347. dataDim = data.getDimension(dataDim);
  37348. for (var i = 0; i < dimensions.length; i++) {
  37349. var dimItem = data.getDimensionInfo(dimensions[i]);
  37350. if (dimItem.name === dataDim) {
  37351. return dimItem.coordDim;
  37352. }
  37353. }
  37354. }
  37355. /**
  37356. * Filter data which is out of coordinateSystem range
  37357. * [dataFilter description]
  37358. * @param {module:echarts/coord/*} [coordSys]
  37359. * @param {Object} item
  37360. * @return {boolean}
  37361. */
  37362. function dataFilter$1(coordSys, item) {
  37363. // Alwalys return true if there is no coordSys
  37364. return (coordSys && coordSys.containData && item.coord && !hasXOrY(item))
  37365. ? coordSys.containData(item.coord) : true;
  37366. }
  37367. function dimValueGetter(item, dimName, dataIndex, dimIndex) {
  37368. // x, y, radius, angle
  37369. if (dimIndex < 2) {
  37370. return item.coord && item.coord[dimIndex];
  37371. }
  37372. return item.value;
  37373. }
  37374. function numCalculate(data, valueDataDim, type) {
  37375. if (type === 'average') {
  37376. var sum = 0;
  37377. var count = 0;
  37378. data.each(valueDataDim, function (val, idx) {
  37379. if (!isNaN(val)) {
  37380. sum += val;
  37381. count++;
  37382. }
  37383. });
  37384. return sum / count;
  37385. }
  37386. else {
  37387. return data.getDataExtent(valueDataDim, true)[type === 'max' ? 1 : 0];
  37388. }
  37389. }
  37390. var MarkerView = extendComponentView({
  37391. type: 'marker',
  37392. init: function () {
  37393. /**
  37394. * Markline grouped by series
  37395. * @private
  37396. * @type {module:zrender/core/util.HashMap}
  37397. */
  37398. this.markerGroupMap = createHashMap();
  37399. },
  37400. render: function (markerModel, ecModel, api) {
  37401. var markerGroupMap = this.markerGroupMap;
  37402. markerGroupMap.each(function (item) {
  37403. item.__keep = false;
  37404. });
  37405. var markerModelKey = this.type + 'Model';
  37406. ecModel.eachSeries(function (seriesModel) {
  37407. var markerModel = seriesModel[markerModelKey];
  37408. markerModel && this.renderSeries(seriesModel, markerModel, ecModel, api);
  37409. }, this);
  37410. markerGroupMap.each(function (item) {
  37411. !item.__keep && this.group.remove(item.group);
  37412. }, this);
  37413. },
  37414. renderSeries: function () {}
  37415. });
  37416. function updateMarkerLayout(mpData, seriesModel, api) {
  37417. var coordSys = seriesModel.coordinateSystem;
  37418. mpData.each(function (idx) {
  37419. var itemModel = mpData.getItemModel(idx);
  37420. var point;
  37421. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  37422. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  37423. if (!isNaN(xPx) && !isNaN(yPx)) {
  37424. point = [xPx, yPx];
  37425. }
  37426. // Chart like bar may have there own marker positioning logic
  37427. else if (seriesModel.getMarkerPosition) {
  37428. // Use the getMarkerPoisition
  37429. point = seriesModel.getMarkerPosition(
  37430. mpData.getValues(mpData.dimensions, idx)
  37431. );
  37432. }
  37433. else if (coordSys) {
  37434. var x = mpData.get(coordSys.dimensions[0], idx);
  37435. var y = mpData.get(coordSys.dimensions[1], idx);
  37436. point = coordSys.dataToPoint([x, y]);
  37437. }
  37438. // Use x, y if has any
  37439. if (!isNaN(xPx)) {
  37440. point[0] = xPx;
  37441. }
  37442. if (!isNaN(yPx)) {
  37443. point[1] = yPx;
  37444. }
  37445. mpData.setItemLayout(idx, point);
  37446. });
  37447. }
  37448. MarkerView.extend({
  37449. type: 'markPoint',
  37450. // updateLayout: function (markPointModel, ecModel, api) {
  37451. // ecModel.eachSeries(function (seriesModel) {
  37452. // var mpModel = seriesModel.markPointModel;
  37453. // if (mpModel) {
  37454. // updateMarkerLayout(mpModel.getData(), seriesModel, api);
  37455. // this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  37456. // }
  37457. // }, this);
  37458. // },
  37459. updateTransform: function (markPointModel, ecModel, api) {
  37460. ecModel.eachSeries(function (seriesModel) {
  37461. var mpModel = seriesModel.markPointModel;
  37462. if (mpModel) {
  37463. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  37464. this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  37465. }
  37466. }, this);
  37467. },
  37468. renderSeries: function (seriesModel, mpModel, ecModel, api) {
  37469. var coordSys = seriesModel.coordinateSystem;
  37470. var seriesId = seriesModel.id;
  37471. var seriesData = seriesModel.getData();
  37472. var symbolDrawMap = this.markerGroupMap;
  37473. var symbolDraw = symbolDrawMap.get(seriesId)
  37474. || symbolDrawMap.set(seriesId, new SymbolDraw());
  37475. var mpData = createList$1(coordSys, seriesModel, mpModel);
  37476. // FIXME
  37477. mpModel.setData(mpData);
  37478. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  37479. mpData.each(function (idx) {
  37480. var itemModel = mpData.getItemModel(idx);
  37481. var symbolSize = itemModel.getShallow('symbolSize');
  37482. if (typeof symbolSize === 'function') {
  37483. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  37484. symbolSize = symbolSize(
  37485. mpModel.getRawValue(idx), mpModel.getDataParams(idx)
  37486. );
  37487. }
  37488. mpData.setItemVisual(idx, {
  37489. symbolSize: symbolSize,
  37490. color: itemModel.get('itemStyle.color')
  37491. || seriesData.getVisual('color'),
  37492. symbol: itemModel.getShallow('symbol')
  37493. });
  37494. });
  37495. // TODO Text are wrong
  37496. symbolDraw.updateData(mpData);
  37497. this.group.add(symbolDraw.group);
  37498. // Set host model for tooltip
  37499. // FIXME
  37500. mpData.eachItemGraphicEl(function (el) {
  37501. el.traverse(function (child) {
  37502. child.dataModel = mpModel;
  37503. });
  37504. });
  37505. symbolDraw.__keep = true;
  37506. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  37507. }
  37508. });
  37509. /**
  37510. * @inner
  37511. * @param {module:echarts/coord/*} [coordSys]
  37512. * @param {module:echarts/model/Series} seriesModel
  37513. * @param {module:echarts/model/Model} mpModel
  37514. */
  37515. function createList$1(coordSys, seriesModel, mpModel) {
  37516. var coordDimsInfos;
  37517. if (coordSys) {
  37518. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  37519. var info = seriesModel.getData().getDimensionInfo(
  37520. seriesModel.getData().mapDimension(coordDim)
  37521. ) || {};
  37522. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  37523. return defaults({name: coordDim}, info);
  37524. });
  37525. }
  37526. else {
  37527. coordDimsInfos =[{
  37528. name: 'value',
  37529. type: 'float'
  37530. }];
  37531. }
  37532. var mpData = new List(coordDimsInfos, mpModel);
  37533. var dataOpt = map(mpModel.get('data'), curry(
  37534. dataTransform, seriesModel
  37535. ));
  37536. if (coordSys) {
  37537. dataOpt = filter(
  37538. dataOpt, curry(dataFilter$1, coordSys)
  37539. );
  37540. }
  37541. mpData.initData(dataOpt, null,
  37542. coordSys ? dimValueGetter : function (item) {
  37543. return item.value;
  37544. }
  37545. );
  37546. return mpData;
  37547. }
  37548. // HINT Markpoint can't be used too much
  37549. registerPreprocessor(function (opt) {
  37550. // Make sure markPoint component is enabled
  37551. opt.markPoint = opt.markPoint || {};
  37552. });
  37553. MarkerModel.extend({
  37554. type: 'markLine',
  37555. defaultOption: {
  37556. zlevel: 0,
  37557. z: 5,
  37558. symbol: ['circle', 'arrow'],
  37559. symbolSize: [8, 16],
  37560. //symbolRotate: 0,
  37561. precision: 2,
  37562. tooltip: {
  37563. trigger: 'item'
  37564. },
  37565. label: {
  37566. show: true,
  37567. position: 'end'
  37568. },
  37569. lineStyle: {
  37570. type: 'dashed'
  37571. },
  37572. emphasis: {
  37573. label: {
  37574. show: true
  37575. },
  37576. lineStyle: {
  37577. width: 3
  37578. }
  37579. },
  37580. animationEasing: 'linear'
  37581. }
  37582. });
  37583. /**
  37584. * Line path for bezier and straight line draw
  37585. */
  37586. var straightLineProto = Line.prototype;
  37587. var bezierCurveProto = BezierCurve.prototype;
  37588. function isLine(shape) {
  37589. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  37590. }
  37591. var LinePath = extendShape({
  37592. type: 'ec-line',
  37593. style: {
  37594. stroke: '#000',
  37595. fill: null
  37596. },
  37597. shape: {
  37598. x1: 0,
  37599. y1: 0,
  37600. x2: 0,
  37601. y2: 0,
  37602. percent: 1,
  37603. cpx1: null,
  37604. cpy1: null
  37605. },
  37606. buildPath: function (ctx, shape) {
  37607. (isLine(shape) ? straightLineProto : bezierCurveProto).buildPath(ctx, shape);
  37608. },
  37609. pointAt: function (t) {
  37610. return isLine(this.shape)
  37611. ? straightLineProto.pointAt.call(this, t)
  37612. : bezierCurveProto.pointAt.call(this, t);
  37613. },
  37614. tangentAt: function (t) {
  37615. var shape = this.shape;
  37616. var p = isLine(shape)
  37617. ? [shape.x2 - shape.x1, shape.y2 - shape.y1]
  37618. : bezierCurveProto.tangentAt.call(this, t);
  37619. return normalize(p, p);
  37620. }
  37621. });
  37622. /**
  37623. * @module echarts/chart/helper/Line
  37624. */
  37625. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  37626. function makeSymbolTypeKey(symbolCategory) {
  37627. return '_' + symbolCategory + 'Type';
  37628. }
  37629. /**
  37630. * @inner
  37631. */
  37632. function createSymbol$1(name, lineData, idx) {
  37633. var color = lineData.getItemVisual(idx, 'color');
  37634. var symbolType = lineData.getItemVisual(idx, name);
  37635. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  37636. if (!symbolType || symbolType === 'none') {
  37637. return;
  37638. }
  37639. if (!isArray(symbolSize)) {
  37640. symbolSize = [symbolSize, symbolSize];
  37641. }
  37642. var symbolPath = createSymbol(
  37643. symbolType, -symbolSize[0] / 2, -symbolSize[1] / 2,
  37644. symbolSize[0], symbolSize[1], color
  37645. );
  37646. symbolPath.name = name;
  37647. return symbolPath;
  37648. }
  37649. function createLine(points) {
  37650. var line = new LinePath({
  37651. name: 'line'
  37652. });
  37653. setLinePoints(line.shape, points);
  37654. return line;
  37655. }
  37656. function setLinePoints(targetShape, points) {
  37657. var p1 = points[0];
  37658. var p2 = points[1];
  37659. var cp1 = points[2];
  37660. targetShape.x1 = p1[0];
  37661. targetShape.y1 = p1[1];
  37662. targetShape.x2 = p2[0];
  37663. targetShape.y2 = p2[1];
  37664. targetShape.percent = 1;
  37665. if (cp1) {
  37666. targetShape.cpx1 = cp1[0];
  37667. targetShape.cpy1 = cp1[1];
  37668. }
  37669. else {
  37670. targetShape.cpx1 = NaN;
  37671. targetShape.cpy1 = NaN;
  37672. }
  37673. }
  37674. function updateSymbolAndLabelBeforeLineUpdate () {
  37675. var lineGroup = this;
  37676. var symbolFrom = lineGroup.childOfName('fromSymbol');
  37677. var symbolTo = lineGroup.childOfName('toSymbol');
  37678. var label = lineGroup.childOfName('label');
  37679. // Quick reject
  37680. if (!symbolFrom && !symbolTo && label.ignore) {
  37681. return;
  37682. }
  37683. var invScale = 1;
  37684. var parentNode = this.parent;
  37685. while (parentNode) {
  37686. if (parentNode.scale) {
  37687. invScale /= parentNode.scale[0];
  37688. }
  37689. parentNode = parentNode.parent;
  37690. }
  37691. var line = lineGroup.childOfName('line');
  37692. // If line not changed
  37693. // FIXME Parent scale changed
  37694. if (!this.__dirty && !line.__dirty) {
  37695. return;
  37696. }
  37697. var percent = line.shape.percent;
  37698. var fromPos = line.pointAt(0);
  37699. var toPos = line.pointAt(percent);
  37700. var d = sub([], toPos, fromPos);
  37701. normalize(d, d);
  37702. if (symbolFrom) {
  37703. symbolFrom.attr('position', fromPos);
  37704. var tangent = line.tangentAt(0);
  37705. symbolFrom.attr('rotation', Math.PI / 2 - Math.atan2(
  37706. tangent[1], tangent[0]
  37707. ));
  37708. symbolFrom.attr('scale', [invScale * percent, invScale * percent]);
  37709. }
  37710. if (symbolTo) {
  37711. symbolTo.attr('position', toPos);
  37712. var tangent = line.tangentAt(1);
  37713. symbolTo.attr('rotation', -Math.PI / 2 - Math.atan2(
  37714. tangent[1], tangent[0]
  37715. ));
  37716. symbolTo.attr('scale', [invScale * percent, invScale * percent]);
  37717. }
  37718. if (!label.ignore) {
  37719. label.attr('position', toPos);
  37720. var textPosition;
  37721. var textAlign;
  37722. var textVerticalAlign;
  37723. var distance$$1 = 5 * invScale;
  37724. // End
  37725. if (label.__position === 'end') {
  37726. textPosition = [d[0] * distance$$1 + toPos[0], d[1] * distance$$1 + toPos[1]];
  37727. textAlign = d[0] > 0.8 ? 'left' : (d[0] < -0.8 ? 'right' : 'center');
  37728. textVerticalAlign = d[1] > 0.8 ? 'top' : (d[1] < -0.8 ? 'bottom' : 'middle');
  37729. }
  37730. // Middle
  37731. else if (label.__position === 'middle') {
  37732. var halfPercent = percent / 2;
  37733. var tangent = line.tangentAt(halfPercent);
  37734. var n = [tangent[1], -tangent[0]];
  37735. var cp = line.pointAt(halfPercent);
  37736. if (n[1] > 0) {
  37737. n[0] = -n[0];
  37738. n[1] = -n[1];
  37739. }
  37740. textPosition = [cp[0] + n[0] * distance$$1, cp[1] + n[1] * distance$$1];
  37741. textAlign = 'center';
  37742. textVerticalAlign = 'bottom';
  37743. var rotation = -Math.atan2(tangent[1], tangent[0]);
  37744. if (toPos[0] < fromPos[0]) {
  37745. rotation = Math.PI + rotation;
  37746. }
  37747. label.attr('rotation', rotation);
  37748. }
  37749. // Start
  37750. else {
  37751. textPosition = [-d[0] * distance$$1 + fromPos[0], -d[1] * distance$$1 + fromPos[1]];
  37752. textAlign = d[0] > 0.8 ? 'right' : (d[0] < -0.8 ? 'left' : 'center');
  37753. textVerticalAlign = d[1] > 0.8 ? 'bottom' : (d[1] < -0.8 ? 'top' : 'middle');
  37754. }
  37755. label.attr({
  37756. style: {
  37757. // Use the user specified text align and baseline first
  37758. textVerticalAlign: label.__verticalAlign || textVerticalAlign,
  37759. textAlign: label.__textAlign || textAlign
  37760. },
  37761. position: textPosition,
  37762. scale: [invScale, invScale]
  37763. });
  37764. }
  37765. }
  37766. /**
  37767. * @constructor
  37768. * @extends {module:zrender/graphic/Group}
  37769. * @alias {module:echarts/chart/helper/Line}
  37770. */
  37771. function Line$1(lineData, idx, seriesScope) {
  37772. Group.call(this);
  37773. this._createLine(lineData, idx, seriesScope);
  37774. }
  37775. var lineProto = Line$1.prototype;
  37776. // Update symbol position and rotation
  37777. lineProto.beforeUpdate = updateSymbolAndLabelBeforeLineUpdate;
  37778. lineProto._createLine = function (lineData, idx, seriesScope) {
  37779. var seriesModel = lineData.hostModel;
  37780. var linePoints = lineData.getItemLayout(idx);
  37781. var line = createLine(linePoints);
  37782. line.shape.percent = 0;
  37783. initProps(line, {
  37784. shape: {
  37785. percent: 1
  37786. }
  37787. }, seriesModel, idx);
  37788. this.add(line);
  37789. var label = new Text({
  37790. name: 'label'
  37791. });
  37792. this.add(label);
  37793. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  37794. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  37795. // symbols must added after line to make sure
  37796. // it will be updated after line#update.
  37797. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  37798. this.add(symbol);
  37799. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  37800. }, this);
  37801. this._updateCommonStl(lineData, idx, seriesScope);
  37802. };
  37803. lineProto.updateData = function (lineData, idx, seriesScope) {
  37804. var seriesModel = lineData.hostModel;
  37805. var line = this.childOfName('line');
  37806. var linePoints = lineData.getItemLayout(idx);
  37807. var target = {
  37808. shape: {}
  37809. };
  37810. setLinePoints(target.shape, linePoints);
  37811. updateProps(line, target, seriesModel, idx);
  37812. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  37813. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  37814. var key = makeSymbolTypeKey(symbolCategory);
  37815. // Symbol changed
  37816. if (this[key] !== symbolType) {
  37817. this.remove(this.childOfName(symbolCategory));
  37818. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  37819. this.add(symbol);
  37820. }
  37821. this[key] = symbolType;
  37822. }, this);
  37823. this._updateCommonStl(lineData, idx, seriesScope);
  37824. };
  37825. lineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  37826. var seriesModel = lineData.hostModel;
  37827. var line = this.childOfName('line');
  37828. var lineStyle = seriesScope && seriesScope.lineStyle;
  37829. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  37830. var labelModel = seriesScope && seriesScope.labelModel;
  37831. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  37832. // Optimization for large dataset
  37833. if (!seriesScope || lineData.hasItemOption) {
  37834. var itemModel = lineData.getItemModel(idx);
  37835. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  37836. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  37837. labelModel = itemModel.getModel('label');
  37838. hoverLabelModel = itemModel.getModel('emphasis.label');
  37839. }
  37840. var visualColor = lineData.getItemVisual(idx, 'color');
  37841. var visualOpacity = retrieve3(
  37842. lineData.getItemVisual(idx, 'opacity'),
  37843. lineStyle.opacity,
  37844. 1
  37845. );
  37846. line.useStyle(defaults(
  37847. {
  37848. strokeNoScale: true,
  37849. fill: 'none',
  37850. stroke: visualColor,
  37851. opacity: visualOpacity
  37852. },
  37853. lineStyle
  37854. ));
  37855. line.hoverStyle = hoverLineStyle;
  37856. // Update symbol
  37857. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  37858. var symbol = this.childOfName(symbolCategory);
  37859. if (symbol) {
  37860. symbol.setColor(visualColor);
  37861. symbol.setStyle({
  37862. opacity: visualOpacity
  37863. });
  37864. }
  37865. }, this);
  37866. var showLabel = labelModel.getShallow('show');
  37867. var hoverShowLabel = hoverLabelModel.getShallow('show');
  37868. var label = this.childOfName('label');
  37869. var defaultLabelColor;
  37870. var normalText;
  37871. var emphasisText;
  37872. if (showLabel || hoverShowLabel) {
  37873. defaultLabelColor = visualColor || '#000';
  37874. normalText = seriesModel.getFormattedLabel(idx, 'normal', lineData.dataType);
  37875. if (normalText == null) {
  37876. var rawVal = seriesModel.getRawValue(idx);
  37877. normalText = rawVal == null
  37878. ? lineData.getName(idx)
  37879. : isFinite(rawVal)
  37880. ? round$1(rawVal)
  37881. : rawVal;
  37882. }
  37883. emphasisText = retrieve2(
  37884. seriesModel.getFormattedLabel(idx, 'emphasis', lineData.dataType),
  37885. normalText
  37886. );
  37887. }
  37888. // label.afterUpdate = lineAfterUpdate;
  37889. if (showLabel) {
  37890. var labelStyle = setTextStyle(label.style, labelModel, {
  37891. text: normalText
  37892. }, {
  37893. autoColor: defaultLabelColor
  37894. });
  37895. label.__textAlign = labelStyle.textAlign;
  37896. label.__verticalAlign = labelStyle.textVerticalAlign;
  37897. // 'start', 'middle', 'end'
  37898. label.__position = labelModel.get('position') || 'middle';
  37899. }
  37900. else {
  37901. label.setStyle('text', null);
  37902. }
  37903. if (hoverShowLabel) {
  37904. // Only these properties supported in this emphasis style here.
  37905. label.hoverStyle = {
  37906. text: emphasisText,
  37907. textFill: hoverLabelModel.getTextColor(true),
  37908. // For merging hover style to normal style, do not use
  37909. // `hoverLabelModel.getFont()` here.
  37910. fontStyle: hoverLabelModel.getShallow('fontStyle'),
  37911. fontWeight: hoverLabelModel.getShallow('fontWeight'),
  37912. fontSize: hoverLabelModel.getShallow('fontSize'),
  37913. fontFamily: hoverLabelModel.getShallow('fontFamily')
  37914. };
  37915. }
  37916. else {
  37917. label.hoverStyle = {
  37918. text: null
  37919. };
  37920. }
  37921. label.ignore = !showLabel && !hoverShowLabel;
  37922. setHoverStyle(this);
  37923. };
  37924. lineProto.highlight = function () {
  37925. this.trigger('emphasis');
  37926. };
  37927. lineProto.downplay = function () {
  37928. this.trigger('normal');
  37929. };
  37930. lineProto.updateLayout = function (lineData, idx) {
  37931. this.setLinePoints(lineData.getItemLayout(idx));
  37932. };
  37933. lineProto.setLinePoints = function (points) {
  37934. var linePath = this.childOfName('line');
  37935. setLinePoints(linePath.shape, points);
  37936. linePath.dirty();
  37937. };
  37938. inherits(Line$1, Group);
  37939. /**
  37940. * @module echarts/chart/helper/LineDraw
  37941. */
  37942. // import IncrementalDisplayable from 'zrender/src/graphic/IncrementalDisplayable';
  37943. /**
  37944. * @alias module:echarts/component/marker/LineDraw
  37945. * @constructor
  37946. */
  37947. function LineDraw(ctor) {
  37948. this._ctor = ctor || Line$1;
  37949. this.group = new Group();
  37950. }
  37951. var lineDrawProto = LineDraw.prototype;
  37952. lineDrawProto.isPersistent = function () {
  37953. return true;
  37954. };
  37955. /**
  37956. * @param {module:echarts/data/List} lineData
  37957. */
  37958. lineDrawProto.updateData = function (lineData) {
  37959. var lineDraw = this;
  37960. var group = lineDraw.group;
  37961. var oldLineData = lineDraw._lineData;
  37962. lineDraw._lineData = lineData;
  37963. // There is no oldLineData only when first rendering or switching from
  37964. // stream mode to normal mode, where previous elements should be removed.
  37965. if (!oldLineData) {
  37966. group.removeAll();
  37967. }
  37968. var seriesScope = makeSeriesScope$1(lineData);
  37969. lineData.diff(oldLineData)
  37970. .add(function (idx) {
  37971. doAdd(lineDraw, lineData, idx, seriesScope);
  37972. })
  37973. .update(function (newIdx, oldIdx) {
  37974. doUpdate(lineDraw, oldLineData, lineData, oldIdx, newIdx, seriesScope);
  37975. })
  37976. .remove(function (idx) {
  37977. group.remove(oldLineData.getItemGraphicEl(idx));
  37978. })
  37979. .execute();
  37980. };
  37981. function doAdd(lineDraw, lineData, idx, seriesScope) {
  37982. var itemLayout = lineData.getItemLayout(idx);
  37983. if (!lineNeedsDraw(itemLayout)) {
  37984. return;
  37985. }
  37986. var el = new lineDraw._ctor(lineData, idx, seriesScope);
  37987. lineData.setItemGraphicEl(idx, el);
  37988. lineDraw.group.add(el);
  37989. }
  37990. function doUpdate(lineDraw, oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  37991. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  37992. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  37993. lineDraw.group.remove(itemEl);
  37994. return;
  37995. }
  37996. if (!itemEl) {
  37997. itemEl = new lineDraw._ctor(newLineData, newIdx, seriesScope);
  37998. }
  37999. else {
  38000. itemEl.updateData(newLineData, newIdx, seriesScope);
  38001. }
  38002. newLineData.setItemGraphicEl(newIdx, itemEl);
  38003. lineDraw.group.add(itemEl);
  38004. }
  38005. lineDrawProto.updateLayout = function () {
  38006. var lineData = this._lineData;
  38007. lineData.eachItemGraphicEl(function (el, idx) {
  38008. el.updateLayout(lineData, idx);
  38009. }, this);
  38010. };
  38011. lineDrawProto.incrementalPrepareUpdate = function (lineData) {
  38012. this._seriesScope = makeSeriesScope$1(lineData);
  38013. this._lineData = null;
  38014. this.group.removeAll();
  38015. };
  38016. lineDrawProto.incrementalUpdate = function (taskParams, lineData) {
  38017. function updateIncrementalAndHover(el) {
  38018. if (!el.isGroup) {
  38019. el.incremental = el.useHoverLayer = true;
  38020. }
  38021. }
  38022. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  38023. var itemLayout = lineData.getItemLayout(idx);
  38024. if (lineNeedsDraw(itemLayout)) {
  38025. var el = new this._ctor(lineData, idx, this._seriesScope);
  38026. el.traverse(updateIncrementalAndHover);
  38027. this.group.add(el);
  38028. }
  38029. }
  38030. };
  38031. function makeSeriesScope$1(lineData) {
  38032. var hostModel = lineData.hostModel;
  38033. return {
  38034. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  38035. hoverLineStyle: hostModel.getModel('emphasis.lineStyle').getLineStyle(),
  38036. labelModel: hostModel.getModel('label'),
  38037. hoverLabelModel: hostModel.getModel('emphasis.label')
  38038. };
  38039. }
  38040. lineDrawProto.remove = function () {
  38041. this._clearIncremental();
  38042. this._incremental = null;
  38043. this.group.removeAll();
  38044. };
  38045. lineDrawProto._clearIncremental = function () {
  38046. var incremental = this._incremental;
  38047. if (incremental) {
  38048. incremental.clearDisplaybles();
  38049. }
  38050. };
  38051. function isPointNaN(pt) {
  38052. return isNaN(pt[0]) || isNaN(pt[1]);
  38053. }
  38054. function lineNeedsDraw(pts) {
  38055. return !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  38056. }
  38057. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  38058. var data = seriesModel.getData();
  38059. // Special type markLine like 'min', 'max', 'average'
  38060. var mlType = item.type;
  38061. if (!isArray(item)
  38062. && (
  38063. mlType === 'min' || mlType === 'max' || mlType === 'average'
  38064. // In case
  38065. // data: [{
  38066. // yAxis: 10
  38067. // }]
  38068. || (item.xAxis != null || item.yAxis != null)
  38069. )
  38070. ) {
  38071. var valueAxis;
  38072. var valueDataDim;
  38073. var value;
  38074. if (item.yAxis != null || item.xAxis != null) {
  38075. valueDataDim = item.yAxis != null ? 'y' : 'x';
  38076. valueAxis = coordSys.getAxis(valueDataDim);
  38077. value = retrieve(item.yAxis, item.xAxis);
  38078. }
  38079. else {
  38080. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  38081. valueDataDim = axisInfo.valueDataDim;
  38082. valueAxis = axisInfo.valueAxis;
  38083. value = numCalculate(data, valueDataDim, mlType);
  38084. }
  38085. var valueIndex = valueDataDim === 'x' ? 0 : 1;
  38086. var baseIndex = 1 - valueIndex;
  38087. var mlFrom = clone(item);
  38088. var mlTo = {};
  38089. mlFrom.type = null;
  38090. mlFrom.coord = [];
  38091. mlTo.coord = [];
  38092. mlFrom.coord[baseIndex] = -Infinity;
  38093. mlTo.coord[baseIndex] = Infinity;
  38094. var precision = mlModel.get('precision');
  38095. if (precision >= 0 && typeof value === 'number') {
  38096. value = +value.toFixed(Math.min(precision, 20));
  38097. }
  38098. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  38099. item = [mlFrom, mlTo, { // Extra option for tooltip and label
  38100. type: mlType,
  38101. valueIndex: item.valueIndex,
  38102. // Force to use the value of calculated value.
  38103. value: value
  38104. }];
  38105. }
  38106. item = [
  38107. dataTransform(seriesModel, item[0]),
  38108. dataTransform(seriesModel, item[1]),
  38109. extend({}, item[2])
  38110. ];
  38111. // Avoid line data type is extended by from(to) data type
  38112. item[2].type = item[2].type || '';
  38113. // Merge from option and to option into line option
  38114. merge(item[2], item[0]);
  38115. merge(item[2], item[1]);
  38116. return item;
  38117. };
  38118. function isInifinity(val) {
  38119. return !isNaN(val) && !isFinite(val);
  38120. }
  38121. // If a markLine has one dim
  38122. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  38123. var otherDimIndex = 1 - dimIndex;
  38124. var dimName = coordSys.dimensions[dimIndex];
  38125. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex])
  38126. && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  38127. }
  38128. function markLineFilter(coordSys, item) {
  38129. if (coordSys.type === 'cartesian2d') {
  38130. var fromCoord = item[0].coord;
  38131. var toCoord = item[1].coord;
  38132. // In case
  38133. // {
  38134. // markLine: {
  38135. // data: [{ yAxis: 2 }]
  38136. // }
  38137. // }
  38138. if (
  38139. fromCoord && toCoord &&
  38140. (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys)
  38141. || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))
  38142. ) {
  38143. return true;
  38144. }
  38145. }
  38146. return dataFilter$1(coordSys, item[0])
  38147. && dataFilter$1(coordSys, item[1]);
  38148. }
  38149. function updateSingleMarkerEndLayout(
  38150. data, idx, isFrom, seriesModel, api
  38151. ) {
  38152. var coordSys = seriesModel.coordinateSystem;
  38153. var itemModel = data.getItemModel(idx);
  38154. var point;
  38155. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  38156. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  38157. if (!isNaN(xPx) && !isNaN(yPx)) {
  38158. point = [xPx, yPx];
  38159. }
  38160. else {
  38161. // Chart like bar may have there own marker positioning logic
  38162. if (seriesModel.getMarkerPosition) {
  38163. // Use the getMarkerPoisition
  38164. point = seriesModel.getMarkerPosition(
  38165. data.getValues(data.dimensions, idx)
  38166. );
  38167. }
  38168. else {
  38169. var dims = coordSys.dimensions;
  38170. var x = data.get(dims[0], idx);
  38171. var y = data.get(dims[1], idx);
  38172. point = coordSys.dataToPoint([x, y]);
  38173. }
  38174. // Expand line to the edge of grid if value on one axis is Inifnity
  38175. // In case
  38176. // markLine: {
  38177. // data: [{
  38178. // yAxis: 2
  38179. // // or
  38180. // type: 'average'
  38181. // }]
  38182. // }
  38183. if (coordSys.type === 'cartesian2d') {
  38184. var xAxis = coordSys.getAxis('x');
  38185. var yAxis = coordSys.getAxis('y');
  38186. var dims = coordSys.dimensions;
  38187. if (isInifinity(data.get(dims[0], idx))) {
  38188. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  38189. }
  38190. else if (isInifinity(data.get(dims[1], idx))) {
  38191. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  38192. }
  38193. }
  38194. // Use x, y if has any
  38195. if (!isNaN(xPx)) {
  38196. point[0] = xPx;
  38197. }
  38198. if (!isNaN(yPx)) {
  38199. point[1] = yPx;
  38200. }
  38201. }
  38202. data.setItemLayout(idx, point);
  38203. }
  38204. MarkerView.extend({
  38205. type: 'markLine',
  38206. // updateLayout: function (markLineModel, ecModel, api) {
  38207. // ecModel.eachSeries(function (seriesModel) {
  38208. // var mlModel = seriesModel.markLineModel;
  38209. // if (mlModel) {
  38210. // var mlData = mlModel.getData();
  38211. // var fromData = mlModel.__from;
  38212. // var toData = mlModel.__to;
  38213. // // Update visual and layout of from symbol and to symbol
  38214. // fromData.each(function (idx) {
  38215. // updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  38216. // updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  38217. // });
  38218. // // Update layout of line
  38219. // mlData.each(function (idx) {
  38220. // mlData.setItemLayout(idx, [
  38221. // fromData.getItemLayout(idx),
  38222. // toData.getItemLayout(idx)
  38223. // ]);
  38224. // });
  38225. // this.markerGroupMap.get(seriesModel.id).updateLayout();
  38226. // }
  38227. // }, this);
  38228. // },
  38229. updateTransform: function (markLineModel, ecModel, api) {
  38230. ecModel.eachSeries(function (seriesModel) {
  38231. var mlModel = seriesModel.markLineModel;
  38232. if (mlModel) {
  38233. var mlData = mlModel.getData();
  38234. var fromData = mlModel.__from;
  38235. var toData = mlModel.__to;
  38236. // Update visual and layout of from symbol and to symbol
  38237. fromData.each(function (idx) {
  38238. updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  38239. updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  38240. });
  38241. // Update layout of line
  38242. mlData.each(function (idx) {
  38243. mlData.setItemLayout(idx, [
  38244. fromData.getItemLayout(idx),
  38245. toData.getItemLayout(idx)
  38246. ]);
  38247. });
  38248. this.markerGroupMap.get(seriesModel.id).updateLayout();
  38249. }
  38250. }, this);
  38251. },
  38252. renderSeries: function (seriesModel, mlModel, ecModel, api) {
  38253. var coordSys = seriesModel.coordinateSystem;
  38254. var seriesId = seriesModel.id;
  38255. var seriesData = seriesModel.getData();
  38256. var lineDrawMap = this.markerGroupMap;
  38257. var lineDraw = lineDrawMap.get(seriesId)
  38258. || lineDrawMap.set(seriesId, new LineDraw());
  38259. this.group.add(lineDraw.group);
  38260. var mlData = createList$2(coordSys, seriesModel, mlModel);
  38261. var fromData = mlData.from;
  38262. var toData = mlData.to;
  38263. var lineData = mlData.line;
  38264. mlModel.__from = fromData;
  38265. mlModel.__to = toData;
  38266. // Line data for tooltip and formatter
  38267. mlModel.setData(lineData);
  38268. var symbolType = mlModel.get('symbol');
  38269. var symbolSize = mlModel.get('symbolSize');
  38270. if (!isArray(symbolType)) {
  38271. symbolType = [symbolType, symbolType];
  38272. }
  38273. if (typeof symbolSize === 'number') {
  38274. symbolSize = [symbolSize, symbolSize];
  38275. }
  38276. // Update visual and layout of from symbol and to symbol
  38277. mlData.from.each(function (idx) {
  38278. updateDataVisualAndLayout(fromData, idx, true);
  38279. updateDataVisualAndLayout(toData, idx, false);
  38280. });
  38281. // Update visual and layout of line
  38282. lineData.each(function (idx) {
  38283. var lineColor = lineData.getItemModel(idx).get('lineStyle.color');
  38284. lineData.setItemVisual(idx, {
  38285. color: lineColor || fromData.getItemVisual(idx, 'color')
  38286. });
  38287. lineData.setItemLayout(idx, [
  38288. fromData.getItemLayout(idx),
  38289. toData.getItemLayout(idx)
  38290. ]);
  38291. lineData.setItemVisual(idx, {
  38292. 'fromSymbolSize': fromData.getItemVisual(idx, 'symbolSize'),
  38293. 'fromSymbol': fromData.getItemVisual(idx, 'symbol'),
  38294. 'toSymbolSize': toData.getItemVisual(idx, 'symbolSize'),
  38295. 'toSymbol': toData.getItemVisual(idx, 'symbol')
  38296. });
  38297. });
  38298. lineDraw.updateData(lineData);
  38299. // Set host model for tooltip
  38300. // FIXME
  38301. mlData.line.eachItemGraphicEl(function (el, idx) {
  38302. el.traverse(function (child) {
  38303. child.dataModel = mlModel;
  38304. });
  38305. });
  38306. function updateDataVisualAndLayout(data, idx, isFrom) {
  38307. var itemModel = data.getItemModel(idx);
  38308. updateSingleMarkerEndLayout(
  38309. data, idx, isFrom, seriesModel, api
  38310. );
  38311. data.setItemVisual(idx, {
  38312. symbolSize: itemModel.get('symbolSize') || symbolSize[isFrom ? 0 : 1],
  38313. symbol: itemModel.get('symbol', true) || symbolType[isFrom ? 0 : 1],
  38314. color: itemModel.get('itemStyle.color') || seriesData.getVisual('color')
  38315. });
  38316. }
  38317. lineDraw.__keep = true;
  38318. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  38319. }
  38320. });
  38321. /**
  38322. * @inner
  38323. * @param {module:echarts/coord/*} coordSys
  38324. * @param {module:echarts/model/Series} seriesModel
  38325. * @param {module:echarts/model/Model} mpModel
  38326. */
  38327. function createList$2(coordSys, seriesModel, mlModel) {
  38328. var coordDimsInfos;
  38329. if (coordSys) {
  38330. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  38331. var info = seriesModel.getData().getDimensionInfo(
  38332. seriesModel.getData().mapDimension(coordDim)
  38333. ) || {};
  38334. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  38335. return defaults({name: coordDim}, info);
  38336. });
  38337. }
  38338. else {
  38339. coordDimsInfos =[{
  38340. name: 'value',
  38341. type: 'float'
  38342. }];
  38343. }
  38344. var fromData = new List(coordDimsInfos, mlModel);
  38345. var toData = new List(coordDimsInfos, mlModel);
  38346. // No dimensions
  38347. var lineData = new List([], mlModel);
  38348. var optData = map(mlModel.get('data'), curry(
  38349. markLineTransform, seriesModel, coordSys, mlModel
  38350. ));
  38351. if (coordSys) {
  38352. optData = filter(
  38353. optData, curry(markLineFilter, coordSys)
  38354. );
  38355. }
  38356. var dimValueGetter$$1 = coordSys ? dimValueGetter : function (item) {
  38357. return item.value;
  38358. };
  38359. fromData.initData(
  38360. map(optData, function (item) { return item[0]; }),
  38361. null, dimValueGetter$$1
  38362. );
  38363. toData.initData(
  38364. map(optData, function (item) { return item[1]; }),
  38365. null, dimValueGetter$$1
  38366. );
  38367. lineData.initData(
  38368. map(optData, function (item) { return item[2]; })
  38369. );
  38370. lineData.hasItemOption = true;
  38371. return {
  38372. from: fromData,
  38373. to: toData,
  38374. line: lineData
  38375. };
  38376. }
  38377. registerPreprocessor(function (opt) {
  38378. // Make sure markLine component is enabled
  38379. opt.markLine = opt.markLine || {};
  38380. });
  38381. MarkerModel.extend({
  38382. type: 'markArea',
  38383. defaultOption: {
  38384. zlevel: 0,
  38385. // PENDING
  38386. z: 1,
  38387. tooltip: {
  38388. trigger: 'item'
  38389. },
  38390. // markArea should fixed on the coordinate system
  38391. animation: false,
  38392. label: {
  38393. show: true,
  38394. position: 'top'
  38395. },
  38396. itemStyle: {
  38397. // color and borderColor default to use color from series
  38398. // color: 'auto'
  38399. // borderColor: 'auto'
  38400. borderWidth: 0
  38401. },
  38402. emphasis: {
  38403. label: {
  38404. show: true,
  38405. position: 'top'
  38406. }
  38407. }
  38408. }
  38409. });
  38410. // TODO Better on polar
  38411. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  38412. var lt = dataTransform(seriesModel, item[0]);
  38413. var rb = dataTransform(seriesModel, item[1]);
  38414. var retrieve$$1 = retrieve;
  38415. // FIXME make sure lt is less than rb
  38416. var ltCoord = lt.coord;
  38417. var rbCoord = rb.coord;
  38418. ltCoord[0] = retrieve$$1(ltCoord[0], -Infinity);
  38419. ltCoord[1] = retrieve$$1(ltCoord[1], -Infinity);
  38420. rbCoord[0] = retrieve$$1(rbCoord[0], Infinity);
  38421. rbCoord[1] = retrieve$$1(rbCoord[1], Infinity);
  38422. // Merge option into one
  38423. var result = mergeAll([{}, lt, rb]);
  38424. result.coord = [
  38425. lt.coord, rb.coord
  38426. ];
  38427. result.x0 = lt.x;
  38428. result.y0 = lt.y;
  38429. result.x1 = rb.x;
  38430. result.y1 = rb.y;
  38431. return result;
  38432. };
  38433. function isInifinity$1(val) {
  38434. return !isNaN(val) && !isFinite(val);
  38435. }
  38436. // If a markArea has one dim
  38437. function ifMarkLineHasOnlyDim$1(dimIndex, fromCoord, toCoord, coordSys) {
  38438. var otherDimIndex = 1 - dimIndex;
  38439. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  38440. }
  38441. function markAreaFilter(coordSys, item) {
  38442. var fromCoord = item.coord[0];
  38443. var toCoord = item.coord[1];
  38444. if (coordSys.type === 'cartesian2d') {
  38445. // In case
  38446. // {
  38447. // markArea: {
  38448. // data: [{ yAxis: 2 }]
  38449. // }
  38450. // }
  38451. if (
  38452. fromCoord && toCoord &&
  38453. (ifMarkLineHasOnlyDim$1(1, fromCoord, toCoord, coordSys)
  38454. || ifMarkLineHasOnlyDim$1(0, fromCoord, toCoord, coordSys))
  38455. ) {
  38456. return true;
  38457. }
  38458. }
  38459. return dataFilter$1(coordSys, {
  38460. coord: fromCoord,
  38461. x: item.x0,
  38462. y: item.y0
  38463. })
  38464. || dataFilter$1(coordSys, {
  38465. coord: toCoord,
  38466. x: item.x1,
  38467. y: item.y1
  38468. });
  38469. }
  38470. // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  38471. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  38472. var coordSys = seriesModel.coordinateSystem;
  38473. var itemModel = data.getItemModel(idx);
  38474. var point;
  38475. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  38476. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  38477. if (!isNaN(xPx) && !isNaN(yPx)) {
  38478. point = [xPx, yPx];
  38479. }
  38480. else {
  38481. // Chart like bar may have there own marker positioning logic
  38482. if (seriesModel.getMarkerPosition) {
  38483. // Use the getMarkerPoisition
  38484. point = seriesModel.getMarkerPosition(
  38485. data.getValues(dims, idx)
  38486. );
  38487. }
  38488. else {
  38489. var x = data.get(dims[0], idx);
  38490. var y = data.get(dims[1], idx);
  38491. var pt = [x, y];
  38492. coordSys.clampData && coordSys.clampData(pt, pt);
  38493. point = coordSys.dataToPoint(pt, true);
  38494. }
  38495. if (coordSys.type === 'cartesian2d') {
  38496. var xAxis = coordSys.getAxis('x');
  38497. var yAxis = coordSys.getAxis('y');
  38498. var x = data.get(dims[0], idx);
  38499. var y = data.get(dims[1], idx);
  38500. if (isInifinity$1(x)) {
  38501. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  38502. }
  38503. else if (isInifinity$1(y)) {
  38504. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  38505. }
  38506. }
  38507. // Use x, y if has any
  38508. if (!isNaN(xPx)) {
  38509. point[0] = xPx;
  38510. }
  38511. if (!isNaN(yPx)) {
  38512. point[1] = yPx;
  38513. }
  38514. }
  38515. return point;
  38516. }
  38517. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  38518. MarkerView.extend({
  38519. type: 'markArea',
  38520. // updateLayout: function (markAreaModel, ecModel, api) {
  38521. // ecModel.eachSeries(function (seriesModel) {
  38522. // var maModel = seriesModel.markAreaModel;
  38523. // if (maModel) {
  38524. // var areaData = maModel.getData();
  38525. // areaData.each(function (idx) {
  38526. // var points = zrUtil.map(dimPermutations, function (dim) {
  38527. // return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  38528. // });
  38529. // // Layout
  38530. // areaData.setItemLayout(idx, points);
  38531. // var el = areaData.getItemGraphicEl(idx);
  38532. // el.setShape('points', points);
  38533. // });
  38534. // }
  38535. // }, this);
  38536. // },
  38537. updateTransform: function (markAreaModel, ecModel, api) {
  38538. ecModel.eachSeries(function (seriesModel) {
  38539. var maModel = seriesModel.markAreaModel;
  38540. if (maModel) {
  38541. var areaData = maModel.getData();
  38542. areaData.each(function (idx) {
  38543. var points = map(dimPermutations, function (dim) {
  38544. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  38545. });
  38546. // Layout
  38547. areaData.setItemLayout(idx, points);
  38548. var el = areaData.getItemGraphicEl(idx);
  38549. el.setShape('points', points);
  38550. });
  38551. }
  38552. }, this);
  38553. },
  38554. renderSeries: function (seriesModel, maModel, ecModel, api) {
  38555. var coordSys = seriesModel.coordinateSystem;
  38556. var seriesName = seriesModel.name;
  38557. var seriesData = seriesModel.getData();
  38558. var areaGroupMap = this.markerGroupMap;
  38559. var polygonGroup = areaGroupMap.get(seriesName)
  38560. || areaGroupMap.set(seriesName, {group: new Group()});
  38561. this.group.add(polygonGroup.group);
  38562. polygonGroup.__keep = true;
  38563. var areaData = createList$3(coordSys, seriesModel, maModel);
  38564. // Line data for tooltip and formatter
  38565. maModel.setData(areaData);
  38566. // Update visual and layout of line
  38567. areaData.each(function (idx) {
  38568. // Layout
  38569. areaData.setItemLayout(idx, map(dimPermutations, function (dim) {
  38570. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  38571. }));
  38572. // Visual
  38573. areaData.setItemVisual(idx, {
  38574. color: seriesData.getVisual('color')
  38575. });
  38576. });
  38577. areaData.diff(polygonGroup.__data)
  38578. .add(function (idx) {
  38579. var polygon = new Polygon({
  38580. shape: {
  38581. points: areaData.getItemLayout(idx)
  38582. }
  38583. });
  38584. areaData.setItemGraphicEl(idx, polygon);
  38585. polygonGroup.group.add(polygon);
  38586. })
  38587. .update(function (newIdx, oldIdx) {
  38588. var polygon = polygonGroup.__data.getItemGraphicEl(oldIdx);
  38589. updateProps(polygon, {
  38590. shape: {
  38591. points: areaData.getItemLayout(newIdx)
  38592. }
  38593. }, maModel, newIdx);
  38594. polygonGroup.group.add(polygon);
  38595. areaData.setItemGraphicEl(newIdx, polygon);
  38596. })
  38597. .remove(function (idx) {
  38598. var polygon = polygonGroup.__data.getItemGraphicEl(idx);
  38599. polygonGroup.group.remove(polygon);
  38600. })
  38601. .execute();
  38602. areaData.eachItemGraphicEl(function (polygon, idx) {
  38603. var itemModel = areaData.getItemModel(idx);
  38604. var labelModel = itemModel.getModel('label');
  38605. var labelHoverModel = itemModel.getModel('emphasis.label');
  38606. var color = areaData.getItemVisual(idx, 'color');
  38607. polygon.useStyle(
  38608. defaults(
  38609. itemModel.getModel('itemStyle').getItemStyle(),
  38610. {
  38611. fill: modifyAlpha(color, 0.4),
  38612. stroke: color
  38613. }
  38614. )
  38615. );
  38616. polygon.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  38617. setLabelStyle(
  38618. polygon.style, polygon.hoverStyle, labelModel, labelHoverModel,
  38619. {
  38620. labelFetcher: maModel,
  38621. labelDataIndex: idx,
  38622. defaultText: areaData.getName(idx) || '',
  38623. isRectText: true,
  38624. autoColor: color
  38625. }
  38626. );
  38627. setHoverStyle(polygon, {});
  38628. polygon.dataModel = maModel;
  38629. });
  38630. polygonGroup.__data = areaData;
  38631. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  38632. }
  38633. });
  38634. /**
  38635. * @inner
  38636. * @param {module:echarts/coord/*} coordSys
  38637. * @param {module:echarts/model/Series} seriesModel
  38638. * @param {module:echarts/model/Model} mpModel
  38639. */
  38640. function createList$3(coordSys, seriesModel, maModel) {
  38641. var coordDimsInfos;
  38642. var areaData;
  38643. var dims = ['x0', 'y0', 'x1', 'y1'];
  38644. if (coordSys) {
  38645. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  38646. var data = seriesModel.getData();
  38647. var info = data.getDimensionInfo(
  38648. data.mapDimension(coordDim)
  38649. ) || {};
  38650. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  38651. return defaults({name: coordDim}, info);
  38652. });
  38653. areaData = new List(map(dims, function (dim, idx) {
  38654. return {
  38655. name: dim,
  38656. type: coordDimsInfos[idx % 2].type
  38657. };
  38658. }), maModel);
  38659. }
  38660. else {
  38661. coordDimsInfos =[{
  38662. name: 'value',
  38663. type: 'float'
  38664. }];
  38665. areaData = new List(coordDimsInfos, maModel);
  38666. }
  38667. var optData = map(maModel.get('data'), curry(
  38668. markAreaTransform, seriesModel, coordSys, maModel
  38669. ));
  38670. if (coordSys) {
  38671. optData = filter(
  38672. optData, curry(markAreaFilter, coordSys)
  38673. );
  38674. }
  38675. var dimValueGetter$$1 = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  38676. return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  38677. } : function (item) {
  38678. return item.value;
  38679. };
  38680. areaData.initData(optData, null, dimValueGetter$$1);
  38681. areaData.hasItemOption = true;
  38682. return areaData;
  38683. }
  38684. registerPreprocessor(function (opt) {
  38685. // Make sure markArea component is enabled
  38686. opt.markArea = opt.markArea || {};
  38687. });
  38688. ComponentModel.registerSubTypeDefaulter('dataZoom', function () {
  38689. // Default 'slider' when no type specified.
  38690. return 'slider';
  38691. });
  38692. var AXIS_DIMS = ['x', 'y', 'z', 'radius', 'angle', 'single'];
  38693. // Supported coords.
  38694. var COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  38695. /**
  38696. * @param {string} coordType
  38697. * @return {boolean}
  38698. */
  38699. function isCoordSupported(coordType) {
  38700. return indexOf(COORDS, coordType) >= 0;
  38701. }
  38702. /**
  38703. * Create "each" method to iterate names.
  38704. *
  38705. * @pubilc
  38706. * @param {Array.<string>} names
  38707. * @param {Array.<string>=} attrs
  38708. * @return {Function}
  38709. */
  38710. function createNameEach(names, attrs) {
  38711. names = names.slice();
  38712. var capitalNames = map(names, capitalFirst);
  38713. attrs = (attrs || []).slice();
  38714. var capitalAttrs = map(attrs, capitalFirst);
  38715. return function (callback, context) {
  38716. each$1(names, function (name, index) {
  38717. var nameObj = {name: name, capital: capitalNames[index]};
  38718. for (var j = 0; j < attrs.length; j++) {
  38719. nameObj[attrs[j]] = name + capitalAttrs[j];
  38720. }
  38721. callback.call(context, nameObj);
  38722. });
  38723. };
  38724. }
  38725. /**
  38726. * Iterate each dimension name.
  38727. *
  38728. * @public
  38729. * @param {Function} callback The parameter is like:
  38730. * {
  38731. * name: 'angle',
  38732. * capital: 'Angle',
  38733. * axis: 'angleAxis',
  38734. * axisIndex: 'angleAixs',
  38735. * index: 'angleIndex'
  38736. * }
  38737. * @param {Object} context
  38738. */
  38739. var eachAxisDim$1 = createNameEach(AXIS_DIMS, ['axisIndex', 'axis', 'index', 'id']);
  38740. /**
  38741. * If tow dataZoomModels has the same axis controlled, we say that they are 'linked'.
  38742. * dataZoomModels and 'links' make up one or more graphics.
  38743. * This function finds the graphic where the source dataZoomModel is in.
  38744. *
  38745. * @public
  38746. * @param {Function} forEachNode Node iterator.
  38747. * @param {Function} forEachEdgeType edgeType iterator
  38748. * @param {Function} edgeIdGetter Giving node and edgeType, return an array of edge id.
  38749. * @return {Function} Input: sourceNode, Output: Like {nodes: [], dims: {}}
  38750. */
  38751. function createLinkedNodesFinder(forEachNode, forEachEdgeType, edgeIdGetter) {
  38752. return function (sourceNode) {
  38753. var result = {
  38754. nodes: [],
  38755. records: {} // key: edgeType.name, value: Object (key: edge id, value: boolean).
  38756. };
  38757. forEachEdgeType(function (edgeType) {
  38758. result.records[edgeType.name] = {};
  38759. });
  38760. if (!sourceNode) {
  38761. return result;
  38762. }
  38763. absorb(sourceNode, result);
  38764. var existsLink;
  38765. do {
  38766. existsLink = false;
  38767. forEachNode(processSingleNode);
  38768. }
  38769. while (existsLink);
  38770. function processSingleNode(node) {
  38771. if (!isNodeAbsorded(node, result) && isLinked(node, result)) {
  38772. absorb(node, result);
  38773. existsLink = true;
  38774. }
  38775. }
  38776. return result;
  38777. };
  38778. function isNodeAbsorded(node, result) {
  38779. return indexOf(result.nodes, node) >= 0;
  38780. }
  38781. function isLinked(node, result) {
  38782. var hasLink = false;
  38783. forEachEdgeType(function (edgeType) {
  38784. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  38785. result.records[edgeType.name][edgeId] && (hasLink = true);
  38786. });
  38787. });
  38788. return hasLink;
  38789. }
  38790. function absorb(node, result) {
  38791. result.nodes.push(node);
  38792. forEachEdgeType(function (edgeType) {
  38793. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  38794. result.records[edgeType.name][edgeId] = true;
  38795. });
  38796. });
  38797. }
  38798. }
  38799. var each$14 = each$1;
  38800. var asc$1 = asc;
  38801. /**
  38802. * Operate single axis.
  38803. * One axis can only operated by one axis operator.
  38804. * Different dataZoomModels may be defined to operate the same axis.
  38805. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  38806. * So dataZoomModels share one axisProxy in that case.
  38807. *
  38808. * @class
  38809. */
  38810. var AxisProxy = function (dimName, axisIndex, dataZoomModel, ecModel) {
  38811. /**
  38812. * @private
  38813. * @type {string}
  38814. */
  38815. this._dimName = dimName;
  38816. /**
  38817. * @private
  38818. */
  38819. this._axisIndex = axisIndex;
  38820. /**
  38821. * @private
  38822. * @type {Array.<number>}
  38823. */
  38824. this._valueWindow;
  38825. /**
  38826. * @private
  38827. * @type {Array.<number>}
  38828. */
  38829. this._percentWindow;
  38830. /**
  38831. * @private
  38832. * @type {Array.<number>}
  38833. */
  38834. this._dataExtent;
  38835. /**
  38836. * {minSpan, maxSpan, minValueSpan, maxValueSpan}
  38837. * @private
  38838. * @type {Object}
  38839. */
  38840. this._minMaxSpan;
  38841. /**
  38842. * @readOnly
  38843. * @type {module: echarts/model/Global}
  38844. */
  38845. this.ecModel = ecModel;
  38846. /**
  38847. * @private
  38848. * @type {module: echarts/component/dataZoom/DataZoomModel}
  38849. */
  38850. this._dataZoomModel = dataZoomModel;
  38851. // /**
  38852. // * @readOnly
  38853. // * @private
  38854. // */
  38855. // this.hasSeriesStacked;
  38856. };
  38857. AxisProxy.prototype = {
  38858. constructor: AxisProxy,
  38859. /**
  38860. * Whether the axisProxy is hosted by dataZoomModel.
  38861. *
  38862. * @public
  38863. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  38864. * @return {boolean}
  38865. */
  38866. hostedBy: function (dataZoomModel) {
  38867. return this._dataZoomModel === dataZoomModel;
  38868. },
  38869. /**
  38870. * @return {Array.<number>} Value can only be NaN or finite value.
  38871. */
  38872. getDataValueWindow: function () {
  38873. return this._valueWindow.slice();
  38874. },
  38875. /**
  38876. * @return {Array.<number>}
  38877. */
  38878. getDataPercentWindow: function () {
  38879. return this._percentWindow.slice();
  38880. },
  38881. /**
  38882. * @public
  38883. * @param {number} axisIndex
  38884. * @return {Array} seriesModels
  38885. */
  38886. getTargetSeriesModels: function () {
  38887. var seriesModels = [];
  38888. var ecModel = this.ecModel;
  38889. ecModel.eachSeries(function (seriesModel) {
  38890. if (isCoordSupported(seriesModel.get('coordinateSystem'))) {
  38891. var dimName = this._dimName;
  38892. var axisModel = ecModel.queryComponents({
  38893. mainType: dimName + 'Axis',
  38894. index: seriesModel.get(dimName + 'AxisIndex'),
  38895. id: seriesModel.get(dimName + 'AxisId')
  38896. })[0];
  38897. if (this._axisIndex === (axisModel && axisModel.componentIndex)) {
  38898. seriesModels.push(seriesModel);
  38899. }
  38900. }
  38901. }, this);
  38902. return seriesModels;
  38903. },
  38904. getAxisModel: function () {
  38905. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  38906. },
  38907. getOtherAxisModel: function () {
  38908. var axisDim = this._dimName;
  38909. var ecModel = this.ecModel;
  38910. var axisModel = this.getAxisModel();
  38911. var isCartesian = axisDim === 'x' || axisDim === 'y';
  38912. var otherAxisDim;
  38913. var coordSysIndexName;
  38914. if (isCartesian) {
  38915. coordSysIndexName = 'gridIndex';
  38916. otherAxisDim = axisDim === 'x' ? 'y' : 'x';
  38917. }
  38918. else {
  38919. coordSysIndexName = 'polarIndex';
  38920. otherAxisDim = axisDim === 'angle' ? 'radius' : 'angle';
  38921. }
  38922. var foundOtherAxisModel;
  38923. ecModel.eachComponent(otherAxisDim + 'Axis', function (otherAxisModel) {
  38924. if ((otherAxisModel.get(coordSysIndexName) || 0)
  38925. === (axisModel.get(coordSysIndexName) || 0)
  38926. ) {
  38927. foundOtherAxisModel = otherAxisModel;
  38928. }
  38929. });
  38930. return foundOtherAxisModel;
  38931. },
  38932. getMinMaxSpan: function () {
  38933. return clone(this._minMaxSpan);
  38934. },
  38935. /**
  38936. * Only calculate by given range and this._dataExtent, do not change anything.
  38937. *
  38938. * @param {Object} opt
  38939. * @param {number} [opt.start]
  38940. * @param {number} [opt.end]
  38941. * @param {number} [opt.startValue]
  38942. * @param {number} [opt.endValue]
  38943. */
  38944. calculateDataWindow: function (opt) {
  38945. var dataExtent = this._dataExtent;
  38946. var axisModel = this.getAxisModel();
  38947. var scale = axisModel.axis.scale;
  38948. var rangePropMode = this._dataZoomModel.getRangePropMode();
  38949. var percentExtent = [0, 100];
  38950. var percentWindow = [
  38951. opt.start,
  38952. opt.end
  38953. ];
  38954. var valueWindow = [];
  38955. each$14(['startValue', 'endValue'], function (prop) {
  38956. valueWindow.push(opt[prop] != null ? scale.parse(opt[prop]) : null);
  38957. });
  38958. // Normalize bound.
  38959. each$14([0, 1], function (idx) {
  38960. var boundValue = valueWindow[idx];
  38961. var boundPercent = percentWindow[idx];
  38962. // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  38963. // on `valueProp` ('startValue', 'endValue'). The former one is suitable
  38964. // for cases that a dataZoom component controls multiple axes with different
  38965. // unit or extent, and the latter one is suitable for accurate zoom by pixel
  38966. // (e.g., in dataZoomSelect). `valueProp` can be calculated from `percentProp`,
  38967. // but it is awkward that `percentProp` can not be obtained from `valueProp`
  38968. // accurately (because all of values that are overflow the `dataExtent` will
  38969. // be calculated to percent '100%'). So we have to use
  38970. // `dataZoom.getRangePropMode()` to mark which prop is used.
  38971. // `rangePropMode` is updated only when setOption or dispatchAction, otherwise
  38972. // it remains its original value.
  38973. if (rangePropMode[idx] === 'percent') {
  38974. if (boundPercent == null) {
  38975. boundPercent = percentExtent[idx];
  38976. }
  38977. // Use scale.parse to math round for category or time axis.
  38978. boundValue = scale.parse(linearMap(
  38979. boundPercent, percentExtent, dataExtent, true
  38980. ));
  38981. }
  38982. else {
  38983. // Calculating `percent` from `value` may be not accurate, because
  38984. // This calculation can not be inversed, because all of values that
  38985. // are overflow the `dataExtent` will be calculated to percent '100%'
  38986. boundPercent = linearMap(
  38987. boundValue, dataExtent, percentExtent, true
  38988. );
  38989. }
  38990. // valueWindow[idx] = round(boundValue);
  38991. // percentWindow[idx] = round(boundPercent);
  38992. valueWindow[idx] = boundValue;
  38993. percentWindow[idx] = boundPercent;
  38994. });
  38995. return {
  38996. valueWindow: asc$1(valueWindow),
  38997. percentWindow: asc$1(percentWindow)
  38998. };
  38999. },
  39000. /**
  39001. * Notice: reset should not be called before series.restoreData() called,
  39002. * so it is recommanded to be called in "process stage" but not "model init
  39003. * stage".
  39004. *
  39005. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  39006. */
  39007. reset: function (dataZoomModel) {
  39008. if (dataZoomModel !== this._dataZoomModel) {
  39009. return;
  39010. }
  39011. var targetSeries = this.getTargetSeriesModels();
  39012. // Culculate data window and data extent, and record them.
  39013. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries);
  39014. // this.hasSeriesStacked = false;
  39015. // each(targetSeries, function (series) {
  39016. // var data = series.getData();
  39017. // var dataDim = data.mapDimension(this._dimName);
  39018. // var stackedDimension = data.getCalculationInfo('stackedDimension');
  39019. // if (stackedDimension && stackedDimension === dataDim) {
  39020. // this.hasSeriesStacked = true;
  39021. // }
  39022. // }, this);
  39023. var dataWindow = this.calculateDataWindow(dataZoomModel.option);
  39024. this._valueWindow = dataWindow.valueWindow;
  39025. this._percentWindow = dataWindow.percentWindow;
  39026. setMinMaxSpan(this);
  39027. // Update axis setting then.
  39028. setAxisModel(this);
  39029. },
  39030. /**
  39031. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  39032. */
  39033. restore: function (dataZoomModel) {
  39034. if (dataZoomModel !== this._dataZoomModel) {
  39035. return;
  39036. }
  39037. this._valueWindow = this._percentWindow = null;
  39038. setAxisModel(this, true);
  39039. },
  39040. /**
  39041. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  39042. */
  39043. filterData: function (dataZoomModel, api) {
  39044. if (dataZoomModel !== this._dataZoomModel) {
  39045. return;
  39046. }
  39047. var axisDim = this._dimName;
  39048. var seriesModels = this.getTargetSeriesModels();
  39049. var filterMode = dataZoomModel.get('filterMode');
  39050. var valueWindow = this._valueWindow;
  39051. if (filterMode === 'none') {
  39052. return;
  39053. }
  39054. // FIXME
  39055. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  39056. // with NaN data, NaN will be filtered and stack will be wrong.
  39057. // So we need to force the mode to be set empty.
  39058. // In fect, it is not a big deal that do not support filterMode-'filter'
  39059. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  39060. // selection" some day, which might need "adapt to data extent on the
  39061. // otherAxis", which is disabled by filterMode-'empty'.
  39062. // But currently, stack has been fixed to based on value but not index,
  39063. // so this is not an issue any more.
  39064. // var otherAxisModel = this.getOtherAxisModel();
  39065. // if (dataZoomModel.get('$fromToolbox')
  39066. // && otherAxisModel
  39067. // && otherAxisModel.hasSeriesStacked
  39068. // ) {
  39069. // filterMode = 'empty';
  39070. // }
  39071. // TODO
  39072. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  39073. // Process series data
  39074. each$14(seriesModels, function (seriesModel) {
  39075. var seriesData = seriesModel.getData();
  39076. var dataDims = seriesData.mapDimension(axisDim, true);
  39077. if (filterMode === 'weakFilter') {
  39078. seriesData.filterSelf(function (dataIndex) {
  39079. var leftOut;
  39080. var rightOut;
  39081. var hasValue;
  39082. for (var i = 0; i < dataDims.length; i++) {
  39083. var value = seriesData.get(dataDims[i], dataIndex);
  39084. var thisHasValue = !isNaN(value);
  39085. var thisLeftOut = value < valueWindow[0];
  39086. var thisRightOut = value > valueWindow[1];
  39087. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  39088. return true;
  39089. }
  39090. thisHasValue && (hasValue = true);
  39091. thisLeftOut && (leftOut = true);
  39092. thisRightOut && (rightOut = true);
  39093. }
  39094. // If both left out and right out, do not filter.
  39095. return hasValue && leftOut && rightOut;
  39096. });
  39097. }
  39098. else {
  39099. each$14(dataDims, function (dim) {
  39100. if (filterMode === 'empty') {
  39101. seriesModel.setData(
  39102. seriesData.map(dim, function (value) {
  39103. return !isInWindow(value) ? NaN : value;
  39104. })
  39105. );
  39106. }
  39107. else {
  39108. var range = {};
  39109. range[dim] = valueWindow;
  39110. // console.time('select');
  39111. seriesData.selectRange(range);
  39112. // console.timeEnd('select');
  39113. }
  39114. });
  39115. }
  39116. each$14(dataDims, function (dim) {
  39117. seriesData.setApproximateExtent(valueWindow, dim);
  39118. });
  39119. });
  39120. function isInWindow(value) {
  39121. return value >= valueWindow[0] && value <= valueWindow[1];
  39122. }
  39123. }
  39124. };
  39125. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  39126. var dataExtent = [Infinity, -Infinity];
  39127. each$14(seriesModels, function (seriesModel) {
  39128. var seriesData = seriesModel.getData();
  39129. if (seriesData) {
  39130. each$14(seriesData.mapDimension(axisDim, true), function (dim) {
  39131. var seriesExtent = seriesData.getApproximateExtent(dim);
  39132. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  39133. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  39134. });
  39135. }
  39136. });
  39137. if (dataExtent[1] < dataExtent[0]) {
  39138. dataExtent = [NaN, NaN];
  39139. }
  39140. // It is important to get "consistent" extent when more then one axes is
  39141. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  39142. // when zooming. But it is difficult to know what is "consistent", considering
  39143. // axes have different type or even different meanings (For example, two
  39144. // time axes are used to compare data of the same date in different years).
  39145. // So basically dataZoom just obtains extent by series.data (in category axis
  39146. // extent can be obtained from axis.data).
  39147. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  39148. // consistent.
  39149. fixExtentByAxis(axisProxy, dataExtent);
  39150. return dataExtent;
  39151. }
  39152. function fixExtentByAxis(axisProxy, dataExtent) {
  39153. var axisModel = axisProxy.getAxisModel();
  39154. var min = axisModel.getMin(true);
  39155. // For category axis, if min/max/scale are not set, extent is determined
  39156. // by axis.data by default.
  39157. var isCategoryAxis = axisModel.get('type') === 'category';
  39158. var axisDataLen = isCategoryAxis && axisModel.getCategories().length;
  39159. if (min != null && min !== 'dataMin' && typeof min !== 'function') {
  39160. dataExtent[0] = min;
  39161. }
  39162. else if (isCategoryAxis) {
  39163. dataExtent[0] = axisDataLen > 0 ? 0 : NaN;
  39164. }
  39165. var max = axisModel.getMax(true);
  39166. if (max != null && max !== 'dataMax' && typeof max !== 'function') {
  39167. dataExtent[1] = max;
  39168. }
  39169. else if (isCategoryAxis) {
  39170. dataExtent[1] = axisDataLen > 0 ? axisDataLen - 1 : NaN;
  39171. }
  39172. if (!axisModel.get('scale', true)) {
  39173. dataExtent[0] > 0 && (dataExtent[0] = 0);
  39174. dataExtent[1] < 0 && (dataExtent[1] = 0);
  39175. }
  39176. // For value axis, if min/max/scale are not set, we just use the extent obtained
  39177. // by series data, which may be a little different from the extent calculated by
  39178. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  39179. // little when zooming. So it will not be fixed until some users require it strongly.
  39180. return dataExtent;
  39181. }
  39182. function setAxisModel(axisProxy, isRestore) {
  39183. var axisModel = axisProxy.getAxisModel();
  39184. var percentWindow = axisProxy._percentWindow;
  39185. var valueWindow = axisProxy._valueWindow;
  39186. if (!percentWindow) {
  39187. return;
  39188. }
  39189. // [0, 500]: arbitrary value, guess axis extent.
  39190. var precision = getPixelPrecision(valueWindow, [0, 500]);
  39191. precision = Math.min(precision, 20);
  39192. // isRestore or isFull
  39193. var useOrigin = isRestore || (percentWindow[0] === 0 && percentWindow[1] === 100);
  39194. axisModel.setRange(
  39195. useOrigin ? null : +valueWindow[0].toFixed(precision),
  39196. useOrigin ? null : +valueWindow[1].toFixed(precision)
  39197. );
  39198. }
  39199. function setMinMaxSpan(axisProxy) {
  39200. var minMaxSpan = axisProxy._minMaxSpan = {};
  39201. var dataZoomModel = axisProxy._dataZoomModel;
  39202. each$14(['min', 'max'], function (minMax) {
  39203. minMaxSpan[minMax + 'Span'] = dataZoomModel.get(minMax + 'Span');
  39204. // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  39205. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  39206. if (valueSpan != null) {
  39207. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  39208. valueSpan = axisProxy.getAxisModel().axis.scale.parse(valueSpan);
  39209. if (valueSpan != null) {
  39210. var dataExtent = axisProxy._dataExtent;
  39211. minMaxSpan[minMax + 'Span'] = linearMap(
  39212. dataExtent[0] + valueSpan, dataExtent, [0, 100], true
  39213. );
  39214. }
  39215. }
  39216. });
  39217. }
  39218. var each$13 = each$1;
  39219. var eachAxisDim = eachAxisDim$1;
  39220. var DataZoomModel = extendComponentModel({
  39221. type: 'dataZoom',
  39222. dependencies: [
  39223. 'xAxis', 'yAxis', 'zAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series'
  39224. ],
  39225. /**
  39226. * @protected
  39227. */
  39228. defaultOption: {
  39229. zlevel: 0,
  39230. z: 4, // Higher than normal component (z: 2).
  39231. orient: null, // Default auto by axisIndex. Possible value: 'horizontal', 'vertical'.
  39232. xAxisIndex: null, // Default the first horizontal category axis.
  39233. yAxisIndex: null, // Default the first vertical category axis.
  39234. filterMode: 'filter', // Possible values: 'filter' or 'empty' or 'weakFilter'.
  39235. // 'filter': data items which are out of window will be removed. This option is
  39236. // applicable when filtering outliers. For each data item, it will be
  39237. // filtered if one of the relevant dimensions is out of the window.
  39238. // 'weakFilter': data items which are out of window will be removed. This option
  39239. // is applicable when filtering outliers. For each data item, it will be
  39240. // filtered only if all of the relevant dimensions are out of the same
  39241. // side of the window.
  39242. // 'empty': data items which are out of window will be set to empty.
  39243. // This option is applicable when user should not neglect
  39244. // that there are some data items out of window.
  39245. // 'none': Do not filter.
  39246. // Taking line chart as an example, line will be broken in
  39247. // the filtered points when filterModel is set to 'empty', but
  39248. // be connected when set to 'filter'.
  39249. throttle: null, // Dispatch action by the fixed rate, avoid frequency.
  39250. // default 100. Do not throttle when use null/undefined.
  39251. // If animation === true and animationDurationUpdate > 0,
  39252. // default value is 100, otherwise 20.
  39253. start: 0, // Start percent. 0 ~ 100
  39254. end: 100, // End percent. 0 ~ 100
  39255. startValue: null, // Start value. If startValue specified, start is ignored.
  39256. endValue: null, // End value. If endValue specified, end is ignored.
  39257. minSpan: null, // 0 ~ 100
  39258. maxSpan: null, // 0 ~ 100
  39259. minValueSpan: null, // The range of dataZoom can not be smaller than that.
  39260. maxValueSpan: null, // The range of dataZoom can not be larger than that.
  39261. rangeMode: null // Array, can be 'value' or 'percent'.
  39262. },
  39263. /**
  39264. * @override
  39265. */
  39266. init: function (option, parentModel, ecModel) {
  39267. /**
  39268. * key like x_0, y_1
  39269. * @private
  39270. * @type {Object}
  39271. */
  39272. this._dataIntervalByAxis = {};
  39273. /**
  39274. * @private
  39275. */
  39276. this._dataInfo = {};
  39277. /**
  39278. * key like x_0, y_1
  39279. * @private
  39280. */
  39281. this._axisProxies = {};
  39282. /**
  39283. * @readOnly
  39284. */
  39285. this.textStyleModel;
  39286. /**
  39287. * @private
  39288. */
  39289. this._autoThrottle = true;
  39290. /**
  39291. * 'percent' or 'value'
  39292. * @private
  39293. */
  39294. this._rangePropMode = ['percent', 'percent'];
  39295. var rawOption = retrieveRaw(option);
  39296. this.mergeDefaultAndTheme(option, ecModel);
  39297. this.doInit(rawOption);
  39298. },
  39299. /**
  39300. * @override
  39301. */
  39302. mergeOption: function (newOption) {
  39303. var rawOption = retrieveRaw(newOption);
  39304. //FIX #2591
  39305. merge(this.option, newOption, true);
  39306. this.doInit(rawOption);
  39307. },
  39308. /**
  39309. * @protected
  39310. */
  39311. doInit: function (rawOption) {
  39312. var thisOption = this.option;
  39313. // Disable realtime view update if canvas is not supported.
  39314. if (!env$1.canvasSupported) {
  39315. thisOption.realtime = false;
  39316. }
  39317. this._setDefaultThrottle(rawOption);
  39318. updateRangeUse(this, rawOption);
  39319. each$13([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  39320. // start/end has higher priority over startValue/endValue if they
  39321. // both set, but we should make chart.setOption({endValue: 1000})
  39322. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  39323. if (this._rangePropMode[index] === 'value') {
  39324. thisOption[names[0]] = null;
  39325. }
  39326. // Otherwise do nothing and use the merge result.
  39327. }, this);
  39328. this.textStyleModel = this.getModel('textStyle');
  39329. this._resetTarget();
  39330. this._giveAxisProxies();
  39331. },
  39332. /**
  39333. * @private
  39334. */
  39335. _giveAxisProxies: function () {
  39336. var axisProxies = this._axisProxies;
  39337. this.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel, ecModel) {
  39338. var axisModel = this.dependentModels[dimNames.axis][axisIndex];
  39339. // If exists, share axisProxy with other dataZoomModels.
  39340. var axisProxy = axisModel.__dzAxisProxy || (
  39341. // Use the first dataZoomModel as the main model of axisProxy.
  39342. axisModel.__dzAxisProxy = new AxisProxy(
  39343. dimNames.name, axisIndex, this, ecModel
  39344. )
  39345. );
  39346. // FIXME
  39347. // dispose __dzAxisProxy
  39348. axisProxies[dimNames.name + '_' + axisIndex] = axisProxy;
  39349. }, this);
  39350. },
  39351. /**
  39352. * @private
  39353. */
  39354. _resetTarget: function () {
  39355. var thisOption = this.option;
  39356. var autoMode = this._judgeAutoMode();
  39357. eachAxisDim(function (dimNames) {
  39358. var axisIndexName = dimNames.axisIndex;
  39359. thisOption[axisIndexName] = normalizeToArray(
  39360. thisOption[axisIndexName]
  39361. );
  39362. }, this);
  39363. if (autoMode === 'axisIndex') {
  39364. this._autoSetAxisIndex();
  39365. }
  39366. else if (autoMode === 'orient') {
  39367. this._autoSetOrient();
  39368. }
  39369. },
  39370. /**
  39371. * @private
  39372. */
  39373. _judgeAutoMode: function () {
  39374. // Auto set only works for setOption at the first time.
  39375. // The following is user's reponsibility. So using merged
  39376. // option is OK.
  39377. var thisOption = this.option;
  39378. var hasIndexSpecified = false;
  39379. eachAxisDim(function (dimNames) {
  39380. // When user set axisIndex as a empty array, we think that user specify axisIndex
  39381. // but do not want use auto mode. Because empty array may be encountered when
  39382. // some error occured.
  39383. if (thisOption[dimNames.axisIndex] != null) {
  39384. hasIndexSpecified = true;
  39385. }
  39386. }, this);
  39387. var orient = thisOption.orient;
  39388. if (orient == null && hasIndexSpecified) {
  39389. return 'orient';
  39390. }
  39391. else if (!hasIndexSpecified) {
  39392. if (orient == null) {
  39393. thisOption.orient = 'horizontal';
  39394. }
  39395. return 'axisIndex';
  39396. }
  39397. },
  39398. /**
  39399. * @private
  39400. */
  39401. _autoSetAxisIndex: function () {
  39402. var autoAxisIndex = true;
  39403. var orient = this.get('orient', true);
  39404. var thisOption = this.option;
  39405. var dependentModels = this.dependentModels;
  39406. if (autoAxisIndex) {
  39407. // Find axis that parallel to dataZoom as default.
  39408. var dimName = orient === 'vertical' ? 'y' : 'x';
  39409. if (dependentModels[dimName + 'Axis'].length) {
  39410. thisOption[dimName + 'AxisIndex'] = [0];
  39411. autoAxisIndex = false;
  39412. }
  39413. else {
  39414. each$13(dependentModels.singleAxis, function (singleAxisModel) {
  39415. if (autoAxisIndex && singleAxisModel.get('orient', true) === orient) {
  39416. thisOption.singleAxisIndex = [singleAxisModel.componentIndex];
  39417. autoAxisIndex = false;
  39418. }
  39419. });
  39420. }
  39421. }
  39422. if (autoAxisIndex) {
  39423. // Find the first category axis as default. (consider polar)
  39424. eachAxisDim(function (dimNames) {
  39425. if (!autoAxisIndex) {
  39426. return;
  39427. }
  39428. var axisIndices = [];
  39429. var axisModels = this.dependentModels[dimNames.axis];
  39430. if (axisModels.length && !axisIndices.length) {
  39431. for (var i = 0, len = axisModels.length; i < len; i++) {
  39432. if (axisModels[i].get('type') === 'category') {
  39433. axisIndices.push(i);
  39434. }
  39435. }
  39436. }
  39437. thisOption[dimNames.axisIndex] = axisIndices;
  39438. if (axisIndices.length) {
  39439. autoAxisIndex = false;
  39440. }
  39441. }, this);
  39442. }
  39443. if (autoAxisIndex) {
  39444. // FIXME
  39445. // 这里是兼容ec2的写法(没指定xAxisIndex和yAxisIndex时把scatter和双数值轴折柱纳入dataZoom控制),
  39446. // 但是实际是否需要Grid.js#getScaleByOption来判断(考虑time,log等axis type)?
  39447. // If both dataZoom.xAxisIndex and dataZoom.yAxisIndex is not specified,
  39448. // dataZoom component auto adopts series that reference to
  39449. // both xAxis and yAxis which type is 'value'.
  39450. this.ecModel.eachSeries(function (seriesModel) {
  39451. if (this._isSeriesHasAllAxesTypeOf(seriesModel, 'value')) {
  39452. eachAxisDim(function (dimNames) {
  39453. var axisIndices = thisOption[dimNames.axisIndex];
  39454. var axisIndex = seriesModel.get(dimNames.axisIndex);
  39455. var axisId = seriesModel.get(dimNames.axisId);
  39456. var axisModel = seriesModel.ecModel.queryComponents({
  39457. mainType: dimNames.axis,
  39458. index: axisIndex,
  39459. id: axisId
  39460. })[0];
  39461. if (__DEV__) {
  39462. if (!axisModel) {
  39463. throw new Error(
  39464. dimNames.axis + ' "' + retrieve(
  39465. axisIndex,
  39466. axisId,
  39467. 0
  39468. ) + '" not found'
  39469. );
  39470. }
  39471. }
  39472. axisIndex = axisModel.componentIndex;
  39473. if (indexOf(axisIndices, axisIndex) < 0) {
  39474. axisIndices.push(axisIndex);
  39475. }
  39476. });
  39477. }
  39478. }, this);
  39479. }
  39480. },
  39481. /**
  39482. * @private
  39483. */
  39484. _autoSetOrient: function () {
  39485. var dim;
  39486. // Find the first axis
  39487. this.eachTargetAxis(function (dimNames) {
  39488. !dim && (dim = dimNames.name);
  39489. }, this);
  39490. this.option.orient = dim === 'y' ? 'vertical' : 'horizontal';
  39491. },
  39492. /**
  39493. * @private
  39494. */
  39495. _isSeriesHasAllAxesTypeOf: function (seriesModel, axisType) {
  39496. // FIXME
  39497. // 需要series的xAxisIndex和yAxisIndex都首先自动设置上。
  39498. // 例如series.type === scatter时。
  39499. var is = true;
  39500. eachAxisDim(function (dimNames) {
  39501. var seriesAxisIndex = seriesModel.get(dimNames.axisIndex);
  39502. var axisModel = this.dependentModels[dimNames.axis][seriesAxisIndex];
  39503. if (!axisModel || axisModel.get('type') !== axisType) {
  39504. is = false;
  39505. }
  39506. }, this);
  39507. return is;
  39508. },
  39509. /**
  39510. * @private
  39511. */
  39512. _setDefaultThrottle: function (rawOption) {
  39513. // When first time user set throttle, auto throttle ends.
  39514. if (rawOption.hasOwnProperty('throttle')) {
  39515. this._autoThrottle = false;
  39516. }
  39517. if (this._autoThrottle) {
  39518. var globalOption = this.ecModel.option;
  39519. this.option.throttle =
  39520. (globalOption.animation && globalOption.animationDurationUpdate > 0)
  39521. ? 100 : 20;
  39522. }
  39523. },
  39524. /**
  39525. * @public
  39526. */
  39527. getFirstTargetAxisModel: function () {
  39528. var firstAxisModel;
  39529. eachAxisDim(function (dimNames) {
  39530. if (firstAxisModel == null) {
  39531. var indices = this.get(dimNames.axisIndex);
  39532. if (indices.length) {
  39533. firstAxisModel = this.dependentModels[dimNames.axis][indices[0]];
  39534. }
  39535. }
  39536. }, this);
  39537. return firstAxisModel;
  39538. },
  39539. /**
  39540. * @public
  39541. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  39542. */
  39543. eachTargetAxis: function (callback, context) {
  39544. var ecModel = this.ecModel;
  39545. eachAxisDim(function (dimNames) {
  39546. each$13(
  39547. this.get(dimNames.axisIndex),
  39548. function (axisIndex) {
  39549. callback.call(context, dimNames, axisIndex, this, ecModel);
  39550. },
  39551. this
  39552. );
  39553. }, this);
  39554. },
  39555. /**
  39556. * @param {string} dimName
  39557. * @param {number} axisIndex
  39558. * @return {module:echarts/component/dataZoom/AxisProxy} If not found, return null/undefined.
  39559. */
  39560. getAxisProxy: function (dimName, axisIndex) {
  39561. return this._axisProxies[dimName + '_' + axisIndex];
  39562. },
  39563. /**
  39564. * @param {string} dimName
  39565. * @param {number} axisIndex
  39566. * @return {module:echarts/model/Model} If not found, return null/undefined.
  39567. */
  39568. getAxisModel: function (dimName, axisIndex) {
  39569. var axisProxy = this.getAxisProxy(dimName, axisIndex);
  39570. return axisProxy && axisProxy.getAxisModel();
  39571. },
  39572. /**
  39573. * If not specified, set to undefined.
  39574. *
  39575. * @public
  39576. * @param {Object} opt
  39577. * @param {number} [opt.start]
  39578. * @param {number} [opt.end]
  39579. * @param {number} [opt.startValue]
  39580. * @param {number} [opt.endValue]
  39581. * @param {boolean} [ignoreUpdateRangeUsg=false]
  39582. */
  39583. setRawRange: function (opt, ignoreUpdateRangeUsg) {
  39584. var option = this.option;
  39585. each$13([['start', 'startValue'], ['end', 'endValue']], function (names) {
  39586. // If only one of 'start' and 'startValue' is not null/undefined, the other
  39587. // should be cleared, which enable clear the option.
  39588. // If both of them are not set, keep option with the original value, which
  39589. // enable use only set start but not set end when calling `dispatchAction`.
  39590. // The same as 'end' and 'endValue'.
  39591. if (opt[names[0]] != null || opt[names[1]] != null) {
  39592. option[names[0]] = opt[names[0]];
  39593. option[names[1]] = opt[names[1]];
  39594. }
  39595. }, this);
  39596. !ignoreUpdateRangeUsg && updateRangeUse(this, opt);
  39597. },
  39598. /**
  39599. * @public
  39600. * @return {Array.<number>} [startPercent, endPercent]
  39601. */
  39602. getPercentRange: function () {
  39603. var axisProxy = this.findRepresentativeAxisProxy();
  39604. if (axisProxy) {
  39605. return axisProxy.getDataPercentWindow();
  39606. }
  39607. },
  39608. /**
  39609. * @public
  39610. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  39611. *
  39612. * @param {string} [axisDimName]
  39613. * @param {number} [axisIndex]
  39614. * @return {Array.<number>} [startValue, endValue] value can only be '-' or finite number.
  39615. */
  39616. getValueRange: function (axisDimName, axisIndex) {
  39617. if (axisDimName == null && axisIndex == null) {
  39618. var axisProxy = this.findRepresentativeAxisProxy();
  39619. if (axisProxy) {
  39620. return axisProxy.getDataValueWindow();
  39621. }
  39622. }
  39623. else {
  39624. return this.getAxisProxy(axisDimName, axisIndex).getDataValueWindow();
  39625. }
  39626. },
  39627. /**
  39628. * @public
  39629. * @param {module:echarts/model/Model} [axisModel] If axisModel given, find axisProxy
  39630. * corresponding to the axisModel
  39631. * @return {module:echarts/component/dataZoom/AxisProxy}
  39632. */
  39633. findRepresentativeAxisProxy: function (axisModel) {
  39634. if (axisModel) {
  39635. return axisModel.__dzAxisProxy;
  39636. }
  39637. // Find the first hosted axisProxy
  39638. var axisProxies = this._axisProxies;
  39639. for (var key in axisProxies) {
  39640. if (axisProxies.hasOwnProperty(key) && axisProxies[key].hostedBy(this)) {
  39641. return axisProxies[key];
  39642. }
  39643. }
  39644. // If no hosted axis find not hosted axisProxy.
  39645. // Consider this case: dataZoomModel1 and dataZoomModel2 control the same axis,
  39646. // and the option.start or option.end settings are different. The percentRange
  39647. // should follow axisProxy.
  39648. // (We encounter this problem in toolbox data zoom.)
  39649. for (var key in axisProxies) {
  39650. if (axisProxies.hasOwnProperty(key) && !axisProxies[key].hostedBy(this)) {
  39651. return axisProxies[key];
  39652. }
  39653. }
  39654. },
  39655. /**
  39656. * @return {Array.<string>}
  39657. */
  39658. getRangePropMode: function () {
  39659. return this._rangePropMode.slice();
  39660. }
  39661. });
  39662. function retrieveRaw(option) {
  39663. var ret = {};
  39664. each$13(
  39665. ['start', 'end', 'startValue', 'endValue', 'throttle'],
  39666. function (name) {
  39667. option.hasOwnProperty(name) && (ret[name] = option[name]);
  39668. }
  39669. );
  39670. return ret;
  39671. }
  39672. function updateRangeUse(dataZoomModel, rawOption) {
  39673. var rangePropMode = dataZoomModel._rangePropMode;
  39674. var rangeModeInOption = dataZoomModel.get('rangeMode');
  39675. each$13([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  39676. var percentSpecified = rawOption[names[0]] != null;
  39677. var valueSpecified = rawOption[names[1]] != null;
  39678. if (percentSpecified && !valueSpecified) {
  39679. rangePropMode[index] = 'percent';
  39680. }
  39681. else if (!percentSpecified && valueSpecified) {
  39682. rangePropMode[index] = 'value';
  39683. }
  39684. else if (rangeModeInOption) {
  39685. rangePropMode[index] = rangeModeInOption[index];
  39686. }
  39687. else if (percentSpecified) { // percentSpecified && valueSpecified
  39688. rangePropMode[index] = 'percent';
  39689. }
  39690. // else remain its original setting.
  39691. });
  39692. }
  39693. var DataZoomView = Component$1.extend({
  39694. type: 'dataZoom',
  39695. render: function (dataZoomModel, ecModel, api, payload) {
  39696. this.dataZoomModel = dataZoomModel;
  39697. this.ecModel = ecModel;
  39698. this.api = api;
  39699. },
  39700. /**
  39701. * Find the first target coordinate system.
  39702. *
  39703. * @protected
  39704. * @return {Object} {
  39705. * grid: [
  39706. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  39707. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  39708. * ...
  39709. * ], // cartesians must not be null/undefined.
  39710. * polar: [
  39711. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  39712. * ...
  39713. * ], // polars must not be null/undefined.
  39714. * singleAxis: [
  39715. * {model: coord0, axisModels: [], coordIndex: 0}
  39716. * ]
  39717. */
  39718. getTargetCoordInfo: function () {
  39719. var dataZoomModel = this.dataZoomModel;
  39720. var ecModel = this.ecModel;
  39721. var coordSysLists = {};
  39722. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  39723. var axisModel = ecModel.getComponent(dimNames.axis, axisIndex);
  39724. if (axisModel) {
  39725. var coordModel = axisModel.getCoordSysModel();
  39726. coordModel && save(
  39727. coordModel,
  39728. axisModel,
  39729. coordSysLists[coordModel.mainType] || (coordSysLists[coordModel.mainType] = []),
  39730. coordModel.componentIndex
  39731. );
  39732. }
  39733. }, this);
  39734. function save(coordModel, axisModel, store, coordIndex) {
  39735. var item;
  39736. for (var i = 0; i < store.length; i++) {
  39737. if (store[i].model === coordModel) {
  39738. item = store[i];
  39739. break;
  39740. }
  39741. }
  39742. if (!item) {
  39743. store.push(item = {
  39744. model: coordModel, axisModels: [], coordIndex: coordIndex
  39745. });
  39746. }
  39747. item.axisModels.push(axisModel);
  39748. }
  39749. return coordSysLists;
  39750. }
  39751. });
  39752. var SliderZoomModel = DataZoomModel.extend({
  39753. type: 'dataZoom.slider',
  39754. layoutMode: 'box',
  39755. /**
  39756. * @protected
  39757. */
  39758. defaultOption: {
  39759. show: true,
  39760. // ph => placeholder. Using placehoder here because
  39761. // deault value can only be drived in view stage.
  39762. right: 'ph', // Default align to grid rect.
  39763. top: 'ph', // Default align to grid rect.
  39764. width: 'ph', // Default align to grid rect.
  39765. height: 'ph', // Default align to grid rect.
  39766. left: null, // Default align to grid rect.
  39767. bottom: null, // Default align to grid rect.
  39768. backgroundColor: 'rgba(47,69,84,0)', // Background of slider zoom component.
  39769. // dataBackgroundColor: '#ddd', // Background coor of data shadow and border of box,
  39770. // highest priority, remain for compatibility of
  39771. // previous version, but not recommended any more.
  39772. dataBackground: {
  39773. lineStyle: {
  39774. color: '#2f4554',
  39775. width: 0.5,
  39776. opacity: 0.3
  39777. },
  39778. areaStyle: {
  39779. color: 'rgba(47,69,84,0.3)',
  39780. opacity: 0.3
  39781. }
  39782. },
  39783. borderColor: '#ddd', // border color of the box. For compatibility,
  39784. // if dataBackgroundColor is set, borderColor
  39785. // is ignored.
  39786. fillerColor: 'rgba(167,183,204,0.4)', // Color of selected area.
  39787. // handleColor: 'rgba(89,170,216,0.95)', // Color of handle.
  39788. // 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',
  39789. 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',
  39790. // Percent of the slider height
  39791. handleSize: '100%',
  39792. handleStyle: {
  39793. color: '#a7b7cc'
  39794. },
  39795. labelPrecision: null,
  39796. labelFormatter: null,
  39797. showDetail: true,
  39798. showDataShadow: 'auto', // Default auto decision.
  39799. realtime: true,
  39800. zoomLock: false, // Whether disable zoom.
  39801. textStyle: {
  39802. color: '#333'
  39803. }
  39804. }
  39805. });
  39806. /**
  39807. * Calculate slider move result.
  39808. * Usage:
  39809. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  39810. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  39811. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  39812. *
  39813. * @param {number} delta Move length.
  39814. * @param {Array.<number>} handleEnds handleEnds[0] can be bigger then handleEnds[1].
  39815. * handleEnds will be modified in this method.
  39816. * @param {Array.<number>} extent handleEnds is restricted by extent.
  39817. * extent[0] should less or equals than extent[1].
  39818. * @param {number|string} handleIndex Can be 'all', means that both move the two handleEnds,
  39819. * where the input minSpan and maxSpan will not work.
  39820. * @param {number} [minSpan] The range of dataZoom can not be smaller than that.
  39821. * If not set, handle0 and cross handle1. If set as a non-negative
  39822. * number (including `0`), handles will push each other when reaching
  39823. * the minSpan.
  39824. * @param {number} [maxSpan] The range of dataZoom can not be larger than that.
  39825. * @return {Array.<number>} The input handleEnds.
  39826. */
  39827. var sliderMove = function (delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  39828. // Normalize firstly.
  39829. handleEnds[0] = restrict(handleEnds[0], extent);
  39830. handleEnds[1] = restrict(handleEnds[1], extent);
  39831. delta = delta || 0;
  39832. var extentSpan = extent[1] - extent[0];
  39833. // Notice maxSpan and minSpan can be null/undefined.
  39834. if (minSpan != null) {
  39835. minSpan = restrict(minSpan, [0, extentSpan]);
  39836. }
  39837. if (maxSpan != null) {
  39838. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  39839. }
  39840. if (handleIndex === 'all') {
  39841. minSpan = maxSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  39842. handleIndex = 0;
  39843. }
  39844. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  39845. handleEnds[handleIndex] += delta;
  39846. // Restrict in extent.
  39847. var extentMinSpan = minSpan || 0;
  39848. var realExtent = extent.slice();
  39849. originalDistSign.sign < 0 ? (realExtent[0] += extentMinSpan) : (realExtent[1] -= extentMinSpan);
  39850. handleEnds[handleIndex] = restrict(handleEnds[handleIndex], realExtent);
  39851. // Expand span.
  39852. var currDistSign = getSpanSign(handleEnds, handleIndex);
  39853. if (minSpan != null && (
  39854. currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan
  39855. )) {
  39856. // If minSpan exists, 'cross' is forbinden.
  39857. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  39858. }
  39859. // Shrink span.
  39860. var currDistSign = getSpanSign(handleEnds, handleIndex);
  39861. if (maxSpan != null && currDistSign.span > maxSpan) {
  39862. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  39863. }
  39864. return handleEnds;
  39865. };
  39866. function getSpanSign(handleEnds, handleIndex) {
  39867. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex];
  39868. // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  39869. // is at left of handleEnds[1] for non-cross case.
  39870. return {span: Math.abs(dist), sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1};
  39871. }
  39872. function restrict(value, extend) {
  39873. return Math.min(extend[1], Math.max(extend[0], value));
  39874. }
  39875. var Rect$1 = Rect;
  39876. var linearMap$2 = linearMap;
  39877. var asc$2 = asc;
  39878. var bind$3 = bind;
  39879. var each$15 = each$1;
  39880. // Constants
  39881. var DEFAULT_LOCATION_EDGE_GAP = 7;
  39882. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  39883. var DEFAULT_FILLER_SIZE = 30;
  39884. var HORIZONTAL = 'horizontal';
  39885. var VERTICAL = 'vertical';
  39886. var LABEL_GAP = 5;
  39887. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  39888. var SliderZoomView = DataZoomView.extend({
  39889. type: 'dataZoom.slider',
  39890. init: function (ecModel, api) {
  39891. /**
  39892. * @private
  39893. * @type {Object}
  39894. */
  39895. this._displayables = {};
  39896. /**
  39897. * @private
  39898. * @type {string}
  39899. */
  39900. this._orient;
  39901. /**
  39902. * [0, 100]
  39903. * @private
  39904. */
  39905. this._range;
  39906. /**
  39907. * [coord of the first handle, coord of the second handle]
  39908. * @private
  39909. */
  39910. this._handleEnds;
  39911. /**
  39912. * [length, thick]
  39913. * @private
  39914. * @type {Array.<number>}
  39915. */
  39916. this._size;
  39917. /**
  39918. * @private
  39919. * @type {number}
  39920. */
  39921. this._handleWidth;
  39922. /**
  39923. * @private
  39924. * @type {number}
  39925. */
  39926. this._handleHeight;
  39927. /**
  39928. * @private
  39929. */
  39930. this._location;
  39931. /**
  39932. * @private
  39933. */
  39934. this._dragging;
  39935. /**
  39936. * @private
  39937. */
  39938. this._dataShadowInfo;
  39939. this.api = api;
  39940. },
  39941. /**
  39942. * @override
  39943. */
  39944. render: function (dataZoomModel, ecModel, api, payload) {
  39945. SliderZoomView.superApply(this, 'render', arguments);
  39946. createOrUpdate(
  39947. this,
  39948. '_dispatchZoomAction',
  39949. this.dataZoomModel.get('throttle'),
  39950. 'fixRate'
  39951. );
  39952. this._orient = dataZoomModel.get('orient');
  39953. if (this.dataZoomModel.get('show') === false) {
  39954. this.group.removeAll();
  39955. return;
  39956. }
  39957. // Notice: this._resetInterval() should not be executed when payload.type
  39958. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  39959. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  39960. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  39961. this._buildView();
  39962. }
  39963. this._updateView();
  39964. },
  39965. /**
  39966. * @override
  39967. */
  39968. remove: function () {
  39969. SliderZoomView.superApply(this, 'remove', arguments);
  39970. clear(this, '_dispatchZoomAction');
  39971. },
  39972. /**
  39973. * @override
  39974. */
  39975. dispose: function () {
  39976. SliderZoomView.superApply(this, 'dispose', arguments);
  39977. clear(this, '_dispatchZoomAction');
  39978. },
  39979. _buildView: function () {
  39980. var thisGroup = this.group;
  39981. thisGroup.removeAll();
  39982. this._resetLocation();
  39983. this._resetInterval();
  39984. var barGroup = this._displayables.barGroup = new Group();
  39985. this._renderBackground();
  39986. this._renderHandle();
  39987. this._renderDataShadow();
  39988. thisGroup.add(barGroup);
  39989. this._positionGroup();
  39990. },
  39991. /**
  39992. * @private
  39993. */
  39994. _resetLocation: function () {
  39995. var dataZoomModel = this.dataZoomModel;
  39996. var api = this.api;
  39997. // If some of x/y/width/height are not specified,
  39998. // auto-adapt according to target grid.
  39999. var coordRect = this._findCoordRect();
  40000. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  40001. // Default align by coordinate system rect.
  40002. var positionInfo = this._orient === HORIZONTAL
  40003. ? {
  40004. // Why using 'right', because right should be used in vertical,
  40005. // and it is better to be consistent for dealing with position param merge.
  40006. right: ecSize.width - coordRect.x - coordRect.width,
  40007. top: (ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP),
  40008. width: coordRect.width,
  40009. height: DEFAULT_FILLER_SIZE
  40010. }
  40011. : { // vertical
  40012. right: DEFAULT_LOCATION_EDGE_GAP,
  40013. top: coordRect.y,
  40014. width: DEFAULT_FILLER_SIZE,
  40015. height: coordRect.height
  40016. };
  40017. // Do not write back to option and replace value 'ph', because
  40018. // the 'ph' value should be recalculated when resize.
  40019. var layoutParams = getLayoutParams(dataZoomModel.option);
  40020. // Replace the placeholder value.
  40021. each$1(['right', 'top', 'width', 'height'], function (name) {
  40022. if (layoutParams[name] === 'ph') {
  40023. layoutParams[name] = positionInfo[name];
  40024. }
  40025. });
  40026. var layoutRect = getLayoutRect(
  40027. layoutParams,
  40028. ecSize,
  40029. dataZoomModel.padding
  40030. );
  40031. this._location = {x: layoutRect.x, y: layoutRect.y};
  40032. this._size = [layoutRect.width, layoutRect.height];
  40033. this._orient === VERTICAL && this._size.reverse();
  40034. },
  40035. /**
  40036. * @private
  40037. */
  40038. _positionGroup: function () {
  40039. var thisGroup = this.group;
  40040. var location = this._location;
  40041. var orient = this._orient;
  40042. // Just use the first axis to determine mapping.
  40043. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  40044. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  40045. var barGroup = this._displayables.barGroup;
  40046. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse;
  40047. // Transform barGroup.
  40048. barGroup.attr(
  40049. (orient === HORIZONTAL && !inverse)
  40050. ? {scale: otherAxisInverse ? [1, 1] : [1, -1]}
  40051. : (orient === HORIZONTAL && inverse)
  40052. ? {scale: otherAxisInverse ? [-1, 1] : [-1, -1]}
  40053. : (orient === VERTICAL && !inverse)
  40054. ? {scale: otherAxisInverse ? [1, -1] : [1, 1], rotation: Math.PI / 2}
  40055. // Dont use Math.PI, considering shadow direction.
  40056. : {scale: otherAxisInverse ? [-1, -1] : [-1, 1], rotation: Math.PI / 2}
  40057. );
  40058. // Position barGroup
  40059. var rect = thisGroup.getBoundingRect([barGroup]);
  40060. thisGroup.attr('position', [location.x - rect.x, location.y - rect.y]);
  40061. },
  40062. /**
  40063. * @private
  40064. */
  40065. _getViewExtent: function () {
  40066. return [0, this._size[0]];
  40067. },
  40068. _renderBackground: function () {
  40069. var dataZoomModel = this.dataZoomModel;
  40070. var size = this._size;
  40071. var barGroup = this._displayables.barGroup;
  40072. barGroup.add(new Rect$1({
  40073. silent: true,
  40074. shape: {
  40075. x: 0, y: 0, width: size[0], height: size[1]
  40076. },
  40077. style: {
  40078. fill: dataZoomModel.get('backgroundColor')
  40079. },
  40080. z2: -40
  40081. }));
  40082. // Click panel, over shadow, below handles.
  40083. barGroup.add(new Rect$1({
  40084. shape: {
  40085. x: 0, y: 0, width: size[0], height: size[1]
  40086. },
  40087. style: {
  40088. fill: 'transparent'
  40089. },
  40090. z2: 0,
  40091. onclick: bind(this._onClickPanelClick, this)
  40092. }));
  40093. },
  40094. _renderDataShadow: function () {
  40095. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  40096. if (!info) {
  40097. return;
  40098. }
  40099. var size = this._size;
  40100. var seriesModel = info.series;
  40101. var data = seriesModel.getRawData();
  40102. var otherDim = seriesModel.getShadowDim
  40103. ? seriesModel.getShadowDim() // @see candlestick
  40104. : info.otherDim;
  40105. if (otherDim == null) {
  40106. return;
  40107. }
  40108. var otherDataExtent = data.getDataExtent(otherDim);
  40109. // Nice extent.
  40110. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
  40111. otherDataExtent = [
  40112. otherDataExtent[0] - otherOffset,
  40113. otherDataExtent[1] + otherOffset
  40114. ];
  40115. var otherShadowExtent = [0, size[1]];
  40116. var thisShadowExtent = [0, size[0]];
  40117. var areaPoints = [[size[0], 0], [0, 0]];
  40118. var linePoints = [];
  40119. var step = thisShadowExtent[1] / (data.count() - 1);
  40120. var thisCoord = 0;
  40121. // Optimize for large data shadow
  40122. var stride = Math.round(data.count() / size[0]);
  40123. var lastIsEmpty;
  40124. data.each([otherDim], function (value, index) {
  40125. if (stride > 0 && (index % stride)) {
  40126. thisCoord += step;
  40127. return;
  40128. }
  40129. // FIXME
  40130. // Should consider axis.min/axis.max when drawing dataShadow.
  40131. // FIXME
  40132. // 应该使用统一的空判断?还是在list里进行空判断?
  40133. var isEmpty = value == null || isNaN(value) || value === '';
  40134. // See #4235.
  40135. var otherCoord = isEmpty
  40136. ? 0 : linearMap$2(value, otherDataExtent, otherShadowExtent, true);
  40137. // Attempt to draw data shadow precisely when there are empty value.
  40138. if (isEmpty && !lastIsEmpty && index) {
  40139. areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
  40140. linePoints.push([linePoints[linePoints.length - 1][0], 0]);
  40141. }
  40142. else if (!isEmpty && lastIsEmpty) {
  40143. areaPoints.push([thisCoord, 0]);
  40144. linePoints.push([thisCoord, 0]);
  40145. }
  40146. areaPoints.push([thisCoord, otherCoord]);
  40147. linePoints.push([thisCoord, otherCoord]);
  40148. thisCoord += step;
  40149. lastIsEmpty = isEmpty;
  40150. });
  40151. var dataZoomModel = this.dataZoomModel;
  40152. // var dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  40153. this._displayables.barGroup.add(new Polygon({
  40154. shape: {points: areaPoints},
  40155. style: defaults(
  40156. {fill: dataZoomModel.get('dataBackgroundColor')},
  40157. dataZoomModel.getModel('dataBackground.areaStyle').getAreaStyle()
  40158. ),
  40159. silent: true,
  40160. z2: -20
  40161. }));
  40162. this._displayables.barGroup.add(new Polyline({
  40163. shape: {points: linePoints},
  40164. style: dataZoomModel.getModel('dataBackground.lineStyle').getLineStyle(),
  40165. silent: true,
  40166. z2: -19
  40167. }));
  40168. },
  40169. _prepareDataShadowInfo: function () {
  40170. var dataZoomModel = this.dataZoomModel;
  40171. var showDataShadow = dataZoomModel.get('showDataShadow');
  40172. if (showDataShadow === false) {
  40173. return;
  40174. }
  40175. // Find a representative series.
  40176. var result;
  40177. var ecModel = this.ecModel;
  40178. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  40179. var seriesModels = dataZoomModel
  40180. .getAxisProxy(dimNames.name, axisIndex)
  40181. .getTargetSeriesModels();
  40182. each$1(seriesModels, function (seriesModel) {
  40183. if (result) {
  40184. return;
  40185. }
  40186. if (showDataShadow !== true && indexOf(
  40187. SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')
  40188. ) < 0
  40189. ) {
  40190. return;
  40191. }
  40192. var thisAxis = ecModel.getComponent(dimNames.axis, axisIndex).axis;
  40193. var otherDim = getOtherDim(dimNames.name);
  40194. var otherAxisInverse;
  40195. var coordSys = seriesModel.coordinateSystem;
  40196. if (otherDim != null && coordSys.getOtherAxis) {
  40197. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  40198. }
  40199. otherDim = seriesModel.getData().mapDimension(otherDim);
  40200. result = {
  40201. thisAxis: thisAxis,
  40202. series: seriesModel,
  40203. thisDim: dimNames.name,
  40204. otherDim: otherDim,
  40205. otherAxisInverse: otherAxisInverse
  40206. };
  40207. }, this);
  40208. }, this);
  40209. return result;
  40210. },
  40211. _renderHandle: function () {
  40212. var displaybles = this._displayables;
  40213. var handles = displaybles.handles = [];
  40214. var handleLabels = displaybles.handleLabels = [];
  40215. var barGroup = this._displayables.barGroup;
  40216. var size = this._size;
  40217. var dataZoomModel = this.dataZoomModel;
  40218. barGroup.add(displaybles.filler = new Rect$1({
  40219. draggable: true,
  40220. cursor: getCursor(this._orient),
  40221. drift: bind$3(this._onDragMove, this, 'all'),
  40222. onmousemove: function (e) {
  40223. // Fot mobile devicem, prevent screen slider on the button.
  40224. stop(e.event);
  40225. },
  40226. ondragstart: bind$3(this._showDataInfo, this, true),
  40227. ondragend: bind$3(this._onDragEnd, this),
  40228. onmouseover: bind$3(this._showDataInfo, this, true),
  40229. onmouseout: bind$3(this._showDataInfo, this, false),
  40230. style: {
  40231. fill: dataZoomModel.get('fillerColor'),
  40232. textPosition : 'inside'
  40233. }
  40234. }));
  40235. // Frame border.
  40236. barGroup.add(new Rect$1(subPixelOptimizeRect({
  40237. silent: true,
  40238. shape: {
  40239. x: 0,
  40240. y: 0,
  40241. width: size[0],
  40242. height: size[1]
  40243. },
  40244. style: {
  40245. stroke: dataZoomModel.get('dataBackgroundColor')
  40246. || dataZoomModel.get('borderColor'),
  40247. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  40248. fill: 'rgba(0,0,0,0)'
  40249. }
  40250. })));
  40251. each$15([0, 1], function (handleIndex) {
  40252. var path = createIcon(
  40253. dataZoomModel.get('handleIcon'),
  40254. {
  40255. cursor: getCursor(this._orient),
  40256. draggable: true,
  40257. drift: bind$3(this._onDragMove, this, handleIndex),
  40258. onmousemove: function (e) {
  40259. // Fot mobile devicem, prevent screen slider on the button.
  40260. stop(e.event);
  40261. },
  40262. ondragend: bind$3(this._onDragEnd, this),
  40263. onmouseover: bind$3(this._showDataInfo, this, true),
  40264. onmouseout: bind$3(this._showDataInfo, this, false)
  40265. },
  40266. {x: -1, y: 0, width: 2, height: 2}
  40267. );
  40268. var bRect = path.getBoundingRect();
  40269. this._handleHeight = parsePercent$1(dataZoomModel.get('handleSize'), this._size[1]);
  40270. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  40271. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  40272. var handleColor = dataZoomModel.get('handleColor');
  40273. // Compatitable with previous version
  40274. if (handleColor != null) {
  40275. path.style.fill = handleColor;
  40276. }
  40277. barGroup.add(handles[handleIndex] = path);
  40278. var textStyleModel = dataZoomModel.textStyleModel;
  40279. this.group.add(
  40280. handleLabels[handleIndex] = new Text({
  40281. silent: true,
  40282. invisible: true,
  40283. style: {
  40284. x: 0, y: 0, text: '',
  40285. textVerticalAlign: 'middle',
  40286. textAlign: 'center',
  40287. textFill: textStyleModel.getTextColor(),
  40288. textFont: textStyleModel.getFont()
  40289. },
  40290. z2: 10
  40291. }));
  40292. }, this);
  40293. },
  40294. /**
  40295. * @private
  40296. */
  40297. _resetInterval: function () {
  40298. var range = this._range = this.dataZoomModel.getPercentRange();
  40299. var viewExtent = this._getViewExtent();
  40300. this._handleEnds = [
  40301. linearMap$2(range[0], [0, 100], viewExtent, true),
  40302. linearMap$2(range[1], [0, 100], viewExtent, true)
  40303. ];
  40304. },
  40305. /**
  40306. * @private
  40307. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  40308. * @param {number} delta
  40309. */
  40310. _updateInterval: function (handleIndex, delta) {
  40311. var dataZoomModel = this.dataZoomModel;
  40312. var handleEnds = this._handleEnds;
  40313. var viewExtend = this._getViewExtent();
  40314. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  40315. var percentExtent = [0, 100];
  40316. sliderMove(
  40317. delta,
  40318. handleEnds,
  40319. viewExtend,
  40320. dataZoomModel.get('zoomLock') ? 'all' : handleIndex,
  40321. minMaxSpan.minSpan != null
  40322. ? linearMap$2(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null,
  40323. minMaxSpan.maxSpan != null
  40324. ? linearMap$2(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null
  40325. );
  40326. this._range = asc$2([
  40327. linearMap$2(handleEnds[0], viewExtend, percentExtent, true),
  40328. linearMap$2(handleEnds[1], viewExtend, percentExtent, true)
  40329. ]);
  40330. },
  40331. /**
  40332. * @private
  40333. */
  40334. _updateView: function (nonRealtime) {
  40335. var displaybles = this._displayables;
  40336. var handleEnds = this._handleEnds;
  40337. var handleInterval = asc$2(handleEnds.slice());
  40338. var size = this._size;
  40339. each$15([0, 1], function (handleIndex) {
  40340. // Handles
  40341. var handle = displaybles.handles[handleIndex];
  40342. var handleHeight = this._handleHeight;
  40343. handle.attr({
  40344. scale: [handleHeight / 2, handleHeight / 2],
  40345. position: [handleEnds[handleIndex], size[1] / 2 - handleHeight / 2]
  40346. });
  40347. }, this);
  40348. // Filler
  40349. displaybles.filler.setShape({
  40350. x: handleInterval[0],
  40351. y: 0,
  40352. width: handleInterval[1] - handleInterval[0],
  40353. height: size[1]
  40354. });
  40355. this._updateDataInfo(nonRealtime);
  40356. },
  40357. /**
  40358. * @private
  40359. */
  40360. _updateDataInfo: function (nonRealtime) {
  40361. var dataZoomModel = this.dataZoomModel;
  40362. var displaybles = this._displayables;
  40363. var handleLabels = displaybles.handleLabels;
  40364. var orient = this._orient;
  40365. var labelTexts = ['', ''];
  40366. // FIXME
  40367. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  40368. if (dataZoomModel.get('showDetail')) {
  40369. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  40370. if (axisProxy) {
  40371. var axis = axisProxy.getAxisModel().axis;
  40372. var range = this._range;
  40373. var dataInterval = nonRealtime
  40374. // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  40375. ? axisProxy.calculateDataWindow({
  40376. start: range[0], end: range[1]
  40377. }).valueWindow
  40378. : axisProxy.getDataValueWindow();
  40379. labelTexts = [
  40380. this._formatLabel(dataInterval[0], axis),
  40381. this._formatLabel(dataInterval[1], axis)
  40382. ];
  40383. }
  40384. }
  40385. var orderedHandleEnds = asc$2(this._handleEnds.slice());
  40386. setLabel.call(this, 0);
  40387. setLabel.call(this, 1);
  40388. function setLabel(handleIndex) {
  40389. // Label
  40390. // Text should not transform by barGroup.
  40391. // Ignore handlers transform
  40392. var barTransform = getTransform(
  40393. displaybles.handles[handleIndex].parent, this.group
  40394. );
  40395. var direction = transformDirection(
  40396. handleIndex === 0 ? 'right' : 'left', barTransform
  40397. );
  40398. var offset = this._handleWidth / 2 + LABEL_GAP;
  40399. var textPoint = applyTransform$1(
  40400. [
  40401. orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset),
  40402. this._size[1] / 2
  40403. ],
  40404. barTransform
  40405. );
  40406. handleLabels[handleIndex].setStyle({
  40407. x: textPoint[0],
  40408. y: textPoint[1],
  40409. textVerticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  40410. textAlign: orient === HORIZONTAL ? direction : 'center',
  40411. text: labelTexts[handleIndex]
  40412. });
  40413. }
  40414. },
  40415. /**
  40416. * @private
  40417. */
  40418. _formatLabel: function (value, axis) {
  40419. var dataZoomModel = this.dataZoomModel;
  40420. var labelFormatter = dataZoomModel.get('labelFormatter');
  40421. var labelPrecision = dataZoomModel.get('labelPrecision');
  40422. if (labelPrecision == null || labelPrecision === 'auto') {
  40423. labelPrecision = axis.getPixelPrecision();
  40424. }
  40425. var valueStr = (value == null || isNaN(value))
  40426. ? ''
  40427. // FIXME Glue code
  40428. : (axis.type === 'category' || axis.type === 'time')
  40429. ? axis.scale.getLabel(Math.round(value))
  40430. // param of toFixed should less then 20.
  40431. : value.toFixed(Math.min(labelPrecision, 20));
  40432. return isFunction$1(labelFormatter)
  40433. ? labelFormatter(value, valueStr)
  40434. : isString(labelFormatter)
  40435. ? labelFormatter.replace('{value}', valueStr)
  40436. : valueStr;
  40437. },
  40438. /**
  40439. * @private
  40440. * @param {boolean} showOrHide true: show, false: hide
  40441. */
  40442. _showDataInfo: function (showOrHide) {
  40443. // Always show when drgging.
  40444. showOrHide = this._dragging || showOrHide;
  40445. var handleLabels = this._displayables.handleLabels;
  40446. handleLabels[0].attr('invisible', !showOrHide);
  40447. handleLabels[1].attr('invisible', !showOrHide);
  40448. },
  40449. _onDragMove: function (handleIndex, dx, dy) {
  40450. this._dragging = true;
  40451. // Transform dx, dy to bar coordination.
  40452. var barTransform = this._displayables.barGroup.getLocalTransform();
  40453. var vertex = applyTransform$1([dx, dy], barTransform, true);
  40454. this._updateInterval(handleIndex, vertex[0]);
  40455. var realtime = this.dataZoomModel.get('realtime');
  40456. this._updateView(!realtime);
  40457. realtime && this._dispatchZoomAction();
  40458. },
  40459. _onDragEnd: function () {
  40460. this._dragging = false;
  40461. this._showDataInfo(false);
  40462. // While in realtime mode and stream mode, dispatch action when
  40463. // drag end will cause the whole view rerender, which is unnecessary.
  40464. var realtime = this.dataZoomModel.get('realtime');
  40465. !realtime && this._dispatchZoomAction();
  40466. },
  40467. _onClickPanelClick: function (e) {
  40468. var size = this._size;
  40469. var localPoint = this._displayables.barGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  40470. if (localPoint[0] < 0 || localPoint[0] > size[0]
  40471. || localPoint[1] < 0 || localPoint[1] > size[1]
  40472. ) {
  40473. return;
  40474. }
  40475. var handleEnds = this._handleEnds;
  40476. var center = (handleEnds[0] + handleEnds[1]) / 2;
  40477. this._updateInterval('all', localPoint[0] - center);
  40478. this._updateView();
  40479. this._dispatchZoomAction();
  40480. },
  40481. /**
  40482. * This action will be throttled.
  40483. * @private
  40484. */
  40485. _dispatchZoomAction: function () {
  40486. var range = this._range;
  40487. this.api.dispatchAction({
  40488. type: 'dataZoom',
  40489. from: this.uid,
  40490. dataZoomId: this.dataZoomModel.id,
  40491. start: range[0],
  40492. end: range[1]
  40493. });
  40494. },
  40495. /**
  40496. * @private
  40497. */
  40498. _findCoordRect: function () {
  40499. // Find the grid coresponding to the first axis referred by dataZoom.
  40500. var rect;
  40501. each$15(this.getTargetCoordInfo(), function (coordInfoList) {
  40502. if (!rect && coordInfoList.length) {
  40503. var coordSys = coordInfoList[0].model.coordinateSystem;
  40504. rect = coordSys.getRect && coordSys.getRect();
  40505. }
  40506. });
  40507. if (!rect) {
  40508. var width = this.api.getWidth();
  40509. var height = this.api.getHeight();
  40510. rect = {
  40511. x: width * 0.2,
  40512. y: height * 0.2,
  40513. width: width * 0.6,
  40514. height: height * 0.6
  40515. };
  40516. }
  40517. return rect;
  40518. }
  40519. });
  40520. function getOtherDim(thisDim) {
  40521. // FIXME
  40522. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  40523. var map$$1 = {x: 'y', y: 'x', radius: 'angle', angle: 'radius'};
  40524. return map$$1[thisDim];
  40525. }
  40526. function getCursor(orient) {
  40527. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  40528. }
  40529. DataZoomModel.extend({
  40530. type: 'dataZoom.inside',
  40531. /**
  40532. * @protected
  40533. */
  40534. defaultOption: {
  40535. disabled: false, // Whether disable this inside zoom.
  40536. zoomLock: false, // Whether disable zoom but only pan.
  40537. zoomOnMouseWheel: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  40538. moveOnMouseMove: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  40539. preventDefaultMouseMove: true
  40540. }
  40541. });
  40542. var ATTR$1 = '\0_ec_interaction_mutex';
  40543. function take(zr, resourceKey, userKey) {
  40544. var store = getStore(zr);
  40545. store[resourceKey] = userKey;
  40546. }
  40547. function release(zr, resourceKey, userKey) {
  40548. var store = getStore(zr);
  40549. var uKey = store[resourceKey];
  40550. if (uKey === userKey) {
  40551. store[resourceKey] = null;
  40552. }
  40553. }
  40554. function isTaken(zr, resourceKey) {
  40555. return !!getStore(zr)[resourceKey];
  40556. }
  40557. function getStore(zr) {
  40558. return zr[ATTR$1] || (zr[ATTR$1] = {});
  40559. }
  40560. /**
  40561. * payload: {
  40562. * type: 'takeGlobalCursor',
  40563. * key: 'dataZoomSelect', or 'brush', or ...,
  40564. * If no userKey, release global cursor.
  40565. * }
  40566. */
  40567. registerAction(
  40568. {type: 'takeGlobalCursor', event: 'globalCursorTaken', update: 'update'},
  40569. function () {}
  40570. );
  40571. /**
  40572. * @alias module:echarts/component/helper/RoamController
  40573. * @constructor
  40574. * @mixin {module:zrender/mixin/Eventful}
  40575. *
  40576. * @param {module:zrender/zrender~ZRender} zr
  40577. */
  40578. function RoamController(zr) {
  40579. /**
  40580. * @type {Function}
  40581. */
  40582. this.pointerChecker;
  40583. /**
  40584. * @type {module:zrender}
  40585. */
  40586. this._zr = zr;
  40587. /**
  40588. * @type {Object}
  40589. */
  40590. this._opt = {};
  40591. // Avoid two roamController bind the same handler
  40592. var bind$$1 = bind;
  40593. var mousedownHandler = bind$$1(mousedown, this);
  40594. var mousemoveHandler = bind$$1(mousemove, this);
  40595. var mouseupHandler = bind$$1(mouseup, this);
  40596. var mousewheelHandler = bind$$1(mousewheel, this);
  40597. var pinchHandler = bind$$1(pinch, this);
  40598. Eventful.call(this);
  40599. /**
  40600. * @param {Function} pointerChecker
  40601. * input: x, y
  40602. * output: boolean
  40603. */
  40604. this.setPointerChecker = function (pointerChecker) {
  40605. this.pointerChecker = pointerChecker;
  40606. };
  40607. /**
  40608. * Notice: only enable needed types. For example, if 'zoom'
  40609. * is not needed, 'zoom' should not be enabled, otherwise
  40610. * default mousewheel behaviour (scroll page) will be disabled.
  40611. *
  40612. * @param {boolean|string} [controlType=true] Specify the control type,
  40613. * which can be null/undefined or true/false
  40614. * or 'pan/move' or 'zoom'/'scale'
  40615. * @param {Object} [opt]
  40616. * @param {Object} [opt.zoomOnMouseWheel=true]
  40617. * @param {Object} [opt.moveOnMouseMove=true]
  40618. * @param {Object} [opt.preventDefaultMouseMove=true] When pan.
  40619. */
  40620. this.enable = function (controlType, opt) {
  40621. // Disable previous first
  40622. this.disable();
  40623. this._opt = defaults(clone(opt) || {}, {
  40624. zoomOnMouseWheel: true,
  40625. moveOnMouseMove: true,
  40626. preventDefaultMouseMove: true
  40627. });
  40628. if (controlType == null) {
  40629. controlType = true;
  40630. }
  40631. if (controlType === true || (controlType === 'move' || controlType === 'pan')) {
  40632. zr.on('mousedown', mousedownHandler);
  40633. zr.on('mousemove', mousemoveHandler);
  40634. zr.on('mouseup', mouseupHandler);
  40635. }
  40636. if (controlType === true || (controlType === 'scale' || controlType === 'zoom')) {
  40637. zr.on('mousewheel', mousewheelHandler);
  40638. zr.on('pinch', pinchHandler);
  40639. }
  40640. };
  40641. this.disable = function () {
  40642. zr.off('mousedown', mousedownHandler);
  40643. zr.off('mousemove', mousemoveHandler);
  40644. zr.off('mouseup', mouseupHandler);
  40645. zr.off('mousewheel', mousewheelHandler);
  40646. zr.off('pinch', pinchHandler);
  40647. };
  40648. this.dispose = this.disable;
  40649. this.isDragging = function () {
  40650. return this._dragging;
  40651. };
  40652. this.isPinching = function () {
  40653. return this._pinching;
  40654. };
  40655. }
  40656. mixin(RoamController, Eventful);
  40657. function mousedown(e) {
  40658. if (notLeftMouse(e)
  40659. || (e.target && e.target.draggable)
  40660. ) {
  40661. return;
  40662. }
  40663. var x = e.offsetX;
  40664. var y = e.offsetY;
  40665. // Only check on mosedown, but not mousemove.
  40666. // Mouse can be out of target when mouse moving.
  40667. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  40668. this._x = x;
  40669. this._y = y;
  40670. this._dragging = true;
  40671. }
  40672. }
  40673. function mousemove(e) {
  40674. if (notLeftMouse(e)
  40675. || !checkKeyBinding(this, 'moveOnMouseMove', e)
  40676. || !this._dragging
  40677. || e.gestureEvent === 'pinch'
  40678. || isTaken(this._zr, 'globalPan')
  40679. ) {
  40680. return;
  40681. }
  40682. var x = e.offsetX;
  40683. var y = e.offsetY;
  40684. var oldX = this._x;
  40685. var oldY = this._y;
  40686. var dx = x - oldX;
  40687. var dy = y - oldY;
  40688. this._x = x;
  40689. this._y = y;
  40690. this._opt.preventDefaultMouseMove && stop(e.event);
  40691. this.trigger('pan', dx, dy, oldX, oldY, x, y);
  40692. }
  40693. function mouseup(e) {
  40694. if (!notLeftMouse(e)) {
  40695. this._dragging = false;
  40696. }
  40697. }
  40698. function mousewheel(e) {
  40699. // wheelDelta maybe -0 in chrome mac.
  40700. if (!checkKeyBinding(this, 'zoomOnMouseWheel', e) || e.wheelDelta === 0) {
  40701. return;
  40702. }
  40703. // Convenience:
  40704. // Mac and VM Windows on Mac: scroll up: zoom out.
  40705. // Windows: scroll up: zoom in.
  40706. var zoomDelta = e.wheelDelta > 0 ? 1.1 : 1 / 1.1;
  40707. zoom.call(this, e, zoomDelta, e.offsetX, e.offsetY);
  40708. }
  40709. function pinch(e) {
  40710. if (isTaken(this._zr, 'globalPan')) {
  40711. return;
  40712. }
  40713. var zoomDelta = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  40714. zoom.call(this, e, zoomDelta, e.pinchX, e.pinchY);
  40715. }
  40716. function zoom(e, zoomDelta, zoomX, zoomY) {
  40717. if (this.pointerChecker && this.pointerChecker(e, zoomX, zoomY)) {
  40718. // When mouse is out of roamController rect,
  40719. // default befavoius should not be be disabled, otherwise
  40720. // page sliding is disabled, contrary to expectation.
  40721. stop(e.event);
  40722. this.trigger('zoom', zoomDelta, zoomX, zoomY);
  40723. }
  40724. }
  40725. function checkKeyBinding(roamController, prop, e) {
  40726. var setting = roamController._opt[prop];
  40727. return setting
  40728. && (!isString(setting) || e.event[setting + 'Key']);
  40729. }
  40730. // Only create one roam controller for each coordinate system.
  40731. // one roam controller might be refered by two inside data zoom
  40732. // components (for example, one for x and one for y). When user
  40733. // pan or zoom, only dispatch one action for those data zoom
  40734. // components.
  40735. var curry$5 = curry;
  40736. var ATTR = '\0_ec_dataZoom_roams';
  40737. /**
  40738. * @public
  40739. * @param {module:echarts/ExtensionAPI} api
  40740. * @param {Object} dataZoomInfo
  40741. * @param {string} dataZoomInfo.coordId
  40742. * @param {Function} dataZoomInfo.containsPoint
  40743. * @param {Array.<string>} dataZoomInfo.allCoordIds
  40744. * @param {string} dataZoomInfo.dataZoomId
  40745. * @param {number} dataZoomInfo.throttleRate
  40746. * @param {Function} dataZoomInfo.panGetRange
  40747. * @param {Function} dataZoomInfo.zoomGetRange
  40748. * @param {boolean} [dataZoomInfo.zoomLock]
  40749. * @param {boolean} [dataZoomInfo.disabled]
  40750. */
  40751. function register$1(api, dataZoomInfo) {
  40752. var store = giveStore(api);
  40753. var theDataZoomId = dataZoomInfo.dataZoomId;
  40754. var theCoordId = dataZoomInfo.coordId;
  40755. // Do clean when a dataZoom changes its target coordnate system.
  40756. // Avoid memory leak, dispose all not-used-registered.
  40757. each$1(store, function (record, coordId) {
  40758. var dataZoomInfos = record.dataZoomInfos;
  40759. if (dataZoomInfos[theDataZoomId]
  40760. && indexOf(dataZoomInfo.allCoordIds, theCoordId) < 0
  40761. ) {
  40762. delete dataZoomInfos[theDataZoomId];
  40763. record.count--;
  40764. }
  40765. });
  40766. cleanStore(store);
  40767. var record = store[theCoordId];
  40768. // Create if needed.
  40769. if (!record) {
  40770. record = store[theCoordId] = {
  40771. coordId: theCoordId,
  40772. dataZoomInfos: {},
  40773. count: 0
  40774. };
  40775. record.controller = createController(api, record);
  40776. record.dispatchAction = curry(dispatchAction, api);
  40777. }
  40778. // Update reference of dataZoom.
  40779. !(record.dataZoomInfos[theDataZoomId]) && record.count++;
  40780. record.dataZoomInfos[theDataZoomId] = dataZoomInfo;
  40781. var controllerParams = mergeControllerParams(record.dataZoomInfos);
  40782. record.controller.enable(controllerParams.controlType, controllerParams.opt);
  40783. // Consider resize, area should be always updated.
  40784. record.controller.setPointerChecker(dataZoomInfo.containsPoint);
  40785. // Update throttle.
  40786. createOrUpdate(
  40787. record,
  40788. 'dispatchAction',
  40789. dataZoomInfo.throttleRate,
  40790. 'fixRate'
  40791. );
  40792. }
  40793. /**
  40794. * @public
  40795. * @param {module:echarts/ExtensionAPI} api
  40796. * @param {string} dataZoomId
  40797. */
  40798. function unregister$1(api, dataZoomId) {
  40799. var store = giveStore(api);
  40800. each$1(store, function (record) {
  40801. record.controller.dispose();
  40802. var dataZoomInfos = record.dataZoomInfos;
  40803. if (dataZoomInfos[dataZoomId]) {
  40804. delete dataZoomInfos[dataZoomId];
  40805. record.count--;
  40806. }
  40807. });
  40808. cleanStore(store);
  40809. }
  40810. /**
  40811. * @public
  40812. */
  40813. function shouldRecordRange(payload, dataZoomId) {
  40814. if (payload && payload.type === 'dataZoom' && payload.batch) {
  40815. for (var i = 0, len = payload.batch.length; i < len; i++) {
  40816. if (payload.batch[i].dataZoomId === dataZoomId) {
  40817. return false;
  40818. }
  40819. }
  40820. }
  40821. return true;
  40822. }
  40823. /**
  40824. * @public
  40825. */
  40826. function generateCoordId(coordModel) {
  40827. return coordModel.type + '\0_' + coordModel.id;
  40828. }
  40829. /**
  40830. * Key: coordId, value: {dataZoomInfos: [], count, controller}
  40831. * @type {Array.<Object>}
  40832. */
  40833. function giveStore(api) {
  40834. // Mount store on zrender instance, so that we do not
  40835. // need to worry about dispose.
  40836. var zr = api.getZr();
  40837. return zr[ATTR] || (zr[ATTR] = {});
  40838. }
  40839. function createController(api, newRecord) {
  40840. var controller = new RoamController(api.getZr());
  40841. controller.on('pan', curry$5(onPan, newRecord));
  40842. controller.on('zoom', curry$5(onZoom, newRecord));
  40843. return controller;
  40844. }
  40845. function cleanStore(store) {
  40846. each$1(store, function (record, coordId) {
  40847. if (!record.count) {
  40848. record.controller.dispose();
  40849. delete store[coordId];
  40850. }
  40851. });
  40852. }
  40853. function onPan(record, dx, dy, oldX, oldY, newX, newY) {
  40854. wrapAndDispatch(record, function (info) {
  40855. return info.panGetRange(record.controller, dx, dy, oldX, oldY, newX, newY);
  40856. });
  40857. }
  40858. function onZoom(record, scale, mouseX, mouseY) {
  40859. wrapAndDispatch(record, function (info) {
  40860. return info.zoomGetRange(record.controller, scale, mouseX, mouseY);
  40861. });
  40862. }
  40863. function wrapAndDispatch(record, getRange) {
  40864. var batch = [];
  40865. each$1(record.dataZoomInfos, function (info) {
  40866. var range = getRange(info);
  40867. !info.disabled && range && batch.push({
  40868. dataZoomId: info.dataZoomId,
  40869. start: range[0],
  40870. end: range[1]
  40871. });
  40872. });
  40873. record.dispatchAction(batch);
  40874. }
  40875. /**
  40876. * This action will be throttled.
  40877. */
  40878. function dispatchAction(api, batch) {
  40879. api.dispatchAction({
  40880. type: 'dataZoom',
  40881. batch: batch
  40882. });
  40883. }
  40884. /**
  40885. * Merge roamController settings when multiple dataZooms share one roamController.
  40886. */
  40887. function mergeControllerParams(dataZoomInfos) {
  40888. var controlType;
  40889. var opt = {};
  40890. // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  40891. // as string, it is probably revert to reserved word by compress tool. See #7411.
  40892. var prefix = 'type_';
  40893. var typePriority = {
  40894. 'type_true': 2,
  40895. 'type_move': 1,
  40896. 'type_false': 0,
  40897. 'type_undefined': -1
  40898. };
  40899. each$1(dataZoomInfos, function (dataZoomInfo) {
  40900. var oneType = dataZoomInfo.disabled ? false : dataZoomInfo.zoomLock ? 'move' : true;
  40901. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  40902. controlType = oneType;
  40903. }
  40904. // Do not support that different 'shift'/'ctrl'/'alt' setting used in one coord sys.
  40905. extend(opt, dataZoomInfo.roamControllerOpt);
  40906. });
  40907. return {
  40908. controlType: controlType,
  40909. opt: opt
  40910. };
  40911. }
  40912. var bind$4 = bind;
  40913. var InsideZoomView = DataZoomView.extend({
  40914. type: 'dataZoom.inside',
  40915. /**
  40916. * @override
  40917. */
  40918. init: function (ecModel, api) {
  40919. /**
  40920. * 'throttle' is used in this.dispatchAction, so we save range
  40921. * to avoid missing some 'pan' info.
  40922. * @private
  40923. * @type {Array.<number>}
  40924. */
  40925. this._range;
  40926. },
  40927. /**
  40928. * @override
  40929. */
  40930. render: function (dataZoomModel, ecModel, api, payload) {
  40931. InsideZoomView.superApply(this, 'render', arguments);
  40932. // Notice: origin this._range should be maintained, and should not be re-fetched
  40933. // from dataZoomModel when payload.type is 'dataZoom', otherwise 'pan' or 'zoom'
  40934. // info will be missed because of 'throttle' of this.dispatchAction.
  40935. if (shouldRecordRange(payload, dataZoomModel.id)) {
  40936. this._range = dataZoomModel.getPercentRange();
  40937. }
  40938. // Reset controllers.
  40939. each$1(this.getTargetCoordInfo(), function (coordInfoList, coordSysName) {
  40940. var allCoordIds = map(coordInfoList, function (coordInfo) {
  40941. return generateCoordId(coordInfo.model);
  40942. });
  40943. each$1(coordInfoList, function (coordInfo) {
  40944. var coordModel = coordInfo.model;
  40945. var dataZoomOption = dataZoomModel.option;
  40946. register$1(
  40947. api,
  40948. {
  40949. coordId: generateCoordId(coordModel),
  40950. allCoordIds: allCoordIds,
  40951. containsPoint: function (e, x, y) {
  40952. return coordModel.coordinateSystem.containPoint([x, y]);
  40953. },
  40954. dataZoomId: dataZoomModel.id,
  40955. throttleRate: dataZoomModel.get('throttle', true),
  40956. panGetRange: bind$4(this._onPan, this, coordInfo, coordSysName),
  40957. zoomGetRange: bind$4(this._onZoom, this, coordInfo, coordSysName),
  40958. zoomLock: dataZoomOption.zoomLock,
  40959. disabled: dataZoomOption.disabled,
  40960. roamControllerOpt: {
  40961. zoomOnMouseWheel: dataZoomOption.zoomOnMouseWheel,
  40962. moveOnMouseMove: dataZoomOption.moveOnMouseMove,
  40963. preventDefaultMouseMove: dataZoomOption.preventDefaultMouseMove
  40964. }
  40965. }
  40966. );
  40967. }, this);
  40968. }, this);
  40969. },
  40970. /**
  40971. * @override
  40972. */
  40973. dispose: function () {
  40974. unregister$1(this.api, this.dataZoomModel.id);
  40975. InsideZoomView.superApply(this, 'dispose', arguments);
  40976. this._range = null;
  40977. },
  40978. /**
  40979. * @private
  40980. */
  40981. _onPan: function (coordInfo, coordSysName, controller, dx, dy, oldX, oldY, newX, newY) {
  40982. var range = this._range.slice();
  40983. // Calculate transform by the first axis.
  40984. var axisModel = coordInfo.axisModels[0];
  40985. if (!axisModel) {
  40986. return;
  40987. }
  40988. var directionInfo = getDirectionInfo[coordSysName](
  40989. [oldX, oldY], [newX, newY], axisModel, controller, coordInfo
  40990. );
  40991. var percentDelta = directionInfo.signal
  40992. * (range[1] - range[0])
  40993. * directionInfo.pixel / directionInfo.pixelLength;
  40994. sliderMove(percentDelta, range, [0, 100], 'all');
  40995. return (this._range = range);
  40996. },
  40997. /**
  40998. * @private
  40999. */
  41000. _onZoom: function (coordInfo, coordSysName, controller, scale, mouseX, mouseY) {
  41001. var range = this._range.slice();
  41002. // Calculate transform by the first axis.
  41003. var axisModel = coordInfo.axisModels[0];
  41004. if (!axisModel) {
  41005. return;
  41006. }
  41007. var directionInfo = getDirectionInfo[coordSysName](
  41008. null, [mouseX, mouseY], axisModel, controller, coordInfo
  41009. );
  41010. var percentPoint = (
  41011. directionInfo.signal > 0
  41012. ? (directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel)
  41013. : (directionInfo.pixel - directionInfo.pixelStart)
  41014. ) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  41015. scale = Math.max(1 / scale, 0);
  41016. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  41017. range[1] = (range[1] - percentPoint) * scale + percentPoint;
  41018. // Restrict range.
  41019. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  41020. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  41021. return (this._range = range);
  41022. }
  41023. });
  41024. var getDirectionInfo = {
  41025. grid: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  41026. var axis = axisModel.axis;
  41027. var ret = {};
  41028. var rect = coordInfo.model.coordinateSystem.getRect();
  41029. oldPoint = oldPoint || [0, 0];
  41030. if (axis.dim === 'x') {
  41031. ret.pixel = newPoint[0] - oldPoint[0];
  41032. ret.pixelLength = rect.width;
  41033. ret.pixelStart = rect.x;
  41034. ret.signal = axis.inverse ? 1 : -1;
  41035. }
  41036. else { // axis.dim === 'y'
  41037. ret.pixel = newPoint[1] - oldPoint[1];
  41038. ret.pixelLength = rect.height;
  41039. ret.pixelStart = rect.y;
  41040. ret.signal = axis.inverse ? -1 : 1;
  41041. }
  41042. return ret;
  41043. },
  41044. polar: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  41045. var axis = axisModel.axis;
  41046. var ret = {};
  41047. var polar = coordInfo.model.coordinateSystem;
  41048. var radiusExtent = polar.getRadiusAxis().getExtent();
  41049. var angleExtent = polar.getAngleAxis().getExtent();
  41050. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  41051. newPoint = polar.pointToCoord(newPoint);
  41052. if (axisModel.mainType === 'radiusAxis') {
  41053. ret.pixel = newPoint[0] - oldPoint[0];
  41054. // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  41055. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  41056. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  41057. ret.pixelStart = radiusExtent[0];
  41058. ret.signal = axis.inverse ? 1 : -1;
  41059. }
  41060. else { // 'angleAxis'
  41061. ret.pixel = newPoint[1] - oldPoint[1];
  41062. // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  41063. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  41064. ret.pixelLength = angleExtent[1] - angleExtent[0];
  41065. ret.pixelStart = angleExtent[0];
  41066. ret.signal = axis.inverse ? -1 : 1;
  41067. }
  41068. return ret;
  41069. },
  41070. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  41071. var axis = axisModel.axis;
  41072. var rect = coordInfo.model.coordinateSystem.getRect();
  41073. var ret = {};
  41074. oldPoint = oldPoint || [0, 0];
  41075. if (axis.orient === 'horizontal') {
  41076. ret.pixel = newPoint[0] - oldPoint[0];
  41077. ret.pixelLength = rect.width;
  41078. ret.pixelStart = rect.x;
  41079. ret.signal = axis.inverse ? 1 : -1;
  41080. }
  41081. else { // 'vertical'
  41082. ret.pixel = newPoint[1] - oldPoint[1];
  41083. ret.pixelLength = rect.height;
  41084. ret.pixelStart = rect.y;
  41085. ret.signal = axis.inverse ? -1 : 1;
  41086. }
  41087. return ret;
  41088. }
  41089. };
  41090. registerProcessor({
  41091. getTargetSeries: function (ecModel) {
  41092. var seriesModelMap = createHashMap();
  41093. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  41094. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  41095. var axisProxy = dataZoomModel.getAxisProxy(dimNames.name, axisIndex);
  41096. each$1(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  41097. seriesModelMap.set(seriesModel.uid, seriesModel);
  41098. });
  41099. });
  41100. });
  41101. return seriesModelMap;
  41102. },
  41103. isOverallFilter: true,
  41104. // Consider appendData, where filter should be performed. Because data process is
  41105. // in block mode currently, it is not need to worry about that the overallProgress
  41106. // execute every frame.
  41107. overallReset: function (ecModel, api) {
  41108. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  41109. // We calculate window and reset axis here but not in model
  41110. // init stage and not after action dispatch handler, because
  41111. // reset should be called after seriesData.restoreData.
  41112. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  41113. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).reset(dataZoomModel, api);
  41114. });
  41115. // Caution: data zoom filtering is order sensitive when using
  41116. // percent range and no min/max/scale set on axis.
  41117. // For example, we have dataZoom definition:
  41118. // [
  41119. // {xAxisIndex: 0, start: 30, end: 70},
  41120. // {yAxisIndex: 0, start: 20, end: 80}
  41121. // ]
  41122. // In this case, [20, 80] of y-dataZoom should be based on data
  41123. // that have filtered by x-dataZoom using range of [30, 70],
  41124. // but should not be based on full raw data. Thus sliding
  41125. // x-dataZoom will change both ranges of xAxis and yAxis,
  41126. // while sliding y-dataZoom will only change the range of yAxis.
  41127. // So we should filter x-axis after reset x-axis immediately,
  41128. // and then reset y-axis and filter y-axis.
  41129. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  41130. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).filterData(dataZoomModel, api);
  41131. });
  41132. });
  41133. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  41134. // Fullfill all of the range props so that user
  41135. // is able to get them from chart.getOption().
  41136. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  41137. var percentRange = axisProxy.getDataPercentWindow();
  41138. var valueRange = axisProxy.getDataValueWindow();
  41139. dataZoomModel.setRawRange({
  41140. start: percentRange[0],
  41141. end: percentRange[1],
  41142. startValue: valueRange[0],
  41143. endValue: valueRange[1]
  41144. }, true);
  41145. });
  41146. }
  41147. });
  41148. registerAction('dataZoom', function (payload, ecModel) {
  41149. var linkedNodesFinder = createLinkedNodesFinder(
  41150. bind(ecModel.eachComponent, ecModel, 'dataZoom'),
  41151. eachAxisDim$1,
  41152. function (model, dimNames) {
  41153. return model.get(dimNames.axisIndex);
  41154. }
  41155. );
  41156. var effectedModels = [];
  41157. ecModel.eachComponent(
  41158. {mainType: 'dataZoom', query: payload},
  41159. function (model, index) {
  41160. effectedModels.push.apply(
  41161. effectedModels, linkedNodesFinder(model).nodes
  41162. );
  41163. }
  41164. );
  41165. each$1(effectedModels, function (dataZoomModel, index) {
  41166. dataZoomModel.setRawRange({
  41167. start: payload.start,
  41168. end: payload.end,
  41169. startValue: payload.startValue,
  41170. endValue: payload.endValue
  41171. });
  41172. });
  41173. });
  41174. /**
  41175. * DataZoom component entry
  41176. */
  41177. var features = {};
  41178. function register$2(name, ctor) {
  41179. features[name] = ctor;
  41180. }
  41181. function get$1(name) {
  41182. return features[name];
  41183. }
  41184. var ToolboxModel = extendComponentModel({
  41185. type: 'toolbox',
  41186. layoutMode: {
  41187. type: 'box',
  41188. ignoreSize: true
  41189. },
  41190. mergeDefaultAndTheme: function (option) {
  41191. ToolboxModel.superApply(this, 'mergeDefaultAndTheme', arguments);
  41192. each$1(this.option.feature, function (featureOpt, featureName) {
  41193. var Feature = get$1(featureName);
  41194. Feature && merge(featureOpt, Feature.defaultOption);
  41195. });
  41196. },
  41197. defaultOption: {
  41198. show: true,
  41199. z: 6,
  41200. zlevel: 0,
  41201. orient: 'horizontal',
  41202. left: 'right',
  41203. top: 'top',
  41204. // right
  41205. // bottom
  41206. backgroundColor: 'transparent',
  41207. borderColor: '#ccc',
  41208. borderRadius: 0,
  41209. borderWidth: 0,
  41210. padding: 5,
  41211. itemSize: 15,
  41212. itemGap: 8,
  41213. showTitle: true,
  41214. iconStyle: {
  41215. borderColor: '#666',
  41216. color: 'none'
  41217. },
  41218. emphasis: {
  41219. iconStyle: {
  41220. borderColor: '#3E98C5'
  41221. }
  41222. }
  41223. // textStyle: {},
  41224. // feature
  41225. }
  41226. });
  41227. extendComponentView({
  41228. type: 'toolbox',
  41229. render: function (toolboxModel, ecModel, api, payload) {
  41230. var group = this.group;
  41231. group.removeAll();
  41232. if (!toolboxModel.get('show')) {
  41233. return;
  41234. }
  41235. var itemSize = +toolboxModel.get('itemSize');
  41236. var featureOpts = toolboxModel.get('feature') || {};
  41237. var features = this._features || (this._features = {});
  41238. var featureNames = [];
  41239. each$1(featureOpts, function (opt, name) {
  41240. featureNames.push(name);
  41241. });
  41242. (new DataDiffer(this._featureNames || [], featureNames))
  41243. .add(processFeature)
  41244. .update(processFeature)
  41245. .remove(curry(processFeature, null))
  41246. .execute();
  41247. // Keep for diff.
  41248. this._featureNames = featureNames;
  41249. function processFeature(newIndex, oldIndex) {
  41250. var featureName = featureNames[newIndex];
  41251. var oldName = featureNames[oldIndex];
  41252. var featureOpt = featureOpts[featureName];
  41253. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  41254. var feature;
  41255. if (featureName && !oldName) { // Create
  41256. if (isUserFeatureName(featureName)) {
  41257. feature = {
  41258. model: featureModel,
  41259. onclick: featureModel.option.onclick,
  41260. featureName: featureName
  41261. };
  41262. }
  41263. else {
  41264. var Feature = get$1(featureName);
  41265. if (!Feature) {
  41266. return;
  41267. }
  41268. feature = new Feature(featureModel, ecModel, api);
  41269. }
  41270. features[featureName] = feature;
  41271. }
  41272. else {
  41273. feature = features[oldName];
  41274. // If feature does not exsit.
  41275. if (!feature) {
  41276. return;
  41277. }
  41278. feature.model = featureModel;
  41279. feature.ecModel = ecModel;
  41280. feature.api = api;
  41281. }
  41282. if (!featureName && oldName) {
  41283. feature.dispose && feature.dispose(ecModel, api);
  41284. return;
  41285. }
  41286. if (!featureModel.get('show') || feature.unusable) {
  41287. feature.remove && feature.remove(ecModel, api);
  41288. return;
  41289. }
  41290. createIconPaths(featureModel, feature, featureName);
  41291. featureModel.setIconStatus = function (iconName, status) {
  41292. var option = this.option;
  41293. var iconPaths = this.iconPaths;
  41294. option.iconStatus = option.iconStatus || {};
  41295. option.iconStatus[iconName] = status;
  41296. // FIXME
  41297. iconPaths[iconName] && iconPaths[iconName].trigger(status);
  41298. };
  41299. if (feature.render) {
  41300. feature.render(featureModel, ecModel, api, payload);
  41301. }
  41302. }
  41303. function createIconPaths(featureModel, feature, featureName) {
  41304. var iconStyleModel = featureModel.getModel('iconStyle');
  41305. var iconStyleEmphasisModel = featureModel.getModel('emphasis.iconStyle');
  41306. // If one feature has mutiple icon. they are orginaized as
  41307. // {
  41308. // icon: {
  41309. // foo: '',
  41310. // bar: ''
  41311. // },
  41312. // title: {
  41313. // foo: '',
  41314. // bar: ''
  41315. // }
  41316. // }
  41317. var icons = feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  41318. var titles = featureModel.get('title') || {};
  41319. if (typeof icons === 'string') {
  41320. var icon = icons;
  41321. var title = titles;
  41322. icons = {};
  41323. titles = {};
  41324. icons[featureName] = icon;
  41325. titles[featureName] = title;
  41326. }
  41327. var iconPaths = featureModel.iconPaths = {};
  41328. each$1(icons, function (iconStr, iconName) {
  41329. var path = createIcon(
  41330. iconStr,
  41331. {},
  41332. {
  41333. x: -itemSize / 2,
  41334. y: -itemSize / 2,
  41335. width: itemSize,
  41336. height: itemSize
  41337. }
  41338. );
  41339. path.setStyle(iconStyleModel.getItemStyle());
  41340. path.hoverStyle = iconStyleEmphasisModel.getItemStyle();
  41341. setHoverStyle(path);
  41342. if (toolboxModel.get('showTitle')) {
  41343. path.__title = titles[iconName];
  41344. path.on('mouseover', function () {
  41345. // Should not reuse above hoverStyle, which might be modified.
  41346. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  41347. path.setStyle({
  41348. text: titles[iconName],
  41349. textPosition: hoverStyle.textPosition || 'bottom',
  41350. textFill: hoverStyle.fill || hoverStyle.stroke || '#000',
  41351. textAlign: hoverStyle.textAlign || 'center'
  41352. });
  41353. })
  41354. .on('mouseout', function () {
  41355. path.setStyle({
  41356. textFill: null
  41357. });
  41358. });
  41359. }
  41360. path.trigger(featureModel.get('iconStatus.' + iconName) || 'normal');
  41361. group.add(path);
  41362. path.on('click', bind(
  41363. feature.onclick, feature, ecModel, api, iconName
  41364. ));
  41365. iconPaths[iconName] = path;
  41366. });
  41367. }
  41368. layout$2(group, toolboxModel, api);
  41369. // Render background after group is layout
  41370. // FIXME
  41371. group.add(makeBackground(group.getBoundingRect(), toolboxModel));
  41372. // Adjust icon title positions to avoid them out of screen
  41373. group.eachChild(function (icon) {
  41374. var titleText = icon.__title;
  41375. var hoverStyle = icon.hoverStyle;
  41376. // May be background element
  41377. if (hoverStyle && titleText) {
  41378. var rect = getBoundingRect(
  41379. titleText, makeFont(hoverStyle)
  41380. );
  41381. var offsetX = icon.position[0] + group.position[0];
  41382. var offsetY = icon.position[1] + group.position[1] + itemSize;
  41383. var needPutOnTop = false;
  41384. if (offsetY + rect.height > api.getHeight()) {
  41385. hoverStyle.textPosition = 'top';
  41386. needPutOnTop = true;
  41387. }
  41388. var topOffset = needPutOnTop ? (-5 - rect.height) : (itemSize + 8);
  41389. if (offsetX + rect.width / 2 > api.getWidth()) {
  41390. hoverStyle.textPosition = ['100%', topOffset];
  41391. hoverStyle.textAlign = 'right';
  41392. }
  41393. else if (offsetX - rect.width / 2 < 0) {
  41394. hoverStyle.textPosition = [0, topOffset];
  41395. hoverStyle.textAlign = 'left';
  41396. }
  41397. }
  41398. });
  41399. },
  41400. updateView: function (toolboxModel, ecModel, api, payload) {
  41401. each$1(this._features, function (feature) {
  41402. feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  41403. });
  41404. },
  41405. // updateLayout: function (toolboxModel, ecModel, api, payload) {
  41406. // zrUtil.each(this._features, function (feature) {
  41407. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  41408. // });
  41409. // },
  41410. remove: function (ecModel, api) {
  41411. each$1(this._features, function (feature) {
  41412. feature.remove && feature.remove(ecModel, api);
  41413. });
  41414. this.group.removeAll();
  41415. },
  41416. dispose: function (ecModel, api) {
  41417. each$1(this._features, function (feature) {
  41418. feature.dispose && feature.dispose(ecModel, api);
  41419. });
  41420. }
  41421. });
  41422. function isUserFeatureName(featureName) {
  41423. return featureName.indexOf('my') === 0;
  41424. }
  41425. var saveAsImageLang = lang.toolbox.saveAsImage;
  41426. function SaveAsImage(model) {
  41427. this.model = model;
  41428. }
  41429. SaveAsImage.defaultOption = {
  41430. show: true,
  41431. 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',
  41432. title: saveAsImageLang.title,
  41433. type: 'png',
  41434. // Default use option.backgroundColor
  41435. // backgroundColor: '#fff',
  41436. name: '',
  41437. excludeComponents: ['toolbox'],
  41438. pixelRatio: 1,
  41439. lang: saveAsImageLang.lang.slice()
  41440. };
  41441. SaveAsImage.prototype.unusable = !env$1.canvasSupported;
  41442. var proto$2 = SaveAsImage.prototype;
  41443. proto$2.onclick = function (ecModel, api) {
  41444. var model = this.model;
  41445. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  41446. var $a = document.createElement('a');
  41447. var type = model.get('type', true) || 'png';
  41448. $a.download = title + '.' + type;
  41449. $a.target = '_blank';
  41450. var url = api.getConnectedDataURL({
  41451. type: type,
  41452. backgroundColor: model.get('backgroundColor', true)
  41453. || ecModel.get('backgroundColor') || '#fff',
  41454. excludeComponents: model.get('excludeComponents'),
  41455. pixelRatio: model.get('pixelRatio')
  41456. });
  41457. $a.href = url;
  41458. // Chrome and Firefox
  41459. if (typeof MouseEvent === 'function' && !env$1.browser.ie && !env$1.browser.edge) {
  41460. var evt = new MouseEvent('click', {
  41461. view: window,
  41462. bubbles: true,
  41463. cancelable: false
  41464. });
  41465. $a.dispatchEvent(evt);
  41466. }
  41467. // IE
  41468. else {
  41469. if (window.navigator.msSaveOrOpenBlob) {
  41470. var bstr = atob(url.split(',')[1]);
  41471. var n = bstr.length;
  41472. var u8arr = new Uint8Array(n);
  41473. while(n--) {
  41474. u8arr[n] = bstr.charCodeAt(n);
  41475. }
  41476. var blob = new Blob([u8arr]);
  41477. window.navigator.msSaveOrOpenBlob(blob, title + '.' + type);
  41478. }
  41479. else {
  41480. var lang$$1 = model.get('lang');
  41481. var html = '' +
  41482. '<body style="margin:0;">' +
  41483. '<img src="' + url + '" style="max-width:100%;" title="' + ((lang$$1 && lang$$1[0]) || '') + '" />' +
  41484. '</body>';
  41485. var tab = window.open();
  41486. tab.document.write(html);
  41487. }
  41488. }
  41489. };
  41490. register$2(
  41491. 'saveAsImage', SaveAsImage
  41492. );
  41493. var magicTypeLang = lang.toolbox.magicType;
  41494. function MagicType(model) {
  41495. this.model = model;
  41496. }
  41497. MagicType.defaultOption = {
  41498. show: true,
  41499. type: [],
  41500. // Icon group
  41501. icon: {
  41502. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  41503. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  41504. 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
  41505. tiled: 'M2.3,2.2h22.8V25H2.3V2.2z M35,2.2h22.8V25H35V2.2zM2.3,35h22.8v22.8H2.3V35z M35,35h22.8v22.8H35V35z'
  41506. },
  41507. // `line`, `bar`, `stack`, `tiled`
  41508. title: clone(magicTypeLang.title),
  41509. option: {},
  41510. seriesIndex: {}
  41511. };
  41512. var proto$3 = MagicType.prototype;
  41513. proto$3.getIcons = function () {
  41514. var model = this.model;
  41515. var availableIcons = model.get('icon');
  41516. var icons = {};
  41517. each$1(model.get('type'), function (type) {
  41518. if (availableIcons[type]) {
  41519. icons[type] = availableIcons[type];
  41520. }
  41521. });
  41522. return icons;
  41523. };
  41524. var seriesOptGenreator = {
  41525. 'line': function (seriesType, seriesId, seriesModel, model) {
  41526. if (seriesType === 'bar') {
  41527. return merge({
  41528. id: seriesId,
  41529. type: 'line',
  41530. // Preserve data related option
  41531. data: seriesModel.get('data'),
  41532. stack: seriesModel.get('stack'),
  41533. markPoint: seriesModel.get('markPoint'),
  41534. markLine: seriesModel.get('markLine')
  41535. }, model.get('option.line') || {}, true);
  41536. }
  41537. },
  41538. 'bar': function (seriesType, seriesId, seriesModel, model) {
  41539. if (seriesType === 'line') {
  41540. return merge({
  41541. id: seriesId,
  41542. type: 'bar',
  41543. // Preserve data related option
  41544. data: seriesModel.get('data'),
  41545. stack: seriesModel.get('stack'),
  41546. markPoint: seriesModel.get('markPoint'),
  41547. markLine: seriesModel.get('markLine')
  41548. }, model.get('option.bar') || {}, true);
  41549. }
  41550. },
  41551. 'stack': function (seriesType, seriesId, seriesModel, model) {
  41552. if (seriesType === 'line' || seriesType === 'bar') {
  41553. return merge({
  41554. id: seriesId,
  41555. stack: '__ec_magicType_stack__'
  41556. }, model.get('option.stack') || {}, true);
  41557. }
  41558. },
  41559. 'tiled': function (seriesType, seriesId, seriesModel, model) {
  41560. if (seriesType === 'line' || seriesType === 'bar') {
  41561. return merge({
  41562. id: seriesId,
  41563. stack: ''
  41564. }, model.get('option.tiled') || {}, true);
  41565. }
  41566. }
  41567. };
  41568. var radioTypes = [
  41569. ['line', 'bar'],
  41570. ['stack', 'tiled']
  41571. ];
  41572. proto$3.onclick = function (ecModel, api, type) {
  41573. var model = this.model;
  41574. var seriesIndex = model.get('seriesIndex.' + type);
  41575. // Not supported magicType
  41576. if (!seriesOptGenreator[type]) {
  41577. return;
  41578. }
  41579. var newOption = {
  41580. series: []
  41581. };
  41582. var generateNewSeriesTypes = function (seriesModel) {
  41583. var seriesType = seriesModel.subType;
  41584. var seriesId = seriesModel.id;
  41585. var newSeriesOpt = seriesOptGenreator[type](
  41586. seriesType, seriesId, seriesModel, model
  41587. );
  41588. if (newSeriesOpt) {
  41589. // PENDING If merge original option?
  41590. defaults(newSeriesOpt, seriesModel.option);
  41591. newOption.series.push(newSeriesOpt);
  41592. }
  41593. // Modify boundaryGap
  41594. var coordSys = seriesModel.coordinateSystem;
  41595. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  41596. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  41597. if (categoryAxis) {
  41598. var axisDim = categoryAxis.dim;
  41599. var axisType = axisDim + 'Axis';
  41600. var axisModel = ecModel.queryComponents({
  41601. mainType: axisType,
  41602. index: seriesModel.get(name + 'Index'),
  41603. id: seriesModel.get(name + 'Id')
  41604. })[0];
  41605. var axisIndex = axisModel.componentIndex;
  41606. newOption[axisType] = newOption[axisType] || [];
  41607. for (var i = 0; i <= axisIndex; i++) {
  41608. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  41609. }
  41610. newOption[axisType][axisIndex].boundaryGap = type === 'bar' ? true : false;
  41611. }
  41612. }
  41613. };
  41614. each$1(radioTypes, function (radio) {
  41615. if (indexOf(radio, type) >= 0) {
  41616. each$1(radio, function (item) {
  41617. model.setIconStatus(item, 'normal');
  41618. });
  41619. }
  41620. });
  41621. model.setIconStatus(type, 'emphasis');
  41622. ecModel.eachComponent(
  41623. {
  41624. mainType: 'series',
  41625. query: seriesIndex == null ? null : {
  41626. seriesIndex: seriesIndex
  41627. }
  41628. }, generateNewSeriesTypes
  41629. );
  41630. api.dispatchAction({
  41631. type: 'changeMagicType',
  41632. currentType: type,
  41633. newOption: newOption
  41634. });
  41635. };
  41636. registerAction({
  41637. type: 'changeMagicType',
  41638. event: 'magicTypeChanged',
  41639. update: 'prepareAndUpdate'
  41640. }, function (payload, ecModel) {
  41641. ecModel.mergeOption(payload.newOption);
  41642. });
  41643. register$2('magicType', MagicType);
  41644. var dataViewLang = lang.toolbox.dataView;
  41645. var BLOCK_SPLITER = new Array(60).join('-');
  41646. var ITEM_SPLITER = '\t';
  41647. /**
  41648. * Group series into two types
  41649. * 1. on category axis, like line, bar
  41650. * 2. others, like scatter, pie
  41651. * @param {module:echarts/model/Global} ecModel
  41652. * @return {Object}
  41653. * @inner
  41654. */
  41655. function groupSeries(ecModel) {
  41656. var seriesGroupByCategoryAxis = {};
  41657. var otherSeries = [];
  41658. var meta = [];
  41659. ecModel.eachRawSeries(function (seriesModel) {
  41660. var coordSys = seriesModel.coordinateSystem;
  41661. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  41662. var baseAxis = coordSys.getBaseAxis();
  41663. if (baseAxis.type === 'category') {
  41664. var key = baseAxis.dim + '_' + baseAxis.index;
  41665. if (!seriesGroupByCategoryAxis[key]) {
  41666. seriesGroupByCategoryAxis[key] = {
  41667. categoryAxis: baseAxis,
  41668. valueAxis: coordSys.getOtherAxis(baseAxis),
  41669. series: []
  41670. };
  41671. meta.push({
  41672. axisDim: baseAxis.dim,
  41673. axisIndex: baseAxis.index
  41674. });
  41675. }
  41676. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  41677. }
  41678. else {
  41679. otherSeries.push(seriesModel);
  41680. }
  41681. }
  41682. else {
  41683. otherSeries.push(seriesModel);
  41684. }
  41685. });
  41686. return {
  41687. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  41688. other: otherSeries,
  41689. meta: meta
  41690. };
  41691. }
  41692. /**
  41693. * Assemble content of series on cateogory axis
  41694. * @param {Array.<module:echarts/model/Series>} series
  41695. * @return {string}
  41696. * @inner
  41697. */
  41698. function assembleSeriesWithCategoryAxis(series) {
  41699. var tables = [];
  41700. each$1(series, function (group, key) {
  41701. var categoryAxis = group.categoryAxis;
  41702. var valueAxis = group.valueAxis;
  41703. var valueAxisDim = valueAxis.dim;
  41704. var headers = [' '].concat(map(group.series, function (series) {
  41705. return series.name;
  41706. }));
  41707. var columns = [categoryAxis.model.getCategories()];
  41708. each$1(group.series, function (series) {
  41709. columns.push(series.getRawData().mapArray(valueAxisDim, function (val) {
  41710. return val;
  41711. }));
  41712. });
  41713. // Assemble table content
  41714. var lines = [headers.join(ITEM_SPLITER)];
  41715. for (var i = 0; i < columns[0].length; i++) {
  41716. var items = [];
  41717. for (var j = 0; j < columns.length; j++) {
  41718. items.push(columns[j][i]);
  41719. }
  41720. lines.push(items.join(ITEM_SPLITER));
  41721. }
  41722. tables.push(lines.join('\n'));
  41723. });
  41724. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  41725. }
  41726. /**
  41727. * Assemble content of other series
  41728. * @param {Array.<module:echarts/model/Series>} series
  41729. * @return {string}
  41730. * @inner
  41731. */
  41732. function assembleOtherSeries(series) {
  41733. return map(series, function (series) {
  41734. var data = series.getRawData();
  41735. var lines = [series.name];
  41736. var vals = [];
  41737. data.each(data.dimensions, function () {
  41738. var argLen = arguments.length;
  41739. var dataIndex = arguments[argLen - 1];
  41740. var name = data.getName(dataIndex);
  41741. for (var i = 0; i < argLen - 1; i++) {
  41742. vals[i] = arguments[i];
  41743. }
  41744. lines.push((name ? (name + ITEM_SPLITER) : '') + vals.join(ITEM_SPLITER));
  41745. });
  41746. return lines.join('\n');
  41747. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  41748. }
  41749. /**
  41750. * @param {module:echarts/model/Global}
  41751. * @return {Object}
  41752. * @inner
  41753. */
  41754. function getContentFromModel(ecModel) {
  41755. var result = groupSeries(ecModel);
  41756. return {
  41757. value: filter([
  41758. assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis),
  41759. assembleOtherSeries(result.other)
  41760. ], function (str) {
  41761. return str.replace(/[\n\t\s]/g, '');
  41762. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  41763. meta: result.meta
  41764. };
  41765. }
  41766. function trim$1(str) {
  41767. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  41768. }
  41769. /**
  41770. * If a block is tsv format
  41771. */
  41772. function isTSVFormat(block) {
  41773. // Simple method to find out if a block is tsv format
  41774. var firstLine = block.slice(0, block.indexOf('\n'));
  41775. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  41776. return true;
  41777. }
  41778. }
  41779. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  41780. /**
  41781. * @param {string} tsv
  41782. * @return {Object}
  41783. */
  41784. function parseTSVContents(tsv) {
  41785. var tsvLines = tsv.split(/\n+/g);
  41786. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  41787. var categories = [];
  41788. var series = map(headers, function (header) {
  41789. return {
  41790. name: header,
  41791. data: []
  41792. };
  41793. });
  41794. for (var i = 0; i < tsvLines.length; i++) {
  41795. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  41796. categories.push(items.shift());
  41797. for (var j = 0; j < items.length; j++) {
  41798. series[j] && (series[j].data[i] = items[j]);
  41799. }
  41800. }
  41801. return {
  41802. series: series,
  41803. categories: categories
  41804. };
  41805. }
  41806. /**
  41807. * @param {string} str
  41808. * @return {Array.<Object>}
  41809. * @inner
  41810. */
  41811. function parseListContents(str) {
  41812. var lines = str.split(/\n+/g);
  41813. var seriesName = trim$1(lines.shift());
  41814. var data = [];
  41815. for (var i = 0; i < lines.length; i++) {
  41816. var items = trim$1(lines[i]).split(itemSplitRegex);
  41817. var name = '';
  41818. var value;
  41819. var hasName = false;
  41820. if (isNaN(items[0])) { // First item is name
  41821. hasName = true;
  41822. name = items[0];
  41823. items = items.slice(1);
  41824. data[i] = {
  41825. name: name,
  41826. value: []
  41827. };
  41828. value = data[i].value;
  41829. }
  41830. else {
  41831. value = data[i] = [];
  41832. }
  41833. for (var j = 0; j < items.length; j++) {
  41834. value.push(+items[j]);
  41835. }
  41836. if (value.length === 1) {
  41837. hasName ? (data[i].value = value[0]) : (data[i] = value[0]);
  41838. }
  41839. }
  41840. return {
  41841. name: seriesName,
  41842. data: data
  41843. };
  41844. }
  41845. /**
  41846. * @param {string} str
  41847. * @param {Array.<Object>} blockMetaList
  41848. * @return {Object}
  41849. * @inner
  41850. */
  41851. function parseContents(str, blockMetaList) {
  41852. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  41853. var newOption = {
  41854. series: []
  41855. };
  41856. each$1(blocks, function (block, idx) {
  41857. if (isTSVFormat(block)) {
  41858. var result = parseTSVContents(block);
  41859. var blockMeta = blockMetaList[idx];
  41860. var axisKey = blockMeta.axisDim + 'Axis';
  41861. if (blockMeta) {
  41862. newOption[axisKey] = newOption[axisKey] || [];
  41863. newOption[axisKey][blockMeta.axisIndex] = {
  41864. data: result.categories
  41865. };
  41866. newOption.series = newOption.series.concat(result.series);
  41867. }
  41868. }
  41869. else {
  41870. var result = parseListContents(block);
  41871. newOption.series.push(result);
  41872. }
  41873. });
  41874. return newOption;
  41875. }
  41876. /**
  41877. * @alias {module:echarts/component/toolbox/feature/DataView}
  41878. * @constructor
  41879. * @param {module:echarts/model/Model} model
  41880. */
  41881. function DataView(model) {
  41882. this._dom = null;
  41883. this.model = model;
  41884. }
  41885. DataView.defaultOption = {
  41886. show: true,
  41887. readOnly: false,
  41888. optionToContent: null,
  41889. contentToOption: null,
  41890. 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',
  41891. title: clone(dataViewLang.title),
  41892. lang: clone(dataViewLang.lang),
  41893. backgroundColor: '#fff',
  41894. textColor: '#000',
  41895. textareaColor: '#fff',
  41896. textareaBorderColor: '#333',
  41897. buttonColor: '#c23531',
  41898. buttonTextColor: '#fff'
  41899. };
  41900. DataView.prototype.onclick = function (ecModel, api) {
  41901. var container = api.getDom();
  41902. var model = this.model;
  41903. if (this._dom) {
  41904. container.removeChild(this._dom);
  41905. }
  41906. var root = document.createElement('div');
  41907. root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;';
  41908. root.style.backgroundColor = model.get('backgroundColor') || '#fff';
  41909. // Create elements
  41910. var header = document.createElement('h4');
  41911. var lang$$1 = model.get('lang') || [];
  41912. header.innerHTML = lang$$1[0] || model.get('title');
  41913. header.style.cssText = 'margin: 10px 20px;';
  41914. header.style.color = model.get('textColor');
  41915. var viewMain = document.createElement('div');
  41916. var textarea = document.createElement('textarea');
  41917. viewMain.style.cssText = 'display:block;width:100%;overflow:auto;';
  41918. var optionToContent = model.get('optionToContent');
  41919. var contentToOption = model.get('contentToOption');
  41920. var result = getContentFromModel(ecModel);
  41921. if (typeof optionToContent === 'function') {
  41922. var htmlOrDom = optionToContent(api.getOption());
  41923. if (typeof htmlOrDom === 'string') {
  41924. viewMain.innerHTML = htmlOrDom;
  41925. }
  41926. else if (isDom(htmlOrDom)) {
  41927. viewMain.appendChild(htmlOrDom);
  41928. }
  41929. }
  41930. else {
  41931. // Use default textarea
  41932. viewMain.appendChild(textarea);
  41933. textarea.readOnly = model.get('readOnly');
  41934. textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;';
  41935. textarea.style.color = model.get('textColor');
  41936. textarea.style.borderColor = model.get('textareaBorderColor');
  41937. textarea.style.backgroundColor = model.get('textareaColor');
  41938. textarea.value = result.value;
  41939. }
  41940. var blockMetaList = result.meta;
  41941. var buttonContainer = document.createElement('div');
  41942. buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;';
  41943. var buttonStyle = 'float:right;margin-right:20px;border:none;'
  41944. + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  41945. var closeButton = document.createElement('div');
  41946. var refreshButton = document.createElement('div');
  41947. buttonStyle += ';background-color:' + model.get('buttonColor');
  41948. buttonStyle += ';color:' + model.get('buttonTextColor');
  41949. var self = this;
  41950. function close() {
  41951. container.removeChild(root);
  41952. self._dom = null;
  41953. }
  41954. addEventListener(closeButton, 'click', close);
  41955. addEventListener(refreshButton, 'click', function () {
  41956. var newOption;
  41957. try {
  41958. if (typeof contentToOption === 'function') {
  41959. newOption = contentToOption(viewMain, api.getOption());
  41960. }
  41961. else {
  41962. newOption = parseContents(textarea.value, blockMetaList);
  41963. }
  41964. }
  41965. catch (e) {
  41966. close();
  41967. throw new Error('Data view format error ' + e);
  41968. }
  41969. if (newOption) {
  41970. api.dispatchAction({
  41971. type: 'changeDataView',
  41972. newOption: newOption
  41973. });
  41974. }
  41975. close();
  41976. });
  41977. closeButton.innerHTML = lang$$1[1];
  41978. refreshButton.innerHTML = lang$$1[2];
  41979. refreshButton.style.cssText = buttonStyle;
  41980. closeButton.style.cssText = buttonStyle;
  41981. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  41982. buttonContainer.appendChild(closeButton);
  41983. // http://stackoverflow.com/questions/6637341/use-tab-to-indent-in-textarea
  41984. addEventListener(textarea, 'keydown', function (e) {
  41985. if ((e.keyCode || e.which) === 9) {
  41986. // get caret position/selection
  41987. var val = this.value;
  41988. var start = this.selectionStart;
  41989. var end = this.selectionEnd;
  41990. // set textarea value to: text before caret + tab + text after caret
  41991. this.value = val.substring(0, start) + ITEM_SPLITER + val.substring(end);
  41992. // put caret at right position again
  41993. this.selectionStart = this.selectionEnd = start + 1;
  41994. // prevent the focus lose
  41995. stop(e);
  41996. }
  41997. });
  41998. root.appendChild(header);
  41999. root.appendChild(viewMain);
  42000. root.appendChild(buttonContainer);
  42001. viewMain.style.height = (container.clientHeight - 80) + 'px';
  42002. container.appendChild(root);
  42003. this._dom = root;
  42004. };
  42005. DataView.prototype.remove = function (ecModel, api) {
  42006. this._dom && api.getDom().removeChild(this._dom);
  42007. };
  42008. DataView.prototype.dispose = function (ecModel, api) {
  42009. this.remove(ecModel, api);
  42010. };
  42011. /**
  42012. * @inner
  42013. */
  42014. function tryMergeDataOption(newData, originalData) {
  42015. return map(newData, function (newVal, idx) {
  42016. var original = originalData && originalData[idx];
  42017. if (isObject$1(original) && !isArray(original)) {
  42018. if (isObject$1(newVal) && !isArray(newVal)) {
  42019. newVal = newVal.value;
  42020. }
  42021. // Original data has option
  42022. return defaults({
  42023. value: newVal
  42024. }, original);
  42025. }
  42026. else {
  42027. return newVal;
  42028. }
  42029. });
  42030. }
  42031. register$2('dataView', DataView);
  42032. registerAction({
  42033. type: 'changeDataView',
  42034. event: 'dataViewChanged',
  42035. update: 'prepareAndUpdate'
  42036. }, function (payload, ecModel) {
  42037. var newSeriesOptList = [];
  42038. each$1(payload.newOption.series, function (seriesOpt) {
  42039. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  42040. if (!seriesModel) {
  42041. // New created series
  42042. // Geuss the series type
  42043. newSeriesOptList.push(extend({
  42044. // Default is scatter
  42045. type: 'scatter'
  42046. }, seriesOpt));
  42047. }
  42048. else {
  42049. var originalData = seriesModel.get('data');
  42050. newSeriesOptList.push({
  42051. name: seriesOpt.name,
  42052. data: tryMergeDataOption(seriesOpt.data, originalData)
  42053. });
  42054. }
  42055. });
  42056. ecModel.mergeOption(defaults({
  42057. series: newSeriesOptList
  42058. }, payload.newOption));
  42059. });
  42060. var curry$6 = curry;
  42061. var each$17 = each$1;
  42062. var map$2 = map;
  42063. var mathMin$4 = Math.min;
  42064. var mathMax$4 = Math.max;
  42065. var mathPow$2 = Math.pow;
  42066. var COVER_Z = 10000;
  42067. var UNSELECT_THRESHOLD = 6;
  42068. var MIN_RESIZE_LINE_WIDTH = 6;
  42069. var MUTEX_RESOURCE_KEY = 'globalPan';
  42070. var DIRECTION_MAP = {
  42071. w: [0, 0],
  42072. e: [0, 1],
  42073. n: [1, 0],
  42074. s: [1, 1]
  42075. };
  42076. var CURSOR_MAP = {
  42077. w: 'ew',
  42078. e: 'ew',
  42079. n: 'ns',
  42080. s: 'ns',
  42081. ne: 'nesw',
  42082. sw: 'nesw',
  42083. nw: 'nwse',
  42084. se: 'nwse'
  42085. };
  42086. var DEFAULT_BRUSH_OPT = {
  42087. brushStyle: {
  42088. lineWidth: 2,
  42089. stroke: 'rgba(0,0,0,0.3)',
  42090. fill: 'rgba(0,0,0,0.1)'
  42091. },
  42092. transformable: true,
  42093. brushMode: 'single',
  42094. removeOnClick: false
  42095. };
  42096. var baseUID = 0;
  42097. /**
  42098. * @alias module:echarts/component/helper/BrushController
  42099. * @constructor
  42100. * @mixin {module:zrender/mixin/Eventful}
  42101. * @event module:echarts/component/helper/BrushController#brush
  42102. * params:
  42103. * areas: Array.<Array>, coord relates to container group,
  42104. * If no container specified, to global.
  42105. * opt {
  42106. * isEnd: boolean,
  42107. * removeOnClick: boolean
  42108. * }
  42109. *
  42110. * @param {module:zrender/zrender~ZRender} zr
  42111. */
  42112. function BrushController(zr) {
  42113. if (__DEV__) {
  42114. assert$1(zr);
  42115. }
  42116. Eventful.call(this);
  42117. /**
  42118. * @type {module:zrender/zrender~ZRender}
  42119. * @private
  42120. */
  42121. this._zr = zr;
  42122. /**
  42123. * @type {module:zrender/container/Group}
  42124. * @readOnly
  42125. */
  42126. this.group = new Group();
  42127. /**
  42128. * Only for drawing (after enabledBrush).
  42129. * 'line', 'rect', 'polygon' or false
  42130. * If passing false/null/undefined, disable brush.
  42131. * If passing 'auto', determined by panel.defaultBrushType
  42132. * @private
  42133. * @type {string}
  42134. */
  42135. this._brushType;
  42136. /**
  42137. * Only for drawing (after enabledBrush).
  42138. *
  42139. * @private
  42140. * @type {Object}
  42141. */
  42142. this._brushOption;
  42143. /**
  42144. * @private
  42145. * @type {Object}
  42146. */
  42147. this._panels;
  42148. /**
  42149. * @private
  42150. * @type {Array.<nubmer>}
  42151. */
  42152. this._track = [];
  42153. /**
  42154. * @private
  42155. * @type {boolean}
  42156. */
  42157. this._dragging;
  42158. /**
  42159. * @private
  42160. * @type {Array}
  42161. */
  42162. this._covers = [];
  42163. /**
  42164. * @private
  42165. * @type {moudule:zrender/container/Group}
  42166. */
  42167. this._creatingCover;
  42168. /**
  42169. * `true` means global panel
  42170. * @private
  42171. * @type {module:zrender/container/Group|boolean}
  42172. */
  42173. this._creatingPanel;
  42174. /**
  42175. * @private
  42176. * @type {boolean}
  42177. */
  42178. this._enableGlobalPan;
  42179. /**
  42180. * @private
  42181. * @type {boolean}
  42182. */
  42183. if (__DEV__) {
  42184. this._mounted;
  42185. }
  42186. /**
  42187. * @private
  42188. * @type {string}
  42189. */
  42190. this._uid = 'brushController_' + baseUID++;
  42191. /**
  42192. * @private
  42193. * @type {Object}
  42194. */
  42195. this._handlers = {};
  42196. each$17(mouseHandlers, function (handler, eventName) {
  42197. this._handlers[eventName] = bind(handler, this);
  42198. }, this);
  42199. }
  42200. BrushController.prototype = {
  42201. constructor: BrushController,
  42202. /**
  42203. * If set to null/undefined/false, select disabled.
  42204. * @param {Object} brushOption
  42205. * @param {string|boolean} brushOption.brushType 'line', 'rect', 'polygon' or false
  42206. * If passing false/null/undefined, disable brush.
  42207. * If passing 'auto', determined by panel.defaultBrushType.
  42208. * ('auto' can not be used in global panel)
  42209. * @param {number} [brushOption.brushMode='single'] 'single' or 'multiple'
  42210. * @param {boolean} [brushOption.transformable=true]
  42211. * @param {boolean} [brushOption.removeOnClick=false]
  42212. * @param {Object} [brushOption.brushStyle]
  42213. * @param {number} [brushOption.brushStyle.width]
  42214. * @param {number} [brushOption.brushStyle.lineWidth]
  42215. * @param {string} [brushOption.brushStyle.stroke]
  42216. * @param {string} [brushOption.brushStyle.fill]
  42217. * @param {number} [brushOption.z]
  42218. */
  42219. enableBrush: function (brushOption) {
  42220. if (__DEV__) {
  42221. assert$1(this._mounted);
  42222. }
  42223. this._brushType && doDisableBrush(this);
  42224. brushOption.brushType && doEnableBrush(this, brushOption);
  42225. return this;
  42226. },
  42227. /**
  42228. * @param {Array.<Object>} panelOpts If not pass, it is global brush.
  42229. * Each items: {
  42230. * panelId, // mandatory.
  42231. * clipPath, // mandatory. function.
  42232. * isTargetByCursor, // mandatory. function.
  42233. * defaultBrushType, // optional, only used when brushType is 'auto'.
  42234. * getLinearBrushOtherExtent, // optional. function.
  42235. * }
  42236. */
  42237. setPanels: function (panelOpts) {
  42238. if (panelOpts && panelOpts.length) {
  42239. var panels = this._panels = {};
  42240. each$1(panelOpts, function (panelOpts) {
  42241. panels[panelOpts.panelId] = clone(panelOpts);
  42242. });
  42243. }
  42244. else {
  42245. this._panels = null;
  42246. }
  42247. return this;
  42248. },
  42249. /**
  42250. * @param {Object} [opt]
  42251. * @return {boolean} [opt.enableGlobalPan=false]
  42252. */
  42253. mount: function (opt) {
  42254. opt = opt || {};
  42255. if (__DEV__) {
  42256. this._mounted = true; // should be at first.
  42257. }
  42258. this._enableGlobalPan = opt.enableGlobalPan;
  42259. var thisGroup = this.group;
  42260. this._zr.add(thisGroup);
  42261. thisGroup.attr({
  42262. position: opt.position || [0, 0],
  42263. rotation: opt.rotation || 0,
  42264. scale: opt.scale || [1, 1]
  42265. });
  42266. this._transform = thisGroup.getLocalTransform();
  42267. return this;
  42268. },
  42269. eachCover: function (cb, context) {
  42270. each$17(this._covers, cb, context);
  42271. },
  42272. /**
  42273. * Update covers.
  42274. * @param {Array.<Object>} brushOptionList Like:
  42275. * [
  42276. * {id: 'xx', brushType: 'line', range: [23, 44], brushStyle, transformable},
  42277. * {id: 'yy', brushType: 'rect', range: [[23, 44], [23, 54]]},
  42278. * ...
  42279. * ]
  42280. * `brushType` is required in each cover info. (can not be 'auto')
  42281. * `id` is not mandatory.
  42282. * `brushStyle`, `transformable` is not mandatory, use DEFAULT_BRUSH_OPT by default.
  42283. * If brushOptionList is null/undefined, all covers removed.
  42284. */
  42285. updateCovers: function (brushOptionList) {
  42286. if (__DEV__) {
  42287. assert$1(this._mounted);
  42288. }
  42289. brushOptionList = map(brushOptionList, function (brushOption) {
  42290. return merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  42291. });
  42292. var tmpIdPrefix = '\0-brush-index-';
  42293. var oldCovers = this._covers;
  42294. var newCovers = this._covers = [];
  42295. var controller = this;
  42296. var creatingCover = this._creatingCover;
  42297. (new DataDiffer(oldCovers, brushOptionList, oldGetKey, getKey))
  42298. .add(addOrUpdate)
  42299. .update(addOrUpdate)
  42300. .remove(remove)
  42301. .execute();
  42302. return this;
  42303. function getKey(brushOption, index) {
  42304. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index)
  42305. + '-' + brushOption.brushType;
  42306. }
  42307. function oldGetKey(cover, index) {
  42308. return getKey(cover.__brushOption, index);
  42309. }
  42310. function addOrUpdate(newIndex, oldIndex) {
  42311. var newBrushOption = brushOptionList[newIndex];
  42312. // Consider setOption in event listener of brushSelect,
  42313. // where updating cover when creating should be forbiden.
  42314. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  42315. newCovers[newIndex] = oldCovers[oldIndex];
  42316. }
  42317. else {
  42318. var cover = newCovers[newIndex] = oldIndex != null
  42319. ? (
  42320. oldCovers[oldIndex].__brushOption = newBrushOption,
  42321. oldCovers[oldIndex]
  42322. )
  42323. : endCreating(controller, createCover(controller, newBrushOption));
  42324. updateCoverAfterCreation(controller, cover);
  42325. }
  42326. }
  42327. function remove(oldIndex) {
  42328. if (oldCovers[oldIndex] !== creatingCover) {
  42329. controller.group.remove(oldCovers[oldIndex]);
  42330. }
  42331. }
  42332. },
  42333. unmount: function () {
  42334. if (__DEV__) {
  42335. if (!this._mounted) {
  42336. return;
  42337. }
  42338. }
  42339. this.enableBrush(false);
  42340. // container may 'removeAll' outside.
  42341. clearCovers(this);
  42342. this._zr.remove(this.group);
  42343. if (__DEV__) {
  42344. this._mounted = false; // should be at last.
  42345. }
  42346. return this;
  42347. },
  42348. dispose: function () {
  42349. this.unmount();
  42350. this.off();
  42351. }
  42352. };
  42353. mixin(BrushController, Eventful);
  42354. function doEnableBrush(controller, brushOption) {
  42355. var zr = controller._zr;
  42356. // Consider roam, which takes globalPan too.
  42357. if (!controller._enableGlobalPan) {
  42358. take(zr, MUTEX_RESOURCE_KEY, controller._uid);
  42359. }
  42360. each$17(controller._handlers, function (handler, eventName) {
  42361. zr.on(eventName, handler);
  42362. });
  42363. controller._brushType = brushOption.brushType;
  42364. controller._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  42365. }
  42366. function doDisableBrush(controller) {
  42367. var zr = controller._zr;
  42368. release(zr, MUTEX_RESOURCE_KEY, controller._uid);
  42369. each$17(controller._handlers, function (handler, eventName) {
  42370. zr.off(eventName, handler);
  42371. });
  42372. controller._brushType = controller._brushOption = null;
  42373. }
  42374. function createCover(controller, brushOption) {
  42375. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  42376. cover.__brushOption = brushOption;
  42377. updateZ$1(cover, brushOption);
  42378. controller.group.add(cover);
  42379. return cover;
  42380. }
  42381. function endCreating(controller, creatingCover) {
  42382. var coverRenderer = getCoverRenderer(creatingCover);
  42383. if (coverRenderer.endCreating) {
  42384. coverRenderer.endCreating(controller, creatingCover);
  42385. updateZ$1(creatingCover, creatingCover.__brushOption);
  42386. }
  42387. return creatingCover;
  42388. }
  42389. function updateCoverShape(controller, cover) {
  42390. var brushOption = cover.__brushOption;
  42391. getCoverRenderer(cover).updateCoverShape(
  42392. controller, cover, brushOption.range, brushOption
  42393. );
  42394. }
  42395. function updateZ$1(cover, brushOption) {
  42396. var z = brushOption.z;
  42397. z == null && (z = COVER_Z);
  42398. cover.traverse(function (el) {
  42399. el.z = z;
  42400. el.z2 = z; // Consider in given container.
  42401. });
  42402. }
  42403. function updateCoverAfterCreation(controller, cover) {
  42404. getCoverRenderer(cover).updateCommon(controller, cover);
  42405. updateCoverShape(controller, cover);
  42406. }
  42407. function getCoverRenderer(cover) {
  42408. return coverRenderers[cover.__brushOption.brushType];
  42409. }
  42410. // return target panel or `true` (means global panel)
  42411. function getPanelByPoint(controller, e, localCursorPoint) {
  42412. var panels = controller._panels;
  42413. if (!panels) {
  42414. return true; // Global panel
  42415. }
  42416. var panel;
  42417. var transform = controller._transform;
  42418. each$17(panels, function (pn) {
  42419. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  42420. });
  42421. return panel;
  42422. }
  42423. // Return a panel or true
  42424. function getPanelByCover(controller, cover) {
  42425. var panels = controller._panels;
  42426. if (!panels) {
  42427. return true; // Global panel
  42428. }
  42429. var panelId = cover.__brushOption.panelId;
  42430. // User may give cover without coord sys info,
  42431. // which is then treated as global panel.
  42432. return panelId != null ? panels[panelId] : true;
  42433. }
  42434. function clearCovers(controller) {
  42435. var covers = controller._covers;
  42436. var originalLength = covers.length;
  42437. each$17(covers, function (cover) {
  42438. controller.group.remove(cover);
  42439. }, controller);
  42440. covers.length = 0;
  42441. return !!originalLength;
  42442. }
  42443. function trigger(controller, opt) {
  42444. var areas = map$2(controller._covers, function (cover) {
  42445. var brushOption = cover.__brushOption;
  42446. var range = clone(brushOption.range);
  42447. return {
  42448. brushType: brushOption.brushType,
  42449. panelId: brushOption.panelId,
  42450. range: range
  42451. };
  42452. });
  42453. controller.trigger('brush', areas, {
  42454. isEnd: !!opt.isEnd,
  42455. removeOnClick: !!opt.removeOnClick
  42456. });
  42457. }
  42458. function shouldShowCover(controller) {
  42459. var track = controller._track;
  42460. if (!track.length) {
  42461. return false;
  42462. }
  42463. var p2 = track[track.length - 1];
  42464. var p1 = track[0];
  42465. var dx = p2[0] - p1[0];
  42466. var dy = p2[1] - p1[1];
  42467. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  42468. return dist > UNSELECT_THRESHOLD;
  42469. }
  42470. function getTrackEnds(track) {
  42471. var tail = track.length - 1;
  42472. tail < 0 && (tail = 0);
  42473. return [track[0], track[tail]];
  42474. }
  42475. function createBaseRectCover(doDrift, controller, brushOption, edgeNames) {
  42476. var cover = new Group();
  42477. cover.add(new Rect({
  42478. name: 'main',
  42479. style: makeStyle(brushOption),
  42480. silent: true,
  42481. draggable: true,
  42482. cursor: 'move',
  42483. drift: curry$6(doDrift, controller, cover, 'nswe'),
  42484. ondragend: curry$6(trigger, controller, {isEnd: true})
  42485. }));
  42486. each$17(
  42487. edgeNames,
  42488. function (name) {
  42489. cover.add(new Rect({
  42490. name: name,
  42491. style: {opacity: 0},
  42492. draggable: true,
  42493. silent: true,
  42494. invisible: true,
  42495. drift: curry$6(doDrift, controller, cover, name),
  42496. ondragend: curry$6(trigger, controller, {isEnd: true})
  42497. }));
  42498. }
  42499. );
  42500. return cover;
  42501. }
  42502. function updateBaseRect(controller, cover, localRange, brushOption) {
  42503. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  42504. var handleSize = mathMax$4(lineWidth, MIN_RESIZE_LINE_WIDTH);
  42505. var x = localRange[0][0];
  42506. var y = localRange[1][0];
  42507. var xa = x - lineWidth / 2;
  42508. var ya = y - lineWidth / 2;
  42509. var x2 = localRange[0][1];
  42510. var y2 = localRange[1][1];
  42511. var x2a = x2 - handleSize + lineWidth / 2;
  42512. var y2a = y2 - handleSize + lineWidth / 2;
  42513. var width = x2 - x;
  42514. var height = y2 - y;
  42515. var widtha = width + lineWidth;
  42516. var heighta = height + lineWidth;
  42517. updateRectShape(controller, cover, 'main', x, y, width, height);
  42518. if (brushOption.transformable) {
  42519. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  42520. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  42521. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  42522. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  42523. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  42524. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  42525. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  42526. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  42527. }
  42528. }
  42529. function updateCommon(controller, cover) {
  42530. var brushOption = cover.__brushOption;
  42531. var transformable = brushOption.transformable;
  42532. var mainEl = cover.childAt(0);
  42533. mainEl.useStyle(makeStyle(brushOption));
  42534. mainEl.attr({
  42535. silent: !transformable,
  42536. cursor: transformable ? 'move' : 'default'
  42537. });
  42538. each$17(
  42539. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw'],
  42540. function (name) {
  42541. var el = cover.childOfName(name);
  42542. var globalDir = getGlobalDirection(controller, name);
  42543. el && el.attr({
  42544. silent: !transformable,
  42545. invisible: !transformable,
  42546. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  42547. });
  42548. }
  42549. );
  42550. }
  42551. function updateRectShape(controller, cover, name, x, y, w, h) {
  42552. var el = cover.childOfName(name);
  42553. el && el.setShape(pointsToRect(
  42554. clipByPanel(controller, cover, [[x, y], [x + w, y + h]])
  42555. ));
  42556. }
  42557. function makeStyle(brushOption) {
  42558. return defaults({strokeNoScale: true}, brushOption.brushStyle);
  42559. }
  42560. function formatRectRange(x, y, x2, y2) {
  42561. var min = [mathMin$4(x, x2), mathMin$4(y, y2)];
  42562. var max = [mathMax$4(x, x2), mathMax$4(y, y2)];
  42563. return [
  42564. [min[0], max[0]], // x range
  42565. [min[1], max[1]] // y range
  42566. ];
  42567. }
  42568. function getTransform$1(controller) {
  42569. return getTransform(controller.group);
  42570. }
  42571. function getGlobalDirection(controller, localDirection) {
  42572. if (localDirection.length > 1) {
  42573. localDirection = localDirection.split('');
  42574. var globalDir = [
  42575. getGlobalDirection(controller, localDirection[0]),
  42576. getGlobalDirection(controller, localDirection[1])
  42577. ];
  42578. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  42579. return globalDir.join('');
  42580. }
  42581. else {
  42582. var map$$1 = {w: 'left', e: 'right', n: 'top', s: 'bottom'};
  42583. var inverseMap = {left: 'w', right: 'e', top: 'n', bottom: 's'};
  42584. var globalDir = transformDirection(
  42585. map$$1[localDirection], getTransform$1(controller)
  42586. );
  42587. return inverseMap[globalDir];
  42588. }
  42589. }
  42590. function driftRect(toRectRange, fromRectRange, controller, cover, name, dx, dy, e) {
  42591. var brushOption = cover.__brushOption;
  42592. var rectRange = toRectRange(brushOption.range);
  42593. var localDelta = toLocalDelta(controller, dx, dy);
  42594. each$17(name.split(''), function (namePart) {
  42595. var ind = DIRECTION_MAP[namePart];
  42596. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  42597. });
  42598. brushOption.range = fromRectRange(formatRectRange(
  42599. rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]
  42600. ));
  42601. updateCoverAfterCreation(controller, cover);
  42602. trigger(controller, {isEnd: false});
  42603. }
  42604. function driftPolygon(controller, cover, dx, dy, e) {
  42605. var range = cover.__brushOption.range;
  42606. var localDelta = toLocalDelta(controller, dx, dy);
  42607. each$17(range, function (point) {
  42608. point[0] += localDelta[0];
  42609. point[1] += localDelta[1];
  42610. });
  42611. updateCoverAfterCreation(controller, cover);
  42612. trigger(controller, {isEnd: false});
  42613. }
  42614. function toLocalDelta(controller, dx, dy) {
  42615. var thisGroup = controller.group;
  42616. var localD = thisGroup.transformCoordToLocal(dx, dy);
  42617. var localZero = thisGroup.transformCoordToLocal(0, 0);
  42618. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  42619. }
  42620. function clipByPanel(controller, cover, data) {
  42621. var panel = getPanelByCover(controller, cover);
  42622. return (panel && panel !== true)
  42623. ? panel.clipPath(data, controller._transform)
  42624. : clone(data);
  42625. }
  42626. function pointsToRect(points) {
  42627. var xmin = mathMin$4(points[0][0], points[1][0]);
  42628. var ymin = mathMin$4(points[0][1], points[1][1]);
  42629. var xmax = mathMax$4(points[0][0], points[1][0]);
  42630. var ymax = mathMax$4(points[0][1], points[1][1]);
  42631. return {
  42632. x: xmin,
  42633. y: ymin,
  42634. width: xmax - xmin,
  42635. height: ymax - ymin
  42636. };
  42637. }
  42638. function resetCursor(controller, e, localCursorPoint) {
  42639. // Check active
  42640. if (!controller._brushType) {
  42641. return;
  42642. }
  42643. var zr = controller._zr;
  42644. var covers = controller._covers;
  42645. var currPanel = getPanelByPoint(controller, e, localCursorPoint);
  42646. // Check whether in covers.
  42647. if (!controller._dragging) {
  42648. for (var i = 0; i < covers.length; i++) {
  42649. var brushOption = covers[i].__brushOption;
  42650. if (currPanel
  42651. && (currPanel === true || brushOption.panelId === currPanel.panelId)
  42652. && coverRenderers[brushOption.brushType].contain(
  42653. covers[i], localCursorPoint[0], localCursorPoint[1]
  42654. )
  42655. ) {
  42656. // Use cursor style set on cover.
  42657. return;
  42658. }
  42659. }
  42660. }
  42661. currPanel && zr.setCursorStyle('crosshair');
  42662. }
  42663. function preventDefault(e) {
  42664. var rawE = e.event;
  42665. rawE.preventDefault && rawE.preventDefault();
  42666. }
  42667. function mainShapeContain(cover, x, y) {
  42668. return cover.childOfName('main').contain(x, y);
  42669. }
  42670. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  42671. var creatingCover = controller._creatingCover;
  42672. var panel = controller._creatingPanel;
  42673. var thisBrushOption = controller._brushOption;
  42674. var eventParams;
  42675. controller._track.push(localCursorPoint.slice());
  42676. if (shouldShowCover(controller) || creatingCover) {
  42677. if (panel && !creatingCover) {
  42678. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  42679. var brushOption = clone(thisBrushOption);
  42680. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  42681. brushOption.panelId = panel === true ? null : panel.panelId;
  42682. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  42683. controller._covers.push(creatingCover);
  42684. }
  42685. if (creatingCover) {
  42686. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  42687. var coverBrushOption = creatingCover.__brushOption;
  42688. coverBrushOption.range = coverRenderer.getCreatingRange(
  42689. clipByPanel(controller, creatingCover, controller._track)
  42690. );
  42691. if (isEnd) {
  42692. endCreating(controller, creatingCover);
  42693. coverRenderer.updateCommon(controller, creatingCover);
  42694. }
  42695. updateCoverShape(controller, creatingCover);
  42696. eventParams = {isEnd: isEnd};
  42697. }
  42698. }
  42699. else if (
  42700. isEnd
  42701. && thisBrushOption.brushMode === 'single'
  42702. && thisBrushOption.removeOnClick
  42703. ) {
  42704. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  42705. // But a single click do not clear covers, because user may have casual
  42706. // clicks (for example, click on other component and do not expect covers
  42707. // disappear).
  42708. // Only some cover removed, trigger action, but not every click trigger action.
  42709. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  42710. eventParams = {isEnd: isEnd, removeOnClick: true};
  42711. }
  42712. }
  42713. return eventParams;
  42714. }
  42715. function determineBrushType(brushType, panel) {
  42716. if (brushType === 'auto') {
  42717. if (__DEV__) {
  42718. assert$1(
  42719. panel && panel.defaultBrushType,
  42720. 'MUST have defaultBrushType when brushType is "atuo"'
  42721. );
  42722. }
  42723. return panel.defaultBrushType;
  42724. }
  42725. return brushType;
  42726. }
  42727. var mouseHandlers = {
  42728. mousedown: function (e) {
  42729. if (this._dragging) {
  42730. // In case some browser do not support globalOut,
  42731. // and release mose out side the browser.
  42732. handleDragEnd.call(this, e);
  42733. }
  42734. else if (!e.target || !e.target.draggable) {
  42735. preventDefault(e);
  42736. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  42737. this._creatingCover = null;
  42738. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  42739. if (panel) {
  42740. this._dragging = true;
  42741. this._track = [localCursorPoint.slice()];
  42742. }
  42743. }
  42744. },
  42745. mousemove: function (e) {
  42746. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  42747. resetCursor(this, e, localCursorPoint);
  42748. if (this._dragging) {
  42749. preventDefault(e);
  42750. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  42751. eventParams && trigger(this, eventParams);
  42752. }
  42753. },
  42754. mouseup: handleDragEnd //,
  42755. // FIXME
  42756. // in tooltip, globalout should not be triggered.
  42757. // globalout: handleDragEnd
  42758. };
  42759. function handleDragEnd(e) {
  42760. if (this._dragging) {
  42761. preventDefault(e);
  42762. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  42763. var eventParams = updateCoverByMouse(this, e, localCursorPoint, true);
  42764. this._dragging = false;
  42765. this._track = [];
  42766. this._creatingCover = null;
  42767. // trigger event shoule be at final, after procedure will be nested.
  42768. eventParams && trigger(this, eventParams);
  42769. }
  42770. }
  42771. /**
  42772. * key: brushType
  42773. * @type {Object}
  42774. */
  42775. var coverRenderers = {
  42776. lineX: getLineRenderer(0),
  42777. lineY: getLineRenderer(1),
  42778. rect: {
  42779. createCover: function (controller, brushOption) {
  42780. return createBaseRectCover(
  42781. curry$6(
  42782. driftRect,
  42783. function (range) {
  42784. return range;
  42785. },
  42786. function (range) {
  42787. return range;
  42788. }
  42789. ),
  42790. controller,
  42791. brushOption,
  42792. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw']
  42793. );
  42794. },
  42795. getCreatingRange: function (localTrack) {
  42796. var ends = getTrackEnds(localTrack);
  42797. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  42798. },
  42799. updateCoverShape: function (controller, cover, localRange, brushOption) {
  42800. updateBaseRect(controller, cover, localRange, brushOption);
  42801. },
  42802. updateCommon: updateCommon,
  42803. contain: mainShapeContain
  42804. },
  42805. polygon: {
  42806. createCover: function (controller, brushOption) {
  42807. var cover = new Group();
  42808. // Do not use graphic.Polygon because graphic.Polyline do not close the
  42809. // border of the shape when drawing, which is a better experience for user.
  42810. cover.add(new Polyline({
  42811. name: 'main',
  42812. style: makeStyle(brushOption),
  42813. silent: true
  42814. }));
  42815. return cover;
  42816. },
  42817. getCreatingRange: function (localTrack) {
  42818. return localTrack;
  42819. },
  42820. endCreating: function (controller, cover) {
  42821. cover.remove(cover.childAt(0));
  42822. // Use graphic.Polygon close the shape.
  42823. cover.add(new Polygon({
  42824. name: 'main',
  42825. draggable: true,
  42826. drift: curry$6(driftPolygon, controller, cover),
  42827. ondragend: curry$6(trigger, controller, {isEnd: true})
  42828. }));
  42829. },
  42830. updateCoverShape: function (controller, cover, localRange, brushOption) {
  42831. cover.childAt(0).setShape({
  42832. points: clipByPanel(controller, cover, localRange)
  42833. });
  42834. },
  42835. updateCommon: updateCommon,
  42836. contain: mainShapeContain
  42837. }
  42838. };
  42839. function getLineRenderer(xyIndex) {
  42840. return {
  42841. createCover: function (controller, brushOption) {
  42842. return createBaseRectCover(
  42843. curry$6(
  42844. driftRect,
  42845. function (range) {
  42846. var rectRange = [range, [0, 100]];
  42847. xyIndex && rectRange.reverse();
  42848. return rectRange;
  42849. },
  42850. function (rectRange) {
  42851. return rectRange[xyIndex];
  42852. }
  42853. ),
  42854. controller,
  42855. brushOption,
  42856. [['w', 'e'], ['n', 's']][xyIndex]
  42857. );
  42858. },
  42859. getCreatingRange: function (localTrack) {
  42860. var ends = getTrackEnds(localTrack);
  42861. var min = mathMin$4(ends[0][xyIndex], ends[1][xyIndex]);
  42862. var max = mathMax$4(ends[0][xyIndex], ends[1][xyIndex]);
  42863. return [min, max];
  42864. },
  42865. updateCoverShape: function (controller, cover, localRange, brushOption) {
  42866. var otherExtent;
  42867. // If brushWidth not specified, fit the panel.
  42868. var panel = getPanelByCover(controller, cover);
  42869. if (panel !== true && panel.getLinearBrushOtherExtent) {
  42870. otherExtent = panel.getLinearBrushOtherExtent(
  42871. xyIndex, controller._transform
  42872. );
  42873. }
  42874. else {
  42875. var zr = controller._zr;
  42876. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  42877. }
  42878. var rectRange = [localRange, otherExtent];
  42879. xyIndex && rectRange.reverse();
  42880. updateBaseRect(controller, cover, rectRange, brushOption);
  42881. },
  42882. updateCommon: updateCommon,
  42883. contain: mainShapeContain
  42884. };
  42885. }
  42886. var IRRELEVANT_EXCLUDES = {'axisPointer': 1, 'tooltip': 1, 'brush': 1};
  42887. /**
  42888. * Avoid that: mouse click on a elements that is over geo or graph,
  42889. * but roam is triggered.
  42890. */
  42891. function onIrrelevantElement(e, api, targetCoordSysModel) {
  42892. var model = api.getComponentByElement(e.topTarget);
  42893. // If model is axisModel, it works only if it is injected with coordinateSystem.
  42894. var coordSys = model && model.coordinateSystem;
  42895. return model
  42896. && model !== targetCoordSysModel
  42897. && !IRRELEVANT_EXCLUDES[model.mainType]
  42898. && (coordSys && coordSys.model !== targetCoordSysModel);
  42899. }
  42900. function makeRectPanelClipPath(rect) {
  42901. rect = normalizeRect(rect);
  42902. return function (localPoints, transform) {
  42903. return clipPointsByRect(localPoints, rect);
  42904. };
  42905. }
  42906. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  42907. rect = normalizeRect(rect);
  42908. return function (xyIndex) {
  42909. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  42910. var brushWidth = idx ? rect.width : rect.height;
  42911. var base = idx ? rect.x : rect.y;
  42912. return [base, base + (brushWidth || 0)];
  42913. };
  42914. }
  42915. function makeRectIsTargetByCursor(rect, api, targetModel) {
  42916. rect = normalizeRect(rect);
  42917. return function (e, localCursorPoint, transform) {
  42918. return rect.contain(localCursorPoint[0], localCursorPoint[1])
  42919. && !onIrrelevantElement(e, api, targetModel);
  42920. };
  42921. }
  42922. // Consider width/height is negative.
  42923. function normalizeRect(rect) {
  42924. return BoundingRect.create(rect);
  42925. }
  42926. var each$18 = each$1;
  42927. var indexOf$2 = indexOf;
  42928. var curry$7 = curry;
  42929. var COORD_CONVERTS = ['dataToPoint', 'pointToData'];
  42930. // FIXME
  42931. // how to genarialize to more coordinate systems.
  42932. var INCLUDE_FINDER_MAIN_TYPES = [
  42933. 'grid', 'xAxis', 'yAxis', 'geo', 'graph',
  42934. 'polar', 'radiusAxis', 'angleAxis', 'bmap'
  42935. ];
  42936. /**
  42937. * [option in constructor]:
  42938. * {
  42939. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  42940. * }
  42941. *
  42942. *
  42943. * [targetInfo]:
  42944. *
  42945. * There can be multiple axes in a single targetInfo. Consider the case
  42946. * of `grid` component, a targetInfo represents a grid which contains one or more
  42947. * cartesian and one or more axes. And consider the case of parallel system,
  42948. * which has multiple axes in a coordinate system.
  42949. * Can be {
  42950. * panelId: ...,
  42951. * coordSys: <a representitive cartesian in grid (first cartesian by default)>,
  42952. * coordSyses: all cartesians.
  42953. * gridModel: <grid component>
  42954. * xAxes: correspond to coordSyses on index
  42955. * yAxes: correspond to coordSyses on index
  42956. * }
  42957. * or {
  42958. * panelId: ...,
  42959. * coordSys: <geo coord sys>
  42960. * coordSyses: [<geo coord sys>]
  42961. * geoModel: <geo component>
  42962. * }
  42963. *
  42964. *
  42965. * [panelOpt]:
  42966. *
  42967. * Make from targetInfo. Input to BrushController.
  42968. * {
  42969. * panelId: ...,
  42970. * rect: ...
  42971. * }
  42972. *
  42973. *
  42974. * [area]:
  42975. *
  42976. * Generated by BrushController or user input.
  42977. * {
  42978. * panelId: Used to locate coordInfo directly. If user inpput, no panelId.
  42979. * brushType: determine how to convert to/from coord('rect' or 'polygon' or 'lineX/Y').
  42980. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  42981. * range: pixel range.
  42982. * coordRange: representitive coord range (the first one of coordRanges).
  42983. * coordRanges: <Array> coord ranges, used in multiple cartesian in one grid.
  42984. * }
  42985. */
  42986. /**
  42987. * @param {Object} option contains Index/Id/Name of xAxis/yAxis/geo/grid
  42988. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  42989. * @param {module:echarts/model/Global} ecModel
  42990. * @param {Object} [opt]
  42991. * @param {Array.<string>} [opt.include] include coordinate system types.
  42992. */
  42993. function BrushTargetManager(option, ecModel, opt) {
  42994. /**
  42995. * @private
  42996. * @type {Array.<Object>}
  42997. */
  42998. var targetInfoList = this._targetInfoList = [];
  42999. var info = {};
  43000. var foundCpts = parseFinder$1(ecModel, option);
  43001. each$18(targetInfoBuilders, function (builder, type) {
  43002. if (!opt || !opt.include || indexOf$2(opt.include, type) >= 0) {
  43003. builder(foundCpts, targetInfoList, info);
  43004. }
  43005. });
  43006. }
  43007. var proto$5 = BrushTargetManager.prototype;
  43008. proto$5.setOutputRanges = function (areas, ecModel) {
  43009. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  43010. (area.coordRanges || (area.coordRanges = [])).push(coordRange);
  43011. // area.coordRange is the first of area.coordRanges
  43012. if (!area.coordRange) {
  43013. area.coordRange = coordRange;
  43014. // In 'category' axis, coord to pixel is not reversible, so we can not
  43015. // rebuild range by coordRange accrately, which may bring trouble when
  43016. // brushing only one item. So we use __rangeOffset to rebuilding range
  43017. // by coordRange. And this it only used in brush component so it is no
  43018. // need to be adapted to coordRanges.
  43019. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  43020. area.__rangeOffset = {
  43021. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  43022. xyMinMax: result.xyMinMax
  43023. };
  43024. }
  43025. });
  43026. };
  43027. proto$5.matchOutputRanges = function (areas, ecModel, cb) {
  43028. each$18(areas, function (area) {
  43029. var targetInfo = this.findTargetInfo(area, ecModel);
  43030. if (targetInfo && targetInfo !== true) {
  43031. each$1(
  43032. targetInfo.coordSyses,
  43033. function (coordSys) {
  43034. var result = coordConvert[area.brushType](1, coordSys, area.range);
  43035. cb(area, result.values, coordSys, ecModel);
  43036. }
  43037. );
  43038. }
  43039. }, this);
  43040. };
  43041. proto$5.setInputRanges = function (areas, ecModel) {
  43042. each$18(areas, function (area) {
  43043. var targetInfo = this.findTargetInfo(area, ecModel);
  43044. if (__DEV__) {
  43045. assert$1(
  43046. !targetInfo || targetInfo === true || area.coordRange,
  43047. 'coordRange must be specified when coord index specified.'
  43048. );
  43049. assert$1(
  43050. !targetInfo || targetInfo !== true || area.range,
  43051. 'range must be specified in global brush.'
  43052. );
  43053. }
  43054. area.range = area.range || [];
  43055. // convert coordRange to global range and set panelId.
  43056. if (targetInfo && targetInfo !== true) {
  43057. area.panelId = targetInfo.panelId;
  43058. // (1) area.range shoule always be calculate from coordRange but does
  43059. // not keep its original value, for the sake of the dataZoom scenario,
  43060. // where area.coordRange remains unchanged but area.range may be changed.
  43061. // (2) Only support converting one coordRange to pixel range in brush
  43062. // component. So do not consider `coordRanges`.
  43063. // (3) About __rangeOffset, see comment above.
  43064. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  43065. var rangeOffset = area.__rangeOffset;
  43066. area.range = rangeOffset
  43067. ? diffProcessor[area.brushType](
  43068. result.values,
  43069. rangeOffset.offset,
  43070. getScales(result.xyMinMax, rangeOffset.xyMinMax)
  43071. )
  43072. : result.values;
  43073. }
  43074. }, this);
  43075. };
  43076. proto$5.makePanelOpts = function (api, getDefaultBrushType) {
  43077. return map(this._targetInfoList, function (targetInfo) {
  43078. var rect = targetInfo.getPanelRect();
  43079. return {
  43080. panelId: targetInfo.panelId,
  43081. defaultBrushType: getDefaultBrushType && getDefaultBrushType(targetInfo),
  43082. clipPath: makeRectPanelClipPath(rect),
  43083. isTargetByCursor: makeRectIsTargetByCursor(
  43084. rect, api, targetInfo.coordSysModel
  43085. ),
  43086. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  43087. };
  43088. });
  43089. };
  43090. proto$5.controlSeries = function (area, seriesModel, ecModel) {
  43091. // Check whether area is bound in coord, and series do not belong to that coord.
  43092. // If do not do this check, some brush (like lineX) will controll all axes.
  43093. var targetInfo = this.findTargetInfo(area, ecModel);
  43094. return targetInfo === true || (
  43095. targetInfo && indexOf$2(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0
  43096. );
  43097. };
  43098. /**
  43099. * If return Object, a coord found.
  43100. * If reutrn true, global found.
  43101. * Otherwise nothing found.
  43102. *
  43103. * @param {Object} area
  43104. * @param {Array} targetInfoList
  43105. * @return {Object|boolean}
  43106. */
  43107. proto$5.findTargetInfo = function (area, ecModel) {
  43108. var targetInfoList = this._targetInfoList;
  43109. var foundCpts = parseFinder$1(ecModel, area);
  43110. for (var i = 0; i < targetInfoList.length; i++) {
  43111. var targetInfo = targetInfoList[i];
  43112. var areaPanelId = area.panelId;
  43113. if (areaPanelId) {
  43114. if (targetInfo.panelId === areaPanelId) {
  43115. return targetInfo;
  43116. }
  43117. }
  43118. else {
  43119. for (var i = 0; i < targetInfoMatchers.length; i++) {
  43120. if (targetInfoMatchers[i](foundCpts, targetInfo)) {
  43121. return targetInfo;
  43122. }
  43123. }
  43124. }
  43125. }
  43126. return true;
  43127. };
  43128. function formatMinMax(minMax) {
  43129. minMax[0] > minMax[1] && minMax.reverse();
  43130. return minMax;
  43131. }
  43132. function parseFinder$1(ecModel, option) {
  43133. return parseFinder(
  43134. ecModel, option, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
  43135. );
  43136. }
  43137. var targetInfoBuilders = {
  43138. grid: function (foundCpts, targetInfoList) {
  43139. var xAxisModels = foundCpts.xAxisModels;
  43140. var yAxisModels = foundCpts.yAxisModels;
  43141. var gridModels = foundCpts.gridModels;
  43142. // Remove duplicated.
  43143. var gridModelMap = createHashMap();
  43144. var xAxesHas = {};
  43145. var yAxesHas = {};
  43146. if (!xAxisModels && !yAxisModels && !gridModels) {
  43147. return;
  43148. }
  43149. each$18(xAxisModels, function (axisModel) {
  43150. var gridModel = axisModel.axis.grid.model;
  43151. gridModelMap.set(gridModel.id, gridModel);
  43152. xAxesHas[gridModel.id] = true;
  43153. });
  43154. each$18(yAxisModels, function (axisModel) {
  43155. var gridModel = axisModel.axis.grid.model;
  43156. gridModelMap.set(gridModel.id, gridModel);
  43157. yAxesHas[gridModel.id] = true;
  43158. });
  43159. each$18(gridModels, function (gridModel) {
  43160. gridModelMap.set(gridModel.id, gridModel);
  43161. xAxesHas[gridModel.id] = true;
  43162. yAxesHas[gridModel.id] = true;
  43163. });
  43164. gridModelMap.each(function (gridModel) {
  43165. var grid = gridModel.coordinateSystem;
  43166. var cartesians = [];
  43167. each$18(grid.getCartesians(), function (cartesian, index) {
  43168. if (indexOf$2(xAxisModels, cartesian.getAxis('x').model) >= 0
  43169. || indexOf$2(yAxisModels, cartesian.getAxis('y').model) >= 0
  43170. ) {
  43171. cartesians.push(cartesian);
  43172. }
  43173. });
  43174. targetInfoList.push({
  43175. panelId: 'grid--' + gridModel.id,
  43176. gridModel: gridModel,
  43177. coordSysModel: gridModel,
  43178. // Use the first one as the representitive coordSys.
  43179. coordSys: cartesians[0],
  43180. coordSyses: cartesians,
  43181. getPanelRect: panelRectBuilder.grid,
  43182. xAxisDeclared: xAxesHas[gridModel.id],
  43183. yAxisDeclared: yAxesHas[gridModel.id]
  43184. });
  43185. });
  43186. },
  43187. geo: function (foundCpts, targetInfoList) {
  43188. each$18(foundCpts.geoModels, function (geoModel) {
  43189. var coordSys = geoModel.coordinateSystem;
  43190. targetInfoList.push({
  43191. panelId: 'geo--' + geoModel.id,
  43192. geoModel: geoModel,
  43193. coordSysModel: geoModel,
  43194. coordSys: coordSys,
  43195. coordSyses: [coordSys],
  43196. getPanelRect: panelRectBuilder.geo
  43197. });
  43198. });
  43199. }
  43200. };
  43201. var targetInfoMatchers = [
  43202. // grid
  43203. function (foundCpts, targetInfo) {
  43204. var xAxisModel = foundCpts.xAxisModel;
  43205. var yAxisModel = foundCpts.yAxisModel;
  43206. var gridModel = foundCpts.gridModel;
  43207. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  43208. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  43209. return gridModel && gridModel === targetInfo.gridModel;
  43210. },
  43211. // geo
  43212. function (foundCpts, targetInfo) {
  43213. var geoModel = foundCpts.geoModel;
  43214. return geoModel && geoModel === targetInfo.geoModel;
  43215. }
  43216. ];
  43217. var panelRectBuilder = {
  43218. grid: function () {
  43219. // grid is not Transformable.
  43220. return this.coordSys.grid.getRect().clone();
  43221. },
  43222. geo: function () {
  43223. var coordSys = this.coordSys;
  43224. var rect = coordSys.getBoundingRect().clone();
  43225. // geo roam and zoom transform
  43226. rect.applyTransform(getTransform(coordSys));
  43227. return rect;
  43228. }
  43229. };
  43230. var coordConvert = {
  43231. lineX: curry$7(axisConvert, 0),
  43232. lineY: curry$7(axisConvert, 1),
  43233. rect: function (to, coordSys, rangeOrCoordRange) {
  43234. var xminymin = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
  43235. var xmaxymax = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
  43236. var values = [
  43237. formatMinMax([xminymin[0], xmaxymax[0]]),
  43238. formatMinMax([xminymin[1], xmaxymax[1]])
  43239. ];
  43240. return {values: values, xyMinMax: values};
  43241. },
  43242. polygon: function (to, coordSys, rangeOrCoordRange) {
  43243. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  43244. var values = map(rangeOrCoordRange, function (item) {
  43245. var p = coordSys[COORD_CONVERTS[to]](item);
  43246. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  43247. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  43248. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  43249. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  43250. return p;
  43251. });
  43252. return {values: values, xyMinMax: xyMinMax};
  43253. }
  43254. };
  43255. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  43256. if (__DEV__) {
  43257. assert$1(
  43258. coordSys.type === 'cartesian2d',
  43259. 'lineX/lineY brush is available only in cartesian2d.'
  43260. );
  43261. }
  43262. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  43263. var values = formatMinMax(map([0, 1], function (i) {
  43264. return to
  43265. ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]))
  43266. : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  43267. }));
  43268. var xyMinMax = [];
  43269. xyMinMax[axisNameIndex] = values;
  43270. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  43271. return {values: values, xyMinMax: xyMinMax};
  43272. }
  43273. var diffProcessor = {
  43274. lineX: curry$7(axisDiffProcessor, 0),
  43275. lineY: curry$7(axisDiffProcessor, 1),
  43276. rect: function (values, refer, scales) {
  43277. return [
  43278. [values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
  43279. [values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
  43280. ];
  43281. },
  43282. polygon: function (values, refer, scales) {
  43283. return map(values, function (item, idx) {
  43284. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  43285. });
  43286. }
  43287. };
  43288. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  43289. return [
  43290. values[0] - scales[axisNameIndex] * refer[0],
  43291. values[1] - scales[axisNameIndex] * refer[1]
  43292. ];
  43293. }
  43294. // We have to process scale caused by dataZoom manually,
  43295. // although it might be not accurate.
  43296. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  43297. var sizeCurr = getSize(xyMinMaxCurr);
  43298. var sizeOrigin = getSize(xyMinMaxOrigin);
  43299. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  43300. isNaN(scales[0]) && (scales[0] = 1);
  43301. isNaN(scales[1]) && (scales[1] = 1);
  43302. return scales;
  43303. }
  43304. function getSize(xyMinMax) {
  43305. return xyMinMax
  43306. ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
  43307. : [NaN, NaN];
  43308. }
  43309. var each$19 = each$1;
  43310. var ATTR$2 = '\0_ec_hist_store';
  43311. /**
  43312. * @param {module:echarts/model/Global} ecModel
  43313. * @param {Object} newSnapshot {dataZoomId, batch: [payloadInfo, ...]}
  43314. */
  43315. function push(ecModel, newSnapshot) {
  43316. var store = giveStore$1(ecModel);
  43317. // If previous dataZoom can not be found,
  43318. // complete an range with current range.
  43319. each$19(newSnapshot, function (batchItem, dataZoomId) {
  43320. var i = store.length - 1;
  43321. for (; i >= 0; i--) {
  43322. var snapshot = store[i];
  43323. if (snapshot[dataZoomId]) {
  43324. break;
  43325. }
  43326. }
  43327. if (i < 0) {
  43328. // No origin range set, create one by current range.
  43329. var dataZoomModel = ecModel.queryComponents(
  43330. {mainType: 'dataZoom', subType: 'select', id: dataZoomId}
  43331. )[0];
  43332. if (dataZoomModel) {
  43333. var percentRange = dataZoomModel.getPercentRange();
  43334. store[0][dataZoomId] = {
  43335. dataZoomId: dataZoomId,
  43336. start: percentRange[0],
  43337. end: percentRange[1]
  43338. };
  43339. }
  43340. }
  43341. });
  43342. store.push(newSnapshot);
  43343. }
  43344. /**
  43345. * @param {module:echarts/model/Global} ecModel
  43346. * @return {Object} snapshot
  43347. */
  43348. function pop(ecModel) {
  43349. var store = giveStore$1(ecModel);
  43350. var head = store[store.length - 1];
  43351. store.length > 1 && store.pop();
  43352. // Find top for all dataZoom.
  43353. var snapshot = {};
  43354. each$19(head, function (batchItem, dataZoomId) {
  43355. for (var i = store.length - 1; i >= 0; i--) {
  43356. var batchItem = store[i][dataZoomId];
  43357. if (batchItem) {
  43358. snapshot[dataZoomId] = batchItem;
  43359. break;
  43360. }
  43361. }
  43362. });
  43363. return snapshot;
  43364. }
  43365. /**
  43366. * @param {module:echarts/model/Global} ecModel
  43367. */
  43368. function clear$1(ecModel) {
  43369. ecModel[ATTR$2] = null;
  43370. }
  43371. /**
  43372. * @param {module:echarts/model/Global} ecModel
  43373. * @return {number} records. always >= 1.
  43374. */
  43375. function count(ecModel) {
  43376. return giveStore$1(ecModel).length;
  43377. }
  43378. /**
  43379. * [{key: dataZoomId, value: {dataZoomId, range}}, ...]
  43380. * History length of each dataZoom may be different.
  43381. * this._history[0] is used to store origin range.
  43382. * @type {Array.<Object>}
  43383. */
  43384. function giveStore$1(ecModel) {
  43385. var store = ecModel[ATTR$2];
  43386. if (!store) {
  43387. store = ecModel[ATTR$2] = [{}];
  43388. }
  43389. return store;
  43390. }
  43391. DataZoomModel.extend({
  43392. type: 'dataZoom.select'
  43393. });
  43394. DataZoomView.extend({
  43395. type: 'dataZoom.select'
  43396. });
  43397. /**
  43398. * DataZoom component entry
  43399. */
  43400. // Use dataZoomSelect
  43401. var dataZoomLang = lang.toolbox.dataZoom;
  43402. var each$16 = each$1;
  43403. // Spectial component id start with \0ec\0, see echarts/model/Global.js~hasInnerId
  43404. var DATA_ZOOM_ID_BASE = '\0_ec_\0toolbox-dataZoom_';
  43405. function DataZoom(model, ecModel, api) {
  43406. /**
  43407. * @private
  43408. * @type {module:echarts/component/helper/BrushController}
  43409. */
  43410. (this._brushController = new BrushController(api.getZr()))
  43411. .on('brush', bind(this._onBrush, this))
  43412. .mount();
  43413. /**
  43414. * @private
  43415. * @type {boolean}
  43416. */
  43417. this._isZoomActive;
  43418. }
  43419. DataZoom.defaultOption = {
  43420. show: true,
  43421. // Icon group
  43422. icon: {
  43423. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  43424. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  43425. },
  43426. // `zoom`, `back`
  43427. title: clone(dataZoomLang.title)
  43428. };
  43429. var proto$4 = DataZoom.prototype;
  43430. proto$4.render = function (featureModel, ecModel, api, payload) {
  43431. this.model = featureModel;
  43432. this.ecModel = ecModel;
  43433. this.api = api;
  43434. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  43435. updateBackBtnStatus(featureModel, ecModel);
  43436. };
  43437. proto$4.onclick = function (ecModel, api, type) {
  43438. handlers[type].call(this);
  43439. };
  43440. proto$4.remove = function (ecModel, api) {
  43441. this._brushController.unmount();
  43442. };
  43443. proto$4.dispose = function (ecModel, api) {
  43444. this._brushController.dispose();
  43445. };
  43446. /**
  43447. * @private
  43448. */
  43449. var handlers = {
  43450. zoom: function () {
  43451. var nextActive = !this._isZoomActive;
  43452. this.api.dispatchAction({
  43453. type: 'takeGlobalCursor',
  43454. key: 'dataZoomSelect',
  43455. dataZoomSelectActive: nextActive
  43456. });
  43457. },
  43458. back: function () {
  43459. this._dispatchZoomAction(pop(this.ecModel));
  43460. }
  43461. };
  43462. /**
  43463. * @private
  43464. */
  43465. proto$4._onBrush = function (areas, opt) {
  43466. if (!opt.isEnd || !areas.length) {
  43467. return;
  43468. }
  43469. var snapshot = {};
  43470. var ecModel = this.ecModel;
  43471. this._brushController.updateCovers([]); // remove cover
  43472. var brushTargetManager = new BrushTargetManager(
  43473. retrieveAxisSetting(this.model.option), ecModel, {include: ['grid']}
  43474. );
  43475. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  43476. if (coordSys.type !== 'cartesian2d') {
  43477. return;
  43478. }
  43479. var brushType = area.brushType;
  43480. if (brushType === 'rect') {
  43481. setBatch('x', coordSys, coordRange[0]);
  43482. setBatch('y', coordSys, coordRange[1]);
  43483. }
  43484. else {
  43485. setBatch(({lineX: 'x', lineY: 'y'})[brushType], coordSys, coordRange);
  43486. }
  43487. });
  43488. push(ecModel, snapshot);
  43489. this._dispatchZoomAction(snapshot);
  43490. function setBatch(dimName, coordSys, minMax) {
  43491. var axis = coordSys.getAxis(dimName);
  43492. var axisModel = axis.model;
  43493. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel);
  43494. // Restrict range.
  43495. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  43496. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  43497. minMax = sliderMove(
  43498. 0, minMax.slice(), axis.scale.getExtent(), 0,
  43499. minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan
  43500. );
  43501. }
  43502. dataZoomModel && (snapshot[dataZoomModel.id] = {
  43503. dataZoomId: dataZoomModel.id,
  43504. startValue: minMax[0],
  43505. endValue: minMax[1]
  43506. });
  43507. }
  43508. function findDataZoom(dimName, axisModel, ecModel) {
  43509. var found;
  43510. ecModel.eachComponent({mainType: 'dataZoom', subType: 'select'}, function (dzModel) {
  43511. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  43512. has && (found = dzModel);
  43513. });
  43514. return found;
  43515. }
  43516. };
  43517. /**
  43518. * @private
  43519. */
  43520. proto$4._dispatchZoomAction = function (snapshot) {
  43521. var batch = [];
  43522. // Convert from hash map to array.
  43523. each$16(snapshot, function (batchItem, dataZoomId) {
  43524. batch.push(clone(batchItem));
  43525. });
  43526. batch.length && this.api.dispatchAction({
  43527. type: 'dataZoom',
  43528. from: this.uid,
  43529. batch: batch
  43530. });
  43531. };
  43532. function retrieveAxisSetting(option) {
  43533. var setting = {};
  43534. // Compatible with previous setting: null => all axis, false => no axis.
  43535. each$1(['xAxisIndex', 'yAxisIndex'], function (name) {
  43536. setting[name] = option[name];
  43537. setting[name] == null && (setting[name] = 'all');
  43538. (setting[name] === false || setting[name] === 'none') && (setting[name] = []);
  43539. });
  43540. return setting;
  43541. }
  43542. function updateBackBtnStatus(featureModel, ecModel) {
  43543. featureModel.setIconStatus(
  43544. 'back',
  43545. count(ecModel) > 1 ? 'emphasis' : 'normal'
  43546. );
  43547. }
  43548. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  43549. var zoomActive = view._isZoomActive;
  43550. if (payload && payload.type === 'takeGlobalCursor') {
  43551. zoomActive = payload.key === 'dataZoomSelect'
  43552. ? payload.dataZoomSelectActive : false;
  43553. }
  43554. view._isZoomActive = zoomActive;
  43555. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  43556. var brushTargetManager = new BrushTargetManager(
  43557. retrieveAxisSetting(featureModel.option), ecModel, {include: ['grid']}
  43558. );
  43559. view._brushController
  43560. .setPanels(brushTargetManager.makePanelOpts(api, function (targetInfo) {
  43561. return (targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared)
  43562. ? 'lineX'
  43563. : (!targetInfo.xAxisDeclared && targetInfo.yAxisDeclared)
  43564. ? 'lineY'
  43565. : 'rect';
  43566. }))
  43567. .enableBrush(
  43568. zoomActive
  43569. ? {
  43570. brushType: 'auto',
  43571. brushStyle: {
  43572. // FIXME user customized?
  43573. lineWidth: 0,
  43574. fill: 'rgba(0,0,0,0.2)'
  43575. }
  43576. }
  43577. : false
  43578. );
  43579. }
  43580. register$2('dataZoom', DataZoom);
  43581. // Create special dataZoom option for select
  43582. registerPreprocessor(function (option) {
  43583. if (!option) {
  43584. return;
  43585. }
  43586. var dataZoomOpts = option.dataZoom || (option.dataZoom = []);
  43587. if (!isArray(dataZoomOpts)) {
  43588. option.dataZoom = dataZoomOpts = [dataZoomOpts];
  43589. }
  43590. var toolboxOpt = option.toolbox;
  43591. if (toolboxOpt) {
  43592. // Assume there is only one toolbox
  43593. if (isArray(toolboxOpt)) {
  43594. toolboxOpt = toolboxOpt[0];
  43595. }
  43596. if (toolboxOpt && toolboxOpt.feature) {
  43597. var dataZoomOpt = toolboxOpt.feature.dataZoom;
  43598. addForAxis('xAxis', dataZoomOpt);
  43599. addForAxis('yAxis', dataZoomOpt);
  43600. }
  43601. }
  43602. function addForAxis(axisName, dataZoomOpt) {
  43603. if (!dataZoomOpt) {
  43604. return;
  43605. }
  43606. // Try not to modify model, because it is not merged yet.
  43607. var axisIndicesName = axisName + 'Index';
  43608. var givenAxisIndices = dataZoomOpt[axisIndicesName];
  43609. if (givenAxisIndices != null
  43610. && givenAxisIndices != 'all'
  43611. && !isArray(givenAxisIndices)
  43612. ) {
  43613. givenAxisIndices = (givenAxisIndices === false || givenAxisIndices === 'none') ? [] : [givenAxisIndices];
  43614. }
  43615. forEachComponent(axisName, function (axisOpt, axisIndex) {
  43616. if (givenAxisIndices != null
  43617. && givenAxisIndices != 'all'
  43618. && indexOf(givenAxisIndices, axisIndex) === -1
  43619. ) {
  43620. return;
  43621. }
  43622. var newOpt = {
  43623. type: 'select',
  43624. $fromToolbox: true,
  43625. // Id for merge mapping.
  43626. id: DATA_ZOOM_ID_BASE + axisName + axisIndex
  43627. };
  43628. // FIXME
  43629. // Only support one axis now.
  43630. newOpt[axisIndicesName] = axisIndex;
  43631. dataZoomOpts.push(newOpt);
  43632. });
  43633. }
  43634. function forEachComponent(mainType, cb) {
  43635. var opts = option[mainType];
  43636. if (!isArray(opts)) {
  43637. opts = opts ? [opts] : [];
  43638. }
  43639. each$16(opts, cb);
  43640. }
  43641. });
  43642. var restoreLang = lang.toolbox.restore;
  43643. function Restore(model) {
  43644. this.model = model;
  43645. }
  43646. Restore.defaultOption = {
  43647. show: true,
  43648. 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',
  43649. title: restoreLang.title
  43650. };
  43651. var proto$6 = Restore.prototype;
  43652. proto$6.onclick = function (ecModel, api, type) {
  43653. clear$1(ecModel);
  43654. api.dispatchAction({
  43655. type: 'restore',
  43656. from: this.uid
  43657. });
  43658. };
  43659. register$2('restore', Restore);
  43660. registerAction(
  43661. {type: 'restore', event: 'restore', update: 'prepareAndUpdate'},
  43662. function (payload, ecModel) {
  43663. ecModel.resetOption('recreate');
  43664. }
  43665. );
  43666. var urn = 'urn:schemas-microsoft-com:vml';
  43667. var win = typeof window === 'undefined' ? null : window;
  43668. var vmlInited = false;
  43669. var doc = win && win.document;
  43670. function createNode(tagName) {
  43671. return doCreateNode(tagName);
  43672. }
  43673. // Avoid assign to an exported variable, for transforming to cjs.
  43674. var doCreateNode;
  43675. if (doc && !env$1.canvasSupported) {
  43676. try {
  43677. !doc.namespaces.zrvml && doc.namespaces.add('zrvml', urn);
  43678. doCreateNode = function (tagName) {
  43679. return doc.createElement('<zrvml:' + tagName + ' class="zrvml">');
  43680. };
  43681. }
  43682. catch (e) {
  43683. doCreateNode = function (tagName) {
  43684. return doc.createElement('<' + tagName + ' xmlns="' + urn + '" class="zrvml">');
  43685. };
  43686. }
  43687. }
  43688. // From raphael
  43689. function initVML() {
  43690. if (vmlInited || !doc) {
  43691. return;
  43692. }
  43693. vmlInited = true;
  43694. var styleSheets = doc.styleSheets;
  43695. if (styleSheets.length < 31) {
  43696. doc.createStyleSheet().addRule('.zrvml', 'behavior:url(#default#VML)');
  43697. }
  43698. else {
  43699. // http://msdn.microsoft.com/en-us/library/ms531194%28VS.85%29.aspx
  43700. styleSheets[0].addRule('.zrvml', 'behavior:url(#default#VML)');
  43701. }
  43702. }
  43703. // http://www.w3.org/TR/NOTE-VML
  43704. // TODO Use proxy like svg instead of overwrite brush methods
  43705. var CMD$3 = PathProxy.CMD;
  43706. var round$2 = Math.round;
  43707. var sqrt = Math.sqrt;
  43708. var abs$1 = Math.abs;
  43709. var cos = Math.cos;
  43710. var sin = Math.sin;
  43711. var mathMax$5 = Math.max;
  43712. if (!env$1.canvasSupported) {
  43713. var comma = ',';
  43714. var imageTransformPrefix = 'progid:DXImageTransform.Microsoft';
  43715. var Z = 21600;
  43716. var Z2 = Z / 2;
  43717. var ZLEVEL_BASE = 100000;
  43718. var Z_BASE = 1000;
  43719. var initRootElStyle = function (el) {
  43720. el.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;';
  43721. el.coordsize = Z + ',' + Z;
  43722. el.coordorigin = '0,0';
  43723. };
  43724. var encodeHtmlAttribute = function (s) {
  43725. return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
  43726. };
  43727. var rgb2Str = function (r, g, b) {
  43728. return 'rgb(' + [r, g, b].join(',') + ')';
  43729. };
  43730. var append = function (parent, child) {
  43731. if (child && parent && child.parentNode !== parent) {
  43732. parent.appendChild(child);
  43733. }
  43734. };
  43735. var remove = function (parent, child) {
  43736. if (child && parent && child.parentNode === parent) {
  43737. parent.removeChild(child);
  43738. }
  43739. };
  43740. var getZIndex = function (zlevel, z, z2) {
  43741. // z 的取值范围为 [0, 1000]
  43742. return (parseFloat(zlevel) || 0) * ZLEVEL_BASE + (parseFloat(z) || 0) * Z_BASE + z2;
  43743. };
  43744. var parsePercent$3 = function (value, maxValue) {
  43745. if (typeof value === 'string') {
  43746. if (value.lastIndexOf('%') >= 0) {
  43747. return parseFloat(value) / 100 * maxValue;
  43748. }
  43749. return parseFloat(value);
  43750. }
  43751. return value;
  43752. };
  43753. /***************************************************
  43754. * PATH
  43755. **************************************************/
  43756. var setColorAndOpacity = function (el, color, opacity) {
  43757. var colorArr = parse(color);
  43758. opacity = +opacity;
  43759. if (isNaN(opacity)) {
  43760. opacity = 1;
  43761. }
  43762. if (colorArr) {
  43763. el.color = rgb2Str(colorArr[0], colorArr[1], colorArr[2]);
  43764. el.opacity = opacity * colorArr[3];
  43765. }
  43766. };
  43767. var getColorAndAlpha = function (color) {
  43768. var colorArr = parse(color);
  43769. return [
  43770. rgb2Str(colorArr[0], colorArr[1], colorArr[2]),
  43771. colorArr[3]
  43772. ];
  43773. };
  43774. var updateFillNode = function (el, style, zrEl) {
  43775. // TODO pattern
  43776. var fill = style.fill;
  43777. if (fill != null) {
  43778. // Modified from excanvas
  43779. if (fill instanceof Gradient) {
  43780. var gradientType;
  43781. var angle = 0;
  43782. var focus = [0, 0];
  43783. // additional offset
  43784. var shift = 0;
  43785. // scale factor for offset
  43786. var expansion = 1;
  43787. var rect = zrEl.getBoundingRect();
  43788. var rectWidth = rect.width;
  43789. var rectHeight = rect.height;
  43790. if (fill.type === 'linear') {
  43791. gradientType = 'gradient';
  43792. var transform = zrEl.transform;
  43793. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  43794. var p1 = [fill.x2 * rectWidth, fill.y2 * rectHeight];
  43795. if (transform) {
  43796. applyTransform(p0, p0, transform);
  43797. applyTransform(p1, p1, transform);
  43798. }
  43799. var dx = p1[0] - p0[0];
  43800. var dy = p1[1] - p0[1];
  43801. angle = Math.atan2(dx, dy) * 180 / Math.PI;
  43802. // The angle should be a non-negative number.
  43803. if (angle < 0) {
  43804. angle += 360;
  43805. }
  43806. // Very small angles produce an unexpected result because they are
  43807. // converted to a scientific notation string.
  43808. if (angle < 1e-6) {
  43809. angle = 0;
  43810. }
  43811. }
  43812. else {
  43813. gradientType = 'gradientradial';
  43814. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  43815. var transform = zrEl.transform;
  43816. var scale$$1 = zrEl.scale;
  43817. var width = rectWidth;
  43818. var height = rectHeight;
  43819. focus = [
  43820. // Percent in bounding rect
  43821. (p0[0] - rect.x) / width,
  43822. (p0[1] - rect.y) / height
  43823. ];
  43824. if (transform) {
  43825. applyTransform(p0, p0, transform);
  43826. }
  43827. width /= scale$$1[0] * Z;
  43828. height /= scale$$1[1] * Z;
  43829. var dimension = mathMax$5(width, height);
  43830. shift = 2 * 0 / dimension;
  43831. expansion = 2 * fill.r / dimension - shift;
  43832. }
  43833. // We need to sort the color stops in ascending order by offset,
  43834. // otherwise IE won't interpret it correctly.
  43835. var stops = fill.colorStops.slice();
  43836. stops.sort(function(cs1, cs2) {
  43837. return cs1.offset - cs2.offset;
  43838. });
  43839. var length$$1 = stops.length;
  43840. // Color and alpha list of first and last stop
  43841. var colorAndAlphaList = [];
  43842. var colors = [];
  43843. for (var i = 0; i < length$$1; i++) {
  43844. var stop = stops[i];
  43845. var colorAndAlpha = getColorAndAlpha(stop.color);
  43846. colors.push(stop.offset * expansion + shift + ' ' + colorAndAlpha[0]);
  43847. if (i === 0 || i === length$$1 - 1) {
  43848. colorAndAlphaList.push(colorAndAlpha);
  43849. }
  43850. }
  43851. if (length$$1 >= 2) {
  43852. var color1 = colorAndAlphaList[0][0];
  43853. var color2 = colorAndAlphaList[1][0];
  43854. var opacity1 = colorAndAlphaList[0][1] * style.opacity;
  43855. var opacity2 = colorAndAlphaList[1][1] * style.opacity;
  43856. el.type = gradientType;
  43857. el.method = 'none';
  43858. el.focus = '100%';
  43859. el.angle = angle;
  43860. el.color = color1;
  43861. el.color2 = color2;
  43862. el.colors = colors.join(',');
  43863. // When colors attribute is used, the meanings of opacity and o:opacity2
  43864. // are reversed.
  43865. el.opacity = opacity2;
  43866. // FIXME g_o_:opacity ?
  43867. el.opacity2 = opacity1;
  43868. }
  43869. if (gradientType === 'radial') {
  43870. el.focusposition = focus.join(',');
  43871. }
  43872. }
  43873. else {
  43874. // FIXME Change from Gradient fill to color fill
  43875. setColorAndOpacity(el, fill, style.opacity);
  43876. }
  43877. }
  43878. };
  43879. var updateStrokeNode = function (el, style) {
  43880. // if (style.lineJoin != null) {
  43881. // el.joinstyle = style.lineJoin;
  43882. // }
  43883. // if (style.miterLimit != null) {
  43884. // el.miterlimit = style.miterLimit * Z;
  43885. // }
  43886. // if (style.lineCap != null) {
  43887. // el.endcap = style.lineCap;
  43888. // }
  43889. if (style.lineDash != null) {
  43890. el.dashstyle = style.lineDash.join(' ');
  43891. }
  43892. if (style.stroke != null && !(style.stroke instanceof Gradient)) {
  43893. setColorAndOpacity(el, style.stroke, style.opacity);
  43894. }
  43895. };
  43896. var updateFillAndStroke = function (vmlEl, type, style, zrEl) {
  43897. var isFill = type == 'fill';
  43898. var el = vmlEl.getElementsByTagName(type)[0];
  43899. // Stroke must have lineWidth
  43900. if (style[type] != null && style[type] !== 'none' && (isFill || (!isFill && style.lineWidth))) {
  43901. vmlEl[isFill ? 'filled' : 'stroked'] = 'true';
  43902. // FIXME Remove before updating, or set `colors` will throw error
  43903. if (style[type] instanceof Gradient) {
  43904. remove(vmlEl, el);
  43905. }
  43906. if (!el) {
  43907. el = createNode(type);
  43908. }
  43909. isFill ? updateFillNode(el, style, zrEl) : updateStrokeNode(el, style);
  43910. append(vmlEl, el);
  43911. }
  43912. else {
  43913. vmlEl[isFill ? 'filled' : 'stroked'] = 'false';
  43914. remove(vmlEl, el);
  43915. }
  43916. };
  43917. var points$1 = [[], [], []];
  43918. var pathDataToString = function (path, m) {
  43919. var M = CMD$3.M;
  43920. var C = CMD$3.C;
  43921. var L = CMD$3.L;
  43922. var A = CMD$3.A;
  43923. var Q = CMD$3.Q;
  43924. var str = [];
  43925. var nPoint;
  43926. var cmdStr;
  43927. var cmd;
  43928. var i;
  43929. var xi;
  43930. var yi;
  43931. var data = path.data;
  43932. var dataLength = path.len();
  43933. for (i = 0; i < dataLength;) {
  43934. cmd = data[i++];
  43935. cmdStr = '';
  43936. nPoint = 0;
  43937. switch (cmd) {
  43938. case M:
  43939. cmdStr = ' m ';
  43940. nPoint = 1;
  43941. xi = data[i++];
  43942. yi = data[i++];
  43943. points$1[0][0] = xi;
  43944. points$1[0][1] = yi;
  43945. break;
  43946. case L:
  43947. cmdStr = ' l ';
  43948. nPoint = 1;
  43949. xi = data[i++];
  43950. yi = data[i++];
  43951. points$1[0][0] = xi;
  43952. points$1[0][1] = yi;
  43953. break;
  43954. case Q:
  43955. case C:
  43956. cmdStr = ' c ';
  43957. nPoint = 3;
  43958. var x1 = data[i++];
  43959. var y1 = data[i++];
  43960. var x2 = data[i++];
  43961. var y2 = data[i++];
  43962. var x3;
  43963. var y3;
  43964. if (cmd === Q) {
  43965. // Convert quadratic to cubic using degree elevation
  43966. x3 = x2;
  43967. y3 = y2;
  43968. x2 = (x2 + 2 * x1) / 3;
  43969. y2 = (y2 + 2 * y1) / 3;
  43970. x1 = (xi + 2 * x1) / 3;
  43971. y1 = (yi + 2 * y1) / 3;
  43972. }
  43973. else {
  43974. x3 = data[i++];
  43975. y3 = data[i++];
  43976. }
  43977. points$1[0][0] = x1;
  43978. points$1[0][1] = y1;
  43979. points$1[1][0] = x2;
  43980. points$1[1][1] = y2;
  43981. points$1[2][0] = x3;
  43982. points$1[2][1] = y3;
  43983. xi = x3;
  43984. yi = y3;
  43985. break;
  43986. case A:
  43987. var x = 0;
  43988. var y = 0;
  43989. var sx = 1;
  43990. var sy = 1;
  43991. var angle = 0;
  43992. if (m) {
  43993. // Extract SRT from matrix
  43994. x = m[4];
  43995. y = m[5];
  43996. sx = sqrt(m[0] * m[0] + m[1] * m[1]);
  43997. sy = sqrt(m[2] * m[2] + m[3] * m[3]);
  43998. angle = Math.atan2(-m[1] / sy, m[0] / sx);
  43999. }
  44000. var cx = data[i++];
  44001. var cy = data[i++];
  44002. var rx = data[i++];
  44003. var ry = data[i++];
  44004. var startAngle = data[i++] + angle;
  44005. var endAngle = data[i++] + startAngle + angle;
  44006. // FIXME
  44007. // var psi = data[i++];
  44008. i++;
  44009. var clockwise = data[i++];
  44010. var x0 = cx + cos(startAngle) * rx;
  44011. var y0 = cy + sin(startAngle) * ry;
  44012. var x1 = cx + cos(endAngle) * rx;
  44013. var y1 = cy + sin(endAngle) * ry;
  44014. var type = clockwise ? ' wa ' : ' at ';
  44015. if (Math.abs(x0 - x1) < 1e-4) {
  44016. // IE won't render arches drawn counter clockwise if x0 == x1.
  44017. if (Math.abs(endAngle - startAngle) > 1e-2) {
  44018. // Offset x0 by 1/80 of a pixel. Use something
  44019. // that can be represented in binary
  44020. if (clockwise) {
  44021. x0 += 270 / Z;
  44022. }
  44023. }
  44024. else {
  44025. // Avoid case draw full circle
  44026. if (Math.abs(y0 - cy) < 1e-4) {
  44027. if ((clockwise && x0 < cx) || (!clockwise && x0 > cx)) {
  44028. y1 -= 270 / Z;
  44029. }
  44030. else {
  44031. y1 += 270 / Z;
  44032. }
  44033. }
  44034. else if ((clockwise && y0 < cy) || (!clockwise && y0 > cy)) {
  44035. x1 += 270 / Z;
  44036. }
  44037. else {
  44038. x1 -= 270 / Z;
  44039. }
  44040. }
  44041. }
  44042. str.push(
  44043. type,
  44044. round$2(((cx - rx) * sx + x) * Z - Z2), comma,
  44045. round$2(((cy - ry) * sy + y) * Z - Z2), comma,
  44046. round$2(((cx + rx) * sx + x) * Z - Z2), comma,
  44047. round$2(((cy + ry) * sy + y) * Z - Z2), comma,
  44048. round$2((x0 * sx + x) * Z - Z2), comma,
  44049. round$2((y0 * sy + y) * Z - Z2), comma,
  44050. round$2((x1 * sx + x) * Z - Z2), comma,
  44051. round$2((y1 * sy + y) * Z - Z2)
  44052. );
  44053. xi = x1;
  44054. yi = y1;
  44055. break;
  44056. case CMD$3.R:
  44057. var p0 = points$1[0];
  44058. var p1 = points$1[1];
  44059. // x0, y0
  44060. p0[0] = data[i++];
  44061. p0[1] = data[i++];
  44062. // x1, y1
  44063. p1[0] = p0[0] + data[i++];
  44064. p1[1] = p0[1] + data[i++];
  44065. if (m) {
  44066. applyTransform(p0, p0, m);
  44067. applyTransform(p1, p1, m);
  44068. }
  44069. p0[0] = round$2(p0[0] * Z - Z2);
  44070. p1[0] = round$2(p1[0] * Z - Z2);
  44071. p0[1] = round$2(p0[1] * Z - Z2);
  44072. p1[1] = round$2(p1[1] * Z - Z2);
  44073. str.push(
  44074. // x0, y0
  44075. ' m ', p0[0], comma, p0[1],
  44076. // x1, y0
  44077. ' l ', p1[0], comma, p0[1],
  44078. // x1, y1
  44079. ' l ', p1[0], comma, p1[1],
  44080. // x0, y1
  44081. ' l ', p0[0], comma, p1[1]
  44082. );
  44083. break;
  44084. case CMD$3.Z:
  44085. // FIXME Update xi, yi
  44086. str.push(' x ');
  44087. }
  44088. if (nPoint > 0) {
  44089. str.push(cmdStr);
  44090. for (var k = 0; k < nPoint; k++) {
  44091. var p = points$1[k];
  44092. m && applyTransform(p, p, m);
  44093. // 不 round 会非常慢
  44094. str.push(
  44095. round$2(p[0] * Z - Z2), comma, round$2(p[1] * Z - Z2),
  44096. k < nPoint - 1 ? comma : ''
  44097. );
  44098. }
  44099. }
  44100. }
  44101. return str.join('');
  44102. };
  44103. // Rewrite the original path method
  44104. Path.prototype.brushVML = function (vmlRoot) {
  44105. var style = this.style;
  44106. var vmlEl = this._vmlEl;
  44107. if (!vmlEl) {
  44108. vmlEl = createNode('shape');
  44109. initRootElStyle(vmlEl);
  44110. this._vmlEl = vmlEl;
  44111. }
  44112. updateFillAndStroke(vmlEl, 'fill', style, this);
  44113. updateFillAndStroke(vmlEl, 'stroke', style, this);
  44114. var m = this.transform;
  44115. var needTransform = m != null;
  44116. var strokeEl = vmlEl.getElementsByTagName('stroke')[0];
  44117. if (strokeEl) {
  44118. var lineWidth = style.lineWidth;
  44119. // Get the line scale.
  44120. // Determinant of this.m_ means how much the area is enlarged by the
  44121. // transformation. So its square root can be used as a scale factor
  44122. // for width.
  44123. if (needTransform && !style.strokeNoScale) {
  44124. var det = m[0] * m[3] - m[1] * m[2];
  44125. lineWidth *= sqrt(abs$1(det));
  44126. }
  44127. strokeEl.weight = lineWidth + 'px';
  44128. }
  44129. var path = this.path || (this.path = new PathProxy());
  44130. if (this.__dirtyPath) {
  44131. path.beginPath();
  44132. this.buildPath(path, this.shape);
  44133. path.toStatic();
  44134. this.__dirtyPath = false;
  44135. }
  44136. vmlEl.path = pathDataToString(path, this.transform);
  44137. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  44138. // Append to root
  44139. append(vmlRoot, vmlEl);
  44140. // Text
  44141. if (style.text != null) {
  44142. this.drawRectText(vmlRoot, this.getBoundingRect());
  44143. }
  44144. else {
  44145. this.removeRectText(vmlRoot);
  44146. }
  44147. };
  44148. Path.prototype.onRemove = function (vmlRoot) {
  44149. remove(vmlRoot, this._vmlEl);
  44150. this.removeRectText(vmlRoot);
  44151. };
  44152. Path.prototype.onAdd = function (vmlRoot) {
  44153. append(vmlRoot, this._vmlEl);
  44154. this.appendRectText(vmlRoot);
  44155. };
  44156. /***************************************************
  44157. * IMAGE
  44158. **************************************************/
  44159. var isImage = function (img) {
  44160. // FIXME img instanceof Image 如果 img 是一个字符串的时候,IE8 下会报错
  44161. return (typeof img === 'object') && img.tagName && img.tagName.toUpperCase() === 'IMG';
  44162. // return img instanceof Image;
  44163. };
  44164. // Rewrite the original path method
  44165. ZImage.prototype.brushVML = function (vmlRoot) {
  44166. var style = this.style;
  44167. var image = style.image;
  44168. // Image original width, height
  44169. var ow;
  44170. var oh;
  44171. if (isImage(image)) {
  44172. var src = image.src;
  44173. if (src === this._imageSrc) {
  44174. ow = this._imageWidth;
  44175. oh = this._imageHeight;
  44176. }
  44177. else {
  44178. var imageRuntimeStyle = image.runtimeStyle;
  44179. var oldRuntimeWidth = imageRuntimeStyle.width;
  44180. var oldRuntimeHeight = imageRuntimeStyle.height;
  44181. imageRuntimeStyle.width = 'auto';
  44182. imageRuntimeStyle.height = 'auto';
  44183. // get the original size
  44184. ow = image.width;
  44185. oh = image.height;
  44186. // and remove overides
  44187. imageRuntimeStyle.width = oldRuntimeWidth;
  44188. imageRuntimeStyle.height = oldRuntimeHeight;
  44189. // Caching image original width, height and src
  44190. this._imageSrc = src;
  44191. this._imageWidth = ow;
  44192. this._imageHeight = oh;
  44193. }
  44194. image = src;
  44195. }
  44196. else {
  44197. if (image === this._imageSrc) {
  44198. ow = this._imageWidth;
  44199. oh = this._imageHeight;
  44200. }
  44201. }
  44202. if (!image) {
  44203. return;
  44204. }
  44205. var x = style.x || 0;
  44206. var y = style.y || 0;
  44207. var dw = style.width;
  44208. var dh = style.height;
  44209. var sw = style.sWidth;
  44210. var sh = style.sHeight;
  44211. var sx = style.sx || 0;
  44212. var sy = style.sy || 0;
  44213. var hasCrop = sw && sh;
  44214. var vmlEl = this._vmlEl;
  44215. if (!vmlEl) {
  44216. // FIXME 使用 group 在 left, top 都不是 0 的时候就无法显示了。
  44217. // vmlEl = vmlCore.createNode('group');
  44218. vmlEl = doc.createElement('div');
  44219. initRootElStyle(vmlEl);
  44220. this._vmlEl = vmlEl;
  44221. }
  44222. var vmlElStyle = vmlEl.style;
  44223. var hasRotation = false;
  44224. var m;
  44225. var scaleX = 1;
  44226. var scaleY = 1;
  44227. if (this.transform) {
  44228. m = this.transform;
  44229. scaleX = sqrt(m[0] * m[0] + m[1] * m[1]);
  44230. scaleY = sqrt(m[2] * m[2] + m[3] * m[3]);
  44231. hasRotation = m[1] || m[2];
  44232. }
  44233. if (hasRotation) {
  44234. // If filters are necessary (rotation exists), create them
  44235. // filters are bog-slow, so only create them if abbsolutely necessary
  44236. // The following check doesn't account for skews (which don't exist
  44237. // in the canvas spec (yet) anyway.
  44238. // From excanvas
  44239. var p0 = [x, y];
  44240. var p1 = [x + dw, y];
  44241. var p2 = [x, y + dh];
  44242. var p3 = [x + dw, y + dh];
  44243. applyTransform(p0, p0, m);
  44244. applyTransform(p1, p1, m);
  44245. applyTransform(p2, p2, m);
  44246. applyTransform(p3, p3, m);
  44247. var maxX = mathMax$5(p0[0], p1[0], p2[0], p3[0]);
  44248. var maxY = mathMax$5(p0[1], p1[1], p2[1], p3[1]);
  44249. var transformFilter = [];
  44250. transformFilter.push('M11=', m[0] / scaleX, comma,
  44251. 'M12=', m[2] / scaleY, comma,
  44252. 'M21=', m[1] / scaleX, comma,
  44253. 'M22=', m[3] / scaleY, comma,
  44254. 'Dx=', round$2(x * scaleX + m[4]), comma,
  44255. 'Dy=', round$2(y * scaleY + m[5]));
  44256. vmlElStyle.padding = '0 ' + round$2(maxX) + 'px ' + round$2(maxY) + 'px 0';
  44257. // FIXME DXImageTransform 在 IE11 的兼容模式下不起作用
  44258. vmlElStyle.filter = imageTransformPrefix + '.Matrix('
  44259. + transformFilter.join('') + ', SizingMethod=clip)';
  44260. }
  44261. else {
  44262. if (m) {
  44263. x = x * scaleX + m[4];
  44264. y = y * scaleY + m[5];
  44265. }
  44266. vmlElStyle.filter = '';
  44267. vmlElStyle.left = round$2(x) + 'px';
  44268. vmlElStyle.top = round$2(y) + 'px';
  44269. }
  44270. var imageEl = this._imageEl;
  44271. var cropEl = this._cropEl;
  44272. if (!imageEl) {
  44273. imageEl = doc.createElement('div');
  44274. this._imageEl = imageEl;
  44275. }
  44276. var imageELStyle = imageEl.style;
  44277. if (hasCrop) {
  44278. // Needs know image original width and height
  44279. if (! (ow && oh)) {
  44280. var tmpImage = new Image();
  44281. var self = this;
  44282. tmpImage.onload = function () {
  44283. tmpImage.onload = null;
  44284. ow = tmpImage.width;
  44285. oh = tmpImage.height;
  44286. // Adjust image width and height to fit the ratio destinationSize / sourceSize
  44287. imageELStyle.width = round$2(scaleX * ow * dw / sw) + 'px';
  44288. imageELStyle.height = round$2(scaleY * oh * dh / sh) + 'px';
  44289. // Caching image original width, height and src
  44290. self._imageWidth = ow;
  44291. self._imageHeight = oh;
  44292. self._imageSrc = image;
  44293. };
  44294. tmpImage.src = image;
  44295. }
  44296. else {
  44297. imageELStyle.width = round$2(scaleX * ow * dw / sw) + 'px';
  44298. imageELStyle.height = round$2(scaleY * oh * dh / sh) + 'px';
  44299. }
  44300. if (! cropEl) {
  44301. cropEl = doc.createElement('div');
  44302. cropEl.style.overflow = 'hidden';
  44303. this._cropEl = cropEl;
  44304. }
  44305. var cropElStyle = cropEl.style;
  44306. cropElStyle.width = round$2((dw + sx * dw / sw) * scaleX);
  44307. cropElStyle.height = round$2((dh + sy * dh / sh) * scaleY);
  44308. cropElStyle.filter = imageTransformPrefix + '.Matrix(Dx='
  44309. + (-sx * dw / sw * scaleX) + ',Dy=' + (-sy * dh / sh * scaleY) + ')';
  44310. if (! cropEl.parentNode) {
  44311. vmlEl.appendChild(cropEl);
  44312. }
  44313. if (imageEl.parentNode != cropEl) {
  44314. cropEl.appendChild(imageEl);
  44315. }
  44316. }
  44317. else {
  44318. imageELStyle.width = round$2(scaleX * dw) + 'px';
  44319. imageELStyle.height = round$2(scaleY * dh) + 'px';
  44320. vmlEl.appendChild(imageEl);
  44321. if (cropEl && cropEl.parentNode) {
  44322. vmlEl.removeChild(cropEl);
  44323. this._cropEl = null;
  44324. }
  44325. }
  44326. var filterStr = '';
  44327. var alpha = style.opacity;
  44328. if (alpha < 1) {
  44329. filterStr += '.Alpha(opacity=' + round$2(alpha * 100) + ') ';
  44330. }
  44331. filterStr += imageTransformPrefix + '.AlphaImageLoader(src=' + image + ', SizingMethod=scale)';
  44332. imageELStyle.filter = filterStr;
  44333. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  44334. // Append to root
  44335. append(vmlRoot, vmlEl);
  44336. // Text
  44337. if (style.text != null) {
  44338. this.drawRectText(vmlRoot, this.getBoundingRect());
  44339. }
  44340. };
  44341. ZImage.prototype.onRemove = function (vmlRoot) {
  44342. remove(vmlRoot, this._vmlEl);
  44343. this._vmlEl = null;
  44344. this._cropEl = null;
  44345. this._imageEl = null;
  44346. this.removeRectText(vmlRoot);
  44347. };
  44348. ZImage.prototype.onAdd = function (vmlRoot) {
  44349. append(vmlRoot, this._vmlEl);
  44350. this.appendRectText(vmlRoot);
  44351. };
  44352. /***************************************************
  44353. * TEXT
  44354. **************************************************/
  44355. var DEFAULT_STYLE_NORMAL = 'normal';
  44356. var fontStyleCache = {};
  44357. var fontStyleCacheCount = 0;
  44358. var MAX_FONT_CACHE_SIZE = 100;
  44359. var fontEl = document.createElement('div');
  44360. var getFontStyle = function (fontString) {
  44361. var fontStyle = fontStyleCache[fontString];
  44362. if (!fontStyle) {
  44363. // Clear cache
  44364. if (fontStyleCacheCount > MAX_FONT_CACHE_SIZE) {
  44365. fontStyleCacheCount = 0;
  44366. fontStyleCache = {};
  44367. }
  44368. var style = fontEl.style;
  44369. var fontFamily;
  44370. try {
  44371. style.font = fontString;
  44372. fontFamily = style.fontFamily.split(',')[0];
  44373. }
  44374. catch (e) {
  44375. }
  44376. fontStyle = {
  44377. style: style.fontStyle || DEFAULT_STYLE_NORMAL,
  44378. variant: style.fontVariant || DEFAULT_STYLE_NORMAL,
  44379. weight: style.fontWeight || DEFAULT_STYLE_NORMAL,
  44380. size: parseFloat(style.fontSize || 12) | 0,
  44381. family: fontFamily || 'Microsoft YaHei'
  44382. };
  44383. fontStyleCache[fontString] = fontStyle;
  44384. fontStyleCacheCount++;
  44385. }
  44386. return fontStyle;
  44387. };
  44388. var textMeasureEl;
  44389. // Overwrite measure text method
  44390. $override$1('measureText', function (text, textFont) {
  44391. var doc$$1 = doc;
  44392. if (!textMeasureEl) {
  44393. textMeasureEl = doc$$1.createElement('div');
  44394. textMeasureEl.style.cssText = 'position:absolute;top:-20000px;left:0;'
  44395. + 'padding:0;margin:0;border:none;white-space:pre;';
  44396. doc.body.appendChild(textMeasureEl);
  44397. }
  44398. try {
  44399. textMeasureEl.style.font = textFont;
  44400. } catch (ex) {
  44401. // Ignore failures to set to invalid font.
  44402. }
  44403. textMeasureEl.innerHTML = '';
  44404. // Don't use innerHTML or innerText because they allow markup/whitespace.
  44405. textMeasureEl.appendChild(doc$$1.createTextNode(text));
  44406. return {
  44407. width: textMeasureEl.offsetWidth
  44408. };
  44409. });
  44410. var tmpRect$2 = new BoundingRect();
  44411. var drawRectText = function (vmlRoot, rect, textRect, fromTextEl) {
  44412. var style = this.style;
  44413. // Optimize, avoid normalize every time.
  44414. this.__dirty && normalizeTextStyle(style, true);
  44415. var text = style.text;
  44416. // Convert to string
  44417. text != null && (text += '');
  44418. if (!text) {
  44419. return;
  44420. }
  44421. // Convert rich text to plain text. Rich text is not supported in
  44422. // IE8-, but tags in rich text template will be removed.
  44423. if (style.rich) {
  44424. var contentBlock = parseRichText(text, style);
  44425. text = [];
  44426. for (var i = 0; i < contentBlock.lines.length; i++) {
  44427. var tokens = contentBlock.lines[i].tokens;
  44428. var textLine = [];
  44429. for (var j = 0; j < tokens.length; j++) {
  44430. textLine.push(tokens[j].text);
  44431. }
  44432. text.push(textLine.join(''));
  44433. }
  44434. text = text.join('\n');
  44435. }
  44436. var x;
  44437. var y;
  44438. var align = style.textAlign;
  44439. var verticalAlign = style.textVerticalAlign;
  44440. var fontStyle = getFontStyle(style.font);
  44441. // FIXME encodeHtmlAttribute ?
  44442. var font = fontStyle.style + ' ' + fontStyle.variant + ' ' + fontStyle.weight + ' '
  44443. + fontStyle.size + 'px "' + fontStyle.family + '"';
  44444. textRect = textRect || getBoundingRect(text, font, align, verticalAlign);
  44445. // Transform rect to view space
  44446. var m = this.transform;
  44447. // Ignore transform for text in other element
  44448. if (m && !fromTextEl) {
  44449. tmpRect$2.copy(rect);
  44450. tmpRect$2.applyTransform(m);
  44451. rect = tmpRect$2;
  44452. }
  44453. if (!fromTextEl) {
  44454. var textPosition = style.textPosition;
  44455. var distance$$1 = style.textDistance;
  44456. // Text position represented by coord
  44457. if (textPosition instanceof Array) {
  44458. x = rect.x + parsePercent$3(textPosition[0], rect.width);
  44459. y = rect.y + parsePercent$3(textPosition[1], rect.height);
  44460. align = align || 'left';
  44461. }
  44462. else {
  44463. var res = adjustTextPositionOnRect(
  44464. textPosition, rect, distance$$1
  44465. );
  44466. x = res.x;
  44467. y = res.y;
  44468. // Default align and baseline when has textPosition
  44469. align = align || res.textAlign;
  44470. verticalAlign = verticalAlign || res.textVerticalAlign;
  44471. }
  44472. }
  44473. else {
  44474. x = rect.x;
  44475. y = rect.y;
  44476. }
  44477. x = adjustTextX(x, textRect.width, align);
  44478. y = adjustTextY(y, textRect.height, verticalAlign);
  44479. // Force baseline 'middle'
  44480. y += textRect.height / 2;
  44481. // var fontSize = fontStyle.size;
  44482. // 1.75 is an arbitrary number, as there is no info about the text baseline
  44483. // switch (baseline) {
  44484. // case 'hanging':
  44485. // case 'top':
  44486. // y += fontSize / 1.75;
  44487. // break;
  44488. // case 'middle':
  44489. // break;
  44490. // default:
  44491. // // case null:
  44492. // // case 'alphabetic':
  44493. // // case 'ideographic':
  44494. // // case 'bottom':
  44495. // y -= fontSize / 2.25;
  44496. // break;
  44497. // }
  44498. // switch (align) {
  44499. // case 'left':
  44500. // break;
  44501. // case 'center':
  44502. // x -= textRect.width / 2;
  44503. // break;
  44504. // case 'right':
  44505. // x -= textRect.width;
  44506. // break;
  44507. // case 'end':
  44508. // align = elementStyle.direction == 'ltr' ? 'right' : 'left';
  44509. // break;
  44510. // case 'start':
  44511. // align = elementStyle.direction == 'rtl' ? 'right' : 'left';
  44512. // break;
  44513. // default:
  44514. // align = 'left';
  44515. // }
  44516. var createNode$$1 = createNode;
  44517. var textVmlEl = this._textVmlEl;
  44518. var pathEl;
  44519. var textPathEl;
  44520. var skewEl;
  44521. if (!textVmlEl) {
  44522. textVmlEl = createNode$$1('line');
  44523. pathEl = createNode$$1('path');
  44524. textPathEl = createNode$$1('textpath');
  44525. skewEl = createNode$$1('skew');
  44526. // FIXME Why here is not cammel case
  44527. // Align 'center' seems wrong
  44528. textPathEl.style['v-text-align'] = 'left';
  44529. initRootElStyle(textVmlEl);
  44530. pathEl.textpathok = true;
  44531. textPathEl.on = true;
  44532. textVmlEl.from = '0 0';
  44533. textVmlEl.to = '1000 0.05';
  44534. append(textVmlEl, skewEl);
  44535. append(textVmlEl, pathEl);
  44536. append(textVmlEl, textPathEl);
  44537. this._textVmlEl = textVmlEl;
  44538. }
  44539. else {
  44540. // 这里是在前面 appendChild 保证顺序的前提下
  44541. skewEl = textVmlEl.firstChild;
  44542. pathEl = skewEl.nextSibling;
  44543. textPathEl = pathEl.nextSibling;
  44544. }
  44545. var coords = [x, y];
  44546. var textVmlElStyle = textVmlEl.style;
  44547. // Ignore transform for text in other element
  44548. if (m && fromTextEl) {
  44549. applyTransform(coords, coords, m);
  44550. skewEl.on = true;
  44551. skewEl.matrix = m[0].toFixed(3) + comma + m[2].toFixed(3) + comma +
  44552. m[1].toFixed(3) + comma + m[3].toFixed(3) + ',0,0';
  44553. // Text position
  44554. skewEl.offset = (round$2(coords[0]) || 0) + ',' + (round$2(coords[1]) || 0);
  44555. // Left top point as origin
  44556. skewEl.origin = '0 0';
  44557. textVmlElStyle.left = '0px';
  44558. textVmlElStyle.top = '0px';
  44559. }
  44560. else {
  44561. skewEl.on = false;
  44562. textVmlElStyle.left = round$2(x) + 'px';
  44563. textVmlElStyle.top = round$2(y) + 'px';
  44564. }
  44565. textPathEl.string = encodeHtmlAttribute(text);
  44566. // TODO
  44567. try {
  44568. textPathEl.style.font = font;
  44569. }
  44570. // Error font format
  44571. catch (e) {}
  44572. updateFillAndStroke(textVmlEl, 'fill', {
  44573. fill: style.textFill,
  44574. opacity: style.opacity
  44575. }, this);
  44576. updateFillAndStroke(textVmlEl, 'stroke', {
  44577. stroke: style.textStroke,
  44578. opacity: style.opacity,
  44579. lineDash: style.lineDash
  44580. }, this);
  44581. textVmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  44582. // Attached to root
  44583. append(vmlRoot, textVmlEl);
  44584. };
  44585. var removeRectText = function (vmlRoot) {
  44586. remove(vmlRoot, this._textVmlEl);
  44587. this._textVmlEl = null;
  44588. };
  44589. var appendRectText = function (vmlRoot) {
  44590. append(vmlRoot, this._textVmlEl);
  44591. };
  44592. var list = [RectText, Displayable, ZImage, Path, Text];
  44593. // In case Displayable has been mixed in RectText
  44594. for (var i$1 = 0; i$1 < list.length; i$1++) {
  44595. var proto$7 = list[i$1].prototype;
  44596. proto$7.drawRectText = drawRectText;
  44597. proto$7.removeRectText = removeRectText;
  44598. proto$7.appendRectText = appendRectText;
  44599. }
  44600. Text.prototype.brushVML = function (vmlRoot) {
  44601. var style = this.style;
  44602. if (style.text != null) {
  44603. this.drawRectText(vmlRoot, {
  44604. x: style.x || 0, y: style.y || 0,
  44605. width: 0, height: 0
  44606. }, this.getBoundingRect(), true);
  44607. }
  44608. else {
  44609. this.removeRectText(vmlRoot);
  44610. }
  44611. };
  44612. Text.prototype.onRemove = function (vmlRoot) {
  44613. this.removeRectText(vmlRoot);
  44614. };
  44615. Text.prototype.onAdd = function (vmlRoot) {
  44616. this.appendRectText(vmlRoot);
  44617. };
  44618. }
  44619. /**
  44620. * VML Painter.
  44621. *
  44622. * @module zrender/vml/Painter
  44623. */
  44624. function parseInt10$1(val) {
  44625. return parseInt(val, 10);
  44626. }
  44627. /**
  44628. * @alias module:zrender/vml/Painter
  44629. */
  44630. function VMLPainter(root, storage) {
  44631. initVML();
  44632. this.root = root;
  44633. this.storage = storage;
  44634. var vmlViewport = document.createElement('div');
  44635. var vmlRoot = document.createElement('div');
  44636. vmlViewport.style.cssText = 'display:inline-block;overflow:hidden;position:relative;width:300px;height:150px;';
  44637. vmlRoot.style.cssText = 'position:absolute;left:0;top:0;';
  44638. root.appendChild(vmlViewport);
  44639. this._vmlRoot = vmlRoot;
  44640. this._vmlViewport = vmlViewport;
  44641. this.resize();
  44642. // Modify storage
  44643. var oldDelFromStorage = storage.delFromStorage;
  44644. var oldAddToStorage = storage.addToStorage;
  44645. storage.delFromStorage = function (el) {
  44646. oldDelFromStorage.call(storage, el);
  44647. if (el) {
  44648. el.onRemove && el.onRemove(vmlRoot);
  44649. }
  44650. };
  44651. storage.addToStorage = function (el) {
  44652. // Displayable already has a vml node
  44653. el.onAdd && el.onAdd(vmlRoot);
  44654. oldAddToStorage.call(storage, el);
  44655. };
  44656. this._firstPaint = true;
  44657. }
  44658. VMLPainter.prototype = {
  44659. constructor: VMLPainter,
  44660. getType: function () {
  44661. return 'vml';
  44662. },
  44663. /**
  44664. * @return {HTMLDivElement}
  44665. */
  44666. getViewportRoot: function () {
  44667. return this._vmlViewport;
  44668. },
  44669. getViewportRootOffset: function () {
  44670. var viewportRoot = this.getViewportRoot();
  44671. if (viewportRoot) {
  44672. return {
  44673. offsetLeft: viewportRoot.offsetLeft || 0,
  44674. offsetTop: viewportRoot.offsetTop || 0
  44675. };
  44676. }
  44677. },
  44678. /**
  44679. * 刷新
  44680. */
  44681. refresh: function () {
  44682. var list = this.storage.getDisplayList(true, true);
  44683. this._paintList(list);
  44684. },
  44685. _paintList: function (list) {
  44686. var vmlRoot = this._vmlRoot;
  44687. for (var i = 0; i < list.length; i++) {
  44688. var el = list[i];
  44689. if (el.invisible || el.ignore) {
  44690. if (!el.__alreadyNotVisible) {
  44691. el.onRemove(vmlRoot);
  44692. }
  44693. // Set as already invisible
  44694. el.__alreadyNotVisible = true;
  44695. }
  44696. else {
  44697. if (el.__alreadyNotVisible) {
  44698. el.onAdd(vmlRoot);
  44699. }
  44700. el.__alreadyNotVisible = false;
  44701. if (el.__dirty) {
  44702. el.beforeBrush && el.beforeBrush();
  44703. (el.brushVML || el.brush).call(el, vmlRoot);
  44704. el.afterBrush && el.afterBrush();
  44705. }
  44706. }
  44707. el.__dirty = false;
  44708. }
  44709. if (this._firstPaint) {
  44710. // Detached from document at first time
  44711. // to avoid page refreshing too many times
  44712. // FIXME 如果每次都先 removeChild 可能会导致一些填充和描边的效果改变
  44713. this._vmlViewport.appendChild(vmlRoot);
  44714. this._firstPaint = false;
  44715. }
  44716. },
  44717. resize: function (width, height) {
  44718. var width = width == null ? this._getWidth() : width;
  44719. var height = height == null ? this._getHeight() : height;
  44720. if (this._width != width || this._height != height) {
  44721. this._width = width;
  44722. this._height = height;
  44723. var vmlViewportStyle = this._vmlViewport.style;
  44724. vmlViewportStyle.width = width + 'px';
  44725. vmlViewportStyle.height = height + 'px';
  44726. }
  44727. },
  44728. dispose: function () {
  44729. this.root.innerHTML = '';
  44730. this._vmlRoot =
  44731. this._vmlViewport =
  44732. this.storage = null;
  44733. },
  44734. getWidth: function () {
  44735. return this._width;
  44736. },
  44737. getHeight: function () {
  44738. return this._height;
  44739. },
  44740. clear: function () {
  44741. if (this._vmlViewport) {
  44742. this.root.removeChild(this._vmlViewport);
  44743. }
  44744. },
  44745. _getWidth: function () {
  44746. var root = this.root;
  44747. var stl = root.currentStyle;
  44748. return ((root.clientWidth || parseInt10$1(stl.width))
  44749. - parseInt10$1(stl.paddingLeft)
  44750. - parseInt10$1(stl.paddingRight)) | 0;
  44751. },
  44752. _getHeight: function () {
  44753. var root = this.root;
  44754. var stl = root.currentStyle;
  44755. return ((root.clientHeight || parseInt10$1(stl.height))
  44756. - parseInt10$1(stl.paddingTop)
  44757. - parseInt10$1(stl.paddingBottom)) | 0;
  44758. }
  44759. };
  44760. // Not supported methods
  44761. function createMethodNotSupport(method) {
  44762. return function () {
  44763. zrLog('In IE8.0 VML mode painter not support method "' + method + '"');
  44764. };
  44765. }
  44766. // Unsupported methods
  44767. each$1([
  44768. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer', 'eachOtherLayer', 'getLayers',
  44769. 'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage'
  44770. ], function (name) {
  44771. VMLPainter.prototype[name] = createMethodNotSupport(name);
  44772. });
  44773. registerPainter('vml', VMLPainter);
  44774. var svgURI = 'http://www.w3.org/2000/svg';
  44775. function createElement(name) {
  44776. return document.createElementNS(svgURI, name);
  44777. }
  44778. // TODO
  44779. // 1. shadow
  44780. // 2. Image: sx, sy, sw, sh
  44781. var CMD$4 = PathProxy.CMD;
  44782. var arrayJoin = Array.prototype.join;
  44783. var NONE = 'none';
  44784. var mathRound = Math.round;
  44785. var mathSin$3 = Math.sin;
  44786. var mathCos$3 = Math.cos;
  44787. var PI$3 = Math.PI;
  44788. var PI2$5 = Math.PI * 2;
  44789. var degree = 180 / PI$3;
  44790. var EPSILON$4 = 1e-4;
  44791. function round4(val) {
  44792. return mathRound(val * 1e4) / 1e4;
  44793. }
  44794. function isAroundZero$1(val) {
  44795. return val < EPSILON$4 && val > -EPSILON$4;
  44796. }
  44797. function pathHasFill(style, isText) {
  44798. var fill = isText ? style.textFill : style.fill;
  44799. return fill != null && fill !== NONE;
  44800. }
  44801. function pathHasStroke(style, isText) {
  44802. var stroke = isText ? style.textStroke : style.stroke;
  44803. return stroke != null && stroke !== NONE;
  44804. }
  44805. function setTransform(svgEl, m) {
  44806. if (m) {
  44807. attr(svgEl, 'transform', 'matrix(' + arrayJoin.call(m, ',') + ')');
  44808. }
  44809. }
  44810. function attr(el, key, val) {
  44811. if (!val || val.type !== 'linear' && val.type !== 'radial') {
  44812. // Don't set attribute for gradient, since it need new dom nodes
  44813. el.setAttribute(key, val);
  44814. }
  44815. }
  44816. function attrXLink(el, key, val) {
  44817. el.setAttributeNS('http://www.w3.org/1999/xlink', key, val);
  44818. }
  44819. function bindStyle(svgEl, style, isText) {
  44820. if (pathHasFill(style, isText)) {
  44821. var fill = isText ? style.textFill : style.fill;
  44822. fill = fill === 'transparent' ? NONE : fill;
  44823. /**
  44824. * FIXME:
  44825. * This is a temporary fix for Chrome's clipping bug
  44826. * that happens when a clip-path is referring another one.
  44827. * This fix should be used before Chrome's bug is fixed.
  44828. * For an element that has clip-path, and fill is none,
  44829. * set it to be "rgba(0, 0, 0, 0.002)" will hide the element.
  44830. * Otherwise, it will show black fill color.
  44831. * 0.002 is used because this won't work for alpha values smaller
  44832. * than 0.002.
  44833. *
  44834. * See
  44835. * https://bugs.chromium.org/p/chromium/issues/detail?id=659790
  44836. * for more information.
  44837. */
  44838. if (svgEl.getAttribute('clip-path') !== 'none' && fill === NONE) {
  44839. fill = 'rgba(0, 0, 0, 0.002)';
  44840. }
  44841. attr(svgEl, 'fill', fill);
  44842. attr(svgEl, 'fill-opacity', style.opacity);
  44843. }
  44844. else {
  44845. attr(svgEl, 'fill', NONE);
  44846. }
  44847. if (pathHasStroke(style, isText)) {
  44848. var stroke = isText ? style.textStroke : style.stroke;
  44849. stroke = stroke === 'transparent' ? NONE : stroke;
  44850. attr(svgEl, 'stroke', stroke);
  44851. var strokeWidth = isText
  44852. ? style.textStrokeWidth
  44853. : style.lineWidth;
  44854. var strokeScale = !isText && style.strokeNoScale
  44855. ? style.host.getLineScale()
  44856. : 1;
  44857. attr(svgEl, 'stroke-width', strokeWidth / strokeScale);
  44858. // stroke then fill for text; fill then stroke for others
  44859. attr(svgEl, 'paint-order', isText ? 'stroke' : 'fill');
  44860. attr(svgEl, 'stroke-opacity', style.opacity);
  44861. var lineDash = style.lineDash;
  44862. if (lineDash) {
  44863. attr(svgEl, 'stroke-dasharray', style.lineDash.join(','));
  44864. attr(svgEl, 'stroke-dashoffset', mathRound(style.lineDashOffset || 0));
  44865. }
  44866. else {
  44867. attr(svgEl, 'stroke-dasharray', '');
  44868. }
  44869. // PENDING
  44870. style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap);
  44871. style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin);
  44872. style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit);
  44873. }
  44874. else {
  44875. attr(svgEl, 'stroke', NONE);
  44876. }
  44877. }
  44878. /***************************************************
  44879. * PATH
  44880. **************************************************/
  44881. function pathDataToString$1(path) {
  44882. var str = [];
  44883. var data = path.data;
  44884. var dataLength = path.len();
  44885. for (var i = 0; i < dataLength;) {
  44886. var cmd = data[i++];
  44887. var cmdStr = '';
  44888. var nData = 0;
  44889. switch (cmd) {
  44890. case CMD$4.M:
  44891. cmdStr = 'M';
  44892. nData = 2;
  44893. break;
  44894. case CMD$4.L:
  44895. cmdStr = 'L';
  44896. nData = 2;
  44897. break;
  44898. case CMD$4.Q:
  44899. cmdStr = 'Q';
  44900. nData = 4;
  44901. break;
  44902. case CMD$4.C:
  44903. cmdStr = 'C';
  44904. nData = 6;
  44905. break;
  44906. case CMD$4.A:
  44907. var cx = data[i++];
  44908. var cy = data[i++];
  44909. var rx = data[i++];
  44910. var ry = data[i++];
  44911. var theta = data[i++];
  44912. var dTheta = data[i++];
  44913. var psi = data[i++];
  44914. var clockwise = data[i++];
  44915. var dThetaPositive = Math.abs(dTheta);
  44916. var isCircle = isAroundZero$1(dThetaPositive - PI2$5)
  44917. && !isAroundZero$1(dThetaPositive);
  44918. var large = false;
  44919. if (dThetaPositive >= PI2$5) {
  44920. large = true;
  44921. }
  44922. else if (isAroundZero$1(dThetaPositive)) {
  44923. large = false;
  44924. }
  44925. else {
  44926. large = (dTheta > -PI$3 && dTheta < 0 || dTheta > PI$3)
  44927. === !!clockwise;
  44928. }
  44929. var x0 = round4(cx + rx * mathCos$3(theta));
  44930. var y0 = round4(cy + ry * mathSin$3(theta));
  44931. // It will not draw if start point and end point are exactly the same
  44932. // We need to shift the end point with a small value
  44933. // FIXME A better way to draw circle ?
  44934. if (isCircle) {
  44935. if (clockwise) {
  44936. dTheta = PI2$5 - 1e-4;
  44937. }
  44938. else {
  44939. dTheta = -PI2$5 + 1e-4;
  44940. }
  44941. large = true;
  44942. if (i === 9) {
  44943. // Move to (x0, y0) only when CMD.A comes at the
  44944. // first position of a shape.
  44945. // For instance, when drawing a ring, CMD.A comes
  44946. // after CMD.M, so it's unnecessary to move to
  44947. // (x0, y0).
  44948. str.push('M', x0, y0);
  44949. }
  44950. }
  44951. var x = round4(cx + rx * mathCos$3(theta + dTheta));
  44952. var y = round4(cy + ry * mathSin$3(theta + dTheta));
  44953. // FIXME Ellipse
  44954. str.push('A', round4(rx), round4(ry),
  44955. mathRound(psi * degree), +large, +clockwise, x, y);
  44956. break;
  44957. case CMD$4.Z:
  44958. cmdStr = 'Z';
  44959. break;
  44960. case CMD$4.R:
  44961. var x = round4(data[i++]);
  44962. var y = round4(data[i++]);
  44963. var w = round4(data[i++]);
  44964. var h = round4(data[i++]);
  44965. str.push(
  44966. 'M', x, y,
  44967. 'L', x + w, y,
  44968. 'L', x + w, y + h,
  44969. 'L', x, y + h,
  44970. 'L', x, y
  44971. );
  44972. break;
  44973. }
  44974. cmdStr && str.push(cmdStr);
  44975. for (var j = 0; j < nData; j++) {
  44976. // PENDING With scale
  44977. str.push(round4(data[i++]));
  44978. }
  44979. }
  44980. return str.join(' ');
  44981. }
  44982. var svgPath = {};
  44983. svgPath.brush = function (el) {
  44984. var style = el.style;
  44985. var svgEl = el.__svgEl;
  44986. if (!svgEl) {
  44987. svgEl = createElement('path');
  44988. el.__svgEl = svgEl;
  44989. }
  44990. if (!el.path) {
  44991. el.createPathProxy();
  44992. }
  44993. var path = el.path;
  44994. if (el.__dirtyPath) {
  44995. path.beginPath();
  44996. el.buildPath(path, el.shape);
  44997. el.__dirtyPath = false;
  44998. var pathStr = pathDataToString$1(path);
  44999. if (pathStr.indexOf('NaN') < 0) {
  45000. // Ignore illegal path, which may happen such in out-of-range
  45001. // data in Calendar series.
  45002. attr(svgEl, 'd', pathStr);
  45003. }
  45004. }
  45005. bindStyle(svgEl, style);
  45006. setTransform(svgEl, el.transform);
  45007. if (style.text != null) {
  45008. svgTextDrawRectText(el, el.getBoundingRect());
  45009. }
  45010. };
  45011. /***************************************************
  45012. * IMAGE
  45013. **************************************************/
  45014. var svgImage = {};
  45015. svgImage.brush = function (el) {
  45016. var style = el.style;
  45017. var image = style.image;
  45018. if (image instanceof HTMLImageElement) {
  45019. var src = image.src;
  45020. image = src;
  45021. }
  45022. if (! image) {
  45023. return;
  45024. }
  45025. var x = style.x || 0;
  45026. var y = style.y || 0;
  45027. var dw = style.width;
  45028. var dh = style.height;
  45029. var svgEl = el.__svgEl;
  45030. if (! svgEl) {
  45031. svgEl = createElement('image');
  45032. el.__svgEl = svgEl;
  45033. }
  45034. if (image !== el.__imageSrc) {
  45035. attrXLink(svgEl, 'href', image);
  45036. // Caching image src
  45037. el.__imageSrc = image;
  45038. }
  45039. attr(svgEl, 'width', dw);
  45040. attr(svgEl, 'height', dh);
  45041. attr(svgEl, 'x', x);
  45042. attr(svgEl, 'y', y);
  45043. setTransform(svgEl, el.transform);
  45044. if (style.text != null) {
  45045. svgTextDrawRectText(el, el.getBoundingRect());
  45046. }
  45047. };
  45048. /***************************************************
  45049. * TEXT
  45050. **************************************************/
  45051. var svgText = {};
  45052. var tmpRect$3 = new BoundingRect();
  45053. var svgTextDrawRectText = function (el, rect, textRect) {
  45054. var style = el.style;
  45055. el.__dirty && normalizeTextStyle(style, true);
  45056. var text = style.text;
  45057. // Convert to string
  45058. if (text == null) {
  45059. // Draw no text only when text is set to null, but not ''
  45060. return;
  45061. }
  45062. else {
  45063. text += '';
  45064. }
  45065. var textSvgEl = el.__textSvgEl;
  45066. if (! textSvgEl) {
  45067. textSvgEl = createElement('text');
  45068. el.__textSvgEl = textSvgEl;
  45069. }
  45070. var x;
  45071. var y;
  45072. var textPosition = style.textPosition;
  45073. var distance = style.textDistance;
  45074. var align = style.textAlign || 'left';
  45075. if (typeof style.fontSize === 'number') {
  45076. style.fontSize += 'px';
  45077. }
  45078. var font = style.font
  45079. || [
  45080. style.fontStyle || '',
  45081. style.fontWeight || '',
  45082. style.fontSize || '',
  45083. style.fontFamily || ''
  45084. ].join(' ')
  45085. || DEFAULT_FONT;
  45086. var verticalAlign = getVerticalAlignForSvg(style.textVerticalAlign);
  45087. textRect = getBoundingRect(text, font, align,
  45088. verticalAlign);
  45089. var lineHeight = textRect.lineHeight;
  45090. // Text position represented by coord
  45091. if (textPosition instanceof Array) {
  45092. x = rect.x + textPosition[0];
  45093. y = rect.y + textPosition[1];
  45094. }
  45095. else {
  45096. var newPos = adjustTextPositionOnRect(
  45097. textPosition, rect, distance
  45098. );
  45099. x = newPos.x;
  45100. y = newPos.y;
  45101. verticalAlign = getVerticalAlignForSvg(newPos.textVerticalAlign);
  45102. align = newPos.textAlign;
  45103. }
  45104. attr(textSvgEl, 'alignment-baseline', verticalAlign);
  45105. if (font) {
  45106. textSvgEl.style.font = font;
  45107. }
  45108. var textPadding = style.textPadding;
  45109. // Make baseline top
  45110. attr(textSvgEl, 'x', x);
  45111. attr(textSvgEl, 'y', y);
  45112. bindStyle(textSvgEl, style, true);
  45113. if (el instanceof Text || el.style.transformText) {
  45114. // Transform text with element
  45115. setTransform(textSvgEl, el.transform);
  45116. }
  45117. else {
  45118. if (el.transform) {
  45119. tmpRect$3.copy(rect);
  45120. tmpRect$3.applyTransform(el.transform);
  45121. rect = tmpRect$3;
  45122. }
  45123. else {
  45124. var pos = el.transformCoordToGlobal(rect.x, rect.y);
  45125. rect.x = pos[0];
  45126. rect.y = pos[1];
  45127. }
  45128. // Text rotation, but no element transform
  45129. var origin = style.textOrigin;
  45130. if (origin === 'center') {
  45131. x = textRect.width / 2 + x;
  45132. y = textRect.height / 2 + y;
  45133. }
  45134. else if (origin) {
  45135. x = origin[0] + x;
  45136. y = origin[1] + y;
  45137. }
  45138. var rotate = -style.textRotation * 180 / Math.PI;
  45139. attr(textSvgEl, 'transform', 'rotate(' + rotate + ','
  45140. + x + ',' + y + ')');
  45141. }
  45142. var textLines = text.split('\n');
  45143. var nTextLines = textLines.length;
  45144. var textAnchor = align;
  45145. // PENDING
  45146. if (textAnchor === 'left') {
  45147. textAnchor = 'start';
  45148. textPadding && (x += textPadding[3]);
  45149. }
  45150. else if (textAnchor === 'right') {
  45151. textAnchor = 'end';
  45152. textPadding && (x -= textPadding[1]);
  45153. }
  45154. else if (textAnchor === 'center') {
  45155. textAnchor = 'middle';
  45156. textPadding && (x += (textPadding[3] - textPadding[1]) / 2);
  45157. }
  45158. var dy = 0;
  45159. if (verticalAlign === 'baseline') {
  45160. dy = -textRect.height + lineHeight;
  45161. textPadding && (dy -= textPadding[2]);
  45162. }
  45163. else if (verticalAlign === 'middle') {
  45164. dy = (-textRect.height + lineHeight) / 2;
  45165. textPadding && (y += (textPadding[0] - textPadding[2]) / 2);
  45166. }
  45167. else {
  45168. textPadding && (dy += textPadding[0]);
  45169. }
  45170. // Font may affect position of each tspan elements
  45171. if (el.__text !== text || el.__textFont !== font) {
  45172. var tspanList = el.__tspanList || [];
  45173. el.__tspanList = tspanList;
  45174. for (var i = 0; i < nTextLines; i++) {
  45175. // Using cached tspan elements
  45176. var tspan = tspanList[i];
  45177. if (! tspan) {
  45178. tspan = tspanList[i] = createElement('tspan');
  45179. textSvgEl.appendChild(tspan);
  45180. attr(tspan, 'alignment-baseline', verticalAlign);
  45181. attr(tspan, 'text-anchor', textAnchor);
  45182. }
  45183. else {
  45184. tspan.innerHTML = '';
  45185. }
  45186. attr(tspan, 'x', x);
  45187. attr(tspan, 'y', y + i * lineHeight + dy);
  45188. tspan.appendChild(document.createTextNode(textLines[i]));
  45189. }
  45190. // Remove unsed tspan elements
  45191. for (; i < tspanList.length; i++) {
  45192. textSvgEl.removeChild(tspanList[i]);
  45193. }
  45194. tspanList.length = nTextLines;
  45195. el.__text = text;
  45196. el.__textFont = font;
  45197. }
  45198. else if (el.__tspanList.length) {
  45199. // Update span x and y
  45200. var len = el.__tspanList.length;
  45201. for (var i = 0; i < len; ++i) {
  45202. var tspan = el.__tspanList[i];
  45203. if (tspan) {
  45204. attr(tspan, 'x', x);
  45205. attr(tspan, 'y', y + i * lineHeight + dy);
  45206. }
  45207. }
  45208. }
  45209. };
  45210. function getVerticalAlignForSvg(verticalAlign) {
  45211. if (verticalAlign === 'middle') {
  45212. return 'middle';
  45213. }
  45214. else if (verticalAlign === 'bottom') {
  45215. return 'baseline';
  45216. }
  45217. else {
  45218. return 'hanging';
  45219. }
  45220. }
  45221. svgText.drawRectText = svgTextDrawRectText;
  45222. svgText.brush = function (el) {
  45223. var style = el.style;
  45224. if (style.text != null) {
  45225. // 强制设置 textPosition
  45226. style.textPosition = [0, 0];
  45227. svgTextDrawRectText(el, {
  45228. x: style.x || 0, y: style.y || 0,
  45229. width: 0, height: 0
  45230. }, el.getBoundingRect());
  45231. }
  45232. };
  45233. // Myers' Diff Algorithm
  45234. // Modified from https://github.com/kpdecker/jsdiff/blob/master/src/diff/base.js
  45235. function Diff() {}
  45236. Diff.prototype = {
  45237. diff: function (oldArr, newArr, equals) {
  45238. if (!equals) {
  45239. equals = function (a, b) {
  45240. return a === b;
  45241. };
  45242. }
  45243. this.equals = equals;
  45244. var self = this;
  45245. oldArr = oldArr.slice();
  45246. newArr = newArr.slice();
  45247. // Allow subclasses to massage the input prior to running
  45248. var newLen = newArr.length;
  45249. var oldLen = oldArr.length;
  45250. var editLength = 1;
  45251. var maxEditLength = newLen + oldLen;
  45252. var bestPath = [{ newPos: -1, components: [] }];
  45253. // Seed editLength = 0, i.e. the content starts with the same values
  45254. var oldPos = this.extractCommon(bestPath[0], newArr, oldArr, 0);
  45255. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  45256. var indices = [];
  45257. for (var i = 0; i < newArr.length; i++) {
  45258. indices.push(i);
  45259. }
  45260. // Identity per the equality and tokenizer
  45261. return [{
  45262. indices: indices, count: newArr.length
  45263. }];
  45264. }
  45265. // Main worker method. checks all permutations of a given edit length for acceptance.
  45266. function execEditLength() {
  45267. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  45268. var basePath;
  45269. var addPath = bestPath[diagonalPath - 1];
  45270. var removePath = bestPath[diagonalPath + 1];
  45271. var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  45272. if (addPath) {
  45273. // No one else is going to attempt to use this value, clear it
  45274. bestPath[diagonalPath - 1] = undefined;
  45275. }
  45276. var canAdd = addPath && addPath.newPos + 1 < newLen;
  45277. var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
  45278. if (!canAdd && !canRemove) {
  45279. // If this path is a terminal then prune
  45280. bestPath[diagonalPath] = undefined;
  45281. continue;
  45282. }
  45283. // Select the diagonal that we want to branch from. We select the prior
  45284. // path whose position in the new string is the farthest from the origin
  45285. // and does not pass the bounds of the diff graph
  45286. if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
  45287. basePath = clonePath(removePath);
  45288. self.pushComponent(basePath.components, undefined, true);
  45289. }
  45290. else {
  45291. basePath = addPath; // No need to clone, we've pulled it from the list
  45292. basePath.newPos++;
  45293. self.pushComponent(basePath.components, true, undefined);
  45294. }
  45295. oldPos = self.extractCommon(basePath, newArr, oldArr, diagonalPath);
  45296. // If we have hit the end of both strings, then we are done
  45297. if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  45298. return buildValues(self, basePath.components, newArr, oldArr);
  45299. }
  45300. else {
  45301. // Otherwise track this path as a potential candidate and continue.
  45302. bestPath[diagonalPath] = basePath;
  45303. }
  45304. }
  45305. editLength++;
  45306. }
  45307. while (editLength <= maxEditLength) {
  45308. var ret = execEditLength();
  45309. if (ret) {
  45310. return ret;
  45311. }
  45312. }
  45313. },
  45314. pushComponent: function (components, added, removed) {
  45315. var last = components[components.length - 1];
  45316. if (last && last.added === added && last.removed === removed) {
  45317. // We need to clone here as the component clone operation is just
  45318. // as shallow array clone
  45319. components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
  45320. }
  45321. else {
  45322. components.push({count: 1, added: added, removed: removed });
  45323. }
  45324. },
  45325. extractCommon: function (basePath, newArr, oldArr, diagonalPath) {
  45326. var newLen = newArr.length;
  45327. var oldLen = oldArr.length;
  45328. var newPos = basePath.newPos;
  45329. var oldPos = newPos - diagonalPath;
  45330. var commonCount = 0;
  45331. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newArr[newPos + 1], oldArr[oldPos + 1])) {
  45332. newPos++;
  45333. oldPos++;
  45334. commonCount++;
  45335. }
  45336. if (commonCount) {
  45337. basePath.components.push({count: commonCount});
  45338. }
  45339. basePath.newPos = newPos;
  45340. return oldPos;
  45341. },
  45342. tokenize: function (value) {
  45343. return value.slice();
  45344. },
  45345. join: function (value) {
  45346. return value.slice();
  45347. }
  45348. };
  45349. function buildValues(diff, components, newArr, oldArr) {
  45350. var componentPos = 0;
  45351. var componentLen = components.length;
  45352. var newPos = 0;
  45353. var oldPos = 0;
  45354. for (; componentPos < componentLen; componentPos++) {
  45355. var component = components[componentPos];
  45356. if (!component.removed) {
  45357. var indices = [];
  45358. for (var i = newPos; i < newPos + component.count; i++) {
  45359. indices.push(i);
  45360. }
  45361. component.indices = indices;
  45362. newPos += component.count;
  45363. // Common case
  45364. if (!component.added) {
  45365. oldPos += component.count;
  45366. }
  45367. }
  45368. else {
  45369. var indices = [];
  45370. for (var i = oldPos; i < oldPos + component.count; i++) {
  45371. indices.push(i);
  45372. }
  45373. component.indices = indices;
  45374. oldPos += component.count;
  45375. }
  45376. }
  45377. return components;
  45378. }
  45379. function clonePath(path) {
  45380. return { newPos: path.newPos, components: path.components.slice(0) };
  45381. }
  45382. var arrayDiff = new Diff();
  45383. var arrayDiff$1 = function (oldArr, newArr, callback) {
  45384. return arrayDiff.diff(oldArr, newArr, callback);
  45385. };
  45386. /**
  45387. * @file Manages elements that can be defined in <defs> in SVG,
  45388. * e.g., gradients, clip path, etc.
  45389. * @author Zhang Wenli
  45390. */
  45391. var MARK_UNUSED = '0';
  45392. var MARK_USED = '1';
  45393. /**
  45394. * Manages elements that can be defined in <defs> in SVG,
  45395. * e.g., gradients, clip path, etc.
  45396. *
  45397. * @class
  45398. * @param {number} zrId zrender instance id
  45399. * @param {SVGElement} svgRoot root of SVG document
  45400. * @param {string|string[]} tagNames possible tag names
  45401. * @param {string} markLabel label name to make if the element
  45402. * is used
  45403. */
  45404. function Definable(
  45405. zrId,
  45406. svgRoot,
  45407. tagNames,
  45408. markLabel,
  45409. domName
  45410. ) {
  45411. this._zrId = zrId;
  45412. this._svgRoot = svgRoot;
  45413. this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames;
  45414. this._markLabel = markLabel;
  45415. this._domName = domName || '_dom';
  45416. this.nextId = 0;
  45417. }
  45418. Definable.prototype.createElement = createElement;
  45419. /**
  45420. * Get the <defs> tag for svgRoot; optionally creates one if not exists.
  45421. *
  45422. * @param {boolean} isForceCreating if need to create when not exists
  45423. * @return {SVGDefsElement} SVG <defs> element, null if it doesn't
  45424. * exist and isForceCreating is false
  45425. */
  45426. Definable.prototype.getDefs = function (isForceCreating) {
  45427. var svgRoot = this._svgRoot;
  45428. var defs = this._svgRoot.getElementsByTagName('defs');
  45429. if (defs.length === 0) {
  45430. // Not exist
  45431. if (isForceCreating) {
  45432. defs = svgRoot.insertBefore(
  45433. this.createElement('defs'), // Create new tag
  45434. svgRoot.firstChild // Insert in the front of svg
  45435. );
  45436. if (!defs.contains) {
  45437. // IE doesn't support contains method
  45438. defs.contains = function (el) {
  45439. var children = defs.children;
  45440. if (!children) {
  45441. return false;
  45442. }
  45443. for (var i = children.length - 1; i >= 0; --i) {
  45444. if (children[i] === el) {
  45445. return true;
  45446. }
  45447. }
  45448. return false;
  45449. };
  45450. }
  45451. return defs;
  45452. }
  45453. else {
  45454. return null;
  45455. }
  45456. }
  45457. else {
  45458. return defs[0];
  45459. }
  45460. };
  45461. /**
  45462. * Update DOM element if necessary.
  45463. *
  45464. * @param {Object|string} element style element. e.g., for gradient,
  45465. * it may be '#ccc' or {type: 'linear', ...}
  45466. * @param {Function|undefined} onUpdate update callback
  45467. */
  45468. Definable.prototype.update = function (element, onUpdate) {
  45469. if (!element) {
  45470. return;
  45471. }
  45472. var defs = this.getDefs(false);
  45473. if (element[this._domName] && defs.contains(element[this._domName])) {
  45474. // Update DOM
  45475. if (typeof onUpdate === 'function') {
  45476. onUpdate(element);
  45477. }
  45478. }
  45479. else {
  45480. // No previous dom, create new
  45481. var dom = this.add(element);
  45482. if (dom) {
  45483. element[this._domName] = dom;
  45484. }
  45485. }
  45486. };
  45487. /**
  45488. * Add gradient dom to defs
  45489. *
  45490. * @param {SVGElement} dom DOM to be added to <defs>
  45491. */
  45492. Definable.prototype.addDom = function (dom) {
  45493. var defs = this.getDefs(true);
  45494. defs.appendChild(dom);
  45495. };
  45496. /**
  45497. * Remove DOM of a given element.
  45498. *
  45499. * @param {SVGElement} element element to remove dom
  45500. */
  45501. Definable.prototype.removeDom = function (element) {
  45502. var defs = this.getDefs(false);
  45503. if (defs && element[this._domName]) {
  45504. defs.removeChild(element[this._domName]);
  45505. element[this._domName] = null;
  45506. }
  45507. };
  45508. /**
  45509. * Get DOMs of this element.
  45510. *
  45511. * @return {HTMLDomElement} doms of this defineable elements in <defs>
  45512. */
  45513. Definable.prototype.getDoms = function () {
  45514. var defs = this.getDefs(false);
  45515. if (!defs) {
  45516. // No dom when defs is not defined
  45517. return [];
  45518. }
  45519. var doms = [];
  45520. each$1(this._tagNames, function (tagName) {
  45521. var tags = defs.getElementsByTagName(tagName);
  45522. // Note that tags is HTMLCollection, which is array-like
  45523. // rather than real array.
  45524. // So `doms.concat(tags)` add tags as one object.
  45525. doms = doms.concat([].slice.call(tags));
  45526. });
  45527. return doms;
  45528. };
  45529. /**
  45530. * Mark DOMs to be unused before painting, and clear unused ones at the end
  45531. * of the painting.
  45532. */
  45533. Definable.prototype.markAllUnused = function () {
  45534. var doms = this.getDoms();
  45535. var that = this;
  45536. each$1(doms, function (dom) {
  45537. dom[that._markLabel] = MARK_UNUSED;
  45538. });
  45539. };
  45540. /**
  45541. * Mark a single DOM to be used.
  45542. *
  45543. * @param {SVGElement} dom DOM to mark
  45544. */
  45545. Definable.prototype.markUsed = function (dom) {
  45546. if (dom) {
  45547. dom[this._markLabel] = MARK_USED;
  45548. }
  45549. };
  45550. /**
  45551. * Remove unused DOMs defined in <defs>
  45552. */
  45553. Definable.prototype.removeUnused = function () {
  45554. var defs = this.getDefs(false);
  45555. if (!defs) {
  45556. // Nothing to remove
  45557. return;
  45558. }
  45559. var doms = this.getDoms();
  45560. var that = this;
  45561. each$1(doms, function (dom) {
  45562. if (dom[that._markLabel] !== MARK_USED) {
  45563. // Remove gradient
  45564. defs.removeChild(dom);
  45565. }
  45566. });
  45567. };
  45568. /**
  45569. * Get SVG proxy.
  45570. *
  45571. * @param {Displayable} displayable displayable element
  45572. * @return {Path|Image|Text} svg proxy of given element
  45573. */
  45574. Definable.prototype.getSvgProxy = function (displayable) {
  45575. if (displayable instanceof Path) {
  45576. return svgPath;
  45577. }
  45578. else if (displayable instanceof ZImage) {
  45579. return svgImage;
  45580. }
  45581. else if (displayable instanceof Text) {
  45582. return svgText;
  45583. }
  45584. else {
  45585. return svgPath;
  45586. }
  45587. };
  45588. /**
  45589. * Get text SVG element.
  45590. *
  45591. * @param {Displayable} displayable displayable element
  45592. * @return {SVGElement} SVG element of text
  45593. */
  45594. Definable.prototype.getTextSvgElement = function (displayable) {
  45595. return displayable.__textSvgEl;
  45596. };
  45597. /**
  45598. * Get SVG element.
  45599. *
  45600. * @param {Displayable} displayable displayable element
  45601. * @return {SVGElement} SVG element
  45602. */
  45603. Definable.prototype.getSvgElement = function (displayable) {
  45604. return displayable.__svgEl;
  45605. };
  45606. /**
  45607. * @file Manages SVG gradient elements.
  45608. * @author Zhang Wenli
  45609. */
  45610. /**
  45611. * Manages SVG gradient elements.
  45612. *
  45613. * @class
  45614. * @extends Definable
  45615. * @param {number} zrId zrender instance id
  45616. * @param {SVGElement} svgRoot root of SVG document
  45617. */
  45618. function GradientManager(zrId, svgRoot) {
  45619. Definable.call(
  45620. this,
  45621. zrId,
  45622. svgRoot,
  45623. ['linearGradient', 'radialGradient'],
  45624. '__gradient_in_use__'
  45625. );
  45626. }
  45627. inherits(GradientManager, Definable);
  45628. /**
  45629. * Create new gradient DOM for fill or stroke if not exist,
  45630. * but will not update gradient if exists.
  45631. *
  45632. * @param {SvgElement} svgElement SVG element to paint
  45633. * @param {Displayable} displayable zrender displayable element
  45634. */
  45635. GradientManager.prototype.addWithoutUpdate = function (
  45636. svgElement,
  45637. displayable
  45638. ) {
  45639. if (displayable && displayable.style) {
  45640. var that = this;
  45641. each$1(['fill', 'stroke'], function (fillOrStroke) {
  45642. if (displayable.style[fillOrStroke]
  45643. && (displayable.style[fillOrStroke].type === 'linear'
  45644. || displayable.style[fillOrStroke].type === 'radial')
  45645. ) {
  45646. var gradient = displayable.style[fillOrStroke];
  45647. var defs = that.getDefs(true);
  45648. // Create dom in <defs> if not exists
  45649. var dom;
  45650. if (gradient._dom) {
  45651. // Gradient exists
  45652. dom = gradient._dom;
  45653. if (!defs.contains(gradient._dom)) {
  45654. // _dom is no longer in defs, recreate
  45655. that.addDom(dom);
  45656. }
  45657. }
  45658. else {
  45659. // New dom
  45660. dom = that.add(gradient);
  45661. }
  45662. that.markUsed(displayable);
  45663. var id = dom.getAttribute('id');
  45664. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  45665. }
  45666. });
  45667. }
  45668. };
  45669. /**
  45670. * Add a new gradient tag in <defs>
  45671. *
  45672. * @param {Gradient} gradient zr gradient instance
  45673. * @return {SVGLinearGradientElement | SVGRadialGradientElement}
  45674. * created DOM
  45675. */
  45676. GradientManager.prototype.add = function (gradient) {
  45677. var dom;
  45678. if (gradient.type === 'linear') {
  45679. dom = this.createElement('linearGradient');
  45680. }
  45681. else if (gradient.type === 'radial') {
  45682. dom = this.createElement('radialGradient');
  45683. }
  45684. else {
  45685. zrLog('Illegal gradient type.');
  45686. return null;
  45687. }
  45688. // Set dom id with gradient id, since each gradient instance
  45689. // will have no more than one dom element.
  45690. // id may exists before for those dirty elements, in which case
  45691. // id should remain the same, and other attributes should be
  45692. // updated.
  45693. gradient.id = gradient.id || this.nextId++;
  45694. dom.setAttribute('id', 'zr' + this._zrId
  45695. + '-gradient-' + gradient.id);
  45696. this.updateDom(gradient, dom);
  45697. this.addDom(dom);
  45698. return dom;
  45699. };
  45700. /**
  45701. * Update gradient.
  45702. *
  45703. * @param {Gradient} gradient zr gradient instance
  45704. */
  45705. GradientManager.prototype.update = function (gradient) {
  45706. var that = this;
  45707. Definable.prototype.update.call(this, gradient, function () {
  45708. var type = gradient.type;
  45709. var tagName = gradient._dom.tagName;
  45710. if (type === 'linear' && tagName === 'linearGradient'
  45711. || type === 'radial' && tagName === 'radialGradient'
  45712. ) {
  45713. // Gradient type is not changed, update gradient
  45714. that.updateDom(gradient, gradient._dom);
  45715. }
  45716. else {
  45717. // Remove and re-create if type is changed
  45718. that.removeDom(gradient);
  45719. that.add(gradient);
  45720. }
  45721. });
  45722. };
  45723. /**
  45724. * Update gradient dom
  45725. *
  45726. * @param {Gradient} gradient zr gradient instance
  45727. * @param {SVGLinearGradientElement | SVGRadialGradientElement} dom
  45728. * DOM to update
  45729. */
  45730. GradientManager.prototype.updateDom = function (gradient, dom) {
  45731. if (gradient.type === 'linear') {
  45732. dom.setAttribute('x1', gradient.x);
  45733. dom.setAttribute('y1', gradient.y);
  45734. dom.setAttribute('x2', gradient.x2);
  45735. dom.setAttribute('y2', gradient.y2);
  45736. }
  45737. else if (gradient.type === 'radial') {
  45738. dom.setAttribute('cx', gradient.x);
  45739. dom.setAttribute('cy', gradient.y);
  45740. dom.setAttribute('r', gradient.r);
  45741. }
  45742. else {
  45743. zrLog('Illegal gradient type.');
  45744. return;
  45745. }
  45746. if (gradient.global) {
  45747. // x1, x2, y1, y2 in range of 0 to canvas width or height
  45748. dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  45749. }
  45750. else {
  45751. // x1, x2, y1, y2 in range of 0 to 1
  45752. dom.setAttribute('gradientUnits', 'objectBoundingBox');
  45753. }
  45754. // Remove color stops if exists
  45755. dom.innerHTML = '';
  45756. // Add color stops
  45757. var colors = gradient.colorStops;
  45758. for (var i = 0, len = colors.length; i < len; ++i) {
  45759. var stop = this.createElement('stop');
  45760. stop.setAttribute('offset', colors[i].offset * 100 + '%');
  45761. stop.setAttribute('stop-color', colors[i].color);
  45762. dom.appendChild(stop);
  45763. }
  45764. // Store dom element in gradient, to avoid creating multiple
  45765. // dom instances for the same gradient element
  45766. gradient._dom = dom;
  45767. };
  45768. /**
  45769. * Mark a single gradient to be used
  45770. *
  45771. * @param {Displayable} displayable displayable element
  45772. */
  45773. GradientManager.prototype.markUsed = function (displayable) {
  45774. if (displayable.style) {
  45775. var gradient = displayable.style.fill;
  45776. if (gradient && gradient._dom) {
  45777. Definable.prototype.markUsed.call(this, gradient._dom);
  45778. }
  45779. gradient = displayable.style.stroke;
  45780. if (gradient && gradient._dom) {
  45781. Definable.prototype.markUsed.call(this, gradient._dom);
  45782. }
  45783. }
  45784. };
  45785. /**
  45786. * @file Manages SVG clipPath elements.
  45787. * @author Zhang Wenli
  45788. */
  45789. /**
  45790. * Manages SVG clipPath elements.
  45791. *
  45792. * @class
  45793. * @extends Definable
  45794. * @param {number} zrId zrender instance id
  45795. * @param {SVGElement} svgRoot root of SVG document
  45796. */
  45797. function ClippathManager(zrId, svgRoot) {
  45798. Definable.call(this, zrId, svgRoot, 'clipPath', '__clippath_in_use__');
  45799. }
  45800. inherits(ClippathManager, Definable);
  45801. /**
  45802. * Update clipPath.
  45803. *
  45804. * @param {Displayable} displayable displayable element
  45805. */
  45806. ClippathManager.prototype.update = function (displayable) {
  45807. var svgEl = this.getSvgElement(displayable);
  45808. if (svgEl) {
  45809. this.updateDom(svgEl, displayable.__clipPaths, false);
  45810. }
  45811. var textEl = this.getTextSvgElement(displayable);
  45812. if (textEl) {
  45813. // Make another clipPath for text, since it's transform
  45814. // matrix is not the same with svgElement
  45815. this.updateDom(textEl, displayable.__clipPaths, true);
  45816. }
  45817. this.markUsed(displayable);
  45818. };
  45819. /**
  45820. * Create an SVGElement of displayable and create a <clipPath> of its
  45821. * clipPath
  45822. *
  45823. * @param {Displayable} parentEl parent element
  45824. * @param {ClipPath[]} clipPaths clipPaths of parent element
  45825. * @param {boolean} isText if parent element is Text
  45826. */
  45827. ClippathManager.prototype.updateDom = function (
  45828. parentEl,
  45829. clipPaths,
  45830. isText
  45831. ) {
  45832. if (clipPaths && clipPaths.length > 0) {
  45833. // Has clipPath, create <clipPath> with the first clipPath
  45834. var defs = this.getDefs(true);
  45835. var clipPath = clipPaths[0];
  45836. var clipPathEl;
  45837. var id;
  45838. var dom = isText ? '_textDom' : '_dom';
  45839. if (clipPath[dom]) {
  45840. // Use a dom that is already in <defs>
  45841. id = clipPath[dom].getAttribute('id');
  45842. clipPathEl = clipPath[dom];
  45843. // Use a dom that is already in <defs>
  45844. if (!defs.contains(clipPathEl)) {
  45845. // This happens when set old clipPath that has
  45846. // been previously removed
  45847. defs.appendChild(clipPathEl);
  45848. }
  45849. }
  45850. else {
  45851. // New <clipPath>
  45852. id = 'zr' + this._zrId + '-clip-' + this.nextId;
  45853. ++this.nextId;
  45854. clipPathEl = this.createElement('clipPath');
  45855. clipPathEl.setAttribute('id', id);
  45856. defs.appendChild(clipPathEl);
  45857. clipPath[dom] = clipPathEl;
  45858. }
  45859. // Build path and add to <clipPath>
  45860. var svgProxy = this.getSvgProxy(clipPath);
  45861. if (clipPath.transform
  45862. && clipPath.parent.invTransform
  45863. && !isText
  45864. ) {
  45865. /**
  45866. * If a clipPath has a parent with transform, the transform
  45867. * of parent should not be considered when setting transform
  45868. * of clipPath. So we need to transform back from parent's
  45869. * transform, which is done by multiplying parent's inverse
  45870. * transform.
  45871. */
  45872. // Store old transform
  45873. var transform = Array.prototype.slice.call(
  45874. clipPath.transform
  45875. );
  45876. // Transform back from parent, and brush path
  45877. mul$1(
  45878. clipPath.transform,
  45879. clipPath.parent.invTransform,
  45880. clipPath.transform
  45881. );
  45882. svgProxy.brush(clipPath);
  45883. // Set back transform of clipPath
  45884. clipPath.transform = transform;
  45885. }
  45886. else {
  45887. svgProxy.brush(clipPath);
  45888. }
  45889. var pathEl = this.getSvgElement(clipPath);
  45890. clipPathEl.innerHTML = '';
  45891. /**
  45892. * Use `cloneNode()` here to appendChild to multiple parents,
  45893. * which may happend when Text and other shapes are using the same
  45894. * clipPath. Since Text will create an extra clipPath DOM due to
  45895. * different transform rules.
  45896. */
  45897. clipPathEl.appendChild(pathEl.cloneNode());
  45898. parentEl.setAttribute('clip-path', 'url(#' + id + ')');
  45899. if (clipPaths.length > 1) {
  45900. // Make the other clipPaths recursively
  45901. this.updateDom(clipPathEl, clipPaths.slice(1), isText);
  45902. }
  45903. }
  45904. else {
  45905. // No clipPath
  45906. if (parentEl) {
  45907. parentEl.setAttribute('clip-path', 'none');
  45908. }
  45909. }
  45910. };
  45911. /**
  45912. * Mark a single clipPath to be used
  45913. *
  45914. * @param {Displayable} displayable displayable element
  45915. */
  45916. ClippathManager.prototype.markUsed = function (displayable) {
  45917. var that = this;
  45918. if (displayable.__clipPaths && displayable.__clipPaths.length > 0) {
  45919. each$1(displayable.__clipPaths, function (clipPath) {
  45920. if (clipPath._dom) {
  45921. Definable.prototype.markUsed.call(that, clipPath._dom);
  45922. }
  45923. if (clipPath._textDom) {
  45924. Definable.prototype.markUsed.call(that, clipPath._textDom);
  45925. }
  45926. });
  45927. }
  45928. };
  45929. /**
  45930. * @file Manages SVG shadow elements.
  45931. * @author Zhang Wenli
  45932. */
  45933. /**
  45934. * Manages SVG shadow elements.
  45935. *
  45936. * @class
  45937. * @extends Definable
  45938. * @param {number} zrId zrender instance id
  45939. * @param {SVGElement} svgRoot root of SVG document
  45940. */
  45941. function ShadowManager(zrId, svgRoot) {
  45942. Definable.call(
  45943. this,
  45944. zrId,
  45945. svgRoot,
  45946. ['filter'],
  45947. '__filter_in_use__',
  45948. '_shadowDom'
  45949. );
  45950. }
  45951. inherits(ShadowManager, Definable);
  45952. /**
  45953. * Create new shadow DOM for fill or stroke if not exist,
  45954. * but will not update shadow if exists.
  45955. *
  45956. * @param {SvgElement} svgElement SVG element to paint
  45957. * @param {Displayable} displayable zrender displayable element
  45958. */
  45959. ShadowManager.prototype.addWithoutUpdate = function (
  45960. svgElement,
  45961. displayable
  45962. ) {
  45963. if (displayable && hasShadow(displayable.style)) {
  45964. var style = displayable.style;
  45965. // Create dom in <defs> if not exists
  45966. var dom;
  45967. if (style._shadowDom) {
  45968. // Gradient exists
  45969. dom = style._shadowDom;
  45970. var defs = this.getDefs(true);
  45971. if (!defs.contains(style._shadowDom)) {
  45972. // _shadowDom is no longer in defs, recreate
  45973. this.addDom(dom);
  45974. }
  45975. }
  45976. else {
  45977. // New dom
  45978. dom = this.add(displayable);
  45979. }
  45980. this.markUsed(displayable);
  45981. var id = dom.getAttribute('id');
  45982. svgElement.style.filter = 'url(#' + id + ')';
  45983. }
  45984. };
  45985. /**
  45986. * Add a new shadow tag in <defs>
  45987. *
  45988. * @param {Displayable} displayable zrender displayable element
  45989. * @return {SVGFilterElement} created DOM
  45990. */
  45991. ShadowManager.prototype.add = function (displayable) {
  45992. var dom = this.createElement('filter');
  45993. var style = displayable.style;
  45994. // Set dom id with shadow id, since each shadow instance
  45995. // will have no more than one dom element.
  45996. // id may exists before for those dirty elements, in which case
  45997. // id should remain the same, and other attributes should be
  45998. // updated.
  45999. style._shadowDomId = style._shadowDomId || this.nextId++;
  46000. dom.setAttribute('id', 'zr' + this._zrId
  46001. + '-shadow-' + style._shadowDomId);
  46002. this.updateDom(displayable, dom);
  46003. this.addDom(dom);
  46004. return dom;
  46005. };
  46006. /**
  46007. * Update shadow.
  46008. *
  46009. * @param {Displayable} displayable zrender displayable element
  46010. */
  46011. ShadowManager.prototype.update = function (svgElement, displayable) {
  46012. var style = displayable.style;
  46013. if (hasShadow(style)) {
  46014. var that = this;
  46015. Definable.prototype.update.call(this, displayable, function (style) {
  46016. that.updateDom(displayable, style._shadowDom);
  46017. });
  46018. }
  46019. else {
  46020. // Remove shadow
  46021. this.remove(svgElement, style);
  46022. }
  46023. };
  46024. /**
  46025. * Remove DOM and clear parent filter
  46026. */
  46027. ShadowManager.prototype.remove = function (svgElement, style) {
  46028. if (style._shadowDomId != null) {
  46029. this.removeDom(style);
  46030. svgElement.style.filter = '';
  46031. }
  46032. };
  46033. /**
  46034. * Update shadow dom
  46035. *
  46036. * @param {Displayable} displayable zrender displayable element
  46037. * @param {SVGFilterElement} dom DOM to update
  46038. */
  46039. ShadowManager.prototype.updateDom = function (displayable, dom) {
  46040. var domChild = dom.getElementsByTagName('feDropShadow');
  46041. if (domChild.length === 0) {
  46042. domChild = this.createElement('feDropShadow');
  46043. }
  46044. else {
  46045. domChild = domChild[0];
  46046. }
  46047. var style = displayable.style;
  46048. var scaleX = displayable.scale ? (displayable.scale[0] || 1) : 1;
  46049. var scaleY = displayable.scale ? (displayable.scale[1] || 1) : 1;
  46050. // TODO: textBoxShadowBlur is not supported yet
  46051. var offsetX, offsetY, blur, color;
  46052. if (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY) {
  46053. offsetX = style.shadowOffsetX || 0;
  46054. offsetY = style.shadowOffsetY || 0;
  46055. blur = style.shadowBlur;
  46056. color = style.shadowColor;
  46057. }
  46058. else if (style.textShadowBlur) {
  46059. offsetX = style.textShadowOffsetX || 0;
  46060. offsetY = style.textShadowOffsetY || 0;
  46061. blur = style.textShadowBlur;
  46062. color = style.textShadowColor;
  46063. }
  46064. else {
  46065. // Remove shadow
  46066. this.removeDom(dom, style);
  46067. return;
  46068. }
  46069. domChild.setAttribute('dx', offsetX / scaleX);
  46070. domChild.setAttribute('dy', offsetY / scaleY);
  46071. domChild.setAttribute('flood-color', color);
  46072. // Divide by two here so that it looks the same as in canvas
  46073. // See: https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowblur
  46074. var stdDx = blur / 2 / scaleX;
  46075. var stdDy = blur / 2 / scaleY;
  46076. var stdDeviation = stdDx + ' ' + stdDy;
  46077. domChild.setAttribute('stdDeviation', stdDeviation);
  46078. // Fix filter clipping problem
  46079. dom.setAttribute('x', '-100%');
  46080. dom.setAttribute('y', '-100%');
  46081. dom.setAttribute('width', Math.ceil(blur / 2 * 200) + '%');
  46082. dom.setAttribute('height', Math.ceil(blur / 2 * 200) + '%');
  46083. dom.appendChild(domChild);
  46084. // Store dom element in shadow, to avoid creating multiple
  46085. // dom instances for the same shadow element
  46086. style._shadowDom = dom;
  46087. };
  46088. /**
  46089. * Mark a single shadow to be used
  46090. *
  46091. * @param {Displayable} displayable displayable element
  46092. */
  46093. ShadowManager.prototype.markUsed = function (displayable) {
  46094. var style = displayable.style;
  46095. if (style && style._shadowDom) {
  46096. Definable.prototype.markUsed.call(this, style._shadowDom);
  46097. }
  46098. };
  46099. function hasShadow(style) {
  46100. // TODO: textBoxShadowBlur is not supported yet
  46101. return style
  46102. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY
  46103. || style.textShadowBlur || style.textShadowOffsetX
  46104. || style.textShadowOffsetY);
  46105. }
  46106. /**
  46107. * SVG Painter
  46108. * @module zrender/svg/Painter
  46109. */
  46110. function parseInt10$2(val) {
  46111. return parseInt(val, 10);
  46112. }
  46113. function getSvgProxy(el) {
  46114. if (el instanceof Path) {
  46115. return svgPath;
  46116. }
  46117. else if (el instanceof ZImage) {
  46118. return svgImage;
  46119. }
  46120. else if (el instanceof Text) {
  46121. return svgText;
  46122. }
  46123. else {
  46124. return svgPath;
  46125. }
  46126. }
  46127. function checkParentAvailable(parent, child) {
  46128. return child && parent && child.parentNode !== parent;
  46129. }
  46130. function insertAfter(parent, child, prevSibling) {
  46131. if (checkParentAvailable(parent, child) && prevSibling) {
  46132. var nextSibling = prevSibling.nextSibling;
  46133. nextSibling ? parent.insertBefore(child, nextSibling)
  46134. : parent.appendChild(child);
  46135. }
  46136. }
  46137. function prepend(parent, child) {
  46138. if (checkParentAvailable(parent, child)) {
  46139. var firstChild = parent.firstChild;
  46140. firstChild ? parent.insertBefore(child, firstChild)
  46141. : parent.appendChild(child);
  46142. }
  46143. }
  46144. function remove$1(parent, child) {
  46145. if (child && parent && child.parentNode === parent) {
  46146. parent.removeChild(child);
  46147. }
  46148. }
  46149. function getTextSvgElement(displayable) {
  46150. return displayable.__textSvgEl;
  46151. }
  46152. function getSvgElement(displayable) {
  46153. return displayable.__svgEl;
  46154. }
  46155. /**
  46156. * @alias module:zrender/svg/Painter
  46157. * @constructor
  46158. * @param {HTMLElement} root 绘图容器
  46159. * @param {module:zrender/Storage} storage
  46160. * @param {Object} opts
  46161. */
  46162. var SVGPainter = function (root, storage, opts, zrId) {
  46163. this.root = root;
  46164. this.storage = storage;
  46165. this._opts = opts = extend({}, opts || {});
  46166. var svgRoot = createElement('svg');
  46167. svgRoot.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  46168. svgRoot.setAttribute('version', '1.1');
  46169. svgRoot.setAttribute('baseProfile', 'full');
  46170. svgRoot.style.cssText = 'user-select:none;position:absolute;left:0;top:0;';
  46171. this.gradientManager = new GradientManager(zrId, svgRoot);
  46172. this.clipPathManager = new ClippathManager(zrId, svgRoot);
  46173. this.shadowManager = new ShadowManager(zrId, svgRoot);
  46174. var viewport = document.createElement('div');
  46175. viewport.style.cssText = 'overflow:hidden;position:relative';
  46176. this._svgRoot = svgRoot;
  46177. this._viewport = viewport;
  46178. root.appendChild(viewport);
  46179. viewport.appendChild(svgRoot);
  46180. this.resize(opts.width, opts.height);
  46181. this._visibleList = [];
  46182. };
  46183. SVGPainter.prototype = {
  46184. constructor: SVGPainter,
  46185. getType: function () {
  46186. return 'svg';
  46187. },
  46188. getViewportRoot: function () {
  46189. return this._viewport;
  46190. },
  46191. getViewportRootOffset: function () {
  46192. var viewportRoot = this.getViewportRoot();
  46193. if (viewportRoot) {
  46194. return {
  46195. offsetLeft: viewportRoot.offsetLeft || 0,
  46196. offsetTop: viewportRoot.offsetTop || 0
  46197. };
  46198. }
  46199. },
  46200. refresh: function () {
  46201. var list = this.storage.getDisplayList(true);
  46202. this._paintList(list);
  46203. },
  46204. setBackgroundColor: function (backgroundColor) {
  46205. // TODO gradient
  46206. this._viewport.style.background = backgroundColor;
  46207. },
  46208. _paintList: function (list) {
  46209. this.gradientManager.markAllUnused();
  46210. this.clipPathManager.markAllUnused();
  46211. this.shadowManager.markAllUnused();
  46212. var svgRoot = this._svgRoot;
  46213. var visibleList = this._visibleList;
  46214. var listLen = list.length;
  46215. var newVisibleList = [];
  46216. var i;
  46217. for (i = 0; i < listLen; i++) {
  46218. var displayable = list[i];
  46219. var svgProxy = getSvgProxy(displayable);
  46220. var svgElement = getSvgElement(displayable)
  46221. || getTextSvgElement(displayable);
  46222. if (!displayable.invisible) {
  46223. if (displayable.__dirty) {
  46224. svgProxy && svgProxy.brush(displayable);
  46225. // Update clipPath
  46226. this.clipPathManager.update(displayable);
  46227. // Update gradient and shadow
  46228. if (displayable.style) {
  46229. this.gradientManager
  46230. .update(displayable.style.fill);
  46231. this.gradientManager
  46232. .update(displayable.style.stroke);
  46233. this.shadowManager
  46234. .update(svgElement, displayable);
  46235. }
  46236. displayable.__dirty = false;
  46237. }
  46238. newVisibleList.push(displayable);
  46239. }
  46240. }
  46241. var diff = arrayDiff$1(visibleList, newVisibleList);
  46242. var prevSvgElement;
  46243. // First do remove, in case element moved to the head and do remove
  46244. // after add
  46245. for (i = 0; i < diff.length; i++) {
  46246. var item = diff[i];
  46247. if (item.removed) {
  46248. for (var k = 0; k < item.count; k++) {
  46249. var displayable = visibleList[item.indices[k]];
  46250. var svgElement = getSvgElement(displayable);
  46251. var textSvgElement = getTextSvgElement(displayable);
  46252. remove$1(svgRoot, svgElement);
  46253. remove$1(svgRoot, textSvgElement);
  46254. }
  46255. }
  46256. }
  46257. for (i = 0; i < diff.length; i++) {
  46258. var item = diff[i];
  46259. if (item.added) {
  46260. for (var k = 0; k < item.count; k++) {
  46261. var displayable = newVisibleList[item.indices[k]];
  46262. var svgElement = getSvgElement(displayable);
  46263. var textSvgElement = getTextSvgElement(displayable);
  46264. prevSvgElement
  46265. ? insertAfter(svgRoot, svgElement, prevSvgElement)
  46266. : prepend(svgRoot, svgElement);
  46267. if (svgElement) {
  46268. insertAfter(svgRoot, textSvgElement, svgElement);
  46269. }
  46270. else if (prevSvgElement) {
  46271. insertAfter(
  46272. svgRoot, textSvgElement, prevSvgElement
  46273. );
  46274. }
  46275. else {
  46276. prepend(svgRoot, textSvgElement);
  46277. }
  46278. // Insert text
  46279. insertAfter(svgRoot, textSvgElement, svgElement);
  46280. prevSvgElement = textSvgElement || svgElement
  46281. || prevSvgElement;
  46282. this.gradientManager
  46283. .addWithoutUpdate(svgElement, displayable);
  46284. this.shadowManager
  46285. .addWithoutUpdate(prevSvgElement, displayable);
  46286. this.clipPathManager.markUsed(displayable);
  46287. }
  46288. }
  46289. else if (!item.removed) {
  46290. for (var k = 0; k < item.count; k++) {
  46291. var displayable = newVisibleList[item.indices[k]];
  46292. prevSvgElement
  46293. = svgElement
  46294. = getTextSvgElement(displayable)
  46295. || getSvgElement(displayable)
  46296. || prevSvgElement;
  46297. this.gradientManager.markUsed(displayable);
  46298. this.gradientManager
  46299. .addWithoutUpdate(svgElement, displayable);
  46300. this.shadowManager.markUsed(displayable);
  46301. this.shadowManager
  46302. .addWithoutUpdate(svgElement, displayable);
  46303. this.clipPathManager.markUsed(displayable);
  46304. }
  46305. }
  46306. }
  46307. this.gradientManager.removeUnused();
  46308. this.clipPathManager.removeUnused();
  46309. this.shadowManager.removeUnused();
  46310. this._visibleList = newVisibleList;
  46311. },
  46312. _getDefs: function (isForceCreating) {
  46313. var svgRoot = this._svgRoot;
  46314. var defs = this._svgRoot.getElementsByTagName('defs');
  46315. if (defs.length === 0) {
  46316. // Not exist
  46317. if (isForceCreating) {
  46318. var defs = svgRoot.insertBefore(
  46319. createElement('defs'), // Create new tag
  46320. svgRoot.firstChild // Insert in the front of svg
  46321. );
  46322. if (!defs.contains) {
  46323. // IE doesn't support contains method
  46324. defs.contains = function (el) {
  46325. var children = defs.children;
  46326. if (!children) {
  46327. return false;
  46328. }
  46329. for (var i = children.length - 1; i >= 0; --i) {
  46330. if (children[i] === el) {
  46331. return true;
  46332. }
  46333. }
  46334. return false;
  46335. };
  46336. }
  46337. return defs;
  46338. }
  46339. else {
  46340. return null;
  46341. }
  46342. }
  46343. else {
  46344. return defs[0];
  46345. }
  46346. },
  46347. resize: function (width, height) {
  46348. var viewport = this._viewport;
  46349. // FIXME Why ?
  46350. viewport.style.display = 'none';
  46351. // Save input w/h
  46352. var opts = this._opts;
  46353. width != null && (opts.width = width);
  46354. height != null && (opts.height = height);
  46355. width = this._getSize(0);
  46356. height = this._getSize(1);
  46357. viewport.style.display = '';
  46358. if (this._width !== width || this._height !== height) {
  46359. this._width = width;
  46360. this._height = height;
  46361. var viewportStyle = viewport.style;
  46362. viewportStyle.width = width + 'px';
  46363. viewportStyle.height = height + 'px';
  46364. var svgRoot = this._svgRoot;
  46365. // Set width by 'svgRoot.width = width' is invalid
  46366. svgRoot.setAttribute('width', width);
  46367. svgRoot.setAttribute('height', height);
  46368. }
  46369. },
  46370. /**
  46371. * 获取绘图区域宽度
  46372. */
  46373. getWidth: function () {
  46374. return this._width;
  46375. },
  46376. /**
  46377. * 获取绘图区域高度
  46378. */
  46379. getHeight: function () {
  46380. return this._height;
  46381. },
  46382. _getSize: function (whIdx) {
  46383. var opts = this._opts;
  46384. var wh = ['width', 'height'][whIdx];
  46385. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  46386. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  46387. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  46388. if (opts[wh] != null && opts[wh] !== 'auto') {
  46389. return parseFloat(opts[wh]);
  46390. }
  46391. var root = this.root;
  46392. // IE8 does not support getComputedStyle, but it use VML.
  46393. var stl = document.defaultView.getComputedStyle(root);
  46394. return (
  46395. (root[cwh] || parseInt10$2(stl[wh]) || parseInt10$2(root.style[wh]))
  46396. - (parseInt10$2(stl[plt]) || 0)
  46397. - (parseInt10$2(stl[prb]) || 0)
  46398. ) | 0;
  46399. },
  46400. dispose: function () {
  46401. this.root.innerHTML = '';
  46402. this._svgRoot
  46403. = this._viewport
  46404. = this.storage
  46405. = null;
  46406. },
  46407. clear: function () {
  46408. if (this._viewport) {
  46409. this.root.removeChild(this._viewport);
  46410. }
  46411. },
  46412. pathToDataUrl: function () {
  46413. this.refresh();
  46414. var html = this._svgRoot.outerHTML;
  46415. return 'data:image/svg+xml;charset=UTF-8,' + html;
  46416. }
  46417. };
  46418. // Not supported methods
  46419. function createMethodNotSupport$1(method) {
  46420. return function () {
  46421. zrLog('In SVG mode painter not support method "' + method + '"');
  46422. };
  46423. }
  46424. // Unsuppoted methods
  46425. each$1([
  46426. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer',
  46427. 'eachOtherLayer', 'getLayers', 'modLayer', 'delLayer', 'clearLayer',
  46428. 'toDataURL', 'pathToImage'
  46429. ], function (name) {
  46430. SVGPainter.prototype[name] = createMethodNotSupport$1(name);
  46431. });
  46432. registerPainter('svg', SVGPainter);
  46433. exports.version = version;
  46434. exports.dependencies = dependencies;
  46435. exports.PRIORITY = PRIORITY;
  46436. exports.init = init;
  46437. exports.connect = connect;
  46438. exports.disConnect = disConnect;
  46439. exports.disconnect = disconnect;
  46440. exports.dispose = dispose;
  46441. exports.getInstanceByDom = getInstanceByDom;
  46442. exports.getInstanceById = getInstanceById;
  46443. exports.registerTheme = registerTheme;
  46444. exports.registerPreprocessor = registerPreprocessor;
  46445. exports.registerProcessor = registerProcessor;
  46446. exports.registerPostUpdate = registerPostUpdate;
  46447. exports.registerAction = registerAction;
  46448. exports.registerCoordinateSystem = registerCoordinateSystem;
  46449. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  46450. exports.registerLayout = registerLayout;
  46451. exports.registerVisual = registerVisual;
  46452. exports.registerLoading = registerLoading;
  46453. exports.extendComponentModel = extendComponentModel;
  46454. exports.extendComponentView = extendComponentView;
  46455. exports.extendSeriesModel = extendSeriesModel;
  46456. exports.extendChartView = extendChartView;
  46457. exports.setCanvasCreator = setCanvasCreator;
  46458. exports.registerMap = registerMap;
  46459. exports.getMap = getMap;
  46460. exports.dataTool = dataTool;
  46461. exports.zrender = zrender;
  46462. exports.graphic = graphic;
  46463. exports.number = number;
  46464. exports.format = format;
  46465. exports.throttle = throttle;
  46466. exports.helper = helper;
  46467. exports.matrix = matrix;
  46468. exports.vector = vector;
  46469. exports.color = color;
  46470. exports.parseGeoJSON = parseGeoJSON;
  46471. exports.parseGeoJson = parseGeoJson;
  46472. exports.util = ecUtil;
  46473. exports.List = List;
  46474. exports.Model = Model;
  46475. exports.Axis = Axis;
  46476. exports.env = env$1;
  46477. })));